Skip to content

Commit

Permalink
feat: add DecodedProofRetainer (#84)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rjected authored Feb 11, 2025
1 parent 4d91c0f commit 1ff76a6
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
48 changes: 48 additions & 0 deletions src/proof/decoded_retainer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use crate::{proof::DecodedProofNodes, Nibbles};
use alloy_primitives::Bytes;

use alloc::vec::Vec;

/// Proof retainer is used to store proofs during merkle trie construction.
/// It is intended to be used within the [`HashBuilder`](crate::HashBuilder).
#[derive(Default, Clone, Debug)]
pub struct DecodedProofRetainer {
/// The nibbles of the target trie keys to retain proofs for.
targets: Vec<Nibbles>,
/// The map retained trie node keys to RLP serialized trie nodes.
proof_nodes: DecodedProofNodes,
}

impl FromIterator<Nibbles> for DecodedProofRetainer {
fn from_iter<T: IntoIterator<Item = Nibbles>>(iter: T) -> Self {
Self::new(FromIterator::from_iter(iter))
}
}

impl DecodedProofRetainer {
/// Create new retainer with target nibbles.
pub fn new(targets: Vec<Nibbles>) -> Self {
Self { targets, proof_nodes: Default::default() }
}

/// Returns `true` if the given prefix matches the retainer target.
pub fn matches(&self, prefix: &Nibbles) -> bool {
self.targets.iter().any(|target| target.starts_with(prefix))
}

/// Returns all collected proofs.
pub fn into_proof_nodes(self) -> DecodedProofNodes {
self.proof_nodes
}

/// Retain the proof if the key matches any of the targets.
///
/// Returns an error if the proof could not be decoded from the given proof bytes.
pub fn retain(&mut self, prefix: &Nibbles, proof: &[u8]) -> Result<(), alloy_rlp::Error> {
if prefix.is_empty() || self.matches(prefix) {
self.proof_nodes.insert_encoded(prefix.clone(), Bytes::from(proof.to_vec()))?;
}

Ok(())
}
}
3 changes: 3 additions & 0 deletions src/proof/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ pub use error::ProofVerificationError;
mod decoded_proof_nodes;
pub use decoded_proof_nodes::DecodedProofNodes;

mod decoded_retainer;
pub use decoded_retainer::DecodedProofRetainer;

mod proof_nodes;
pub use proof_nodes::ProofNodes;

Expand Down
1 change: 0 additions & 1 deletion src/proof/retainer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::{proof::ProofNodes, Nibbles};
use alloy_primitives::Bytes;

#[allow(unused_imports)]
use alloc::vec::Vec;

/// Proof retainer is used to store proofs during merkle trie construction.
Expand Down

0 comments on commit 1ff76a6

Please sign in to comment.