Skip to content

Commit

Permalink
tx_ibc wasm again
Browse files Browse the repository at this point in the history
  • Loading branch information
yito88 committed May 20, 2024
1 parent 4ed6229 commit 50bf63a
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 260 deletions.
93 changes: 9 additions & 84 deletions crates/ibc/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ use namada_events::{EmitEvents, EventTypeBuilder};
use namada_governance::storage::proposal::PGFIbcTarget;
use namada_parameters::read_epoch_duration_parameter;
use namada_state::{
DBIter, Epochs, ResultExt, State, StateRead, StorageError, StorageHasher,
StorageRead, StorageResult, StorageWrite, TxHostEnvState, WlState, DB,
DBIter, Epochs, ResultExt, State, StorageError, StorageHasher, StorageRead,
StorageResult, StorageWrite, WlState, DB,
};
use namada_token as token;
use token::DenominatedAmount;
Expand Down Expand Up @@ -114,80 +114,6 @@ where
}
}

impl<D, H> IbcStorageContext for TxHostEnvState<'_, D, H>
where
D: 'static + DB + for<'iter> DBIter<'iter>,
H: 'static + StorageHasher,
{
fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), StorageError> {
let gas = self.write_log_mut().emit_event(event);
self.charge_gas(gas).into_storage_result()?;
Ok(())
}

fn get_ibc_events(
&self,
event_type: impl AsRef<str>,
) -> Result<Vec<IbcEvent>, StorageError> {
let event_type = EventTypeBuilder::new_of::<IbcEvent>()
.with_segment(event_type)
.build();

Ok(self
.write_log()
.lookup_events_with_prefix(&event_type)
.filter_map(|event| IbcEvent::try_from(event).ok())
.collect())
}

fn transfer_token(
&mut self,
src: &Address,
dest: &Address,
token: &Address,
amount: Amount,
) -> Result<(), StorageError> {
token::transfer(self, token, src, dest, amount)
}

fn handle_masp_tx(
&mut self,
shielded: &masp_primitives::transaction::Transaction,
) -> Result<(), StorageError> {
namada_token::utils::handle_masp_tx(self, shielded)?;
namada_token::utils::update_note_commitment_tree(self, shielded)
}

fn mint_token(
&mut self,
target: &Address,
token: &Address,
amount: Amount,
) -> Result<(), StorageError> {
ibc_storage::mint_tokens(self, target, token, amount)
}

fn burn_token(
&mut self,
target: &Address,
token: &Address,
amount: Amount,
) -> Result<(), StorageError> {
ibc_storage::burn_tokens(self, target, token, amount)
}

fn log_string(&self, message: String) {
tracing::trace!(message);
}
}

impl<D, H> IbcCommonContext for TxHostEnvState<'_, D, H>
where
D: 'static + DB + for<'iter> DBIter<'iter>,
H: 'static + StorageHasher,
{
}

impl<S> IbcStorageContext for IbcProtocolContext<'_, S>
where
S: State + EmitEvents,
Expand Down Expand Up @@ -225,14 +151,6 @@ where
token::transfer(self.state, token, src, dest, amount)
}

/// Handle masp tx
fn handle_masp_tx(
&mut self,
_shielded: &masp_primitives::transaction::Transaction,
) -> Result<(), StorageError> {
unimplemented!("No MASP transfer in an IBC protocol transaction")
}

/// Mint token
fn mint_token(
&mut self,
Expand All @@ -253,6 +171,13 @@ where
ibc_storage::burn_tokens(self.state, target, token, amount)
}

fn insert_verifier(
&mut self,
_verifier: &Address,
) -> Result<(), StorageError> {
Ok(())
}

fn log_string(&self, message: String) {
tracing::trace!(message);
}
Expand Down
9 changes: 3 additions & 6 deletions crates/ibc/src/context/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,6 @@ pub trait IbcStorageContext: StorageRead + StorageWrite {
amount: Amount,
) -> Result<(), Error>;

/// Handle masp tx
fn handle_masp_tx(
&mut self,
shielded: &masp_primitives::transaction::Transaction,
) -> Result<(), Error>;

/// Mint token
fn mint_token(
&mut self,
Expand All @@ -49,6 +43,9 @@ pub trait IbcStorageContext: StorageRead + StorageWrite {
amount: Amount,
) -> Result<(), Error>;

/// Insert the verifier
fn insert_verifier(&mut self, verifier: &Address) -> Result<(), Error>;

/// Logging
fn log_string(&self, message: String);
}
14 changes: 12 additions & 2 deletions crates/ibc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ pub enum Error {
Trace(String),
#[error("Invalid chain ID: {0}")]
ChainId(IdentifierError),
#[error("Handling MASP transaction error: {0}")]
MaspTx(String),
#[error("Verifier insertion error: {0}")]
Verifier(namada_storage::Error),
}

/// IBC actions to handle IBC operations
Expand Down Expand Up @@ -133,6 +133,7 @@ where
self.ctx.inner.clone(),
self.verifiers.clone(),
);
self.insert_verifiers()?;
send_transfer_execute(
&mut self.ctx,
&mut token_transfer_ctx,
Expand Down Expand Up @@ -349,6 +350,7 @@ where
self.ctx.inner.clone(),
verifiers.clone(),
);
self.insert_verifiers()?;
send_transfer_validate(
&self.ctx,
&token_transfer_ctx,
Expand Down Expand Up @@ -390,6 +392,14 @@ where
}
}
}

fn insert_verifiers(&self) -> Result<(), Error> {
let mut ctx = self.ctx.inner.borrow_mut();
for verifier in self.verifiers.borrow().iter() {
ctx.insert_verifier(verifier).map_err(Error::Verifier)?;
}
Ok(())
}
}

fn is_ack_successful(ack: &Acknowledgement) -> Result<bool, Error> {
Expand Down
23 changes: 8 additions & 15 deletions crates/namada/src/ledger/native_vp/ibc/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,14 +223,6 @@ where
transfer(self, token, src, dest, amount)
}

fn handle_masp_tx(
&mut self,
shielded: &masp_primitives::transaction::Transaction,
) -> Result<()> {
crate::token::utils::handle_masp_tx(self, shielded)?;
crate::token::utils::update_note_commitment_tree(self, shielded)
}

fn mint_token(
&mut self,
target: &Address,
Expand All @@ -255,6 +247,10 @@ where
burn_tokens(self, token, target, amount)
}

fn insert_verifier(&mut self, _verifier: &Address) -> Result<()> {
Ok(())
}

fn log_string(&self, message: String) {
tracing::debug!("{message} in the pseudo execution for IBC VP");
}
Expand Down Expand Up @@ -393,13 +389,6 @@ where
unimplemented!("Validation doesn't transfer")
}

fn handle_masp_tx(
&mut self,
_shielded: &masp_primitives::transaction::Transaction,
) -> Result<()> {
unimplemented!("Validation doesn't handle a masp tx")
}

fn mint_token(
&mut self,
_target: &Address,
Expand All @@ -418,6 +407,10 @@ where
unimplemented!("Validation doesn't burn")
}

fn insert_verifier(&mut self, _verifier: &Address) -> Result<()> {
Ok(())
}

/// Logging
fn log_string(&self, message: String) {
tracing::debug!("{message} for validation in IBC VP");
Expand Down
66 changes: 0 additions & 66 deletions crates/namada/src/vm/host_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::num::TryFromIntError;

use borsh::BorshDeserialize;
use borsh_ext::BorshSerializeExt;
use gas::IBC_TX_GAS;
use masp_primitives::transaction::Transaction;
use namada_core::address::ESTABLISHED_ADDRESS_BYTES_LEN;
use namada_core::internal::KeyVal;
Expand Down Expand Up @@ -75,10 +74,6 @@ pub enum TxRuntimeError {
NumConversionError(TryFromIntError),
#[error("Memory error: {0}")]
MemoryError(Box<dyn std::error::Error + Sync + Send + 'static>),
#[error("Missing tx data")]
MissingTxData,
#[error("IBC: {0}")]
Ibc(#[from] namada_ibc::Error),
#[error("No value found in result buffer")]
NoValueInResultBuffer,
#[error("VP code is not allowed in allowlist parameter.")]
Expand Down Expand Up @@ -2018,67 +2013,6 @@ where
Ok(())
}

/// Execute IBC tx.
// Temporarily the IBC tx execution is implemented via a host function to
// workaround wasm issue.
pub fn tx_ibc_execute<MEM, D, H, CA>(
env: &TxVmEnv<MEM, D, H, CA>,
) -> TxResult<i64>
where
MEM: VmMemory,
D: 'static + DB + for<'iter> DBIter<'iter>,
H: 'static + StorageHasher,
CA: WasmCacheAccess,
{
use std::rc::Rc;

use namada_ibc::{IbcActions, NftTransferModule, TransferModule};

tx_charge_gas::<MEM, D, H, CA>(env, IBC_TX_GAS)?;

let tx = unsafe { env.ctx.tx.get() };
let tx_data = tx.data().ok_or_else(|| {
let sentinel = unsafe { env.ctx.sentinel.get() };
sentinel.borrow_mut().set_invalid_commitment();
TxRuntimeError::MissingTxData
})?;
let state = Rc::new(RefCell::new(env.state()));
// Verifier set populated in tx execution
let verifiers = Rc::new(RefCell::new(BTreeSet::<Address>::new()));
// Scoped to drop `verifiers.clone`s after `actions.execute`
let transfer = {
let mut actions = IbcActions::new(state.clone(), verifiers.clone());
let module = TransferModule::new(state.clone(), verifiers.clone());
actions.add_transfer_module(module);
let module = NftTransferModule::new(state);
actions.add_transfer_module(module);
actions.execute(&tx_data)?
};
// NB: There must be no other strong references to this Rc
let verifiers = Rc::into_inner(verifiers)
.expect("There must be only one strong ref to verifiers set")
.into_inner();

// Insert all the verifiers from the tx into the verifier set in env
let verifiers_in_env = unsafe { env.ctx.verifiers.get() };
for addr in verifiers.into_iter() {
tx_charge_gas::<MEM, D, H, CA>(
env,
ESTABLISHED_ADDRESS_BYTES_LEN as u64 * MEMORY_ACCESS_GAS_PER_BYTE,
)?;
verifiers_in_env.insert(addr);
}

let value = transfer.serialize_to_vec();
let len: i64 = value
.len()
.try_into()
.map_err(TxRuntimeError::NumConversionError)?;
let result_buffer = unsafe { env.ctx.result_buffer.get() };
result_buffer.replace(value);
Ok(len)
}

/// Validate a VP WASM code hash in a tx environment.
fn tx_validate_vp_code_hash<MEM, D, H, CA>(
env: &TxVmEnv<MEM, D, H, CA>,
Expand Down
1 change: 0 additions & 1 deletion crates/namada/src/vm/wasm/host_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ where
"namada_tx_get_pred_epochs" => Function::new_native_with_env(wasm_store, env.clone(), host_env::tx_get_pred_epochs),
"namada_tx_get_native_token" => Function::new_native_with_env(wasm_store, env.clone(), host_env::tx_get_native_token),
"namada_tx_log_string" => Function::new_native_with_env(wasm_store, env.clone(), host_env::tx_log_string),
"namada_tx_ibc_execute" => Function::new_native_with_env(wasm_store, env.clone(), host_env::tx_ibc_execute),
"namada_tx_set_commitment_sentinel" => Function::new_native_with_env(wasm_store, env.clone(), host_env::tx_set_commitment_sentinel),
"namada_tx_verify_tx_section_signature" => Function::new_native_with_env(wasm_store, env.clone(), host_env::tx_verify_tx_section_signature),
"namada_tx_update_masp_note_commitment_tree" => Function::new_native_with_env(wasm_store, env.clone(), host_env::tx_update_masp_note_commitment_tree),
Expand Down
Loading

0 comments on commit 50bf63a

Please sign in to comment.