Skip to content

Commit

Permalink
Emit masp sections references in the events
Browse files Browse the repository at this point in the history
  • Loading branch information
grarco committed May 22, 2024
1 parent 09fcca0 commit f4eeb94
Show file tree
Hide file tree
Showing 10 changed files with 358 additions and 328 deletions.
38 changes: 22 additions & 16 deletions crates/events/src/extend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::fmt::Display;
use std::marker::PhantomData;
use std::ops::ControlFlow;
use std::ops::{ControlFlow, DerefMut};
use std::str::FromStr;

use namada_core::collections::HashMap;
Expand Down Expand Up @@ -498,28 +498,34 @@ impl EventAttributeEntry<'static> for MaspTxBlockIndex {
}
}

/// A displyable collection of hashes.
#[derive(Serialize, Deserialize)]
pub struct DisplayableHashVec(Vec<Hash>);
//FIXME: move to tx crate?
/// Reference to a valid masp transaction
#[derive(Clone, Serialize, Deserialize)]
pub struct MaspTxRef {
//FIXME: actually, are we using the commitment? Probably if I give the masp section ref I don't need the commitment anymore right?
//FIXME: If we don't need the commitment then we definetely need to section ref to be in the event and not in the result otherwise we need to loop
pub cmt: Hash,
pub masp_section_ref: Hash,
}

/// The collection of valid masp transactions
#[derive(Default, Clone, Serialize, Deserialize)]
//FIXME: move somewhere else?
//FIXME: maybe rename
pub struct ValidMaspTxs(pub Vec<MaspTxRef>);

impl Display for DisplayableHashVec {
impl Display for ValidMaspTxs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}

impl From<Vec<Hash>> for DisplayableHashVec {
fn from(value: Vec<Hash>) -> Self {
Self(value)
}
}

/// Extend an [`Event`] with `masp_tx_batch_refs` data, indicating the specific
/// inner transactions inside the batch that are valid masp txs.
pub struct MaspTxBatchRefs(pub DisplayableHashVec);
/// inner transactions inside the batch that are valid masp txs and the references to the relative masp sections..
pub struct MaspTxBatchRefs(pub ValidMaspTxs);

impl EventAttributeEntry<'static> for MaspTxBatchRefs {
type Value = DisplayableHashVec;
type Value = ValidMaspTxs;
type ValueOwned = Self::Value;

const KEY: &'static str = "masp_tx_batch_refs";
Expand Down Expand Up @@ -621,8 +627,8 @@ where
}

/// Return a new implementation of [`EventAttributeChecker`].
pub fn attribute_checker<'value, DATA, ATTR>()
-> Box<dyn EventAttributeChecker<'value, ATTR>>
pub fn attribute_checker<'value, DATA, ATTR>(
) -> Box<dyn EventAttributeChecker<'value, ATTR>>
where
DATA: EventAttributeEntry<'value> + 'static,
ATTR: AttributesMap,
Expand Down
64 changes: 47 additions & 17 deletions crates/namada/src/ledger/protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,18 @@ use namada_core::booleans::BoolResultUnitExt;
use namada_core::hash::Hash;
use namada_core::storage::Key;
use namada_events::extend::{
ComposeEvent, Height as HeightAttr, TxHash as TxHashAttr,
ComposeEvent, Height as HeightAttr, MaspTxRef, TxHash as TxHashAttr
};
use namada_events::EventLevel;
use namada_gas::TxGasMeter;
use namada_sdk::tx::TX_TRANSFER_WASM;
use namada_state::StorageWrite;
use namada_state::{StateRead, StorageWrite};
use namada_token::event::{TokenEvent, TokenOperation, UserAccount};
use namada_tx::action::{Action, MaspAction, Read};
use namada_tx::data::protocol::ProtocolTxType;
use namada_tx::data::{
BatchResults, BatchedTxResult, TxResult, TxType, VpStatusFlags, VpsResult,
WrapperTx,
BatchResults, BatchedTxResult, ExtendedTxResult, TxResult, TxType,
VpStatusFlags, VpsResult, WrapperTx,
};
use namada_tx::{BatchedTxRef, Tx};
use namada_vote_ext::EthereumTxData;
Expand Down Expand Up @@ -163,8 +164,8 @@ pub type Result<T> = std::result::Result<T, Error>;
pub struct DispatchError {
/// The result of the function call
pub error: Error,
/// The tx result produced. It could produced even in case of an error
pub tx_result: Option<TxResult<Error>>,
/// The extended tx result produced. It could be produced even in case of an error
pub tx_result: Option<ExtendedTxResult<Error>>,
}

impl From<Error> for DispatchError {
Expand All @@ -189,7 +190,7 @@ pub fn dispatch_tx<'a, D, H, CA>(
vp_wasm_cache: &'a mut VpCache<CA>,
tx_wasm_cache: &'a mut TxCache<CA>,
block_proposer: Option<&Address>,
) -> std::result::Result<TxResult<Error>, DispatchError>
) -> std::result::Result<ExtendedTxResult<Error>, DispatchError>
where
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
Expand Down Expand Up @@ -218,7 +219,8 @@ where
.into_iter()
.collect(),
),
})
}
.to_extended_result(None))
}
TxType::Protocol(protocol_tx) => {
// No bundles of protocol transactions, only take the first one
Expand All @@ -233,10 +235,11 @@ where
.collect(),
),
..Default::default()
})
}
.to_extended_result(None))
}
TxType::Wrapper(ref wrapper) => {
let mut tx_result = apply_wrapper_tx(
let tx_result = apply_wrapper_tx(
tx.clone(),
wrapper,
tx_bytes,
Expand All @@ -261,6 +264,8 @@ where
});
}

let mut extended_tx_result = tx_result.to_extended_result(None);

// TODO(namada#2597): handle masp fee payment in the first inner tx
// if necessary
for cmt in tx.commitments() {
Expand All @@ -276,26 +281,51 @@ where
) {
Err(Error::GasError(ref msg)) => {
// Gas error aborts the execution of the entire batch
tx_result.gas_used =
extended_tx_result.tx_result.gas_used =
tx_gas_meter.borrow().get_tx_consumed_gas();
tx_result.batch_results.0.insert(
extended_tx_result.tx_result.batch_results.0.insert(
cmt.get_hash(),
Err(Error::GasError(msg.to_owned())),
);
state.write_log_mut().drop_tx();
return Err(DispatchError {
error: Error::GasError(msg.to_owned()),
tx_result: Some(tx_result),
tx_result: Some(extended_tx_result),
});
}
res => {
//FIXME: move out to seaparate function, maybe the entire loop
let is_accepted =
matches!(&res, Ok(result) if result.is_accepted());

tx_result.batch_results.0.insert(cmt.get_hash(), res);
tx_result.gas_used =
extended_tx_result
.tx_result
.batch_results
.0
.insert(cmt.get_hash(), res);
extended_tx_result.tx_result.gas_used =
tx_gas_meter.borrow().get_tx_consumed_gas();
if is_accepted {
// If the transaction was a masp one append the transaction refs for the events
if let Some(masp_section_ref) = state.read_actions().map_err(|e| Error::StateError(e))?.into_iter().find_map(|action|
// In case of multiple masp actions we only get the first one
if let Action::Masp(MaspAction{
masp_section_ref,
}) = action
{
Some(masp_section_ref)

} else {
None
}

) {

extended_tx_result.masp_tx_refs.0.push(MaspTxRef {
cmt: cmt.get_hash(),
masp_section_ref
});
}
state.write_log_mut().commit_tx_to_batch();
} else {
state.write_log_mut().drop_tx();
Expand All @@ -307,14 +337,14 @@ where
error: Error::FailingAtomicBatch(
cmt.get_hash(),
),
tx_result: Some(tx_result),
tx_result: Some(extended_tx_result),
});
}
}
}
};
}
Ok(tx_result)
Ok(extended_tx_result)
}
}
}
Expand Down
30 changes: 23 additions & 7 deletions crates/node/src/bench_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ use namada::core::masp::{
use namada::core::storage::{BlockHeight, Epoch, Key, KeySeg, TxIndex};
use namada::core::time::DateTimeUtc;
use namada::core::token::{Amount, DenominatedAmount, Transfer};
use namada::events::extend::{ComposeEvent, MaspTxBatchRefs, MaspTxBlockIndex};
use namada::events::extend::{
ComposeEvent, MaspTxBatchRefs, MaspTxBlockIndex, MaspTxRef, ValidMaspTxs,
};
use namada::events::Event;
use namada::governance::storage::proposal::ProposalType;
use namada::governance::InitProposalData;
Expand Down Expand Up @@ -922,12 +924,26 @@ impl Client for BenchShell {
.with(MaspTxBlockIndex(TxIndex::must_from_usize(
idx,
)))
.with(MaspTxBatchRefs(
vec![
tx.first_commitments().unwrap().get_hash(),
]
.into(),
))
.with(MaspTxBatchRefs(ValidMaspTxs(vec![
MaspTxRef {
cmt: tx
.first_commitments()
.unwrap()
.get_hash(),
masp_section_ref: tx
.sections
.iter()
.find_map(|section| {
if let Section::MaspTx(_) = section
{
Some(section.get_hash())
} else {
None
}
})
.unwrap(),
},
])))
.into();
namada::tendermint::abci::Event::from(event)
})
Expand Down
Loading

0 comments on commit f4eeb94

Please sign in to comment.