Skip to content

Commit

Permalink
evil: move GenIbcShieldedTransafer
Browse files Browse the repository at this point in the history
  • Loading branch information
yito88 committed Oct 17, 2023
1 parent 4262206 commit a5a82dc
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 75 deletions.
11 changes: 3 additions & 8 deletions apps/src/lib/cli/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,15 +497,10 @@ impl CliApi {
&mut args.query.ledger_address,
)
});
client
.wait_until_node_is_synced::<IO>()
.await
.proceed_or_else(error)?;
client.wait_until_node_is_synced(io).await?;
let args = args.to_sdk(&mut ctx);
tx::gen_ibc_shielded_transfer::<_, IO>(
&client, &mut ctx, args,
)
.await?;
let namada = ctx.to_sdk(&client, io);
tx::gen_ibc_shielded_transfer(&namada, args).await?;
}
}
}
Expand Down
20 changes: 6 additions & 14 deletions apps/src/lib/client/tx.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::fs::File;
use std::io::Write;

use namada::core::ledger::governance::cli::offline::{
OfflineProposal, OfflineSignedProposal, OfflineVote,
Expand Down Expand Up @@ -1093,21 +1094,12 @@ pub async fn submit_tx<'a>(
tx::submit_tx(namada, to_broadcast).await
}

pub async fn gen_ibc_shielded_transfer<C, IO: Io>(
client: &C,
ctx: &mut Context,
pub async fn gen_ibc_shielded_transfer<'a>(
context: &impl Namada<'a>,
args: args::GenIbcShieldedTransafer,
) -> Result<(), error::Error>
where
C: namada::ledger::queries::Client + Sync,
C::Error: std::fmt::Display,
{
if let Some(shielded_transfer) = tx::gen_ibc_shielded_transfer::<_, _, IO>(
client,
&mut ctx.shielded,
args.clone(),
)
.await?
) -> Result<(), error::Error> {
if let Some(shielded_transfer) =
tx::gen_ibc_shielded_transfer(context, args.clone()).await?
{
let tx_id = shielded_transfer.masp_tx.txid().to_string();
let filename = format!("ibc_shielded_transfer_{}.memo", tx_id);
Expand Down
1 change: 0 additions & 1 deletion benches/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ use namada_apps::facade::tendermint_proto::google::protobuf::Timestamp;
use namada_apps::node::ledger::shell::Shell;
use namada_apps::wallet::{defaults, CliWalletUtils};
use namada_apps::{config, wasm_loader};
use namada_sdk::args::InputAmount;
use namada_sdk::masp::{
self, ShieldedContext, ShieldedTransfer, ShieldedUtils,
};
Expand Down
6 changes: 3 additions & 3 deletions core/src/types/ibc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ mod ibc_rs_conversion {
use std::collections::HashMap;
use std::str::FromStr;

use borsh::{BorshDeserialize, BorshSerialize};
use borsh::BorshDeserialize;
use borsh_ext::BorshSerializeExt;
use data_encoding::HEXUPPER;
use thiserror::Error;

Expand Down Expand Up @@ -124,8 +125,7 @@ mod ibc_rs_conversion {

impl From<IbcShieldedTransfer> for Memo {
fn from(shielded: IbcShieldedTransfer) -> Self {
let bytes =
shielded.try_to_vec().expect("Encoding shouldn't failed");
let bytes = shielded.serialize_to_vec();
HEXUPPER.encode(&bytes).into()
}
}
Expand Down
19 changes: 19 additions & 0 deletions sdk/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1995,3 +1995,22 @@ pub struct ValidatorSetUpdateRelay<C: NamadaTypes = SdkTypes> {
/// Ethereum transfers aren't canceled midway through.
pub safe_mode: bool,
}

/// IBC shielded transfer generation arguments
#[derive(Clone, Debug)]
pub struct GenIbcShieldedTransafer<C: NamadaTypes = SdkTypes> {
/// The query parameters.
pub query: Query<C>,
/// The output directory path to where serialize the data
pub output_folder: Option<PathBuf>,
/// The target address
pub target: C::TransferTarget,
/// The token address
pub token: C::Address,
/// Transferred token amount
pub amount: InputAmount,
/// Port ID via which the token is received
pub port_id: PortId,
/// Channel ID via which the token is received
pub channel_id: ChannelId,
}
7 changes: 3 additions & 4 deletions sdk/src/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ use masp_proofs::prover::LocalTxProver;
use masp_proofs::sapling::SaplingVerificationContext;
use namada_core::types::address::{masp, Address};
use namada_core::types::masp::{
BalanceOwner, ExtendedViewingKey, PaymentAddress,
BalanceOwner, ExtendedViewingKey, PaymentAddress, TransferSource,
TransferTarget,
};
use namada_core::types::storage::{BlockHeight, Epoch, Key, KeySeg, TxIndex};
use namada_core::types::token;
Expand All @@ -69,7 +70,6 @@ use ripemd::Digest as RipemdDigest;
use sha2::Digest;
use thiserror::Error;

use crate::args::InputAmount;
#[cfg(feature = "testing")]
use crate::error::EncodingError;
use crate::error::{Error, PinnedBalanceError, QueryError};
Expand All @@ -80,8 +80,7 @@ use crate::rpc::{query_conversion, query_storage_value};
use crate::tendermint_rpc::query::Query;
use crate::tendermint_rpc::Order;
use crate::tx::decode_component;
use crate::{args, display_line, edisplay_line, rpc, Namada};
use namada_core::types::masp::{TransferSource, TransferTarget};
use crate::{display_line, edisplay_line, rpc, Namada};

/// Env var to point to a dir with MASP parameters. When not specified,
/// the default OS specific path is used.
Expand Down
37 changes: 19 additions & 18 deletions sdk/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ use namada_core::ledger::pgf::cli::steward::Commission;
use namada_core::types::address::{masp, Address, InternalAddress};
use namada_core::types::dec::Dec;
use namada_core::types::hash::Hash;
use namada_core::types::ibc::IbcShieldedTransfer;
use namada_core::types::key::*;
use namada_core::types::masp::TransferTarget;
use namada_core::types::masp::{TransferSource, TransferTarget};
use namada_core::types::storage::Epoch;
use namada_core::types::time::DateTimeUtc;
use namada_core::types::token::MaspDenom;
Expand All @@ -52,13 +53,12 @@ use namada_proof_of_stake::types::{CommissionPair, ValidatorState};
use crate::args::{self, InputAmount};
use crate::control_flow::time;
use crate::error::{EncodingError, Error, QueryError, Result, TxError};
use crate::ibc::core::ics24_host::identifier::{ChannelId, PortId};
use crate::io::Io;
use crate::masp::TransferErr::Build;
use crate::masp::{ShieldedContext, ShieldedTransfer};
use crate::masp::{make_asset_type, ShieldedContext, ShieldedTransfer};
use crate::proto::{MaspBuilder, Tx};
use crate::queries::Client;
use crate::ibc::core::ics24_host::identifier::{ChannelId, PortId};
use crate::masp::make_asset_type;
use crate::rpc::{
self, query_wasm_code_hash, validate_amount, TxBroadcastData, TxResponse,
};
Expand All @@ -67,8 +67,6 @@ use crate::tendermint_rpc::endpoint::broadcast::tx_sync::Response;
use crate::tendermint_rpc::error::Error as RpcError;
use crate::wallet::WalletIo;
use crate::{display_line, edisplay_line, Namada};
use namada_core::types::ibc::IbcShieldedTransfer;
use namada_core::types::masp::TransferSource;

/// Initialize account transaction WASM
pub const TX_INIT_ACCOUNT_WASM: &str = "tx_init_account.wasm";
Expand Down Expand Up @@ -2126,7 +2124,7 @@ pub async fn build_custom<'a>(

/// Generate IBC shielded transfer
pub async fn gen_ibc_shielded_transfer<'a, N: Namada<'a>>(
context: &impl Namada<'a>,
context: &N,
args: args::GenIbcShieldedTransafer,
) -> Result<Option<IbcShieldedTransfer>> {
let key = match args.target.payment_address() {
Expand Down Expand Up @@ -2177,7 +2175,7 @@ pub async fn gen_ibc_shielded_transfer<'a, N: Namada<'a>>(
};
if let Some(shielded_transfer) = shielded_transfer {
// TODO: Workaround for decoding the asset_type later
let shielded = context.shielded().await;
let mut shielded = context.shielded_mut().await;
let mut asset_types = Vec::new();
for denom in MaspDenom::iter() {
let epoch = shielded_transfer.epoch;
Expand Down Expand Up @@ -2207,16 +2205,19 @@ async fn get_ibc_src_port_channel<'a>(
use crate::ibc_proto::protobuf::Protobuf;

let channel_key = channel_key(dest_port_id, dest_channel_id);
let bytes =
rpc::query_storage_value_bytes(context.client(), &channel_key, None, false)
.await?
.0
.ok_or_else(|| {
Error::Other(format!(
"No channel end: port {dest_port_id}, channel \
{dest_channel_id}"
))
})?;
let bytes = rpc::query_storage_value_bytes(
context.client(),
&channel_key,
None,
false,
)
.await?
.0
.ok_or_else(|| {
Error::Other(format!(
"No channel end: port {dest_port_id}, channel {dest_channel_id}"
))
})?;
let channel = ChannelEnd::decode_vec(&bytes).map_err(|_| {
Error::Other(format!(
"Decoding channel end failed: port {dest_port_id}, channel \
Expand Down
19 changes: 3 additions & 16 deletions shared/src/ledger/native_vp/ibc/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,27 +183,14 @@ where
shielded.transfer.clone(),
shielded.masp_tx.clone(),
);
self.write(
&current_tx_key,
record.try_to_vec().expect("encoding shouldn't failed"),
)?;
self.write(
&head_tx_key,
(current_tx_idx + 1)
.try_to_vec()
.expect("encoding shouldn't failed"),
)?;
self.write(&current_tx_key, record.serialize_to_vec())?;
self.write(&head_tx_key, (current_tx_idx + 1).serialize_to_vec())?;
// If storage key has been supplied, then pin this transaction to it
if let Some(key) = &shielded.transfer.key {
let pin_key = Key::from(masp_addr.to_db_key())
.push(&(PIN_KEY_PREFIX.to_owned() + key))
.expect("Cannot obtain a storage key");
self.write(
&pin_key,
current_tx_idx
.try_to_vec()
.expect("encoding shouldn't fail"),
)?;
self.write(&pin_key, current_tx_idx.serialize_to_vec())?;
}
Ok(())
}
Expand Down
4 changes: 1 addition & 3 deletions shared/src/vm/host_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1795,9 +1795,7 @@ where

let write_log = unsafe { env.ctx.write_log.get() };
let events = vp_host_fns::get_ibc_events(gas_meter, write_log, event_type)?;
let value = events
.try_to_vec()
.map_err(vp_host_fns::RuntimeError::EncodingError)?;
let value = events.serialize_to_vec();
let len: i64 = value
.len()
.try_into()
Expand Down
5 changes: 2 additions & 3 deletions tests/src/e2e/ibc_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,21 +60,20 @@ use namada::ledger::storage::traits::Sha256Hasher;
use namada::tendermint::abci::Event as AbciEvent;
use namada::tendermint::block::Height as TmHeight;
use namada::types::address::{Address, InternalAddress};
use namada::types::io::DefaultIo;
use namada::types::key::PublicKey;
use namada::types::storage::{BlockHeight, Key};
use namada::types::token::Amount;
use namada_apps::client::rpc::{
query_pos_parameters, query_storage_value, query_storage_value_bytes,
};
use namada_apps::client::tx::CLIShieldedUtils;
use namada_apps::client::utils::id_from_pk;
use namada_apps::config::ethereum_bridge;
use namada_apps::config::genesis::genesis_config::GenesisConfig;
use namada_apps::facade::tendermint::block::Header as TmHeader;
use namada_apps::facade::tendermint::merkle::proof::Proof as TmProof;
use namada_apps::facade::tendermint_config::net::Address as TendermintAddress;
use namada_apps::facade::tendermint_rpc::{Client, HttpClient, Url};
use namada_sdk::masp::fs::FsShieldedUtils;
use prost::Message;
use setup::constants::*;
use tendermint_light_client::components::io::{Io, ProdIo as TmLightClientIo};
Expand Down Expand Up @@ -209,7 +208,7 @@ fn run_ledger_ibc() -> Result<()> {

fn setup_two_single_node_nets() -> Result<(Test, Test)> {
// Download the shielded pool parameters before starting node
let _ = CLIShieldedUtils::new::<DefaultIo>(PathBuf::new());
let _ = FsShieldedUtils::new(PathBuf::new());

// epoch per 100 seconds
let update_genesis = |mut genesis: GenesisConfig| {
Expand Down
7 changes: 2 additions & 5 deletions wasm/wasm_source/src/vp_masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,7 @@ fn validate_tx(
transparent_tx_pool -= transp_amt;

// Satisfies 4.
let target_enc = transfer
.target
.try_to_vec()
.expect("target address encoding");
let target_enc = transfer.target.serialize_to_vec();

let hash = Ripemd160::digest(sha256(&target_enc).0.as_slice());

Expand Down Expand Up @@ -251,5 +248,5 @@ fn validate_tx(
_ => {}
}
// Do the expensive proof verification in the VM at the end.
ctx.verify_masp(shielded_tx.try_to_vec().unwrap())
ctx.verify_masp(shielded_tx.serialize_to_vec())
}

0 comments on commit a5a82dc

Please sign in to comment.