Skip to content

Commit

Permalink
Unified the functions that construct AssetType to ensure encoding con…
Browse files Browse the repository at this point in the history
…sistency.
  • Loading branch information
murisi committed Jan 12, 2024
1 parent cf2a89e commit cdf7597
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 61 deletions.
8 changes: 5 additions & 3 deletions apps/src/lib/client/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,14 @@ use namada::types::hash::Hash;
use namada::types::ibc::{is_ibc_denom, IbcTokenHash};
use namada::types::io::Io;
use namada::types::key::*;
use namada::types::masp::{BalanceOwner, ExtendedViewingKey, PaymentAddress};
use namada::types::masp::{
encode_asset_type, BalanceOwner, ExtendedViewingKey, PaymentAddress,
};
use namada::types::storage::{BlockHeight, BlockResults, Epoch, Key, KeySeg};
use namada::types::token::{Change, MaspDenom};
use namada::types::{storage, token};
use namada_sdk::error::{is_pinned_error, Error, PinnedBalanceError};
use namada_sdk::masp::{make_asset_type, Conversions, MaspChange};
use namada_sdk::masp::{Conversions, MaspChange};
use namada_sdk::proof_of_stake::types::ValidatorMetaData;
use namada_sdk::rpc::{
self, enriched_bonds_and_unbonds, query_epoch, TxResponse,
Expand Down Expand Up @@ -786,7 +788,7 @@ pub fn extract_amount(
) -> token::Amount {
let mut amount = token::Amount::zero();
for denom in MaspDenom::iter() {
let asset_type = make_asset_type(Some(epoch), token, denom).expect(
let asset_type = encode_asset_type(epoch, token, denom).expect(
"unable to make asset type given token, epoch, and denomination",
);
let value: u128 = value_sum[&asset_type]
Expand Down
50 changes: 19 additions & 31 deletions core/src/ledger/masp_conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use std::collections::BTreeMap;

use borsh::{BorshDeserialize, BorshSerialize};
use borsh_ext::BorshSerializeExt;
use masp_primitives::asset_type::AssetType;
use masp_primitives::convert::AllowedConversion;
use masp_primitives::merkle_tree::FrozenCommitmentTree;
Expand Down Expand Up @@ -212,6 +211,8 @@ where
};
use rayon::prelude::ParallelSlice;

use crate::ledger::storage_api::ResultExt;
use crate::types::masp::encode_asset_type;
use crate::types::storage::{Key, KeySeg};
use crate::types::token::MASP_CONVERT_ANCHOR_KEY;

Expand Down Expand Up @@ -245,10 +246,14 @@ where
// notes clients have to use. This trick works under the assumption that
// reward tokens will then be reinflated back to the current epoch.
let reward_assets = [
encode_asset_type(native_token.clone(), MaspDenom::Zero, Epoch(0)),
encode_asset_type(native_token.clone(), MaspDenom::One, Epoch(0)),
encode_asset_type(native_token.clone(), MaspDenom::Two, Epoch(0)),
encode_asset_type(native_token.clone(), MaspDenom::Three, Epoch(0)),
encode_asset_type(Epoch(0), &native_token, MaspDenom::Zero)
.into_storage_result()?,
encode_asset_type(Epoch(0), &native_token, MaspDenom::One)
.into_storage_result()?,
encode_asset_type(Epoch(0), &native_token, MaspDenom::Two)
.into_storage_result()?,
encode_asset_type(Epoch(0), &native_token, MaspDenom::Three)
.into_storage_result()?,
];
// Conversions from the previous to current asset for each address
let mut current_convs =
Expand All @@ -271,16 +276,12 @@ where
// Provide an allowed conversion from previous timestamp. The
// negative sign allows each instance of the old asset to be
// cancelled out/replaced with the new asset
let old_asset = encode_asset_type(
addr.clone(),
denom,
wl_storage.storage.last_epoch,
);
let new_asset = encode_asset_type(
addr.clone(),
denom,
wl_storage.storage.block.epoch,
);
let old_asset =
encode_asset_type(wl_storage.storage.last_epoch, addr, denom)
.into_storage_result()?;
let new_asset =
encode_asset_type(wl_storage.storage.block.epoch, addr, denom)
.into_storage_result()?;
// Get the last rewarded amount of the native token
let normed_inflation = wl_storage
.storage
Expand Down Expand Up @@ -466,11 +467,9 @@ where
for denom in token::MaspDenom::iter() {
// Add the decoding entry for the new asset type. An uncommitted
// node position is used since this is not a conversion.
let new_asset = encode_asset_type(
addr.clone(),
denom,
wl_storage.storage.block.epoch,
);
let new_asset =
encode_asset_type(wl_storage.storage.block.epoch, &addr, denom)
.into_storage_result()?;
wl_storage.storage.conversion_state.assets.insert(
new_asset,
(
Expand All @@ -486,17 +485,6 @@ where
Ok(())
}

/// Construct MASP asset type with given epoch for given token
pub fn encode_asset_type(
addr: Address,
denom: MaspDenom,
epoch: Epoch,
) -> AssetType {
let new_asset_bytes = (addr, denom, epoch.0).serialize_to_vec();
AssetType::new(new_asset_bytes.as_ref())
.expect("unable to derive asset identifier")
}

#[cfg(test)]
mod tests {
use std::collections::HashMap;
Expand Down
2 changes: 1 addition & 1 deletion core/src/ledger/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use crate::ledger::gas::{
STORAGE_ACCESS_GAS_PER_BYTE, STORAGE_WRITE_GAS_PER_BYTE,
};
pub use crate::ledger::masp_conversions::{
calculate_masp_rewards, encode_asset_type, ConversionState,
calculate_masp_rewards, ConversionState,
};
use crate::ledger::parameters::{self, EpochDuration, Parameters};
use crate::ledger::storage::merkle_tree::{
Expand Down
20 changes: 20 additions & 0 deletions core/src/types/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,34 @@ use std::str::FromStr;

use borsh::{BorshDeserialize, BorshSerialize};
use borsh_ext::BorshSerializeExt;
use masp_primitives::asset_type::AssetType;
use sha2::{Digest, Sha256};

use crate::impl_display_and_from_str_via_format;
use crate::types::address::{Address, DecodeError, HASH_HEX_LEN, MASP};
use crate::types::storage::Epoch;
use crate::types::string_encoding::{
self, MASP_EXT_FULL_VIEWING_KEY_HRP, MASP_EXT_SPENDING_KEY_HRP,
MASP_PAYMENT_ADDRESS_HRP,
};
use crate::types::token::MaspDenom;

/// Make asset type corresponding to given address and epoch
pub fn encode_asset_type(
epoch: Epoch,
token: &Address,
denom: MaspDenom,
) -> Result<AssetType, std::io::Error> {
// Timestamp the chosen token with the current epoch
let token_bytes = (token, denom, epoch.0).serialize_to_vec();
// Generate the unique asset identifier from the unique token address
AssetType::new(token_bytes.as_ref()).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::Other,
"unable to create asset type".to_string(),
)
})
}

// enough capacity to store the payment address
// plus the pinned/unpinned discriminant
Expand Down
32 changes: 12 additions & 20 deletions sdk/src/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ use masp_proofs::prover::LocalTxProver;
use masp_proofs::sapling::SaplingVerificationContext;
use namada_core::types::address::{Address, MASP};
use namada_core::types::masp::{
BalanceOwner, ExtendedViewingKey, PaymentAddress, TransferSource,
TransferTarget,
encode_asset_type, BalanceOwner, ExtendedViewingKey, PaymentAddress,
TransferSource, TransferTarget,
};
use namada_core::types::storage::{BlockHeight, Epoch, Key, KeySeg, TxIndex};
use namada_core::types::time::{DateTimeUtc, DurationSecs};
Expand Down Expand Up @@ -1057,8 +1057,13 @@ impl<U: ShieldedUtils + MaybeSend + MaybeSync> ShieldedContext<U> {
.decode_asset_type(client, asset_type)
.await
.map(|(addr, denom, epoch)| {
make_asset_type(Some(target_epoch), &addr, denom)
encode_asset_type(target_epoch, &addr, denom)
.map(|asset_type| (asset_type, target_epoch >= epoch))
.map_err(|_| {
Error::Other(
"unable to create asset type".to_string(),
)
})
})
.transpose()?
.unwrap_or((asset_type, false));
Expand Down Expand Up @@ -2022,22 +2027,6 @@ fn extract_payload(
Ok(())
}

/// Make asset type corresponding to given address and epoch
pub fn make_asset_type(
epoch: Option<Epoch>,
token: &Address,
denom: MaspDenom,
) -> Result<AssetType, Error> {
// Typestamp the chosen token with the current epoch
let token_bytes = match epoch {
None => (token, denom).serialize_to_vec(),
Some(epoch) => (token, denom, epoch.0).serialize_to_vec(),
};
// Generate the unique asset identifier from the unique token address
AssetType::new(token_bytes.as_ref())
.map_err(|_| Error::Other("unable to create asset type".to_string()))
}

/// Convert Anoma amount and token type to MASP equivalents
fn convert_amount(
epoch: Epoch,
Expand All @@ -2047,7 +2036,10 @@ fn convert_amount(
let mut amount = U64Sum::zero();
let asset_types: [AssetType; 4] = MaspDenom::iter()
.map(|denom| {
let asset_type = make_asset_type(Some(epoch), token, denom)?;
let asset_type =
encode_asset_type(epoch, token, denom).map_err(|_| {
Error::Other("unable to create asset type".to_string())
})?;
// Combine the value and unit into one amount
amount +=
U64Sum::from_nonnegative(asset_type, denom.denominate(&val))
Expand Down
7 changes: 4 additions & 3 deletions sdk/src/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ use namada_core::types::address::{
masp_tx_key, Address, ImplicitAddress, InternalAddress, MASP,
};
use namada_core::types::key::*;
use namada_core::types::masp::{ExtendedViewingKey, PaymentAddress};
use namada_core::types::masp::{
encode_asset_type, ExtendedViewingKey, PaymentAddress,
};
use namada_core::types::storage::Epoch;
use namada_core::types::token;
use namada_core::types::token::Transfer;
Expand Down Expand Up @@ -47,7 +49,6 @@ use crate::error::{EncodingError, Error, TxError};
use crate::ibc::apps::transfer::types::msgs::transfer::MsgTransfer;
use crate::ibc::primitives::proto::Any;
use crate::io::*;
use crate::masp::make_asset_type;
use crate::proto::{MaspBuilder, Section, Tx};
use crate::rpc::validate_amount;
use crate::tx::{
Expand Down Expand Up @@ -1265,7 +1266,7 @@ pub async fn to_ledger_vector(
if builder.target == shielded_hash =>
{
for (addr, denom, epoch) in &builder.asset_types {
match make_asset_type(Some(*epoch), addr, *denom) {
match encode_asset_type(*epoch, addr, *denom) {
Err(_) => None,
Ok(asset) => {
asset_types.insert(
Expand Down
11 changes: 8 additions & 3 deletions sdk/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ use namada_core::types::dec::Dec;
use namada_core::types::hash::Hash;
use namada_core::types::ibc::{IbcShieldedTransfer, MsgShieldedTransfer};
use namada_core::types::key::*;
use namada_core::types::masp::{TransferSource, TransferTarget};
use namada_core::types::masp::{
encode_asset_type, TransferSource, TransferTarget,
};
use namada_core::types::storage::Epoch;
use namada_core::types::time::DateTimeUtc;
use namada_core::types::token::MaspDenom;
Expand All @@ -56,7 +58,7 @@ use crate::control_flow::time;
use crate::error::{EncodingError, Error, QueryError, Result, TxError};
use crate::io::Io;
use crate::masp::TransferErr::Build;
use crate::masp::{make_asset_type, ShieldedContext, ShieldedTransfer};
use crate::masp::{ShieldedContext, ShieldedTransfer};
use crate::proto::{MaspBuilder, Tx};
use crate::queries::Client;
use crate::rpc::{
Expand Down Expand Up @@ -2677,7 +2679,10 @@ pub async fn gen_ibc_shielded_transfer<N: Namada>(
let mut asset_types = Vec::new();
for denom in MaspDenom::iter() {
let epoch = shielded_transfer.epoch;
let asset_type = make_asset_type(Some(epoch), &token, denom)?;
let asset_type =
encode_asset_type(epoch, &token, denom).map_err(|_| {
Error::Other("unable to create asset type".to_string())
})?;
shielded
.asset_types
.insert(asset_type, (token.clone(), denom, epoch));
Expand Down

0 comments on commit cdf7597

Please sign in to comment.