From 83d53837fe2929e22091eab204f8116a7c05ea87 Mon Sep 17 00:00:00 2001 From: Marco Granelli Date: Fri, 26 Apr 2024 16:57:53 +0200 Subject: [PATCH 1/7] Rmoves old allowlisted gas --- wasm/vp_implicit/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wasm/vp_implicit/src/lib.rs b/wasm/vp_implicit/src/lib.rs index 2b876e2072..1b473a8298 100644 --- a/wasm/vp_implicit/src/lib.rs +++ b/wasm/vp_implicit/src/lib.rs @@ -15,7 +15,7 @@ use booleans::BoolResultUnitExt; use namada_vp_prelude::tx::action::*; use namada_vp_prelude::*; -#[validity_predicate(gas = 118452)] +#[validity_predicate] fn validate_tx( ctx: &Ctx, tx: Tx, From 023ccc94331bfbf057341991055786fa44886445 Mon Sep 17 00:00:00 2001 From: Marco Granelli Date: Fri, 26 Apr 2024 17:31:02 +0200 Subject: [PATCH 2/7] Removes masp pin key --- crates/apps/src/lib/bench_utils.rs | 1 - crates/apps/src/lib/cli/context.rs | 3 - crates/apps/src/lib/client/rpc.rs | 206 +------------- crates/benches/host_env.rs | 1 - crates/benches/native_vps.rs | 1 - crates/benches/process_wrapper.rs | 1 - crates/benches/vps.rs | 4 - crates/core/src/masp.rs | 11 - crates/core/src/token.rs | 5 - crates/ibc/src/actions.rs | 4 +- crates/ibc/src/context/storage.rs | 1 - crates/light_sdk/src/transaction/transfer.rs | 2 - .../src/ledger/native_vp/ibc/context.rs | 4 +- crates/namada/src/ledger/native_vp/masp.rs | 41 +-- crates/sdk/src/masp.rs | 259 +++--------------- crates/sdk/src/tx.rs | 15 - crates/shielded_token/src/storage_key.rs | 30 +- crates/shielded_token/src/utils.rs | 16 +- crates/tests/src/integration/ledger_tests.rs | 1 - crates/tx/src/data/wrapper.rs | 1 - crates/tx_prelude/src/ibc.rs | 3 +- 21 files changed, 49 insertions(+), 561 deletions(-) diff --git a/crates/apps/src/lib/bench_utils.rs b/crates/apps/src/lib/bench_utils.rs index cc72bddb48..848ad8fb67 100644 --- a/crates/apps/src/lib/bench_utils.rs +++ b/crates/apps/src/lib/bench_utils.rs @@ -1086,7 +1086,6 @@ impl BenchShieldedCtx { } else { DenominatedAmount::native(amount) }, - key: None, shielded: shielded_section_hash, }, shielded, diff --git a/crates/apps/src/lib/cli/context.rs b/crates/apps/src/lib/cli/context.rs index bf4d0569e4..709ebdb05b 100644 --- a/crates/apps/src/lib/cli/context.rs +++ b/crates/apps/src/lib/cli/context.rs @@ -621,8 +621,5 @@ impl ArgFromMutContext for BalanceOwner { ExtendedViewingKey::arg_from_mut_ctx(ctx, raw) .map(Self::FullViewingKey) }) - .or_else(|_| { - PaymentAddress::arg_from_ctx(ctx, raw).map(Self::PaymentAddress) - }) } } diff --git a/crates/apps/src/lib/client/rpc.rs b/crates/apps/src/lib/client/rpc.rs index 7364e5a8c2..1629756bd4 100644 --- a/crates/apps/src/lib/client/rpc.rs +++ b/crates/apps/src/lib/client/rpc.rs @@ -2,20 +2,19 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io; -use std::str::FromStr; use borsh::BorshDeserialize; use data_encoding::HEXLOWER; use masp_primitives::asset_type::AssetType; use masp_primitives::merkle_tree::MerklePath; -use masp_primitives::sapling::{Node, ViewingKey}; +use masp_primitives::sapling::Node; use masp_primitives::transaction::components::I128Sum; use masp_primitives::zip32::ExtendedFullViewingKey; use namada::core::address::{Address, InternalAddress, MASP, MULTITOKEN}; use namada::core::collections::{HashMap, HashSet}; use namada::core::hash::Hash; use namada::core::key::*; -use namada::core::masp::{BalanceOwner, ExtendedViewingKey, PaymentAddress}; +use namada::core::masp::BalanceOwner; use namada::core::storage::{BlockHeight, BlockResults, Epoch, Key, KeySeg}; use namada::core::token::MaspDigitPos; use namada::governance::parameters::GovernanceParameters; @@ -38,9 +37,7 @@ use namada::proof_of_stake::types::{ ValidatorState, ValidatorStateInfo, WeightedValidator, }; use namada::{state as storage, token}; -use namada_sdk::error::{ - is_pinned_error, Error, PinnedBalanceError, QueryError, -}; +use namada_sdk::error::QueryError; use namada_sdk::masp::MaspTokenRewardData; use namada_sdk::proof_of_stake::types::ValidatorMetaData; use namada_sdk::queries::Client; @@ -50,7 +47,7 @@ use namada_sdk::rpc::{ use namada_sdk::tendermint_rpc::endpoint::status; use namada_sdk::tx::display_inner_resp; use namada_sdk::wallet::AddressVpType; -use namada_sdk::{display, display_line, edisplay_line, error, prompt, Namada}; +use namada_sdk::{display, display_line, edisplay_line, error, Namada}; use tokio::time::Instant; use crate::cli::{self, args}; @@ -194,12 +191,7 @@ pub async fn query_balance(context: &impl Namada, args: args::QueryBalance) { Some(BalanceOwner::Address(_owner)) => { query_transparent_balance(context, args).await } - Some(BalanceOwner::PaymentAddress(_owner)) => { - query_pinned_balance(context, args).await - } None => { - // Print pinned balance - query_pinned_balance(context, args.clone()).await; // Print shielded balance query_shielded_balance(context, args.clone()).await; // Then print transparent balance @@ -301,196 +293,6 @@ pub async fn query_transparent_balance( } } -/// Query the token pinned balance(s) -pub async fn query_pinned_balance( - context: &impl Namada, - args: args::QueryBalance, -) { - // Map addresses to token names - let wallet = context.wallet().await; - let owners = if let Some(pa) = args.owner.and_then(|x| x.payment_address()) - { - vec![pa] - } else { - wallet - .get_payment_addrs() - .into_values() - .filter(PaymentAddress::is_pinned) - .collect() - }; - // Get the viewing keys with which to try note decryptions - let viewing_keys: Vec = wallet - .get_viewing_keys() - .values() - .map(|fvk| ExtendedFullViewingKey::from(*fvk).fvk.vk) - .collect(); - let _ = context.shielded_mut().await.load().await; - // Precompute asset types to increase chances of success in decoding - let token_map = - query_tokens(context, args.token.as_ref(), None, args.show_ibc_tokens) - .await; - let tokens = token_map.values().collect(); - let _ = context - .shielded_mut() - .await - .precompute_asset_types(context.client(), tokens) - .await; - // Print the token balances by payment address - for owner in owners { - let mut balance = - Err(Error::from(PinnedBalanceError::InvalidViewingKey)); - // Find the viewing key that can recognize payments the current payment - // address - for vk in &viewing_keys { - balance = context - .shielded_mut() - .await - .compute_exchanged_pinned_balance(context, owner, vk) - .await; - if !is_pinned_error(&balance) { - break; - } - } - // If a suitable viewing key was not found, then demand it from the user - if is_pinned_error(&balance) { - let vk_str = - prompt!(context.io(), "Enter the viewing key for {}: ", owner) - .await; - let fvk = match ExtendedViewingKey::from_str(vk_str.trim()) { - Ok(fvk) => fvk, - _ => { - edisplay_line!(context.io(), "Invalid viewing key entered"); - continue; - } - }; - let vk = ExtendedFullViewingKey::from(fvk).fvk.vk; - // Use the given viewing key to decrypt pinned transaction data - balance = context - .shielded_mut() - .await - .compute_exchanged_pinned_balance(context, owner, &vk) - .await - } - - // Now print out the received quantities according to CLI arguments - match (balance, args.token.as_ref()) { - (Err(Error::Pinned(PinnedBalanceError::InvalidViewingKey)), _) => { - display_line!( - context.io(), - "Supplied viewing key cannot decode transactions to given \ - payment address." - ) - } - ( - Err(Error::Pinned(PinnedBalanceError::NoTransactionPinned)), - _, - ) => { - display_line!( - context.io(), - "Payment address {} has not yet been consumed.", - owner - ) - } - (Err(other), _) => { - display_line!( - context.io(), - "Error in Querying Pinned balance {}", - other - ) - } - (Ok((balance, _undecoded, epoch)), Some(base_token)) => { - let tokens = query_tokens( - context, - Some(base_token), - None, - args.show_ibc_tokens, - ) - .await; - for (token_alias, token) in &tokens { - let total_balance = balance - .0 - .get(&token.clone()) - .cloned() - .unwrap_or_default(); - - if total_balance.is_zero() { - display_line!( - context.io(), - "Payment address {} was consumed during epoch {}. \ - Received no shielded {}", - owner, - epoch, - token_alias - ); - } else { - let formatted = context - .format_amount(token, total_balance.into()) - .await; - display_line!( - context.io(), - "Payment address {} was consumed during epoch {}. \ - Received {} {}", - owner, - epoch, - formatted, - token_alias, - ); - } - } - } - (Ok((balance, undecoded, epoch)), None) => { - let mut found_any = false; - - for (token_addr, value) in balance.components() { - if !found_any { - display_line!( - context.io(), - "Payment address {} was consumed during epoch {}. \ - Received:", - owner, - epoch - ); - found_any = true; - } - let formatted = context - .format_amount(token_addr, (*value).into()) - .await; - let token_alias = - lookup_token_alias(context, token_addr, &MASP).await; - display_line!( - context.io(), - " {}: {}", - token_alias, - formatted, - ); - } - for (asset_type, value) in undecoded.components() { - if !found_any { - display_line!( - context.io(), - "Payment address {} was consumed during epoch {}. \ - Received:", - owner, - epoch - ); - found_any = true; - } - display_line!(context.io(), " {}: {}", asset_type, value,); - } - if !found_any { - display_line!( - context.io(), - "Payment address {} was consumed during epoch {}. \ - Received no shielded assets.", - owner, - epoch - ); - } - } - } - } -} - async fn print_balances( context: &impl Namada, balances: impl Iterator, diff --git a/crates/benches/host_env.rs b/crates/benches/host_env.rs index 8b29e75098..6d663864dd 100644 --- a/crates/benches/host_env.rs +++ b/crates/benches/host_env.rs @@ -22,7 +22,6 @@ fn tx_section_signature_validation(c: &mut Criterion) { target: defaults::bertha_address(), token: address::testing::nam(), amount: Amount::native_whole(500).native_denominated(), - key: None, shielded: None, }; let tx = shell.generate_tx( diff --git a/crates/benches/native_vps.rs b/crates/benches/native_vps.rs index dfa2863c93..036786eb10 100644 --- a/crates/benches/native_vps.rs +++ b/crates/benches/native_vps.rs @@ -473,7 +473,6 @@ fn vp_multitoken(c: &mut Criterion) { target: defaults::bertha_address(), token: address::testing::nam(), amount: Amount::native_whole(1000).native_denominated(), - key: None, shielded: None, }, None, diff --git a/crates/benches/process_wrapper.rs b/crates/benches/process_wrapper.rs index a15539b9f5..7986755b10 100644 --- a/crates/benches/process_wrapper.rs +++ b/crates/benches/process_wrapper.rs @@ -24,7 +24,6 @@ fn process_tx(c: &mut Criterion) { target: defaults::bertha_address(), token: address::testing::nam(), amount: Amount::native_whole(1).native_denominated(), - key: None, shielded: None, }, None, diff --git a/crates/benches/vps.rs b/crates/benches/vps.rs index 8d12d0393b..ad326743ef 100644 --- a/crates/benches/vps.rs +++ b/crates/benches/vps.rs @@ -45,7 +45,6 @@ fn vp_implicit(c: &mut Criterion) { target: defaults::bertha_address(), token: address::testing::nam(), amount: Amount::native_whole(500).native_denominated(), - key: None, shielded: None, }, None, @@ -60,7 +59,6 @@ fn vp_implicit(c: &mut Criterion) { target: Address::from(&implicit_account.to_public()), token: address::testing::nam(), amount: Amount::native_whole(1000).native_denominated(), - key: None, shielded: None, }, None, @@ -189,7 +187,6 @@ fn vp_user(c: &mut Criterion) { target: defaults::bertha_address(), token: address::testing::nam(), amount: Amount::native_whole(1000).native_denominated(), - key: None, shielded: None, }, None, @@ -204,7 +201,6 @@ fn vp_user(c: &mut Criterion) { target: defaults::validator_address(), token: address::testing::nam(), amount: Amount::native_whole(1000).native_denominated(), - key: None, shielded: None, }, None, diff --git a/crates/core/src/masp.rs b/crates/core/src/masp.rs index cc1e2657d2..a3f626f260 100644 --- a/crates/core/src/masp.rs +++ b/crates/core/src/masp.rs @@ -492,8 +492,6 @@ pub enum BalanceOwner { Address(Address), /// A balance stored at a shielded address FullViewingKey(ExtendedViewingKey), - /// A balance stored at a payment address - PaymentAddress(PaymentAddress), } impl BalanceOwner { @@ -512,14 +510,6 @@ impl BalanceOwner { _ => None, } } - - /// Get the contained PaymentAddress, if any - pub fn payment_address(&self) -> Option { - match self { - Self::PaymentAddress(x) => Some(*x), - _ => None, - } - } } impl Display for BalanceOwner { @@ -527,7 +517,6 @@ impl Display for BalanceOwner { match self { BalanceOwner::Address(addr) => addr.fmt(f), BalanceOwner::FullViewingKey(fvk) => fvk.fmt(f), - BalanceOwner::PaymentAddress(pa) => pa.fmt(f), } } } diff --git a/crates/core/src/token.rs b/crates/core/src/token.rs index 9765a017bc..e05c285f2c 100644 --- a/crates/core/src/token.rs +++ b/crates/core/src/token.rs @@ -1006,8 +1006,6 @@ pub struct Transfer { pub token: Address, /// The amount of tokens pub amount: DenominatedAmount, - /// The unused storage location at which to place TxId - pub key: Option, /// Shielded transaction part pub shielded: Option, } @@ -1024,7 +1022,6 @@ pub enum AmountError { #[cfg(any(test, feature = "testing"))] /// Testing helpers and strategies for tokens pub mod testing { - use proptest::option; use proptest::prelude::*; use super::*; @@ -1056,14 +1053,12 @@ pub mod testing { target in arb_non_internal_address(), token in arb_established_address().prop_map(Address::Established), amount in arb_denominated_amount(), - key in option::of("[a-zA-Z0-9_]*"), ) -> Transfer { Transfer { source, target, token, amount, - key, shielded: None, } } diff --git a/crates/ibc/src/actions.rs b/crates/ibc/src/actions.rs index 9ff0d7e323..331bf74052 100644 --- a/crates/ibc/src/actions.rs +++ b/crates/ibc/src/actions.rs @@ -150,9 +150,8 @@ where fn handle_masp_tx( &mut self, shielded: &masp_primitives::transaction::Transaction, - pin_key: Option<&str>, ) -> Result<(), StorageError> { - namada_token::utils::handle_masp_tx(self, shielded, pin_key)?; + namada_token::utils::handle_masp_tx(self, shielded)?; namada_token::utils::update_note_commitment_tree(self, shielded) } @@ -227,7 +226,6 @@ where fn handle_masp_tx( &mut self, _shielded: &masp_primitives::transaction::Transaction, - _pin_key: Option<&str>, ) -> Result<(), StorageError> { unimplemented!("No MASP transfer in an IBC protocol transaction") } diff --git a/crates/ibc/src/context/storage.rs b/crates/ibc/src/context/storage.rs index 21c0dc4b1d..a271a9309a 100644 --- a/crates/ibc/src/context/storage.rs +++ b/crates/ibc/src/context/storage.rs @@ -30,7 +30,6 @@ pub trait IbcStorageContext: StorageRead + StorageWrite { fn handle_masp_tx( &mut self, shielded: &masp_primitives::transaction::Transaction, - pin_key: Option<&str>, ) -> Result<(), Error>; /// Mint token diff --git a/crates/light_sdk/src/transaction/transfer.rs b/crates/light_sdk/src/transaction/transfer.rs index 3a5d188a21..02b5a22e26 100644 --- a/crates/light_sdk/src/transaction/transfer.rs +++ b/crates/light_sdk/src/transaction/transfer.rs @@ -22,7 +22,6 @@ impl Transfer { target: Address, token: Address, amount: DenominatedAmount, - key: Option, // FIXME: handle masp here shielded: Option, args: GlobalArgs, @@ -32,7 +31,6 @@ impl Transfer { target, token, amount, - key, shielded, }; diff --git a/crates/namada/src/ledger/native_vp/ibc/context.rs b/crates/namada/src/ledger/native_vp/ibc/context.rs index c9824a35f4..3b6a19f456 100644 --- a/crates/namada/src/ledger/native_vp/ibc/context.rs +++ b/crates/namada/src/ledger/native_vp/ibc/context.rs @@ -214,9 +214,8 @@ where fn handle_masp_tx( &mut self, shielded: &masp_primitives::transaction::Transaction, - pin_key: Option<&str>, ) -> Result<()> { - crate::token::utils::handle_masp_tx(self, shielded, pin_key)?; + crate::token::utils::handle_masp_tx(self, shielded)?; crate::token::utils::update_note_commitment_tree(self, shielded) } @@ -385,7 +384,6 @@ where fn handle_masp_tx( &mut self, _shielded: &masp_primitives::transaction::Transaction, - _pin_key: Option<&str>, ) -> Result<()> { unimplemented!("Validation doesn't handle a masp tx") } diff --git a/crates/namada/src/ledger/native_vp/masp.rs b/crates/namada/src/ledger/native_vp/masp.rs index b30b263ed9..db537565af 100644 --- a/crates/namada/src/ledger/native_vp/masp.rs +++ b/crates/namada/src/ledger/native_vp/masp.rs @@ -14,7 +14,7 @@ use namada_core::address::InternalAddress::Masp; use namada_core::booleans::BoolResultUnitExt; use namada_core::collections::{HashMap, HashSet}; use namada_core::masp::encode_asset_type; -use namada_core::storage::{IndexedTx, Key}; +use namada_core::storage::Key; use namada_sdk::masp::verify_shielded_tx; use namada_state::{OptionExt, ResultExt, StateRead}; use namada_token::read_denom; @@ -26,9 +26,8 @@ use sha2::Digest as Sha2Digest; use thiserror::Error; use token::storage_key::{ balance_key, is_any_shielded_action_balance_key, is_masp_allowed_key, - is_masp_key, is_masp_nullifier_key, is_masp_tx_pin_key, - masp_commitment_anchor_key, masp_commitment_tree_key, - masp_convert_anchor_key, masp_nullifier_key, + is_masp_key, is_masp_nullifier_key, masp_commitment_anchor_key, + masp_commitment_tree_key, masp_convert_anchor_key, masp_nullifier_key, }; use token::Amount; @@ -270,40 +269,6 @@ where ))); } - // Validate pin key if found - let pin_keys: Vec<_> = masp_keys_changed - .iter() - .filter(|key| is_masp_tx_pin_key(key)) - .collect(); - match pin_keys.len() { - 0 => (), - 1 => { - match self - .ctx - .read_post::(pin_keys.first().unwrap())? - { - Some(IndexedTx { height, index, .. }) - if height == self.ctx.get_block_height()? - && index == self.ctx.get_tx_index()? => {} - Some(_) => { - return Err(Error::NativeVpError( - native_vp::Error::SimpleMessage( - "Invalid MASP pin key", - ), - )); - } - _ => (), - } - } - _ => { - return Err(Error::NativeVpError( - native_vp::Error::SimpleMessage( - "Found more than one pin key", - ), - )); - } - } - // Verify the changes to balance keys and return the transparent // transfer data Get the token from the balance key of the MASP let balance_addresses: Vec<[&Address; 2]> = keys_changed diff --git a/crates/sdk/src/masp.rs b/crates/sdk/src/masp.rs index 87b90b5d91..bf223f6729 100644 --- a/crates/sdk/src/masp.rs +++ b/crates/sdk/src/masp.rs @@ -75,7 +75,7 @@ use thiserror::Error; use token::storage_key::{balance_key, is_any_shielded_action_balance_key}; use token::Amount; -use crate::error::{Error, PinnedBalanceError, QueryError}; +use crate::error::{Error, QueryError}; use crate::io::Io; use crate::queries::Client; use crate::rpc::{ @@ -881,12 +881,7 @@ impl ShieldedContext { let ExtractedMaspTx { fee_unshielding, inner_tx, - } = Self::extract_masp_tx( - &tx, - ExtractShieldedActionArg::Event::(&tx_event), - true, - ) - .await?; + } = Self::extract_masp_tx(&tx, &tx_event, true).await?; // Collect the current transaction(s) fee_unshielding.and_then(|(changed_keys, masp_transaction)| { shielded_txs.insert( @@ -915,36 +910,33 @@ impl ShieldedContext { } /// Extract the relevant shield portions of a [`Tx`], if any. - async fn extract_masp_tx<'args, C: Client + Sync>( + async fn extract_masp_tx( tx: &Tx, - action_arg: ExtractShieldedActionArg<'args, C>, + tx_event: &crate::tendermint::abci::Event, check_header: bool, ) -> Result { // We use the changed keys instead of the Transfer object // because those are what the masp validity predicate works on - let (wrapper_changed_keys, changed_keys) = - if let ExtractShieldedActionArg::Event(tx_event) = action_arg { - let tx_result_str = tx_event - .attributes - .iter() - .find_map(|attr| { - if attr.key == "inner_tx" { - Some(&attr.value) - } else { - None - } - }) - .ok_or_else(|| { - Error::Other( - "Missing required tx result in event".to_string(), - ) - })?; - let result = TxResult::from_str(tx_result_str) - .map_err(|e| Error::Other(e.to_string()))?; - (result.wrapper_changed_keys, result.changed_keys) - } else { - (Default::default(), Default::default()) - }; + let (wrapper_changed_keys, changed_keys) = { + let tx_result_str = tx_event + .attributes + .iter() + .find_map(|attr| { + if attr.key == "inner_tx" { + Some(&attr.value) + } else { + None + } + }) + .ok_or_else(|| { + Error::Other( + "Missing required tx result in event".to_string(), + ) + })?; + let result = TxResult::from_str(tx_result_str) + .map_err(|e| Error::Other(e.to_string()))?; + (result.wrapper_changed_keys, result.changed_keys) + }; let tx_header = tx.header(); // NOTE: simply looking for masp sections attached to the tx @@ -984,7 +976,7 @@ impl ShieldedContext { // This should be a MASP over IBC transaction, it // could be a ShieldedTransfer or an Envelope // message, need to try both - extract_payload_from_shielded_action::(&tx_data, action_arg) + extract_payload_from_shielded_action(&tx_data, tx_event) .await .ok() } @@ -1716,139 +1708,6 @@ impl ShieldedContext { Ok((val_acc, notes, conversions)) } - /// Compute the combined value of the output notes of the transaction pinned - /// at the given payment address. This computation uses the supplied viewing - /// keys to try to decrypt the output notes. If no transaction is pinned at - /// the given payment address fails with - /// `PinnedBalanceError::NoTransactionPinned`. - pub async fn compute_pinned_balance( - client: &C, - owner: PaymentAddress, - viewing_key: &ViewingKey, - ) -> Result<(I128Sum, Epoch), Error> { - // Check that the supplied viewing key corresponds to given payment - // address - let counter_owner = viewing_key.to_payment_address( - *masp_primitives::sapling::PaymentAddress::diversifier( - &owner.into(), - ), - ); - match counter_owner { - Some(counter_owner) if counter_owner == owner.into() => {} - _ => { - return Err(Error::from(PinnedBalanceError::InvalidViewingKey)); - } - } - // Construct the key for where the transaction ID would be stored - let pin_key = namada_token::storage_key::masp_pin_tx_key(&owner.hash()); - // Obtain the transaction pointer at the key - // If we don't discard the error message then a test fails, - // however the error underlying this will go undetected - let indexed_tx = - rpc::query_storage_value::(client, &pin_key) - .await - .map_err(|_| PinnedBalanceError::NoTransactionPinned)?; - let tx_epoch = query_epoch_at_height(client, indexed_tx.height) - .await? - .ok_or_else(|| { - Error::from(QueryError::General( - "Queried height is greater than the last committed block \ - height" - .to_string(), - )) - })?; - - let block = client - .block(indexed_tx.height.0 as u32) - .await - .map_err(|e| Error::from(QueryError::General(e.to_string())))? - .block - .data; - - let tx = Tx::try_from(block[indexed_tx.index.0 as usize].as_ref()) - .map_err(|e| Error::Other(e.to_string()))?; - let (_, shielded) = Self::extract_masp_tx( - &tx, - ExtractShieldedActionArg::Request(( - client, - indexed_tx.height, - Some(indexed_tx.index), - )), - false, - ) - .await? - .inner_tx - .ok_or_else(|| { - Error::Other("Missing shielded inner portion of pinned tx".into()) - })?; - - // Accumulate the combined output note value into this Amount - let mut val_acc = I128Sum::zero(); - for so in shielded - .sapling_bundle() - .map_or(&vec![], |x| &x.shielded_outputs) - { - // Let's try to see if our viewing key can decrypt current note - let decres = try_sapling_note_decryption::<_, OutputDescription<<::SaplingAuth as masp_primitives::transaction::components::sapling::Authorization>::Proof>>( - &NETWORK, - 1.into(), - &PreparedIncomingViewingKey::new(&viewing_key.ivk()), - so, - ); - match decres { - // So the given viewing key does decrypt this current note... - Some((note, pa, _memo)) if pa == owner.into() => { - val_acc += I128Sum::from_nonnegative( - note.asset_type, - note.value as i128, - ) - .map_err(|()| { - Error::Other( - "found note with invalid value or asset type" - .to_string(), - ) - })?; - } - _ => {} - } - } - Ok((val_acc, tx_epoch)) - } - - /// Compute the combined value of the output notes of the pinned transaction - /// at the given payment address if there's any. The asset types may be from - /// the epoch of the transaction or even before, so exchange all these - /// amounts to the epoch of the transaction in order to get the value that - /// would have been displayed in the epoch of the transaction. - pub async fn compute_exchanged_pinned_balance( - &mut self, - context: &impl Namada, - owner: PaymentAddress, - viewing_key: &ViewingKey, - ) -> Result<(ValueSum, I128Sum, Epoch), Error> { - // Obtain the balance that will be exchanged - let (amt, ep) = - Self::compute_pinned_balance(context.client(), owner, viewing_key) - .await?; - display_line!(context.io(), "Pinned balance: {:?}", amt); - // Finally, exchange the balance to the transaction's epoch - let computed_amount = self - .compute_exchanged_amount( - context.client(), - context.io(), - amt, - ep, - BTreeMap::new(), - ) - .await? - .0; - display_line!(context.io(), "Exchanged amount: {:?}", computed_amount); - let (decoded, undecoded) = self - .decode_combine_sum_to_epoch(context.client(), computed_amount, ep) - .await; - Ok((decoded, undecoded, ep)) - } - /// Convert an amount whose units are AssetTypes to one whose units are /// Addresses that they decode to. All asset types not corresponding to /// the given epoch are ignored. @@ -2433,7 +2292,6 @@ impl ShieldedContext { Either::Left(BalanceOwner::Address(owner)) => vec![owner.clone()], // MASP objects are dealt with outside of tx_search Either::Left(BalanceOwner::FullViewingKey(_viewing_key)) => vec![], - Either::Left(BalanceOwner::PaymentAddress(_owner)) => vec![], // Unspecified owner means all known addresses are considered // relevant Either::Right(addrs) => addrs.clone(), @@ -2647,22 +2505,17 @@ async fn get_indexed_masp_events_at_height( })) } -enum ExtractShieldedActionArg<'args, C: Client + Sync> { - Event(&'args crate::tendermint::abci::Event), - Request((&'args C, BlockHeight, Option)), -} - // Extract the changed keys and Transaction hash from a masp over ibc message -async fn extract_payload_from_shielded_action<'args, C: Client + Sync>( +async fn extract_payload_from_shielded_action( tx_data: &[u8], - args: ExtractShieldedActionArg<'args, C>, + tx_event: &crate::tendermint::abci::Event, ) -> Result<(BTreeSet, Transfer), Error> { let message = namada_ibc::decode_message(tx_data) .map_err(|e| Error::Other(e.to_string()))?; let result = match message { IbcMessage::Transfer(msg) => { - let tx_result = get_sending_result(args)?; + let tx_result = get_tx_result(tx_event)?; let transfer = msg.transfer.ok_or_else(|| { Error::Other("Missing masp tx in the ibc message".to_string()) @@ -2671,7 +2524,7 @@ async fn extract_payload_from_shielded_action<'args, C: Client + Sync>( (tx_result.changed_keys, transfer) } IbcMessage::NftTransfer(msg) => { - let tx_result = get_sending_result(args)?; + let tx_result = get_tx_result(tx_event)?; let transfer = msg.transfer.ok_or_else(|| { Error::Other("Missing masp tx in the ibc message".to_string()) @@ -2680,7 +2533,7 @@ async fn extract_payload_from_shielded_action<'args, C: Client + Sync>( (tx_result.changed_keys, transfer) } IbcMessage::RecvPacket(msg) => { - let tx_result = get_receiving_result(args).await?; + let tx_result = get_tx_result(tx_event)?; let transfer = msg.transfer.ok_or_else(|| { Error::Other("Missing masp tx in the ibc message".to_string()) @@ -2690,7 +2543,7 @@ async fn extract_payload_from_shielded_action<'args, C: Client + Sync>( } IbcMessage::AckPacket(msg) => { // Refund tokens by the ack message - let tx_result = get_receiving_result(args).await?; + let tx_result = get_tx_result(tx_event)?; let transfer = msg.transfer.ok_or_else(|| { Error::Other("Missing masp tx in the ibc message".to_string()) @@ -2700,7 +2553,7 @@ async fn extract_payload_from_shielded_action<'args, C: Client + Sync>( } IbcMessage::Timeout(msg) => { // Refund tokens by the timeout message - let tx_result = get_receiving_result(args).await?; + let tx_result = get_tx_result(tx_event)?; let transfer = msg.transfer.ok_or_else(|| { Error::Other("Missing masp tx in the ibc message".to_string()) @@ -2718,54 +2571,6 @@ async fn extract_payload_from_shielded_action<'args, C: Client + Sync>( Ok(result) } -fn get_sending_result( - args: ExtractShieldedActionArg<'_, C>, -) -> Result { - let tx_event = match args { - ExtractShieldedActionArg::Event(event) => event, - ExtractShieldedActionArg::Request(_) => { - return Err(Error::Other( - "Unexpected event request for ShieldedTransfer".to_string(), - )); - } - }; - - get_tx_result(tx_event) -} - -async fn get_receiving_result( - args: ExtractShieldedActionArg<'_, C>, -) -> Result { - let tx_event = match args { - ExtractShieldedActionArg::Event(event) => { - std::borrow::Cow::Borrowed(event) - } - ExtractShieldedActionArg::Request((client, height, index)) => { - std::borrow::Cow::Owned( - get_indexed_masp_events_at_height(client, height, index) - .await? - .ok_or_else(|| { - Error::Other(format!( - "Missing required ibc event at block height {}", - height - )) - })? - .first() - .ok_or_else(|| { - Error::Other(format!( - "Missing required ibc event at block height {}", - height - )) - })? - .1 - .to_owned(), - ) - } - }; - - get_tx_result(&tx_event) -} - fn get_tx_result( tx_event: &crate::tendermint::abci::Event, ) -> Result { diff --git a/crates/sdk/src/tx.rs b/crates/sdk/src/tx.rs index 66514ca6cb..138be3105d 100644 --- a/crates/sdk/src/tx.rs +++ b/crates/sdk/src/tx.rs @@ -2707,9 +2707,6 @@ pub async fn build_ibc_transfer( target: Address::Internal(InternalAddress::Ibc), token: args.token.clone(), amount: validated_amount, - // The address could be a payment address, but the address isn't - // that of this chain. - key: None, // Link the Transfer to the MASP Transaction by hash code shielded: Some(masp_tx_hash), }; @@ -3007,11 +3004,6 @@ pub async fn build_transfer( } else { (validated_amount, args.token.clone()) }; - // Determine whether to pin this transaction to a storage key - let key = match &args.target { - TransferTarget::PaymentAddress(pa) if pa.is_pinned() => Some(pa.hash()), - _ => None, - }; let shielded_parts = construct_shielded_parts( context, @@ -3030,7 +3022,6 @@ pub async fn build_transfer( target: target.clone(), token: transparent_token.clone(), amount: transparent_amount, - key: key.clone(), // Link the Transfer to the MASP Transaction by hash code shielded: None, }; @@ -3351,11 +3342,6 @@ pub async fn gen_ibc_shielded_transfer( context: &N, args: args::GenIbcShieldedTransfer, ) -> Result> { - let key = match args.target.payment_address() { - Some(pa) if pa.is_pinned() => Some(pa.hash()), - Some(_) => None, - None => return Ok(None), - }; let source = Address::Internal(InternalAddress::Ibc); let (src_port_id, src_channel_id) = get_ibc_src_port_channel(context, &args.port_id, &args.channel_id) @@ -3415,7 +3401,6 @@ pub async fn gen_ibc_shielded_transfer( target: MASP, token: token.clone(), amount: validated_amount, - key, shielded: Some(masp_tx_hash), }; Ok(Some((transfer, shielded_transfer.masp_tx))) diff --git a/crates/shielded_token/src/storage_key.rs b/crates/shielded_token/src/storage_key.rs index 95c7993f7a..fdc8cf20b9 100644 --- a/crates/shielded_token/src/storage_key.rs +++ b/crates/shielded_token/src/storage_key.rs @@ -7,8 +7,6 @@ use namada_core::hash::Hash; use namada_core::storage::{self, DbKeySeg, KeySeg}; use namada_trans_token::storage_key::parameter_prefix; -/// Key segment prefix for pinned shielded transactions -pub const PIN_KEY_PREFIX: &str = "pin-"; /// Key segment prefix for the nullifiers pub const MASP_NULLIFIERS_KEY: &str = "nullifiers"; /// Key segment prefix for the note commitment merkle tree @@ -80,29 +78,20 @@ pub fn is_masp_allowed_key(key: &storage::Key) -> bool { match &key.segments[..] { [DbKeySeg::AddressSeg(addr), DbKeySeg::StringSeg(key)] if *addr == address::MASP - && (key.starts_with(PIN_KEY_PREFIX) - || key == MASP_NOTE_COMMITMENT_TREE_KEY) => + && key == MASP_NOTE_COMMITMENT_TREE_KEY => { true } - [ - DbKeySeg::AddressSeg(addr), - DbKeySeg::StringSeg(key), - DbKeySeg::StringSeg(_nullifier), - ] if *addr == address::MASP && key == MASP_NULLIFIERS_KEY => true, + [DbKeySeg::AddressSeg(addr), DbKeySeg::StringSeg(key), DbKeySeg::StringSeg(_nullifier)] + if *addr == address::MASP && key == MASP_NULLIFIERS_KEY => + { + true + } _ => false, } } -/// Check if the given storage key is a masp tx pin key -pub fn is_masp_tx_pin_key(key: &storage::Key) -> bool { - matches!(&key.segments[..], - [DbKeySeg::AddressSeg(addr), - DbKeySeg::StringSeg(prefix), - ] if *addr == address::MASP && prefix.starts_with(PIN_KEY_PREFIX)) -} - /// Check if the given storage key is a masp nullifier key pub fn is_masp_nullifier_key(key: &storage::Key) -> bool { matches!(&key.segments[..], @@ -121,13 +110,6 @@ pub fn is_masp_commitment_anchor_key(key: &storage::Key) -> bool { ] if *addr == address::MASP && prefix == MASP_NOTE_COMMITMENT_ANCHOR_PREFIX) } -/// Get a key for a masp pin -pub fn masp_pin_tx_key(key: &str) -> storage::Key { - storage::Key::from(address::MASP.to_db_key()) - .push(&(PIN_KEY_PREFIX.to_owned() + key)) - .expect("Cannot obtain a storage key") -} - /// Get a key for a masp nullifier pub fn masp_nullifier_key(nullifier: &Nullifier) -> storage::Key { storage::Key::from(address::MASP.to_db_key()) diff --git a/crates/shielded_token/src/utils.rs b/crates/shielded_token/src/utils.rs index 84e76c646e..c29c3185c0 100644 --- a/crates/shielded_token/src/utils.rs +++ b/crates/shielded_token/src/utils.rs @@ -6,11 +6,10 @@ use masp_primitives::merkle_tree::CommitmentTree; use masp_primitives::sapling::Node; use masp_primitives::transaction::Transaction; use namada_core::storage; -use namada_core::storage::IndexedTx; use namada_storage::{Error, Result, StorageRead, StorageWrite}; use crate::storage_key::{ - is_masp_key, masp_commitment_tree_key, masp_nullifier_key, masp_pin_tx_key, + is_masp_key, masp_commitment_tree_key, masp_nullifier_key, }; // Writes the nullifiers of the provided masp transaction to storage @@ -64,7 +63,6 @@ pub fn update_note_commitment_tree( pub fn handle_masp_tx( ctx: &mut (impl StorageRead + StorageWrite), shielded: &Transaction, - pin_key: Option<&str>, ) -> Result<()> { // TODO: temporarily disabled because of the node aggregation issue in WASM. // Using the host env tx_update_masp_note_commitment_tree or directly the @@ -72,18 +70,6 @@ pub fn handle_masp_tx( // update_note_commitment_tree(ctx, shielded)?; reveal_nullifiers(ctx, shielded)?; - // If storage key has been supplied, then pin this transaction to it - if let Some(key) = pin_key { - ctx.write( - &masp_pin_tx_key(key), - IndexedTx { - height: ctx.get_block_height()?, - index: ctx.get_tx_index()?, - is_wrapper: false, - }, - )?; - } - Ok(()) } diff --git a/crates/tests/src/integration/ledger_tests.rs b/crates/tests/src/integration/ledger_tests.rs index 9299aaff85..c983aaef53 100644 --- a/crates/tests/src/integration/ledger_tests.rs +++ b/crates/tests/src/integration/ledger_tests.rs @@ -59,7 +59,6 @@ fn ledger_txs_and_queries() -> Result<()> { token::Amount::native_whole(10), token::NATIVE_MAX_DECIMAL_PLACES.into(), ), - key: None, shielded: None, } .serialize_to_vec(); diff --git a/crates/tx/src/data/wrapper.rs b/crates/tx/src/data/wrapper.rs index f1fec9dae6..606152cefe 100644 --- a/crates/tx/src/data/wrapper.rs +++ b/crates/tx/src/data/wrapper.rs @@ -223,7 +223,6 @@ pub mod wrapper_tx { target: self.fee_payer(), token: self.fee.token.clone(), amount: self.get_tx_fee()?, - key: None, shielded: Some(masp_hash), }; let data = transfer.serialize_to_vec(); diff --git a/crates/tx_prelude/src/ibc.rs b/crates/tx_prelude/src/ibc.rs index 0c62a53422..b12b6af4d1 100644 --- a/crates/tx_prelude/src/ibc.rs +++ b/crates/tx_prelude/src/ibc.rs @@ -63,9 +63,8 @@ impl IbcStorageContext for Ctx { fn handle_masp_tx( &mut self, shielded: &masp_primitives::transaction::Transaction, - pin_key: Option<&str>, ) -> Result<(), Error> { - namada_token::utils::handle_masp_tx(self, shielded, pin_key)?; + namada_token::utils::handle_masp_tx(self, shielded)?; namada_token::utils::update_note_commitment_tree(self, shielded) } From ffd17e42a66249c16e7336dcab02b6167d20c835 Mon Sep 17 00:00:00 2001 From: Marco Granelli Date: Fri, 26 Apr 2024 17:48:57 +0200 Subject: [PATCH 3/7] Adjusts wasm txs and client args --- crates/apps/src/lib/bench_utils.rs | 2 +- crates/apps/src/lib/cli.rs | 8 -------- crates/apps/src/lib/cli/wallet.rs | 3 +-- crates/core/src/masp.rs | 26 +++++--------------------- crates/sdk/src/args.rs | 2 -- wasm/tx_ibc/src/lib.rs | 6 +----- wasm/tx_transfer/src/lib.rs | 2 +- 7 files changed, 9 insertions(+), 40 deletions(-) diff --git a/crates/apps/src/lib/bench_utils.rs b/crates/apps/src/lib/bench_utils.rs index 848ad8fb67..9334233b5b 100644 --- a/crates/apps/src/lib/bench_utils.rs +++ b/crates/apps/src/lib/bench_utils.rs @@ -993,7 +993,7 @@ impl Default for BenchShieldedCtx { .wallet .insert_payment_addr( alias, - PaymentAddress::from(payment_addr).pinned(false), + PaymentAddress::from(payment_addr), true, ) .unwrap(); diff --git a/crates/apps/src/lib/cli.rs b/crates/apps/src/lib/cli.rs index cb7e039de0..9ba843d4fd 100644 --- a/crates/apps/src/lib/cli.rs +++ b/crates/apps/src/lib/cli.rs @@ -3184,7 +3184,6 @@ pub mod args { pub const OWNER: Arg = arg("owner"); pub const OWNER_OPT: ArgOpt = OWNER.opt(); pub const PATH: Arg = arg("path"); - pub const PIN: ArgFlag = flag("pin"); pub const PORT_ID: ArgDefault = arg_default( "port-id", DefaultFn(|| PortId::from_str("transfer").unwrap()), @@ -6461,7 +6460,6 @@ pub mod args { alias: self.alias, alias_force: self.alias_force, viewing_key, - pin: self.pin, } } } @@ -6471,12 +6469,10 @@ pub mod args { let alias = ALIAS.parse(matches); let alias_force = ALIAS_FORCE.parse(matches); let viewing_key = VIEWING_KEY.parse(matches); - let pin = PIN.parse(matches); Self { alias, alias_force, viewing_key, - pin, } } @@ -6490,10 +6486,6 @@ pub mod args { "Override the alias without confirmation if it already exists.", )) .arg(VIEWING_KEY.def().help("The viewing key.")) - .arg(PIN.def().help( - "Require that the single transaction to this address be \ - pinned.", - )) } } diff --git a/crates/apps/src/lib/cli/wallet.rs b/crates/apps/src/lib/cli/wallet.rs index 3a1796f20b..0f4b8c4e47 100644 --- a/crates/apps/src/lib/cli/wallet.rs +++ b/crates/apps/src/lib/cli/wallet.rs @@ -315,7 +315,6 @@ fn payment_address_gen( alias, alias_force, viewing_key, - pin, .. }: args::PayAddressGen, ) { @@ -326,7 +325,7 @@ fn payment_address_gen( let masp_payment_addr = viewing_key .to_payment_address(div) .expect("a PaymentAddress"); - let payment_addr = PaymentAddress::from(masp_payment_addr).pinned(pin); + let payment_addr = PaymentAddress::from(masp_payment_addr); let alias = wallet .insert_payment_addr(alias, payment_addr, alias_force) .unwrap_or_else(|| { diff --git a/crates/core/src/masp.rs b/crates/core/src/masp.rs index a3f626f260..0b846986bc 100644 --- a/crates/core/src/masp.rs +++ b/crates/core/src/masp.rs @@ -159,7 +159,6 @@ impl string_encoding::Format for PaymentAddress { fn to_bytes(&self) -> Vec { let mut bytes = Vec::with_capacity(PAYMENT_ADDRESS_SIZE); - bytes.push(self.is_pinned() as u8); bytes.extend_from_slice(self.0.to_bytes().as_slice()); bytes } @@ -172,16 +171,11 @@ impl string_encoding::Format for PaymentAddress { "expected {PAYMENT_ADDRESS_SIZE} bytes for the payment address" ))); } - let pinned = match bytes[0] { - 0 => false, - 1 => true, - k => return Err(DecodeError::UnexpectedDiscriminant(k)), - }; let payment_addr = masp_primitives::sapling::PaymentAddress::from_bytes(&{ // NB: the first byte is the pinned/unpinned discriminant let mut payment_addr = [0u8; PAYMENT_ADDRESS_SIZE - 1]; - payment_addr.copy_from_slice(&bytes[1..]); + payment_addr.copy_from_slice(&bytes[0..]); payment_addr }) .ok_or_else(|| { @@ -189,7 +183,7 @@ impl string_encoding::Format for PaymentAddress { "invalid payment address provided".to_string(), ) })?; - Ok(Self(payment_addr, pinned)) + Ok(Self(payment_addr)) } } @@ -256,22 +250,12 @@ impl<'de> serde::Deserialize<'de> for ExtendedViewingKey { BorshDeserialize, BorshDeserializer, )] -pub struct PaymentAddress(masp_primitives::sapling::PaymentAddress, bool); +pub struct PaymentAddress(masp_primitives::sapling::PaymentAddress); impl PaymentAddress { - /// Turn this PaymentAddress into a pinned/unpinned one - pub fn pinned(self, pin: bool) -> PaymentAddress { - PaymentAddress(self.0, pin) - } - - /// Determine whether this PaymentAddress is pinned - pub fn is_pinned(&self) -> bool { - self.1 - } - /// Hash this payment address pub fn hash(&self) -> String { - let bytes = (self.0, self.1).serialize_to_vec(); + let bytes = self.0.serialize_to_vec(); let mut hasher = Sha256::new(); hasher.update(bytes); // hex of the first 40 chars of the hash @@ -287,7 +271,7 @@ impl From for masp_primitives::sapling::PaymentAddress { impl From for PaymentAddress { fn from(addr: masp_primitives::sapling::PaymentAddress) -> Self { - Self(addr, false) + Self(addr) } } diff --git a/crates/sdk/src/args.rs b/crates/sdk/src/args.rs index 979deb46b1..acf869e8f9 100644 --- a/crates/sdk/src/args.rs +++ b/crates/sdk/src/args.rs @@ -2328,8 +2328,6 @@ pub struct PayAddressGen { pub alias_force: bool, /// Viewing key pub viewing_key: C::ViewingKey, - /// Pin - pub pin: bool, } /// Bridge pool batch recommendation. diff --git a/wasm/tx_ibc/src/lib.rs b/wasm/tx_ibc/src/lib.rs index fbf408bf1d..e81f541bd7 100644 --- a/wasm/tx_ibc/src/lib.rs +++ b/wasm/tx_ibc/src/lib.rs @@ -35,11 +35,7 @@ fn apply_tx(ctx: &mut Ctx, tx_data: Tx) -> TxResult { }) .transpose()?; if let Some(shielded) = shielded { - token::utils::handle_masp_tx( - ctx, - &shielded, - transfer.key.as_deref(), - )?; + token::utils::handle_masp_tx(ctx, &shielded)?; update_masp_note_commitment_tree(&shielded)?; } } diff --git a/wasm/tx_transfer/src/lib.rs b/wasm/tx_transfer/src/lib.rs index c2b8baa568..7e9fe8a84a 100644 --- a/wasm/tx_transfer/src/lib.rs +++ b/wasm/tx_transfer/src/lib.rs @@ -41,7 +41,7 @@ fn apply_tx(ctx: &mut Ctx, tx_data: Tx) -> TxResult { }) .transpose()?; if let Some(shielded) = shielded { - token::utils::handle_masp_tx(ctx, &shielded, transfer.key.as_deref()) + token::utils::handle_masp_tx(ctx, &shielded) .wrap_err("Encountered error while handling MASP transaction")?; update_masp_note_commitment_tree(&shielded) .wrap_err("Failed to update the MASP commitment tree")?; From 73e1477ecb9de21135a06906f31fa4b03c2db8dc Mon Sep 17 00:00:00 2001 From: Marco Granelli Date: Fri, 26 Apr 2024 19:24:17 +0200 Subject: [PATCH 4/7] Fixes econding. Updates shielded keys and addresses for tests --- crates/core/src/masp.rs | 6 ++---- crates/core/src/string_encoding.rs | 2 +- crates/tests/src/e2e/setup.rs | 20 ++++++++++---------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/crates/core/src/masp.rs b/crates/core/src/masp.rs index 0b846986bc..cdfa91280e 100644 --- a/crates/core/src/masp.rs +++ b/crates/core/src/masp.rs @@ -98,8 +98,7 @@ pub fn encode_asset_type( pub type TokenMap = BTreeMap; // enough capacity to store the payment address -// plus the pinned/unpinned discriminant -const PAYMENT_ADDRESS_SIZE: usize = 43 + 1; +const PAYMENT_ADDRESS_SIZE: usize = 43; /// Wrapper for masp_primitive's FullViewingKey #[derive( @@ -173,8 +172,7 @@ impl string_encoding::Format for PaymentAddress { } let payment_addr = masp_primitives::sapling::PaymentAddress::from_bytes(&{ - // NB: the first byte is the pinned/unpinned discriminant - let mut payment_addr = [0u8; PAYMENT_ADDRESS_SIZE - 1]; + let mut payment_addr = [0u8; PAYMENT_ADDRESS_SIZE]; payment_addr.copy_from_slice(&bytes[0..]); payment_addr }) diff --git a/crates/core/src/string_encoding.rs b/crates/core/src/string_encoding.rs index e1109ab0d2..c853fde433 100644 --- a/crates/core/src/string_encoding.rs +++ b/crates/core/src/string_encoding.rs @@ -27,7 +27,7 @@ pub const BECH32M_VARIANT: bech32::Variant = Variant::Bech32m; pub const ADDRESS_HRP: &str = "tnam"; /// MASP extended viewing key human-readable part pub const MASP_EXT_FULL_VIEWING_KEY_HRP: &str = "zvknam"; -/// MASP payment address (not pinned) human-readable part +/// MASP payment address human-readable part pub const MASP_PAYMENT_ADDRESS_HRP: &str = "znam"; /// MASP extended spending key human-readable part pub const MASP_EXT_SPENDING_KEY_HRP: &str = "zsknam"; diff --git a/crates/tests/src/e2e/setup.rs b/crates/tests/src/e2e/setup.rs index 267ea15d1d..a36acdcb06 100644 --- a/crates/tests/src/e2e/setup.rs +++ b/crates/tests/src/e2e/setup.rs @@ -1246,23 +1246,23 @@ pub mod constants { pub const MATCHMAKER_KEY: &str = "matchmaker-key"; // Shielded spending and viewing keys and payment addresses - pub const A_SPENDING_KEY: &str = "zsknam1qqqqqqqqqqqqqq9v0sls5r5de7njx8ehu49pqgmqr9ygelg87l5x8y4s9r0pjlvu69au6gn3su5ewneas486hdccyayx32hxvt64p3d0hfuprpgcgv2q9gdx3jvxrn02f0nnp3jtdd6f5vwscfuyum083cvfv4jun75ak5sdgrm2pthzj3sflxc0jx0edrakx3vdcngrfjmru8ywkguru8mxss2uuqxdlglaz6undx5h8w7g70t2es850g48xzdkqay5qs0yw06rtxc9q0cqr"; - pub const B_SPENDING_KEY: &str = "zsknam1qqqqqqqqqqqqqqpagte43rsza46v55dlz8cffahv0fnr6eqacvnrkyuf9lmndgal7c2k4r7f7zu2yr5rjwr374unjjeuzrh6mquzy6grfdcnnu5clzaq2llqhr70a8yyx0p62aajqvrqjxrht3myuyypsvm725uyt5vm0fqzrzuuedtf6fala4r4nnazm9y9hq5yu6pq24arjskmpv4mdgfn3spffxxv8ugvym36kmnj45jcvvmm227vqjm5fq8882yhjsq97p7xrwqf599qq"; + pub const A_SPENDING_KEY: &str = "zsknam1qdrk9kd8qqqqpqy3pxzxu2kexydl7ug22s3808htl604emmz9qlde9cl9mx6euhvh3cpl9w7guustfzjxsyaeqtefhden6q8776t9cr9vkqztj7u0mgs5k9nz945sypev9ppptn5d85as3ccsnu3q6g3acqp2gpsrwe6naqg3stqp43uk9x2cj79gcxuum8a7jayjqlv4ptcfnunqkqzsj6m2r3sn8ft0tyqqpv28nghe4ag68eccaqx7v5f65he95g5uwq2wr4yuqc06jgc7"; + pub const B_SPENDING_KEY: &str = "zsknam1qdml0zguqqqqpqx8elavks722m0cjelgh3r044cfregyw049jze9lwha2cfqdqnekecnttdvygd6s784kch2v3wjs45g5z0n36hpqv5ruy8jjfu5mz2snl8ljyz79h3szmyf43zve79l6hwnlfk94r422tfwr2f62vvgkeqvc4z2dgrvqy033ymq5ylz3gmf6wdzhsdmzm0h9uv9374x755rzgvmcxhxntu6v63acqktv6zk390e9pd6vr0pzqaq6auu59kwpnw0haczfyju8"; // A payment address derived from A_SPENDING_KEY - pub const AA_PAYMENT_ADDRESS: &str = "znam1qr57pyghrt5ek7v42nxsqdqggltwqrgj2hjlvm5sj0nr8hezzryxcu44qzcea7qdx6wh02cvt9jlu"; + pub const AA_PAYMENT_ADDRESS: &str = "znam1ky620tz7z658cralqt693qpvk42wvth468zp38nqvq2apmex5rfut3dfqm2asrsqv0tc7saqje7"; // A payment address derived from B_SPENDING_KEY - pub const AB_PAYMENT_ADDRESS: &str = "znam1qp562jexfndtcw63equndlwgwawutf6l4p4xgkcvp9sjqf9x7kdlvc48mrh3stfvwk9s9fgsmhuz6"; + pub const AB_PAYMENT_ADDRESS: &str = "znam1zxt8e22uz666ce7hxqpc69yfj3tpd9v26ep2epwn34kvyuwjh98hhre9897shcjj4cnqugwlv4q"; // A viewing key derived from B_SPENDING_KEY - pub const AB_VIEWING_KEY: &str = "zvknam1qqqqqqqqqqqqqqpagte43rsza46v55dlz8cffahv0fnr6eqacvnrkyuf9lmndgal7erg38awgq60r259csg3lxeeyy5355f5nj3ywpeqgd2guqd73uxz46645d0ayt9em88wflka0vsrq29u47x55psw93ly80lvftzdr5ccrzuuedtf6fala4r4nnazm9y9hq5yu6pq24arjskmpv4mdgfn3spffxxv8ugvym36kmnj45jcvvmm227vqjm5fq8882yhjsq97p7xrwq7xmucf"; + pub const AB_VIEWING_KEY: &str = "zvknam1qdml0zguqqqqpqx8elavks722m0cjelgh3r044cfregyw049jze9lwha2cfqdqnekem0xdqf9ytuhaxzeunyl7svgvxjv5g73m24k7w0h6q7wtvcltvlzynzhc5grlfgv7037lfh8w3su5krnzzzjh4nsleydtlns4gl0vmnc4z2dgrvqy033ymq5ylz3gmf6wdzhsdmzm0h9uv9374x755rzgvmcxhxntu6v63acqktv6zk390e9pd6vr0pzqaq6auu59kwpnw0hacdsfkws"; // A payment address derived from B_VIEWING_KEY - pub const BB_PAYMENT_ADDRESS: &str = "znam1qpsr9ass6lfmwlkamk3fpwapht94qqe8dq3slykkfd6wjnd4s9snlqszvxsksk3tegqv2yg9rcrzd"; + pub const BB_PAYMENT_ADDRESS: &str = "znam1mqt0ja2zccy70du2d6rcr77jscgq3gkekfvhrqe7zkxa8rr3qsjsrd66gxnrykdmdeh5wmglmcm"; // A viewing key derived from A_SPENDING_KEY - pub const AA_VIEWING_KEY: &str = "zvknam1qqqqqqqqqqqqqq9v0sls5r5de7njx8ehu49pqgmqr9ygelg87l5x8y4s9r0pjlvu6x74w9gjpw856zcu826qesdre628y6tjc26uhgj6d9zqur9l5u3p99d9ggc74ald6s8y3sdtka74qmheyqvdrasqpwyv2fsmxlz57lj4grm2pthzj3sflxc0jx0edrakx3vdcngrfjmru8ywkguru8mxss2uuqxdlglaz6undx5h8w7g70t2es850g48xzdkqay5qs0yw06rtxcpjdve6"; - pub const C_SPENDING_KEY: &str = "zsknam1qqqqqqqqqqqqqq8cxw3ef0fardt9wq0aqeh29wwljyctw39q4j2t5kmwu6c8x2hfwftnwm6pxtmzyyawm3kruxvk2fdgey90pv3jj9ffvdkxq5vmew5s495qwfyrerrwhxcmx6dl08xh7t36fnn99cdkmsefdv3p3cvw7cq8f4y37q0kh60pdsm6vfkgft2thpu6t9y6ucn68aerump87dgv864yfrxg5529kek99uhzheqajyfrynvsm70v44vsxj2pq5x0wwudrygnmqund"; + pub const AA_VIEWING_KEY: &str = "zvknam1qdrk9kd8qqqqpqy3pxzxu2kexydl7ug22s3808htl604emmz9qlde9cl9mx6euhvhnc63hymme53jz3mmwrzfkr9tk82nqacf5vlmj9du3s3rjz0h6usnh47pw0ufw4u6yrfvf95wfa9xj0m8pcrns9yh90s0jkf3cqy2z7c3stqp43uk9x2cj79gcxuum8a7jayjqlv4ptcfnunqkqzsj6m2r3sn8ft0tyqqpv28nghe4ag68eccaqx7v5f65he95g5uwq2wr4yuqc8djdrp"; + pub const C_SPENDING_KEY: &str = "zsknam1qdy5g4udqqqqpqrfdzej0s45m8s6nprder4udwqm3ql8wx34e8f46dv8cwnmcjp40uj3qy5tgetj27jytvxk4vpa3pjsd80y332nj542w39wta8lsrzqzs822ydgmz5g2sd2k29hxc3uh77v5cmcext799fxn6sa9rd3zuggl6flgjz7wz9wwu9kxd4rth4clw6ug4drxln96y96nf8fmvgm5eddm93azuzlkjj0dpw343ukwcfuvkdhd772539cskgggcqsaaf0j7czshjwe"; // A viewing key derived from C_SPENDING_KEY - pub const AC_VIEWING_KEY: &str = "zvknam1qqqqqqqqqqqqqq8cxw3ef0fardt9wq0aqeh29wwljyctw39q4j2t5kmwu6c8x2hfwtlqw4tv6u0me086mffgk9mutyarawfl9mpgjg320fn5jhyes4fmjauwa0yj4gqpg3clnqck5w8xa5svdzm2ngyex4tvpvr7e4t7tcx3f4y37q0kh60pdsm6vfkgft2thpu6t9y6ucn68aerump87dgv864yfrxg5529kek99uhzheqajyfrynvsm70v44vsxj2pq5x0wwudrygca6tgn"; + pub const AC_VIEWING_KEY: &str = "zvknam1qdy5g4udqqqqpqrfdzej0s45m8s6nprder4udwqm3ql8wx34e8f46dv8cwnmcjp40lr4vutffut7ed5x6egd6etcdh9sxh3j9fe5dshhrn3nq4yfp78gt8ve59y4vnu45xlt93vtrzsxtwlxjjgu2p496lc3ye8m83qplsqfl6flgjz7wz9wwu9kxd4rth4clw6ug4drxln96y96nf8fmvgm5eddm93azuzlkjj0dpw343ukwcfuvkdhd772539cskgggcqsaaf0j7cfyd3jr"; // A viewing key derived from C_VIEWING_KEY - pub const AC_PAYMENT_ADDRESS: &str = "znam1qyw2q5ltsvsp8gp8e3uswerwd7ekq7nc6mx7mtphtyumuq8j2qqmg4zau70m0mcseet8wqsf2gg4p"; + pub const AC_PAYMENT_ADDRESS: &str = "znam1xv4ml6fp3zqjhw20xj3srd75cq8tyejdst0xweq60c70732ty2chd2v39tllpzf4uf6s66vfm6w"; // Native VP aliases pub const GOVERNANCE_ADDRESS: &str = "governance"; From 92fa7797565bbd17bd1c52e10b958e2768e14a90 Mon Sep 17 00:00:00 2001 From: Marco Granelli Date: Fri, 26 Apr 2024 19:24:56 +0200 Subject: [PATCH 5/7] Removes unused errors and integration test --- crates/sdk/src/error.rs | 23 ---- crates/tests/src/integration/masp.rs | 187 +-------------------------- 2 files changed, 3 insertions(+), 207 deletions(-) diff --git a/crates/sdk/src/error.rs b/crates/sdk/src/error.rs index c2f87b7651..08027c69a0 100644 --- a/crates/sdk/src/error.rs +++ b/crates/sdk/src/error.rs @@ -11,8 +11,6 @@ use prost::EncodeError; use tendermint_rpc::Error as RpcError; use thiserror::Error; -use crate::error::Error::Pinned; - /// The standard Result type that most code ought to return pub type Result = std::result::Result; @@ -22,9 +20,6 @@ pub type Result = std::result::Result; /// possible errors that one may face. #[derive(Error, Debug)] pub enum Error { - /// Errors that are caused by trying to retrieve a pinned transaction - #[error("Error in retrieving pinned balance: {0}")] - Pinned(#[from] PinnedBalanceError), /// Key Retrieval Errors #[error("Key Error: {0}")] KeyRetrival(#[from] storage::Error), @@ -48,19 +43,6 @@ pub enum Error { Other(String), } -/// Errors that can occur when trying to retrieve pinned transaction -#[derive(PartialEq, Eq, Copy, Clone, Debug, Error)] -pub enum PinnedBalanceError { - /// No transaction has yet been pinned to the given payment address - #[error("No transaction has yet been pinned to the given payment address")] - NoTransactionPinned, - /// The supplied viewing key does not recognize payments to given address - #[error( - "The supplied viewing key does not recognize payments to given address" - )] - InvalidViewingKey, -} - /// Errors that deal with querying some kind of data #[derive(Error, Debug, Clone)] pub enum QueryError { @@ -383,8 +365,3 @@ pub enum EthereumBridgeError { #[error("An identical transfer is already present in the Bridge pool")] TransferAlreadyInPool, } - -/// Checks if the given error is an invalid viewing key -pub fn is_pinned_error(err: &Result) -> bool { - matches!(err, Err(Pinned(PinnedBalanceError::InvalidViewingKey))) -} diff --git a/crates/tests/src/integration/masp.rs b/crates/tests/src/integration/masp.rs index 60ba2b181d..68fdae89e3 100644 --- a/crates/tests/src/integration/masp.rs +++ b/crates/tests/src/integration/masp.rs @@ -18,9 +18,9 @@ use test_log::test; use super::setup; use crate::e2e::setup::constants::{ AA_PAYMENT_ADDRESS, AA_VIEWING_KEY, AB_PAYMENT_ADDRESS, AB_VIEWING_KEY, - AC_PAYMENT_ADDRESS, AC_VIEWING_KEY, ALBERT, ALBERT_KEY, A_SPENDING_KEY, - BB_PAYMENT_ADDRESS, BERTHA, BERTHA_KEY, BTC, B_SPENDING_KEY, CHRISTEL, - CHRISTEL_KEY, ETH, MASP, NAM, + AC_PAYMENT_ADDRESS, ALBERT, ALBERT_KEY, A_SPENDING_KEY, BB_PAYMENT_ADDRESS, + BERTHA, BERTHA_KEY, BTC, B_SPENDING_KEY, CHRISTEL, CHRISTEL_KEY, ETH, MASP, + NAM, }; use crate::strings::TX_APPLIED_SUCCESS; @@ -922,187 +922,6 @@ fn spend_unconverted_asset_type() -> Result<()> { Ok(()) } -/// In this test we: -/// 1. Run the ledger node -/// 2. Assert PPA(C) cannot be recognized by incorrect viewing key -/// 3. Assert PPA(C) has not transaction pinned to it -/// 4. Send 20 BTC from Albert to PPA(C) -/// 5. Assert PPA(C) has the 20 BTC transaction pinned to it -#[test] -fn masp_pinned_txs() -> Result<()> { - // This address doesn't matter for tests. But an argument is required. - let validator_one_rpc = "http://127.0.0.1:26567"; - // Download the shielded pool parameters before starting node - let _ = FsShieldedUtils::new(PathBuf::new()); - - let (mut node, _services) = setup::setup()?; - // Wait till epoch boundary - let _ep0 = node.next_epoch(); - - // sync shielded context - run( - &node, - Bin::Client, - vec![ - "shielded-sync", - "--viewing-keys", - AC_VIEWING_KEY, - "--node", - validator_one_rpc, - ], - )?; - node.assert_success(); - - // Assert PPA(C) cannot be recognized by incorrect viewing key - let captured = - CapturedOutput::with_input(AB_VIEWING_KEY.into()).run(|| { - run( - &node, - Bin::Client, - vec![ - "balance", - "--owner", - AC_PAYMENT_ADDRESS, - "--token", - BTC, - "--node", - validator_one_rpc, - ], - ) - }); - assert!(captured.result.is_ok()); - assert!( - captured.contains("Supplied viewing key cannot decode transactions to") - ); - - // Assert PPA(C) has no transaction pinned to it - let captured = - CapturedOutput::with_input(AC_VIEWING_KEY.into()).run(|| { - run( - &node, - Bin::Client, - vec![ - "balance", - "--owner", - AC_PAYMENT_ADDRESS, - "--token", - BTC, - "--node", - validator_one_rpc, - ], - ) - }); - assert!(captured.result.is_ok()); - assert!(captured.contains("has not yet been consumed")); - - // Wait till epoch boundary - let _ep1 = node.next_epoch(); - - // Send 20 BTC from Albert to PPA(C) - run( - &node, - Bin::Client, - vec![ - "transfer", - "--source", - ALBERT, - "--target", - AC_PAYMENT_ADDRESS, - "--token", - BTC, - "--amount", - "20", - "--node", - validator_one_rpc, - ], - )?; - node.assert_success(); - - // Wait till epoch boundary - // This makes it more consistent for some reason? - let _ep2 = node.next_epoch(); - - // sync shielded context - run( - &node, - Bin::Client, - vec!["shielded-sync", "--node", validator_one_rpc], - )?; - node.assert_success(); - - // Assert PPA(C) has the 20 BTC transaction pinned to it - let captured = - CapturedOutput::with_input(AC_VIEWING_KEY.into()).run(|| { - run( - &node, - Bin::Client, - vec![ - "balance", - "--owner", - AC_PAYMENT_ADDRESS, - "--token", - BTC, - "--node", - validator_one_rpc, - ], - ) - }); - assert!(captured.result.is_ok()); - assert!(captured.contains("Received 20 btc")); - - // Assert PPA(C) has no NAM pinned to it - let captured = - CapturedOutput::with_input(AC_VIEWING_KEY.into()).run(|| { - run( - &node, - Bin::Client, - vec![ - "balance", - "--owner", - AC_PAYMENT_ADDRESS, - "--token", - NAM, - "--node", - validator_one_rpc, - ], - ) - }); - assert!(captured.result.is_ok()); - assert!(captured.contains("Received no shielded nam")); - - // Wait till epoch boundary - let _ep1 = node.next_epoch(); - - // sync shielded context - run( - &node, - Bin::Client, - vec!["shielded-sync", "--node", validator_one_rpc], - )?; - node.assert_success(); - - // Assert PPA(C) does not NAM pinned to it on epoch boundary - let captured = - CapturedOutput::with_input(AC_VIEWING_KEY.into()).run(|| { - run( - &node, - Bin::Client, - vec![ - "balance", - "--owner", - AC_PAYMENT_ADDRESS, - "--token", - NAM, - "--node", - validator_one_rpc, - ], - ) - }); - assert!(captured.result.is_ok()); - assert!(captured.contains("Received no shielded nam")); - Ok(()) -} - /// In this test we: /// 1. Run the ledger node /// 2. Attempt to spend 10 BTC at SK(A) to PA(B) From f6f5e0af821fa9e792837f5cc1d859a83b330d09 Mon Sep 17 00:00:00 2001 From: Marco Granelli Date: Fri, 26 Apr 2024 17:50:08 +0200 Subject: [PATCH 6/7] Changelog #2675 --- .changelog/unreleased/improvements/2675-remove-pin-key.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .changelog/unreleased/improvements/2675-remove-pin-key.md diff --git a/.changelog/unreleased/improvements/2675-remove-pin-key.md b/.changelog/unreleased/improvements/2675-remove-pin-key.md new file mode 100644 index 0000000000..421a4dbfde --- /dev/null +++ b/.changelog/unreleased/improvements/2675-remove-pin-key.md @@ -0,0 +1,2 @@ +- Removed the MASP pin key. + ([\#2675](https://github.com/anoma/namada/issues/2675)) \ No newline at end of file From b3fff8ddc5d0cec5e069888ba61141d3e959f515 Mon Sep 17 00:00:00 2001 From: Marco Granelli Date: Sat, 27 Apr 2024 17:27:33 +0200 Subject: [PATCH 7/7] Removes `query_tx_deltas` --- crates/sdk/src/masp.rs | 149 +---------------------- crates/shielded_token/src/storage_key.rs | 10 +- 2 files changed, 6 insertions(+), 153 deletions(-) diff --git a/crates/sdk/src/masp.rs b/crates/sdk/src/masp.rs index bf223f6729..5941e2b44d 100644 --- a/crates/sdk/src/masp.rs +++ b/crates/sdk/src/masp.rs @@ -10,7 +10,6 @@ use std::str::FromStr; use borsh::{BorshDeserialize, BorshSerialize}; use borsh_ext::BorshSerializeExt; -use itertools::Either; use lazy_static::lazy_static; use masp_primitives::asset_type::AssetType; #[cfg(feature = "mainnet")] @@ -66,7 +65,7 @@ use namada_macros::BorshDeserializer; use namada_migrations::*; use namada_state::StorageError; use namada_token::{self as token, Denomination, MaspDigitPos, Transfer}; -use namada_tx::data::{TxResult, WrapperTx}; +use namada_tx::data::TxResult; use namada_tx::Tx; use rand_core::{CryptoRng, OsRng, RngCore}; use ripemd::Digest as RipemdDigest; @@ -82,8 +81,6 @@ use crate::rpc::{ query_block, query_conversion, query_denom, query_epoch_at_height, query_native_token, }; -use crate::tendermint_rpc::query::Query; -use crate::tendermint_rpc::Order; use crate::{display_line, edisplay_line, rpc, MaybeSend, MaybeSync, Namada}; /// Env var to point to a dir with MASP parameters. When not specified, @@ -2257,137 +2254,6 @@ impl ShieldedContext { Ok(()) } - /// Obtain the known effects of all accepted shielded and transparent - /// transactions. If an owner is specified, then restrict the set to only - /// transactions crediting/debiting the given owner. If token is specified, - /// then restrict set to only transactions involving the given token. - pub async fn query_tx_deltas( - &mut self, - client: &C, - io: &IO, - query_owner: &Either>, - query_token: &Option
, - viewing_keys: &HashMap, - ) -> Result< - BTreeMap, - Error, - > { - const TXS_PER_PAGE: u8 = 100; - let _ = self.load().await; - let vks = viewing_keys; - let fvks: Vec<_> = vks - .values() - .map(|fvk| ExtendedFullViewingKey::from(*fvk).fvk.vk) - .collect(); - self.fetch(client, &DefaultLogger::new(io), None, None, 1, &[], &fvks) - .await?; - // Save the update state so that future fetches can be short-circuited - let _ = self.save().await; - // Required for filtering out rejected transactions from Tendermint - // responses - let block_results = rpc::query_results(client).await?; - let mut transfers = self.get_tx_deltas().clone(); - // Construct the set of addresses relevant to user's query - let relevant_addrs = match &query_owner { - Either::Left(BalanceOwner::Address(owner)) => vec![owner.clone()], - // MASP objects are dealt with outside of tx_search - Either::Left(BalanceOwner::FullViewingKey(_viewing_key)) => vec![], - // Unspecified owner means all known addresses are considered - // relevant - Either::Right(addrs) => addrs.clone(), - }; - // Find all transactions to or from the relevant address set - for addr in relevant_addrs { - for prop in ["transfer.source", "transfer.target"] { - // Query transactions involving the current address - let mut tx_query = Query::eq(prop, addr.encode()); - // Elaborate the query if requested by the user - if let Some(token) = &query_token { - tx_query = - tx_query.and_eq("transfer.token", token.encode()); - } - for page in 1.. { - let txs = &client - .tx_search( - tx_query.clone(), - true, - page, - TXS_PER_PAGE, - Order::Ascending, - ) - .await - .map_err(|e| { - Error::from(QueryError::General(format!( - "for transaction: {e}" - ))) - })? - .txs; - for response_tx in txs { - let height = BlockHeight(response_tx.height.value()); - let idx = TxIndex(response_tx.index); - // Only process yet unprocessed transactions which have - // been accepted by node VPs - // TODO: Check that wrappers shouldn't be considered - // here - let should_process = - !transfers.contains_key(&IndexedTx { - height, - index: idx, - is_wrapper: false, - }) && block_results[u64::from(height) as usize] - .is_accepted(idx.0 as usize); - if !should_process { - continue; - } - let tx = Tx::try_from(response_tx.tx.as_ref()) - .map_err(|e| Error::Other(e.to_string()))?; - let mut wrapper = None; - let mut transfer = None; - extract_payload(tx, &mut wrapper, &mut transfer)?; - // Epoch data is not needed for transparent transactions - let epoch = - wrapper.map(|x| x.epoch).unwrap_or_default(); - if let Some(transfer) = transfer { - // Skip MASP addresses as they are already handled - // by ShieldedContext - if transfer.source == MASP - || transfer.target == MASP - { - continue; - } - // Describe how a Transfer simply subtracts from one - // account and adds the same to another - - let delta = TransferDelta::from([( - transfer.source.clone(), - MaspChange { - asset: transfer.token.clone(), - change: -transfer.amount.amount().change(), - }, - )]); - - // No shielded accounts are affected by this - // Transfer - transfers.insert( - IndexedTx { - height, - index: idx, - is_wrapper: false, - }, - (epoch, delta, TransactionDelta::new()), - ); - } - } - // An incomplete page signifies no more transactions - if (txs.len() as u8) < TXS_PER_PAGE { - break; - } - } - } - } - Ok(transfers) - } - /// Get the asset type with the given epoch, token, and denomination. If it /// does not exist in the protocol, then remove the timestamp. Make sure to /// store the derived AssetType so that future decoding is possible. @@ -2448,19 +2314,6 @@ impl ShieldedContext { } } -/// Extract the payload from the given Tx object -fn extract_payload( - tx: Tx, - wrapper: &mut Option, - transfer: &mut Option, -) -> Result<(), Error> { - *wrapper = tx.header.wrapper(); - let _ = tx.data().map(|signed| { - Transfer::try_from_slice(&signed[..]).map(|tfer| *transfer = Some(tfer)) - }); - Ok(()) -} - // Retrieves all the indexes and tx events at the specified height which refer // to a valid masp transaction. If an index is given, it filters only the // transactions with an index equal or greater to the provided one. diff --git a/crates/shielded_token/src/storage_key.rs b/crates/shielded_token/src/storage_key.rs index fdc8cf20b9..0fb6b68e84 100644 --- a/crates/shielded_token/src/storage_key.rs +++ b/crates/shielded_token/src/storage_key.rs @@ -83,11 +83,11 @@ pub fn is_masp_allowed_key(key: &storage::Key) -> bool { true } - [DbKeySeg::AddressSeg(addr), DbKeySeg::StringSeg(key), DbKeySeg::StringSeg(_nullifier)] - if *addr == address::MASP && key == MASP_NULLIFIERS_KEY => - { - true - } + [ + DbKeySeg::AddressSeg(addr), + DbKeySeg::StringSeg(key), + DbKeySeg::StringSeg(_nullifier), + ] if *addr == address::MASP && key == MASP_NULLIFIERS_KEY => true, _ => false, } }