Skip to content

Commit

Permalink
added trie as attribute to context
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvja committed Oct 17, 2023
1 parent cad2766 commit b1d7b5f
Show file tree
Hide file tree
Showing 8 changed files with 486 additions and 51 deletions.
5 changes: 5 additions & 0 deletions solana/solana-ibc/programs/solana-ibc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ ibc-proto.workspace = true
serde.workspace = true
serde_json.workspace = true

lib.workspace = true
memory.workspace = true
sealable-trie.workspace = true
stdx.workspace = true

[dev-dependencies]
anchor-client.workspace = true
anyhow.workspace = true
Expand Down
10 changes: 5 additions & 5 deletions solana/solana-ibc/programs/solana-ibc/src/client_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl From<AnyClientState> for Any {
}
}

impl ClientStateValidation<SolanaIbcStorage> for AnyClientState {
impl ClientStateValidation<SolanaIbcStorage<'_, '_>> for AnyClientState {
fn verify_client_message(
&self,
ctx: &SolanaIbcStorage,
Expand Down Expand Up @@ -283,7 +283,7 @@ impl From<MockClientState> for AnyClientState {
fn from(value: MockClientState) -> Self { AnyClientState::Mock(value) }
}

impl ClientStateExecution<SolanaIbcStorage> for AnyClientState {
impl ClientStateExecution<SolanaIbcStorage<'_, '_>> for AnyClientState {
fn initialise(
&self,
ctx: &mut SolanaIbcStorage,
Expand Down Expand Up @@ -371,7 +371,7 @@ impl ClientStateExecution<SolanaIbcStorage> for AnyClientState {
}
}

impl ibc::clients::ics07_tendermint::CommonContext for SolanaIbcStorage {
impl ibc::clients::ics07_tendermint::CommonContext for SolanaIbcStorage<'_, '_> {
type ConversionError = ClientError;

type AnyConsensusState = AnyConsensusState;
Expand All @@ -385,7 +385,7 @@ impl ibc::clients::ics07_tendermint::CommonContext for SolanaIbcStorage {
}

#[cfg(any(test, feature = "mocks"))]
impl MockClientContext for SolanaIbcStorage {
impl MockClientContext for SolanaIbcStorage<'_, '_> {
type ConversionError = ClientError;
type AnyConsensusState = AnyConsensusState;

Expand All @@ -401,7 +401,7 @@ impl MockClientContext for SolanaIbcStorage {
}
}

impl ibc::clients::ics07_tendermint::ValidationContext for SolanaIbcStorage {
impl ibc::clients::ics07_tendermint::ValidationContext for SolanaIbcStorage<'_, '_> {
fn host_timestamp(&self) -> Result<Timestamp, ContextError> {
ValidationContext::host_timestamp(self)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crate::{

type Result<T = (), E = ibc::core::ContextError> = core::result::Result<T, E>;

impl ClientExecutionContext for SolanaIbcStorage {
impl ClientExecutionContext for SolanaIbcStorage<'_, '_> {
type ClientValidationContext = Self;
type AnyClientState = AnyClientState;
type AnyConsensusState = AnyConsensusState;
Expand Down Expand Up @@ -77,7 +77,7 @@ impl ClientExecutionContext for SolanaIbcStorage {
}
}

impl ExecutionContext for SolanaIbcStorage {
impl ExecutionContext for SolanaIbcStorage<'_, '_> {
fn increase_client_counter(&mut self) -> Result {
self.client_counter.checked_add(1).unwrap();
msg!("client_counter has increased to: {}", self.client_counter);
Expand Down
170 changes: 134 additions & 36 deletions solana/solana-ibc/programs/solana-ibc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use ibc::core::router::{Module, ModuleId, Router};
use module_holder::ModuleHolder;

const SOLANA_IBC_STORAGE_SEED: &[u8] = b"solana_ibc_storage";
const TEST_TRIE_SEED: &[u8] = b"test_trie";

declare_id!("EnfDJsAK7BGgetnmKzBx86CsgC5kfSPcsktFCQ4YLC81");

Expand All @@ -21,9 +22,16 @@ mod module_holder;
#[cfg(test)]
mod tests;
mod transfer;
mod trie;
mod validation_context;
// mod client_context;

/// Discriminants for the data stored in the accounts.
mod magic {
pub(crate) const UNINITIALISED: u32 = 0;
pub(crate) const TRIE_ROOT: u32 = 1;
}

#[anchor_lang::program]
pub mod solana_ibc {
use super::*;
Expand All @@ -34,7 +42,8 @@ pub mod solana_ibc {
) -> Result<()> {
msg!("Called deliver method");
let _sender = ctx.accounts.sender.to_account_info();
let solana_ibc_store: &mut SolanaIbcStorage = &mut ctx.accounts.storage;
let solana_ibc_store: &SolanaIbcStorageTemp =
&ctx.accounts.storage;
msg!("This is solana_ibc_store {:?}", solana_ibc_store);

let all_messages = messages
Expand All @@ -46,13 +55,73 @@ pub mod solana_ibc {
.collect::<Vec<_>>();

msg!("These are messages {:?}", all_messages);
let router = &mut solana_ibc_store.clone();


let account = &ctx.accounts.trie;
let mut trie = trie::AccountTrie::new(account.try_borrow_mut_data()?)
.ok_or(ProgramError::InvalidAccountData)?;

let mut solana_real_storage = SolanaIbcStorage {
height: solana_ibc_store.height,
module_holder: solana_ibc_store.module_holder.clone(),
clients: solana_ibc_store.clients.clone(),
client_id_set: solana_ibc_store.client_id_set.clone(),
client_counter: solana_ibc_store.client_counter.clone(),
client_processed_times: solana_ibc_store.client_processed_times.clone(),
client_processed_heights: solana_ibc_store.client_processed_heights.clone(),
consensus_states: solana_ibc_store.consensus_states.clone(),
client_consensus_state_height_sets: solana_ibc_store.client_consensus_state_height_sets.clone(),
connection_id_set: solana_ibc_store.connection_id_set.clone(),
connection_counter: solana_ibc_store.connection_counter.clone(),
connections: solana_ibc_store.connections.clone(),
channel_ends: solana_ibc_store.channel_ends.clone(),
connection_to_client: solana_ibc_store.connection_to_client.clone(),
port_channel_id_set: solana_ibc_store.port_channel_id_set.clone(),
channel_counter: solana_ibc_store.channel_counter.clone(),
next_sequence_send: solana_ibc_store.next_sequence_send.clone(),
next_sequence_recv: solana_ibc_store.next_sequence_recv.clone(),
next_sequence_ack: solana_ibc_store.next_sequence_ack.clone(),
packet_commitment_sequence_sets: solana_ibc_store.packet_commitment_sequence_sets.clone(),
packet_receipt_sequence_sets: solana_ibc_store.packet_receipt_sequence_sets.clone(),
packet_acknowledgement_sequence_sets: solana_ibc_store.packet_acknowledgement_sequence_sets.clone(),
ibc_events_history: solana_ibc_store.ibc_events_history.clone(),
trie: Some(trie)
};

let mut solana_real_storage_another = SolanaIbcStorage {
height: solana_ibc_store.height,
module_holder: solana_ibc_store.module_holder.clone(),
clients: solana_ibc_store.clients.clone(),
client_id_set: solana_ibc_store.client_id_set.clone(),
client_counter: solana_ibc_store.client_counter.clone(),
client_processed_times: solana_ibc_store.client_processed_times.clone(),
client_processed_heights: solana_ibc_store.client_processed_heights.clone(),
consensus_states: solana_ibc_store.consensus_states.clone(),
client_consensus_state_height_sets: solana_ibc_store.client_consensus_state_height_sets.clone(),
connection_id_set: solana_ibc_store.connection_id_set.clone(),
connection_counter: solana_ibc_store.connection_counter.clone(),
connections: solana_ibc_store.connections.clone(),
channel_ends: solana_ibc_store.channel_ends.clone(),
connection_to_client: solana_ibc_store.connection_to_client.clone(),
port_channel_id_set: solana_ibc_store.port_channel_id_set.clone(),
channel_counter: solana_ibc_store.channel_counter.clone(),
next_sequence_send: solana_ibc_store.next_sequence_send.clone(),
next_sequence_recv: solana_ibc_store.next_sequence_recv.clone(),
next_sequence_ack: solana_ibc_store.next_sequence_ack.clone(),
packet_commitment_sequence_sets: solana_ibc_store.packet_commitment_sequence_sets.clone(),
packet_receipt_sequence_sets: solana_ibc_store.packet_receipt_sequence_sets.clone(),
packet_acknowledgement_sequence_sets: solana_ibc_store.packet_acknowledgement_sequence_sets.clone(),
ibc_events_history: solana_ibc_store.ibc_events_history.clone(),
trie: None,
};

let router = &mut solana_real_storage_another;

let errors =
all_messages.into_iter().fold(vec![], |mut errors, msg| {
match ibc::core::MsgEnvelope::try_from(msg) {
Ok(msg) => {
match ibc::core::dispatch(solana_ibc_store, router, msg)
match ibc::core::dispatch(&mut solana_real_storage, router, msg)
{
Ok(()) => (),
Err(e) => errors.push(e),
Expand All @@ -68,17 +137,23 @@ pub mod solana_ibc {

Ok(())
}

}

#[derive(Accounts)]
pub struct Deliver<'info> {
#[account(mut)]
pub sender: Signer<'info>,
#[account(init_if_needed, payer = sender, seeds = [SOLANA_IBC_STORAGE_SEED],bump, space = 10000)]
pub storage: Account<'info, SolanaIbcStorage>,
pub storage: Account<'info, SolanaIbcStorageTemp>,
#[account(init_if_needed, payer = sender, seeds = [TEST_TRIE_SEED], bump, space = 1000)]
/// CHECK:
pub trie: AccountInfo<'info>,
pub system_program: Program<'info, System>,
}

pub struct MyTrie {}

#[event]
pub struct EmitIBCEvent {
pub ibc_event: Vec<u8>,
Expand Down Expand Up @@ -116,7 +191,7 @@ pub type InnerConsensusState = String; // Serialized
#[account]
#[derive(Debug)]
/// All the structs from IBC are stored as String since they dont implement AnchorSerialize and AnchorDeserialize
pub struct SolanaIbcStorage {
pub struct SolanaIbcStorageTemp {
pub height: InnerHeight,
/// To support the mutable borrow in `Router::get_route_mut`.
pub module_holder: ModuleHolder,
Expand Down Expand Up @@ -163,47 +238,70 @@ pub struct SolanaIbcStorage {
pub ibc_events_history: BTreeMap<InnerHeight, Vec<InnerIbcEvent>>,
}

impl SolanaIbcStorage {
pub fn new(account: Pubkey) -> Self {
SolanaIbcStorage {
height: (0, 0),
module_holder: ModuleHolder::new(account),
clients: BTreeMap::new(),
client_id_set: Vec::new(),
client_counter: 0,
client_processed_times: BTreeMap::new(),
client_processed_heights: BTreeMap::new(),
consensus_states: BTreeMap::new(),
client_consensus_state_height_sets: BTreeMap::new(),
connection_id_set: Vec::new(),
connection_counter: 0,
connections: BTreeMap::new(),
channel_ends: BTreeMap::new(),
connection_to_client: BTreeMap::new(),
port_channel_id_set: Vec::new(),
channel_counter: 0,
next_sequence_send: BTreeMap::new(),
next_sequence_recv: BTreeMap::new(),
next_sequence_ack: BTreeMap::new(),
packet_commitment_sequence_sets: BTreeMap::new(),
packet_receipt_sequence_sets: BTreeMap::new(),
packet_acknowledgement_sequence_sets: BTreeMap::new(),
ibc_events_history: BTreeMap::new(),
}
}
/// All the structs from IBC are stored as String since they dont implement AnchorSerialize and AnchorDeserialize
pub struct SolanaIbcStorage<'a, 'b> {
pub height: InnerHeight,
/// To support the mutable borrow in `Router::get_route_mut`.
pub module_holder: ModuleHolder,
pub clients: BTreeMap<InnerClientId, InnerClient>,
/// The client ids of the clients.
pub client_id_set: Vec<InnerClientId>,
pub client_counter: u64,
pub client_processed_times:
BTreeMap<InnerClientId, BTreeMap<InnerHeight, SolanaTimestamp>>,
pub client_processed_heights:
BTreeMap<InnerClientId, BTreeMap<InnerHeight, HostHeight>>,
pub consensus_states:
BTreeMap<(InnerClientId, InnerHeight), InnerConsensusState>,
/// This collection contains the heights corresponding to all consensus states of
/// all clients stored in the contract.
pub client_consensus_state_height_sets:
BTreeMap<InnerClientId, Vec<InnerHeight>>,
/// The connection ids of the connections.
pub connection_id_set: Vec<InnerConnectionId>,
pub connection_counter: u64,
pub connections: BTreeMap<InnerConnectionId, InnerConnectionEnd>,
pub channel_ends: BTreeMap<(InnerPortId, InnerChannelId), InnerChannelEnd>,
// Contains the client id corresponding to the connectionId
pub connection_to_client: BTreeMap<InnerConnectionId, InnerClientId>,
/// The port and channel id tuples of the channels.
pub port_channel_id_set: Vec<(InnerPortId, InnerChannelId)>,
pub channel_counter: u64,
pub next_sequence_send:
BTreeMap<(InnerPortId, InnerChannelId), InnerSequence>,
pub next_sequence_recv:
BTreeMap<(InnerPortId, InnerChannelId), InnerSequence>,
pub next_sequence_ack:
BTreeMap<(InnerPortId, InnerChannelId), InnerSequence>,
/// The sequence numbers of the packet commitments.
pub packet_commitment_sequence_sets:
BTreeMap<(InnerPortId, InnerChannelId), Vec<InnerSequence>>,
/// The sequence numbers of the packet receipts.
pub packet_receipt_sequence_sets:
BTreeMap<(InnerPortId, InnerChannelId), Vec<InnerSequence>>,
/// The sequence numbers of the packet acknowledgements.
pub packet_acknowledgement_sequence_sets:
BTreeMap<(InnerPortId, InnerChannelId), Vec<InnerSequence>>,
/// The history of IBC events.
pub ibc_events_history: BTreeMap<InnerHeight, Vec<InnerIbcEvent>>,
pub trie: Option<trie::AccountTrie<'a, 'b>>,
}

pub trait SolanaIbcStorageHost {
///
fn get_solana_ibc_store(_account: Pubkey) -> SolanaIbcStorage {
fn get_solana_ibc_store(
_account: Pubkey,
) -> SolanaIbcStorage<'static, 'static> {
// Unpack the account
todo!()
}
///
fn set_solana_ibc_store(_store: &SolanaIbcStorage) { todo!() }
fn set_solana_ibc_store(_store: &SolanaIbcStorage) {
todo!()
}
}

impl Router for SolanaIbcStorage {
impl Router for SolanaIbcStorage<'_, '_> {
//
fn get_route(&self, module_id: &ModuleId) -> Option<&dyn Module> {
match module_id.to_string().as_str() {
Expand Down
13 changes: 8 additions & 5 deletions solana/solana-ibc/programs/solana-ibc/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use ibc_proto::protobuf::Protobuf;

use crate::{
accounts, instruction, AnyCheck, SolanaIbcStorage, ID,
SOLANA_IBC_STORAGE_SEED,
SOLANA_IBC_STORAGE_SEED, TEST_TRIE_SEED,
};

const TYPE_URL: &str = "/ibc.core.client.v1.MsgCreateClient";
Expand Down Expand Up @@ -66,6 +66,8 @@ fn anchor_test_deliver() -> Result<()> {
// Build, sign, and send program instruction
let seeds = &[SOLANA_IBC_STORAGE_SEED];
let solana_ibc_storage = Pubkey::find_program_address(seeds, &crate::ID).0;
let trie_seeds = &[TEST_TRIE_SEED];
let trie = Pubkey::find_program_address(trie_seeds, &crate::ID).0;

let (mock_client_state, mock_cs_state) = create_mock_client_and_cs_state();
let _client_id = ClientId::new(mock_client_state.client_type(), 0).unwrap();
Expand All @@ -84,6 +86,7 @@ fn anchor_test_deliver() -> Result<()> {
.accounts(accounts::Deliver {
sender: authority.pubkey(),
storage: solana_ibc_storage,
trie,
system_program: system_program::ID,
})
.args(instruction::Deliver { messages: all_messages })
Expand All @@ -96,11 +99,11 @@ fn anchor_test_deliver() -> Result<()> {

println!("demo sig: {sig}");

// Retrieve and validate state
let solana_ibc_storage_account: SolanaIbcStorage =
program.account(solana_ibc_storage).unwrap();
// // Retrieve and validate state
// let solana_ibc_storage_account: SolanaIbcStorage =
// program.account(solana_ibc_storage).unwrap();

println!("This is solana storage account {:?}", solana_ibc_storage_account);
// println!("This is solana storage account {:?}", solana_ibc_storage_account);

Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ impl TokenTransferValidationContext for ModuleHolder {
}

impl SendPacketValidationContext for ModuleHolder {
type ClientValidationContext = SolanaIbcStorage;
type ClientValidationContext = SolanaIbcStorage<'static, 'static>;

type E = SolanaIbcStorage;
type E = SolanaIbcStorage<'static, 'static>;

type AnyConsensusState = AnyConsensusState;

Expand Down
Loading

0 comments on commit b1d7b5f

Please sign in to comment.