Skip to content

Commit

Permalink
Use txids to reference MASP Transactions from Transfers and MaspBuild…
Browse files Browse the repository at this point in the history
…ers.
  • Loading branch information
murisi committed Jun 28, 2024
1 parent 3046602 commit 968dafa
Show file tree
Hide file tree
Showing 18 changed files with 155 additions and 94 deletions.
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ libc = "0.2.97"
libloading = "0.7.2"
linkme = "0.3.24"
# branch = "main"
masp_primitives = { git = "https://github.com/anoma/masp", rev = "4ede1c42d76d6348af8224bc8bfac4404321fe82" }
masp_proofs = { git = "https://github.com/anoma/masp", rev = "4ede1c42d76d6348af8224bc8bfac4404321fe82", default-features = false, features = ["local-prover"] }
masp_primitives = { git = "https://github.com/anoma/masp", rev = "6e8df4193f590344eef191bfa9bdaa7df55becf3" }
masp_proofs = { git = "https://github.com/anoma/masp", rev = "6e8df4193f590344eef191bfa9bdaa7df55becf3", default-features = false, features = ["local-prover"] }
num256 = "0.3.5"
num_cpus = "1.13.0"
num-derive = "0.4"
Expand Down
61 changes: 58 additions & 3 deletions crates/core/src/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@ use masp_primitives::asset_type::AssetType;
use namada_macros::BorshDeserializer;
#[cfg(feature = "migrations")]
use namada_migrations::*;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};

use crate::address::{Address, DecodeError, HASH_HEX_LEN, MASP};
use crate::hash::Hash;
use crate::impl_display_and_from_str_via_format;
use crate::storage::Epoch;
use crate::string_encoding::{
Expand All @@ -24,6 +23,62 @@ use crate::string_encoding::{
};
use crate::token::{Denomination, MaspDigitPos};

/// Serialize the given TxId
pub fn serialize_txid<S>(
txid: &masp_primitives::transaction::TxId,
s: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_bytes(txid.as_ref())
}

/// Deserialize the given TxId
pub fn deserialize_txid<'de, D>(
deserializer: D,
) -> Result<masp_primitives::transaction::TxId, D::Error>
where
D: Deserializer<'de>,
{
Ok(masp_primitives::transaction::TxId::from_bytes(
Deserialize::deserialize(deserializer)?,
))
}

/// Wrapper for masp_primitive's TxId
#[derive(
Serialize,
Deserialize,
Clone,
BorshSerialize,
BorshDeserialize,
BorshSchema,
Debug,
Eq,
PartialEq,
Copy,
Ord,
PartialOrd,
Hash,
)]
pub struct MaspTxId(
#[serde(
serialize_with = "serialize_txid",
deserialize_with = "deserialize_txid"
)]
masp_primitives::transaction::TxId,
);

impl From<masp_primitives::transaction::TxId> for MaspTxId {
fn from(txid: masp_primitives::transaction::TxId) -> Self {
Self(txid)
}
}

/// Wrapper for masp_primitive's TxId
pub type TxId = MaspTxId;

/// Wrapper type around `Epoch` for type safe operations involving the masp
/// epoch
#[derive(
Expand Down Expand Up @@ -603,7 +658,7 @@ impl FromStr for MaspValue {

/// The masp transactions' references of a given batch
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct MaspTxRefs(pub Vec<Hash>);
pub struct MaspTxRefs(pub Vec<TxId>);

impl Display for MaspTxRefs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Expand Down
7 changes: 4 additions & 3 deletions crates/light_sdk/src/transaction/transfer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use namada_sdk::address::Address;
use namada_sdk::hash::Hash;
use namada_sdk::key::common;
use namada_sdk::masp::TxId;
use namada_sdk::token::DenominatedAmount;
use namada_sdk::tx::data::GasLimit;
use namada_sdk::tx::{
Expand Down Expand Up @@ -40,7 +41,7 @@ impl Transfer {
}

/// Build a shielded transfer transaction from the given parameters
pub fn shielded(shielded_section_hash: Hash, args: GlobalArgs) -> Self {
pub fn shielded(shielded_section_hash: TxId, args: GlobalArgs) -> Self {
let data = namada_sdk::token::ShieldedTransfer {
section_hash: shielded_section_hash,
};
Expand All @@ -57,7 +58,7 @@ impl Transfer {
source: Address,
token: Address,
amount: DenominatedAmount,
shielded_section_hash: Hash,
shielded_section_hash: TxId,
args: GlobalArgs,
) -> Self {
let data = namada_sdk::token::ShieldingTransfer {
Expand All @@ -79,7 +80,7 @@ impl Transfer {
target: Address,
token: Address,
amount: DenominatedAmount,
shielded_section_hash: Hash,
shielded_section_hash: TxId,
args: GlobalArgs,
) -> Self {
let data = namada_sdk::token::UnshieldingTransfer {
Expand Down
4 changes: 2 additions & 2 deletions crates/namada/src/ledger/native_vp/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,8 +371,8 @@ where
})?;
let shielded_tx = tx_data
.tx
.get_section(&masp_section_ref)
.and_then(|section| section.masp_tx())
.get_masp_section(&masp_section_ref)
.cloned()
.ok_or_else(|| {
native_vp::Error::new_const(
"Missing MASP section in transaction",
Expand Down
20 changes: 7 additions & 13 deletions crates/node/src/bench_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ use namada_sdk::wallet::Wallet;
use namada_sdk::{Namada, NamadaImpl};
use namada_test_utils::tx_data::TxWriteData;
use rand_core::OsRng;
use sha2::{Digest, Sha256};
use tempfile::TempDir;

use crate::config;
Expand Down Expand Up @@ -936,8 +935,10 @@ impl Client for BenchShell {
tx.sections
.iter()
.find_map(|section| {
if let Section::MaspTx(_) = section {
Some(section.get_hash())
if let Section::MaspTx(transaction) =
section
{
Some(transaction.txid().into())
} else {
None
}
Expand Down Expand Up @@ -1102,13 +1103,7 @@ impl BenchShieldedCtx {
)
.expect("MASP must have shielded part");

let mut hasher = Sha256::new();
let shielded_section_hash = namada::core::hash::Hash(
Section::MaspTx(shielded.clone())
.hash(&mut hasher)
.finalize_reset()
.into(),
);
let shielded_section_hash = shielded.txid().into();
let tx = if source.effective_address() == MASP
&& target.effective_address() == MASP
{
Expand Down Expand Up @@ -1212,10 +1207,9 @@ impl BenchShieldedCtx {
.unwrap();
let masp_tx = tx
.tx
.get_section(&transfer.shielded_section_hash)
.get_masp_section(&transfer.shielded_section_hash)
.unwrap()
.masp_tx()
.unwrap();
.clone();
let msg = MsgTransfer {
message: msg,
transfer: Some(transfer),
Expand Down
15 changes: 6 additions & 9 deletions crates/sdk/src/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ use namada_core::collections::{HashMap, HashSet};
use namada_core::dec::Dec;
pub use namada_core::masp::{
encode_asset_type, AssetData, BalanceOwner, ExtendedViewingKey,
PaymentAddress, TransferSource, TransferTarget,
PaymentAddress, TransferSource, TransferTarget, TxId,
};
use namada_core::masp::{MaspEpoch, MaspTxRefs};
use namada_core::storage::{BlockHeight, TxIndex};
Expand Down Expand Up @@ -851,14 +851,11 @@ impl<U: ShieldedUtils + MaybeSend + MaybeSync> ShieldedContext<U> {
.0
.iter()
.try_fold(vec![], |mut acc, hash| {
match tx
.get_section(hash)
.and_then(|section| section.masp_tx())
.ok_or_else(|| {
Error::Other(
"Missing expected masp transaction".to_string(),
)
}) {
match tx.get_masp_section(hash).cloned().ok_or_else(|| {
Error::Other(
"Missing expected masp transaction".to_string(),
)
}) {
Ok(transaction) => {
acc.push(transaction);
Ok(acc)
Expand Down
13 changes: 7 additions & 6 deletions crates/sdk/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ use masp_primitives::transaction::components::transparent::fees::{
InputView as TransparentInputView, OutputView as TransparentOutputView,
};
use masp_primitives::transaction::components::I128Sum;
use masp_primitives::transaction::{builder, Transaction as MaspTransaction};
use masp_primitives::transaction::{
builder, Transaction as MaspTransaction, TxId,
};
use masp_primitives::zip32::ExtendedFullViewingKey;
use namada_account::{InitAccount, UpdateAccount};
use namada_core::address::{Address, InternalAddress, MASP};
Expand Down Expand Up @@ -2970,7 +2972,7 @@ pub async fn build_shielded_transfer<N: Namada>(

// Construct the tx data with a placeholder shielded section hash
let data = token::ShieldedTransfer {
section_hash: Hash::zero(),
section_hash: TxId::from_bytes(Default::default()).into(),
};
let tx = build_pow_flag(
context,
Expand Down Expand Up @@ -3081,7 +3083,7 @@ pub async fn build_shielding_transfer<N: Namada>(
source: source.clone(),
token: args.token.clone(),
amount: validated_amount,
shielded_section_hash: Hash::zero(),
shielded_section_hash: TxId::from_bytes(Default::default()).into(),
};

let tx = build_pow_flag(
Expand Down Expand Up @@ -3167,7 +3169,7 @@ pub async fn build_unshielding_transfer<N: Namada>(
target: args.target.clone(),
token: args.token.clone(),
amount: validated_amount,
shielded_section_hash: Hash::zero(),
shielded_section_hash: TxId::from_bytes(Default::default()).into(),
};
let tx = build_pow_flag(
context,
Expand Down Expand Up @@ -3539,8 +3541,7 @@ pub async fn gen_ibc_shielding_transfer<N: Namada>(
.map_err(|err| TxSubmitError::MaspError(err.to_string()))?;

if let Some(shielded_transfer) = shielded_transfer {
let masp_tx_hash =
Section::MaspTx(shielded_transfer.masp_tx.clone()).get_hash();
let masp_tx_hash = shielded_transfer.masp_tx.txid().into();
let transfer = token::ShieldingTransfer {
source: source.clone(),
token: token.clone(),
Expand Down
8 changes: 4 additions & 4 deletions crates/token/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
)]

use namada_core::borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use namada_core::hash::Hash;
use namada_macros::BorshDeserializer;
pub use namada_shielded_token::*;
pub use namada_trans_token::*;
Expand All @@ -32,6 +31,7 @@ pub mod storage_key {
}

use namada_core::address::Address;
use namada_core::masp::TxId;
use namada_events::EmitEvents;
use namada_storage::{Result, StorageRead, StorageWrite};

Expand Down Expand Up @@ -110,7 +110,7 @@ pub struct TransparentTransfer {
)]
pub struct ShieldedTransfer {
/// Hash of tx section that contains the MASP transaction
pub section_hash: Hash,
pub section_hash: TxId,
}

/// Arguments for a shielding transfer (from a transparent token to a shielded
Expand All @@ -137,7 +137,7 @@ pub struct ShieldingTransfer {
/// The amount of tokens
pub amount: DenominatedAmount,
/// Hash of tx section that contains the MASP transaction
pub shielded_section_hash: Hash,
pub shielded_section_hash: TxId,
}

/// Arguments for an unshielding transfer (from a shielded token to a
Expand All @@ -164,7 +164,7 @@ pub struct UnshieldingTransfer {
/// The amount of tokens
pub amount: DenominatedAmount,
/// Hash of tx section that contains the MASP transaction
pub shielded_section_hash: Hash,
pub shielded_section_hash: TxId,
}

#[cfg(any(test, feature = "testing"))]
Expand Down
6 changes: 3 additions & 3 deletions crates/tx/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::fmt;

use namada_core::address::Address;
use namada_core::borsh::{BorshDeserialize, BorshSerialize};
use namada_core::hash::Hash;
use namada_core::masp::TxId;
use namada_core::storage::KeySeg;
use namada_core::{address, storage};

Expand Down Expand Up @@ -67,7 +67,7 @@ pub enum PgfAction {
#[derive(Clone, Debug, BorshDeserialize, BorshSerialize)]
pub struct MaspAction {
/// The hash of the masp [`crate::types::Section`]
pub masp_section_ref: Hash,
pub masp_section_ref: TxId,
}

/// Read actions from temporary storage
Expand Down Expand Up @@ -123,7 +123,7 @@ fn storage_key() -> storage::Key {
/// first one
pub fn get_masp_section_ref<T: Read>(
reader: &T,
) -> Result<Option<Hash>, <T as Read>::Err> {
) -> Result<Option<TxId>, <T as Read>::Err> {
Ok(reader.read_actions()?.into_iter().find_map(|action| {
// In case of multiple masp actions we get the first one
if let Action::Masp(MaspAction { masp_section_ref }) = action {
Expand Down
Loading

0 comments on commit 968dafa

Please sign in to comment.