Skip to content

feat: storage backed reward Merkle tree#3936

Open
mrain wants to merge 5 commits intomainfrom
cl/rewardmt
Open

feat: storage backed reward Merkle tree#3936
mrain wants to merge 5 commits intomainfrom
cl/rewardmt

Conversation

@mrain
Copy link
Contributor

@mrain mrain commented Feb 6, 2026

Closes #<ISSUE_NUMBER>

This PR:

This PR does not:

Key places to review:

@gemini-code-assist
Copy link

Summary of Changes

Hello @mrain, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors the reward Merkle tree architecture by introducing a two-level, storage-backed design. This change improves the scalability and persistence of reward account balance management. The new structure allows for flexible storage solutions, with a file system-backed option now available, and ensures compatibility through necessary dependency updates and API adjustments across the codebase.

Highlights

  • Storage-Backed Reward Merkle Tree: Introduced a new two-level Merkle tree implementation for reward account balances, RewardMerkleTreeV2Impl, which supports pluggable storage backends. This design uses an outer tree to manage 16 inner trees, enhancing efficiency for large address spaces.
  • File System Storage Implementation: Added RewardMerkleTreeFSStorage, a concrete implementation of the RewardMerkleTreeStorage trait, enabling persistence of inner Merkle tree roots to the file system using bincode serialization and a single-entry cache.
  • Dependency Updates and Additions: Updated several dependencies in Cargo.lock and Cargo.toml, including jf-advz, jf-merkle-tree-compat, itertools, windows-sys, and heck. New dependencies like rand_chacha, serde_bytes, and tempfile were also added to support the new Merkle tree structure and its testing.
  • Merkle Tree API Adaptation: Modified existing code in sequencer/src/request_response/data_source.rs, types/src/v0/impls/fee_info.rs, types/src/v0/impls/reward.rs, and types/src/v0/impls/state.rs to align with the updated jf-merkle-tree-compat API and the new RewardMerkleTreeV2 structure, primarily by adjusting how LookupResult elements are handled.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • Cargo.lock
    • Updated itertools from 0.13.0 to 0.10.5.
    • Updated windows-sys from 0.59.0 to 0.48.0.
    • Added rand_chacha, serde_bytes, and tempfile dependencies.
    • Updated jf-advz from 0.2.2 to 0.2.4.
    • Updated jf-merkle-tree-compat from 0.2.0 to 0.3.1.
    • Updated heck from 0.5.0 to 0.4.1.
  • Cargo.toml
    • Updated jf-advz tag to jf-advz-v0.2.4.
    • Updated jf-merkle-tree-compat tag to jf-merkle-tree-compat-v0.3.1.
    • Added serde_bytes and tempfile as workspace dependencies.
    • Added rand_chacha as a workspace dependency.
  • sequencer/src/request_response/data_source.rs
    • Modified retain_v2_reward_accounts and retain_v1_reward_accounts to remove dereferencing (*elem) when calling snapshot.remember.
  • types/Cargo.toml
    • Added serde_bytes and tempfile as workspace dependencies.
    • Added rand_chacha as a workspace dependency.
  • types/src/v0/impls/fee_info.rs
    • Modified retain_accounts to remove dereferencing (*balance) when handling LookupResult::Ok.
  • types/src/v0/impls/reward.rs
    • Removed PersistentUniversalMerkleTreeScheme and UniversalMerkleTreeScheme from jf_merkle_tree_compat imports.
    • Changed RewardDistributor::update_reward_tree to use UniversalMerkleTreeScheme trait and tree.update_with.
  • types/src/v0/impls/state.rs
    • Modified balance function to remove dereferencing (*balance) when handling LookupResult::Ok.
  • types/src/v0/mod.rs
    • Added pub mod reward_mt; to expose the new reward Merkle tree module.
  • types/src/v0/reward_mt/fs_storage.rs
    • Added new file: Implements RewardMerkleTreeFSStorage, a file system-backed storage for reward Merkle trees.
  • types/src/v0/reward_mt/mod.rs
    • Added new file: Defines RewardMerkleTreeV2Impl, a two-level Merkle tree structure with pluggable storage, and OuterKeccak256Hasher.
  • types/src/v0/reward_mt/storage.rs
    • Added new file: Defines the RewardMerkleTreeStorage trait and CachedInMemoryStorage implementation.
  • types/src/v0/v0_4/state.rs
    • Removed direct UniversalMerkleTree type alias for RewardMerkleTreeV2.
    • Replaced with pub use crate::v0::reward_mt::{...} to re-export the new RewardMerkleTreeV2 and related constants.
Activity
  • The author, mrain, implemented the new storage-backed reward Merkle tree feature, including the core logic, file system storage, and necessary dependency updates.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a storage-backed, two-level Merkle tree for rewards, which is a significant feature for managing large state efficiently. The implementation includes a RewardMerkleTreeStorage trait with both in-memory and file-system backends. My review primarily focuses on the new storage implementations, highlighting several critical issues in error handling and cache management within the file-system storage that could lead to data loss or corruption. I've also pointed out some incomplete features in the forgettable tree implementation. The other changes, which are mostly refactoring and dependency updates related to this new feature, look good.

}

// Flush the current cache if it exists
if let Err(e) = self.flush_cache() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Ignoring the result of flush_cache() can lead to data loss. If flushing fails, the dirty cache entry is discarded, and a new tree is loaded. This function should panic if flushing fails to prevent data loss. A similar issue exists in clone() on line 136.

        self.flush_cache().expect("Error flushing Reward Merkle tree cache");

Comment on lines +107 to +109
let root = self
.load_from_disk(index)
.unwrap_or(InnerRewardMerkleTreeRoot::Empty);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The use of unwrap_or here can mask critical errors. load_from_disk returns an Err for I/O or deserialization issues (other than NotFound), and unwrap_or will replace this Err with an empty tree. This effectively hides the error and can lead to state corruption. It would be safer to panic on such errors, as they are likely unrecoverable.

load_from_disk already handles the NotFound case by returning an Ok(Empty), so using expect here would only trigger on actual errors.

        let root = self
            .load_from_disk(index)
            .expect("Failed to load Merkle tree root from disk");

impl Drop for RewardMerkleTreeFSStorage {
fn drop(&mut self) {
// Ensure cache is flushed when storage is dropped
let _ = self.flush_cache();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Silently ignoring a failed flush on drop can lead to data loss. While panicking in drop is discouraged, at a minimum, a critical error should be logged to make the failure visible.

        if let Err(e) = self.flush_cache() {
            tracing::error!("Failed to flush cache on drop: {}", e);
        }

Comment on lines +190 to +196
impl Clone for CachedInMemoryStorage {
fn clone(&self) -> Self {
Self {
roots: RwLock::new(self.roots.read().unwrap().clone()),
cache: RwLock::new(self.cache.read().unwrap().clone()),
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current implementation of clone for CachedInMemoryStorage clones the cache, which can lead to inconsistencies. If both the original and the clone are used for modifications, they will have independent but initially identical dirty caches. A safer approach, as seen in RewardMerkleTreeFSStorage, is to flush the cache and provide the clone with a new, empty cache to ensure consistency.

Suggested change
impl Clone for CachedInMemoryStorage {
fn clone(&self) -> Self {
Self {
roots: RwLock::new(self.roots.read().unwrap().clone()),
cache: RwLock::new(self.cache.read().unwrap().clone()),
}
}
impl Clone for CachedInMemoryStorage {
fn clone(&self) -> Self {
// It is important to flush the cache before cloning to ensure the main `roots` map is up to date.
self.flush_cache().expect("Failed to flush cache before cloning");
Self {
roots: RwLock::new(self.roots.read().unwrap().clone()),
cache: RwLock::new(None),
}
}
}

Comment on lines +237 to +291
let _ = self.flush_cache();
let _ = other.flush_cache();
*self.roots.read().unwrap() == *other.roots.read().unwrap()
}
}

impl Eq for CachedInMemoryStorage {}

impl CachedInMemoryStorage {
/// Create a new empty cached storage
pub fn new() -> Self {
Self {
roots: RwLock::new(HashMap::new()),
cache: RwLock::new(None),
}
}

/// Create storage with a pre-allocated capacity
pub fn with_capacity(capacity: usize) -> Self {
Self {
roots: RwLock::new(HashMap::with_capacity(capacity)),
cache: RwLock::new(None),
}
}

/// Get the number of stored roots (excluding cache)
pub fn len(&self) -> usize {
self.roots.read().unwrap().len()
}

/// Check if storage is empty (excluding cache)
pub fn is_empty(&self) -> bool {
self.roots.read().unwrap().is_empty()
}

/// Clear all stored roots and cache
pub fn clear(&self) {
self.roots.write().unwrap().clear();
*self.cache.write().unwrap() = None;
}

/// Internal: Load an inner Merkle tree into the cache
fn load_into_cache(&self, index: OuterIndex) {
// Check if the requested tree is already cached
{
let cache = self.cache.read().unwrap();
if let Some((cached_index, _)) = &*cache {
if *cached_index == index {
return; // Already cached
}
}
}

// Flush the current cache if it exists
let _ = self.flush_cache();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The result of flush_cache() is ignored in eq() (line 237) and load_into_cache() (line 291). A failed flush can lead to data loss or incorrect behavior (e.g., eq() comparing stale data). These calls should expect() a successful flush, causing a panic on failure to prevent further issues.


// Read all tree files from the storage directory
if let Ok(entries) = fs::read_dir(&self.storage_dir) {
for entry in entries.flatten() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The use of flatten() on the ReadDir iterator might silently ignore I/O errors that can occur while iterating over directory entries. It's better practice to handle these errors explicitly, for example by logging a warning for any entry that cannot be read.

            for entry_res in entries {
                if let Ok(entry) = entry_res {

Comment on lines +444 to +522
impl<S: RewardMerkleTreeStorage + Default> ForgetableMerkleTreeScheme
for RewardMerkleTreeV2Impl<S>
{
/// Reconstruct a sparse tree from a commitment with default storage
///
/// Creates an empty tree with the given root. Accounts can be populated with remember.
fn from_commitment(commitment: impl Borrow<Self::Commitment>) -> Self {
let num_leaves = commitment.borrow().size();
Self {
outer: OuterRewardMerkleTreeV2::from_commitment(commitment),
num_leaves,
storage: S::default(),
}
}

/// Remove an account from memory (not yet implemented, currently just performs lookup)
///
/// Returns the account's balance and proof if it exists.
fn forget(
&mut self,
index: impl Borrow<Self::Index>,
) -> LookupResult<Self::Element, Self::MembershipProof, ()> {
self.lookup(index)
// let outer_index = OuterIndex::new(index.borrow());
// let outer_proof = match self.outer.lookup(outer_index) {
// LookupResult::Ok(_, proof) => proof,
// LookupResult::NotInMemory => {
// unreachable!("Outer reward merkle tree will never be forgetten.")
// },
// LookupResult::NotFound(_) => return LookupResult::NotFound(()),
// };
// match self.storage.forget(index) {
// LookupResult::Ok(value, mut proof) => {
// Self::patch_membership_proof(&mut proof, &outer_proof);
// LookupResult::Ok(value, proof)
// },
// LookupResult::NotInMemory => LookupResult::NotInMemory,
// LookupResult::NotFound(_) => LookupResult::NotFound(()),
// }
}

/// Restore an account to memory using a proof (currently a no-op)
///
/// Restores an account that was previously forgotten. Currently does nothing.
fn remember(
&mut self,
_pos: impl Borrow<Self::Index>,
_element: impl Borrow<Self::Element>,
_proof: impl Borrow<Self::MembershipProof>,
) -> Result<(), MerkleTreeError> {
Ok(())
}
}

/// Forgetable universal operations: forget with non-membership proofs
impl<S: RewardMerkleTreeStorage + Default> ForgetableUniversalMerkleTreeScheme
for RewardMerkleTreeV2Impl<S>
{
/// Remove an account and generate proof (membership or non-membership)
///
/// Currently just performs universal_lookup without actually removing from memory.
fn universal_forget(
&mut self,
pos: Self::Index,
) -> LookupResult<Self::Element, Self::MembershipProof, Self::NonMembershipProof> {
self.universal_lookup(pos)
}

/// Restore non-membership information using a proof (currently a no-op)
///
/// Restores non-membership information for an account. Currently does nothing.
fn non_membership_remember(
&mut self,
_pos: Self::Index,
_proof: impl Borrow<Self::NonMembershipProof>,
) -> Result<(), MerkleTreeError> {
Ok(())
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The implementations for ForgetableMerkleTreeScheme and ForgetableUniversalMerkleTreeScheme appear to be incomplete. The methods forget, universal_forget, remember, and non_membership_remember are either stubbed out, are no-ops, or simply delegate to lookup methods without performing their intended 'forget' or 'remember' operations. This should be either fully implemented or clearly documented as a work in progress.

@github-actions
Copy link
Contributor

github-actions bot commented Feb 6, 2026

Created new PR to fix cargo audit.

PR: #3924

Please merge that PR first to fix cargo-audit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant