From 7caaa2ab8b3c4b61f4f7d53655d8082222d07929 Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Tue, 3 Mar 2026 18:26:29 +0700 Subject: [PATCH 01/11] refactor(treeview): squash te/refactor_treeview_2 changes --- src/fork_types/any_beacon_state.zig | 344 +++++----- src/fork_types/beacon_state.zig | 112 ++-- src/ssz/root.zig | 3 +- src/ssz/tree_view/array_basic.zig | 111 ++-- src/ssz/tree_view/array_composite.zig | 193 +++--- src/ssz/tree_view/base.zig | 275 -------- src/ssz/tree_view/bit_array.zig | 89 ++- src/ssz/tree_view/bit_list.zig | 71 ++- src/ssz/tree_view/bit_vector.zig | 89 ++- src/ssz/tree_view/chunks.zig | 387 +++++++++--- src/ssz/tree_view/container.zig | 585 +++++++++++++----- src/ssz/tree_view/list_basic.zig | 349 ++++++----- src/ssz/tree_view/list_composite.zig | 497 +++++++-------- src/ssz/tree_view/root.zig | 4 +- src/ssz/tree_view/utils/assert.zig | 53 ++ src/ssz/tree_view/utils/child_nodes.zig | 106 ++++ src/ssz/tree_view/utils/clone_opts.zig | 5 + src/ssz/type/container.zig | 1 + .../block/process_attestation_phase0.zig | 2 +- .../block/process_bls_to_execution_change.zig | 2 +- .../block/process_consolidation_request.zig | 10 +- .../block/process_deposit.zig | 2 +- .../block/process_voluntary_exit.zig | 6 +- .../block/process_withdrawal_request.zig | 10 +- .../block/process_withdrawals.zig | 2 +- .../block/slash_validator.zig | 6 +- src/state_transition/cache/state_cache.zig | 4 +- .../process_effective_balance_updates.zig | 4 +- ...process_justification_and_finalization.zig | 3 +- .../epoch/process_registry_updates.zig | 4 +- .../epoch/process_slashings.zig | 2 +- src/state_transition/slot/process_slot.zig | 2 +- .../slot/upgrade_state_to_altair.zig | 4 +- src/state_transition/utils/block_root.zig | 2 +- src/state_transition/utils/electra.zig | 2 +- src/state_transition/utils/seed.zig | 2 +- test/spec/test_case.zig | 64 +- 37 files changed, 1935 insertions(+), 1472 deletions(-) delete mode 100644 src/ssz/tree_view/base.zig create mode 100644 src/ssz/tree_view/utils/assert.zig create mode 100644 src/ssz/tree_view/utils/child_nodes.zig create mode 100644 src/ssz/tree_view/utils/clone_opts.zig diff --git a/src/fork_types/any_beacon_state.zig b/src/fork_types/any_beacon_state.zig index 068043eaa..36198891b 100644 --- a/src/fork_types/any_beacon_state.zig +++ b/src/fork_types/any_beacon_state.zig @@ -8,8 +8,7 @@ const Gindex = @import("persistent_merkle_tree").Gindex; const createSingleProof = @import("persistent_merkle_tree").proof.createSingleProof; const SingleProof = @import("persistent_merkle_tree").proof.SingleProof; const isBasicType = @import("ssz").isBasicType; -const BaseTreeView = @import("ssz").BaseTreeView; -const CloneOpts = @import("ssz").BaseTreeView.CloneOpts; +const CloneOpts = @import("ssz").CloneOpts; const ct = @import("consensus_types"); const constants = @import("constants"); const BeaconState = @import("./beacon_state.zig").BeaconState; @@ -23,13 +22,13 @@ pub fn readSlotFromAnyBeaconStateBytes(bytes: []const u8) u64 { /// wrapper for all AnyBeaconState types across forks so that we don't have to do switch/case for all methods pub const AnyBeaconState = union(ForkSeq) { - phase0: ct.phase0.BeaconState.TreeView, - altair: ct.altair.BeaconState.TreeView, - bellatrix: ct.bellatrix.BeaconState.TreeView, - capella: ct.capella.BeaconState.TreeView, - deneb: ct.deneb.BeaconState.TreeView, - electra: ct.electra.BeaconState.TreeView, - fulu: ct.fulu.BeaconState.TreeView, + phase0: *ct.phase0.BeaconState.TreeView, + altair: *ct.altair.BeaconState.TreeView, + bellatrix: *ct.bellatrix.BeaconState.TreeView, + capella: *ct.capella.BeaconState.TreeView, + deneb: *ct.deneb.BeaconState.TreeView, + electra: *ct.electra.BeaconState.TreeView, + fulu: *ct.fulu.BeaconState.TreeView, pub fn fromValue(allocator: Allocator, pool: *Node.Pool, comptime fork_seq: ForkSeq, value: anytype) !AnyBeaconState { return switch (fork_seq) { @@ -84,45 +83,45 @@ pub const AnyBeaconState = union(ForkSeq) { } pub fn serialize(self: AnyBeaconState, allocator: Allocator) ![]u8 { - var s = self; + const s = self; switch (s) { - .phase0 => |*state| { + .phase0 => |state| { const out = try allocator.alloc(u8, try state.serializedSize()); errdefer allocator.free(out); _ = try state.serializeIntoBytes(out); return out; }, - .altair => |*state| { + .altair => |state| { const out = try allocator.alloc(u8, try state.serializedSize()); errdefer allocator.free(out); _ = try state.serializeIntoBytes(out); return out; }, - .bellatrix => |*state| { + .bellatrix => |state| { const out = try allocator.alloc(u8, try state.serializedSize()); errdefer allocator.free(out); _ = try state.serializeIntoBytes(out); return out; }, - .capella => |*state| { + .capella => |state| { const out = try allocator.alloc(u8, try state.serializedSize()); errdefer allocator.free(out); _ = try state.serializeIntoBytes(out); return out; }, - .deneb => |*state| { + .deneb => |state| { const out = try allocator.alloc(u8, try state.serializedSize()); errdefer allocator.free(out); _ = try state.serializeIntoBytes(out); return out; }, - .electra => |*state| { + .electra => |state| { const out = try allocator.alloc(u8, try state.serializedSize()); errdefer allocator.free(out); _ = try state.serializeIntoBytes(out); return out; }, - .fulu => |*state| { + .fulu => |state| { const out = try allocator.alloc(u8, try state.serializedSize()); errdefer allocator.free(out); _ = try state.serializeIntoBytes(out); @@ -146,27 +145,21 @@ pub const AnyBeaconState = union(ForkSeq) { }; } - pub fn baseView(self: *AnyBeaconState) BaseTreeView { - return switch (self.*) { - inline else => |*state| state.base_view, - }; - } - pub fn clone(self: *AnyBeaconState, opts: CloneOpts) !AnyBeaconState { return switch (self.*) { - .phase0 => |*state| .{ .phase0 = try state.clone(opts) }, - .altair => |*state| .{ .altair = try state.clone(opts) }, - .bellatrix => |*state| .{ .bellatrix = try state.clone(opts) }, - .capella => |*state| .{ .capella = try state.clone(opts) }, - .deneb => |*state| .{ .deneb = try state.clone(opts) }, - .electra => |*state| .{ .electra = try state.clone(opts) }, - .fulu => |*state| .{ .fulu = try state.clone(opts) }, + .phase0 => |state| .{ .phase0 = try state.clone(opts) }, + .altair => |state| .{ .altair = try state.clone(opts) }, + .bellatrix => |state| .{ .bellatrix = try state.clone(opts) }, + .capella => |state| .{ .capella = try state.clone(opts) }, + .deneb => |state| .{ .deneb = try state.clone(opts) }, + .electra => |state| .{ .electra = try state.clone(opts) }, + .fulu => |state| .{ .fulu = try state.clone(opts) }, }; } pub fn commit(self: *AnyBeaconState) !void { switch (self.*) { - inline else => |*state| try state.commit(), + inline else => |state| try state.commit(), } } @@ -195,18 +188,18 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn hashTreeRoot(self: *AnyBeaconState) !*const [32]u8 { return switch (self.*) { - inline else => |*state| try state.hashTreeRoot(), + inline else => |state| try state.hashTreeRoot(), }; } pub fn deinit(self: *AnyBeaconState) void { switch (self.*) { - inline else => |*state| state.deinit(), + inline else => |state| state.deinit(), } } pub fn forkSeq(self: *AnyBeaconState) ForkSeq { - return (self.*); + return std.meta.activeTag(self.*); } // pub fn castFromFork(comptime f: ForkSeq, ) @@ -224,39 +217,39 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn genesisTime(self: *AnyBeaconState) !u64 { return switch (self.*) { - inline else => |*state| try state.get("genesis_time"), + inline else => |state| try state.get("genesis_time"), }; } pub fn genesisValidatorsRoot(self: *AnyBeaconState) !*const [32]u8 { return switch (self.*) { - inline else => |*state| try state.getRoot("genesis_validators_root"), + inline else => |state| try state.getFieldRoot("genesis_validators_root"), }; } pub fn slot(self: *AnyBeaconState) !u64 { return switch (self.*) { - inline else => |*state| try state.get("slot"), + inline else => |state| try state.get("slot"), }; } pub fn setSlot(self: *AnyBeaconState, s: u64) !void { switch (self.*) { - inline else => |*state| try state.set("slot", s), + inline else => |state| try state.set("slot", s), } } - pub fn fork(self: *AnyBeaconState) !ct.phase0.Fork.TreeView { + pub fn fork(self: *AnyBeaconState) !*ct.phase0.Fork.TreeView { return switch (self.*) { - inline else => |*state| try state.get("fork"), + inline else => |state| try state.get("fork"), }; } pub fn forkCurrentVersion(self: *AnyBeaconState) ![4]u8 { var f = switch (self.*) { - inline else => |*state| try state.getReadonly("fork"), + inline else => |state| try state.getReadonly("fork"), }; - const current_version_root = try f.getRoot("current_version"); + const current_version_root = try f.getFieldRoot("current_version"); var version: [4]u8 = undefined; @memcpy(&version, current_version_root[0..4]); return version; @@ -264,73 +257,73 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn setFork(self: *AnyBeaconState, f: *const ct.phase0.Fork.Type) !void { switch (self.*) { - inline else => |*state| try state.setValue("fork", f), + inline else => |state| try state.setValue("fork", f), } } - pub fn latestBlockHeader(self: *AnyBeaconState) !ct.phase0.BeaconBlockHeader.TreeView { + pub fn latestBlockHeader(self: *AnyBeaconState) !*ct.phase0.BeaconBlockHeader.TreeView { return switch (self.*) { - inline else => |*state| try state.get("latest_block_header"), + inline else => |state| try state.get("latest_block_header"), }; } pub fn setLatestBlockHeader(self: *AnyBeaconState, header: *const ct.phase0.BeaconBlockHeader.Type) !void { switch (self.*) { - inline else => |*state| try state.setValue("latest_block_header", header), + inline else => |state| try state.setValue("latest_block_header", header), } } - pub fn blockRoots(self: *AnyBeaconState) !ct.phase0.HistoricalBlockRoots.TreeView { + pub fn blockRoots(self: *AnyBeaconState) !*ct.phase0.HistoricalBlockRoots.TreeView { return switch (self.*) { - inline else => |*state| try state.get("block_roots"), + inline else => |state| try state.get("block_roots"), }; } pub fn blockRootsRoot(self: *AnyBeaconState) !*const [32]u8 { return switch (self.*) { - inline else => |*state| try state.getRoot("block_roots"), + inline else => |state| try state.getFieldRoot("block_roots"), }; } - pub fn stateRoots(self: *AnyBeaconState) !ct.phase0.HistoricalStateRoots.TreeView { + pub fn stateRoots(self: *AnyBeaconState) !*ct.phase0.HistoricalStateRoots.TreeView { return switch (self.*) { - inline else => |*state| try state.get("state_roots"), + inline else => |state| try state.get("state_roots"), }; } pub fn stateRootsRoot(self: *AnyBeaconState) !*const [32]u8 { return switch (self.*) { - inline else => |*state| try state.getRoot("state_roots"), + inline else => |state| try state.getFieldRoot("state_roots"), }; } - pub fn historicalRoots(self: *AnyBeaconState) !ct.phase0.HistoricalRoots.TreeView { + pub fn historicalRoots(self: *AnyBeaconState) !*ct.phase0.HistoricalRoots.TreeView { return switch (self.*) { - inline else => |*state| try state.get("historical_roots"), + inline else => |state| try state.get("historical_roots"), }; } - pub fn eth1Data(self: *AnyBeaconState) !ct.phase0.Eth1Data.TreeView { + pub fn eth1Data(self: *AnyBeaconState) !*ct.phase0.Eth1Data.TreeView { return switch (self.*) { - inline else => |*state| try state.get("eth1_data"), + inline else => |state| try state.get("eth1_data"), }; } pub fn setEth1Data(self: *AnyBeaconState, eth1_data: *const ct.phase0.Eth1Data.Type) !void { switch (self.*) { - inline else => |*state| try state.setValue("eth1_data", eth1_data), + inline else => |state| try state.setValue("eth1_data", eth1_data), } } - pub fn eth1DataVotes(self: *AnyBeaconState) !ct.phase0.Eth1DataVotes.TreeView { + pub fn eth1DataVotes(self: *AnyBeaconState) !*ct.phase0.Eth1DataVotes.TreeView { return switch (self.*) { - inline else => |*state| try state.get("eth1_data_votes"), + inline else => |state| try state.get("eth1_data_votes"), }; } - pub fn setEth1DataVotes(self: *AnyBeaconState, eth1_data_votes: ct.phase0.Eth1DataVotes.TreeView) !void { + pub fn setEth1DataVotes(self: *AnyBeaconState, eth1_data_votes: *ct.phase0.Eth1DataVotes.TreeView) !void { switch (self.*) { - inline else => |*state| try state.set("eth1_data_votes", eth1_data_votes), + inline else => |state| try state.set("eth1_data_votes", eth1_data_votes), } } @@ -341,19 +334,19 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn resetEth1DataVotes(self: *AnyBeaconState) !void { switch (self.*) { - inline else => |*state| try state.setValue("eth1_data_votes", &ct.phase0.Eth1DataVotes.default_value), + inline else => |state| try state.setValue("eth1_data_votes", &ct.phase0.Eth1DataVotes.default_value), } } pub fn eth1DepositIndex(self: *AnyBeaconState) !u64 { return switch (self.*) { - inline else => |*state| try state.get("eth1_deposit_index"), + inline else => |state| try state.get("eth1_deposit_index"), }; } pub fn setEth1DepositIndex(self: *AnyBeaconState, index: u64) !void { return switch (self.*) { - inline else => |*state| try state.set("eth1_deposit_index", index), + inline else => |state| try state.set("eth1_deposit_index", index), }; } @@ -361,15 +354,15 @@ pub const AnyBeaconState = union(ForkSeq) { try self.setEth1DepositIndex(try self.eth1DepositIndex() + 1); } - pub fn validators(self: *AnyBeaconState) !ct.phase0.Validators.TreeView { + pub fn validators(self: *AnyBeaconState) !*ct.phase0.Validators.TreeView { return switch (self.*) { - inline else => |*state| try state.get("validators"), + inline else => |state| try state.get("validators"), }; } pub fn validatorsCount(self: *AnyBeaconState) !usize { return switch (self.*) { - inline else => |*state| { + inline else => |state| { var validators_view = try state.getReadonly("validators"); return validators_view.length(); }, @@ -381,16 +374,16 @@ pub const AnyBeaconState = union(ForkSeq) { /// Caller owns the returned slice and must free it with the same allocator. pub fn validatorsSlice(self: *AnyBeaconState, allocator: Allocator) ![]ct.phase0.Validator.Type { return switch (self.*) { - inline else => |*state| { + inline else => |state| { var validators_view = try state.getReadonly("validators"); return validators_view.getAllReadonlyValues(allocator); }, }; } - pub fn balances(self: *AnyBeaconState) !ct.phase0.Balances.TreeView { + pub fn balances(self: *AnyBeaconState) !*ct.phase0.Balances.TreeView { return switch (self.*) { - inline else => |*state| try state.get("balances"), + inline else => |state| try state.get("balances"), }; } @@ -399,7 +392,7 @@ pub const AnyBeaconState = union(ForkSeq) { /// Caller owns the returned slice and must free it with the same allocator. pub fn balancesSlice(self: *AnyBeaconState, allocator: Allocator) ![]u64 { return switch (self.*) { - inline else => |*state| { + inline else => |state| { var balances_view = try state.get("balances"); try balances_view.commit(); return balances_view.getAll(allocator); @@ -409,13 +402,13 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn setBalances(self: *AnyBeaconState, b: *const ct.phase0.Balances.Type) !void { return switch (self.*) { - inline else => |*state| try state.setValue("balances", b), + inline else => |state| try state.setValue("balances", b), }; } - pub fn randaoMixes(self: *AnyBeaconState) !ct.phase0.RandaoMixes.TreeView { + pub fn randaoMixes(self: *AnyBeaconState) !*ct.phase0.RandaoMixes.TreeView { return switch (self.*) { - inline else => |*state| try state.get("randao_mixes"), + inline else => |state| try state.get("randao_mixes"), }; } @@ -424,69 +417,71 @@ pub const AnyBeaconState = union(ForkSeq) { try mixes.setValue(epoch % preset.EPOCHS_PER_HISTORICAL_VECTOR, randao_mix); } - pub fn slashings(self: *AnyBeaconState) !ct.phase0.Slashings.TreeView { + pub fn slashings(self: *AnyBeaconState) !*ct.phase0.Slashings.TreeView { return switch (self.*) { - inline else => |*state| try state.get("slashings"), + inline else => |state| try state.get("slashings"), }; } - pub fn previousEpochPendingAttestations(self: *AnyBeaconState) !ct.phase0.EpochAttestations.TreeView { + pub fn previousEpochPendingAttestations(self: *AnyBeaconState) !*ct.phase0.EpochAttestations.TreeView { return switch (self.*) { - .phase0 => |*state| try state.get("previous_epoch_attestations"), + .phase0 => |state| try state.get("previous_epoch_attestations"), else => error.InvalidAtFork, }; } - pub fn currentEpochPendingAttestations(self: *AnyBeaconState) !ct.phase0.EpochAttestations.TreeView { + pub fn currentEpochPendingAttestations(self: *AnyBeaconState) !*ct.phase0.EpochAttestations.TreeView { return switch (self.*) { - .phase0 => |*state| try state.get("current_epoch_attestations"), + .phase0 => |state| try state.get("current_epoch_attestations"), else => error.InvalidAtFork, }; } pub fn rotateEpochPendingAttestations(self: *AnyBeaconState) !void { return switch (self.*) { - .phase0 => |*state| { - const current_root = try state.getRootNode("current_epoch_attestations"); - try state.setRootNode("previous_epoch_attestations", current_root); + .phase0 => |state| { + // const current_root = try state.getRootNode("current_epoch_attestations"); + // try state.setRootNode("previous_epoch_attestations", current_root); + // TODO - treeview + try state.set("previous_epoch_attestations", try state.get("current_epoch_attestations")); try state.setValue("current_epoch_attestations", &ct.phase0.EpochAttestations.default_value); }, else => error.InvalidAtFork, }; } - pub fn previousEpochParticipation(self: *AnyBeaconState) !ct.altair.EpochParticipation.TreeView { + pub fn previousEpochParticipation(self: *AnyBeaconState) !*ct.altair.EpochParticipation.TreeView { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.get("previous_epoch_participation"), + inline else => |state| try state.get("previous_epoch_participation"), }; } pub fn setPreviousEpochParticipation(self: *AnyBeaconState, participations: *const ct.altair.EpochParticipation.Type) !void { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.setValue("previous_epoch_participation", participations), + inline else => |state| try state.setValue("previous_epoch_participation", participations), }; } - pub fn currentEpochParticipation(self: *AnyBeaconState) !ct.altair.EpochParticipation.TreeView { + pub fn currentEpochParticipation(self: *AnyBeaconState) !*ct.altair.EpochParticipation.TreeView { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.get("current_epoch_participation"), + inline else => |state| try state.get("current_epoch_participation"), }; } pub fn setCurrentEpochParticipation(self: *AnyBeaconState, participations: *const ct.altair.EpochParticipation.Type) !void { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.setValue("current_epoch_participation", participations), + inline else => |state| try state.setValue("current_epoch_participation", participations), }; } pub fn rotateEpochParticipation(self: *AnyBeaconState) !void { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| { + inline else => |state| { var current_epoch_participation = try state.get("current_epoch_participation"); try current_epoch_participation.commit(); const length = try current_epoch_participation.length(); @@ -499,111 +494,111 @@ pub const AnyBeaconState = union(ForkSeq) { // Reset current_epoch_participation by rebuilding a zeroed SSZ List of the same length. const new_current_root = try ct.altair.EpochParticipation.tree.zeros( - state.base_view.pool, + state.pool, length, ); - errdefer state.base_view.pool.unref(new_current_root); + errdefer state.pool.unref(new_current_root); try state.setRootNode("current_epoch_participation", new_current_root); }, }; } - pub fn justificationBits(self: *AnyBeaconState) !ct.phase0.JustificationBits.TreeView { + pub fn justificationBits(self: *AnyBeaconState) !*ct.phase0.JustificationBits.TreeView { return switch (self.*) { - inline else => |*state| try state.get("justification_bits"), + inline else => |state| try state.get("justification_bits"), }; } pub fn setJustificationBits(self: *AnyBeaconState, bits: *const ct.phase0.JustificationBits.Type) !void { return switch (self.*) { - inline else => |*state| try state.setValue("justification_bits", bits), + inline else => |state| try state.setValue("justification_bits", bits), }; } pub fn previousJustifiedCheckpoint(self: *AnyBeaconState, out: *ct.phase0.Checkpoint.Type) !void { return switch (self.*) { - inline else => |*state| try state.getValue(undefined, "previous_justified_checkpoint", out), + inline else => |state| try state.getValue(undefined, "previous_justified_checkpoint", out), }; } pub fn setPreviousJustifiedCheckpoint(self: *AnyBeaconState, checkpoint: *const ct.phase0.Checkpoint.Type) !void { return switch (self.*) { - inline else => |*state| try state.setValue("previous_justified_checkpoint", checkpoint), + inline else => |state| try state.setValue("previous_justified_checkpoint", checkpoint), }; } pub fn currentJustifiedCheckpoint(self: *AnyBeaconState, out: *ct.phase0.Checkpoint.Type) !void { return switch (self.*) { - inline else => |*state| try state.getValue(undefined, "current_justified_checkpoint", out), + inline else => |state| try state.getValue(undefined, "current_justified_checkpoint", out), }; } pub fn setCurrentJustifiedCheckpoint(self: *AnyBeaconState, checkpoint: *const ct.phase0.Checkpoint.Type) !void { return switch (self.*) { - inline else => |*state| try state.setValue("current_justified_checkpoint", checkpoint), + inline else => |state| try state.setValue("current_justified_checkpoint", checkpoint), }; } pub fn finalizedCheckpoint(self: *AnyBeaconState, out: *ct.phase0.Checkpoint.Type) !void { return switch (self.*) { - inline else => |*state| try state.getValue(undefined, "finalized_checkpoint", out), + inline else => |state| try state.getValue(undefined, "finalized_checkpoint", out), }; } pub fn setFinalizedCheckpoint(self: *AnyBeaconState, checkpoint: *const ct.phase0.Checkpoint.Type) !void { return switch (self.*) { - inline else => |*state| try state.setValue("finalized_checkpoint", checkpoint), + inline else => |state| try state.setValue("finalized_checkpoint", checkpoint), }; } pub fn finalizedEpoch(self: *AnyBeaconState) !u64 { return switch (self.*) { - inline else => |*state| { + inline else => |state| { var checkpoint_view = try state.getReadonly("finalized_checkpoint"); return try checkpoint_view.get("epoch"); }, }; } - pub fn inactivityScores(self: *AnyBeaconState) !ct.altair.InactivityScores.TreeView { + pub fn inactivityScores(self: *AnyBeaconState) !*ct.altair.InactivityScores.TreeView { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.get("inactivity_scores"), + inline else => |state| try state.get("inactivity_scores"), }; } - pub fn currentSyncCommittee(self: *AnyBeaconState) !ct.altair.SyncCommittee.TreeView { + pub fn currentSyncCommittee(self: *AnyBeaconState) !*ct.altair.SyncCommittee.TreeView { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.get("current_sync_committee"), + inline else => |state| try state.get("current_sync_committee"), }; } pub fn setCurrentSyncCommittee(self: *AnyBeaconState, sync_committee: *const ct.altair.SyncCommittee.Type) !void { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.setValue("current_sync_committee", sync_committee), + inline else => |state| try state.setValue("current_sync_committee", sync_committee), }; } - pub fn nextSyncCommittee(self: *AnyBeaconState) !ct.altair.SyncCommittee.TreeView { + pub fn nextSyncCommittee(self: *AnyBeaconState) !*ct.altair.SyncCommittee.TreeView { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.get("next_sync_committee"), + inline else => |state| try state.get("next_sync_committee"), }; } pub fn setNextSyncCommittee(self: *AnyBeaconState, sync_committee: *const ct.altair.SyncCommittee.Type) !void { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| try state.setValue("next_sync_committee", sync_committee), + inline else => |state| try state.setValue("next_sync_committee", sync_committee), }; } pub fn rotateSyncCommittees(self: *AnyBeaconState, next_sync_committee: *const ct.altair.SyncCommittee.Type) !void { return switch (self.*) { .phase0 => error.InvalidAtFork, - inline else => |*state| { + inline else => |state| { const next_sync_committee_root = try state.getRootNode("next_sync_committee"); try state.setRootNode("current_sync_committee", next_sync_committee_root); try state.setValue("next_sync_committee", next_sync_committee); @@ -614,23 +609,23 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn latestExecutionPayloadHeader(self: *AnyBeaconState, allocator: Allocator, out: *AnyExecutionPayloadHeader) !void { return switch (self.*) { .phase0, .altair => error.InvalidAtFork, - .bellatrix => |*state| { + .bellatrix => |state| { out.* = .{ .bellatrix = undefined }; try state.getValue(allocator, "latest_execution_payload_header", &out.bellatrix); }, - .capella => |*state| { + .capella => |state| { out.* = .{ .capella = undefined }; try state.getValue(allocator, "latest_execution_payload_header", &out.capella); }, - .deneb => |*state| { + .deneb => |state| { out.* = .{ .deneb = undefined }; try state.getValue(allocator, "latest_execution_payload_header", &out.deneb); }, - .electra => |*state| { + .electra => |state| { out.* = .{ .deneb = undefined }; try state.getValue(allocator, "latest_execution_payload_header", &out.deneb); }, - .fulu => |*state| { + .fulu => |state| { out.* = .{ .deneb = undefined }; try state.getValue(allocator, "latest_execution_payload_header", &out.deneb); }, @@ -640,20 +635,20 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn latestExecutionPayloadHeaderBlockHash(self: *AnyBeaconState) !*const [32]u8 { return switch (self.*) { .phase0, .altair => error.InvalidAtFork, - inline else => |*state| { + inline else => |state| { var header = try state.get("latest_execution_payload_header"); - return try header.getRoot("block_hash"); + return try header.getFieldRoot("block_hash"); }, }; } pub fn setLatestExecutionPayloadHeader(self: *AnyBeaconState, header: *const AnyExecutionPayloadHeader) !void { switch (self.*) { - .bellatrix => |*state| try state.setValue("latest_execution_payload_header", &header.bellatrix), - .capella => |*state| try state.setValue("latest_execution_payload_header", &header.capella), - .deneb => |*state| try state.setValue("latest_execution_payload_header", &header.deneb), - .electra => |*state| try state.setValue("latest_execution_payload_header", &header.deneb), - .fulu => |*state| try state.setValue("latest_execution_payload_header", &header.deneb), + .bellatrix => |state| try state.setValue("latest_execution_payload_header", &header.bellatrix), + .capella => |state| try state.setValue("latest_execution_payload_header", &header.capella), + .deneb => |state| try state.setValue("latest_execution_payload_header", &header.deneb), + .electra => |state| try state.setValue("latest_execution_payload_header", &header.deneb), + .fulu => |state| try state.setValue("latest_execution_payload_header", &header.deneb), else => return error.InvalidAtFork, } } @@ -661,169 +656,169 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn nextWithdrawalIndex(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix => error.InvalidAtFork, - inline else => |*state| try state.get("next_withdrawal_index"), + inline else => |state| try state.get("next_withdrawal_index"), }; } pub fn setNextWithdrawalIndex(self: *AnyBeaconState, next_withdrawal_index: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix => error.InvalidAtFork, - inline else => |*state| try state.set("next_withdrawal_index", next_withdrawal_index), + inline else => |state| try state.set("next_withdrawal_index", next_withdrawal_index), }; } pub fn nextWithdrawalValidatorIndex(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix => error.InvalidAtFork, - inline else => |*state| try state.get("next_withdrawal_validator_index"), + inline else => |state| try state.get("next_withdrawal_validator_index"), }; } pub fn setNextWithdrawalValidatorIndex(self: *AnyBeaconState, next_withdrawal_validator_index: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix => error.InvalidAtFork, - inline else => |*state| try state.set("next_withdrawal_validator_index", next_withdrawal_validator_index), + inline else => |state| try state.set("next_withdrawal_validator_index", next_withdrawal_validator_index), }; } - pub fn historicalSummaries(self: *AnyBeaconState) !ct.capella.HistoricalSummaries.TreeView { + pub fn historicalSummaries(self: *AnyBeaconState) !*ct.capella.HistoricalSummaries.TreeView { return switch (self.*) { .phase0, .altair, .bellatrix => error.InvalidAtFork, - inline else => |*state| try state.get("historical_summaries"), + inline else => |state| try state.get("historical_summaries"), }; } pub fn depositRequestsStartIndex(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("deposit_requests_start_index"), + inline else => |state| try state.get("deposit_requests_start_index"), }; } pub fn setDepositRequestsStartIndex(self: *AnyBeaconState, index: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("deposit_requests_start_index", index), + inline else => |state| try state.set("deposit_requests_start_index", index), }; } pub fn depositBalanceToConsume(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("deposit_balance_to_consume"), + inline else => |state| try state.get("deposit_balance_to_consume"), }; } pub fn setDepositBalanceToConsume(self: *AnyBeaconState, balance: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("deposit_balance_to_consume", balance), + inline else => |state| try state.set("deposit_balance_to_consume", balance), }; } pub fn exitBalanceToConsume(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("exit_balance_to_consume"), + inline else => |state| try state.get("exit_balance_to_consume"), }; } pub fn setExitBalanceToConsume(self: *AnyBeaconState, balance: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("exit_balance_to_consume", balance), + inline else => |state| try state.set("exit_balance_to_consume", balance), }; } pub fn earliestExitEpoch(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("earliest_exit_epoch"), + inline else => |state| try state.get("earliest_exit_epoch"), }; } pub fn setEarliestExitEpoch(self: *AnyBeaconState, epoch: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("earliest_exit_epoch", epoch), + inline else => |state| try state.set("earliest_exit_epoch", epoch), }; } pub fn consolidationBalanceToConsume(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("consolidation_balance_to_consume"), + inline else => |state| try state.get("consolidation_balance_to_consume"), }; } pub fn setConsolidationBalanceToConsume(self: *AnyBeaconState, balance: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("consolidation_balance_to_consume", balance), + inline else => |state| try state.set("consolidation_balance_to_consume", balance), }; } pub fn earliestConsolidationEpoch(self: *AnyBeaconState) !u64 { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("earliest_consolidation_epoch"), + inline else => |state| try state.get("earliest_consolidation_epoch"), }; } pub fn setEarliestConsolidationEpoch(self: *AnyBeaconState, epoch: u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("earliest_consolidation_epoch", epoch), + inline else => |state| try state.set("earliest_consolidation_epoch", epoch), }; } - pub fn pendingDeposits(self: *AnyBeaconState) !ct.electra.PendingDeposits.TreeView { + pub fn pendingDeposits(self: *AnyBeaconState) !*ct.electra.PendingDeposits.TreeView { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("pending_deposits"), + inline else => |state| try state.get("pending_deposits"), }; } - pub fn setPendingDeposits(self: *AnyBeaconState, deposits: ct.electra.PendingDeposits.TreeView) !void { + pub fn setPendingDeposits(self: *AnyBeaconState, deposits: *ct.electra.PendingDeposits.TreeView) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("pending_deposits", deposits), + inline else => |state| try state.set("pending_deposits", deposits), }; } - pub fn pendingPartialWithdrawals(self: *AnyBeaconState) !ct.electra.PendingPartialWithdrawals.TreeView { + pub fn pendingPartialWithdrawals(self: *AnyBeaconState) !*ct.electra.PendingPartialWithdrawals.TreeView { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("pending_partial_withdrawals"), + inline else => |state| try state.get("pending_partial_withdrawals"), }; } - pub fn setPendingPartialWithdrawals(self: *AnyBeaconState, pending_partial_withdrawals: ct.electra.PendingPartialWithdrawals.TreeView) !void { + pub fn setPendingPartialWithdrawals(self: *AnyBeaconState, pending_partial_withdrawals: *ct.electra.PendingPartialWithdrawals.TreeView) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("pending_partial_withdrawals", pending_partial_withdrawals), + inline else => |state| try state.set("pending_partial_withdrawals", pending_partial_withdrawals), }; } - pub fn pendingConsolidations(self: *AnyBeaconState) !ct.electra.PendingConsolidations.TreeView { + pub fn pendingConsolidations(self: *AnyBeaconState) !*ct.electra.PendingConsolidations.TreeView { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.get("pending_consolidations"), + inline else => |state| try state.get("pending_consolidations"), }; } - pub fn setPendingConsolidations(self: *AnyBeaconState, consolidations: ct.electra.PendingConsolidations.TreeView) !void { + pub fn setPendingConsolidations(self: *AnyBeaconState, consolidations: *ct.electra.PendingConsolidations.TreeView) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb => error.InvalidAtFork, - inline else => |*state| try state.set("pending_consolidations", consolidations), + inline else => |state| try state.set("pending_consolidations", consolidations), }; } /// Get proposer_lookahead - pub fn proposerLookahead(self: *AnyBeaconState) !ct.fulu.ProposerLookahead.TreeView { + pub fn proposerLookahead(self: *AnyBeaconState) !*ct.fulu.ProposerLookahead.TreeView { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb, .electra => error.InvalidAtFork, - inline else => |*state| try state.get("proposer_lookahead"), + inline else => |state| try state.get("proposer_lookahead"), }; } @@ -837,7 +832,7 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn setProposerLookahead(self: *AnyBeaconState, proposer_lookahead: *const [ct.fulu.ProposerLookahead.length]u64) !void { return switch (self.*) { .phase0, .altair, .bellatrix, .capella, .deneb, .electra => error.InvalidAtFork, - inline else => |*state| try state.setValue("proposer_lookahead", proposer_lookahead), + inline else => |state| try state.setValue("proposer_lookahead", proposer_lookahead), }; } @@ -848,11 +843,10 @@ pub const AnyBeaconState = union(ForkSeq) { comptime T: type, allocator: Allocator, pool: *Node.Pool, - state: F.TreeView, - ) !T.TreeView { + state: *F.TreeView, + ) !*T.TreeView { // first ensure that the source state is committed - var committed_state = state; - try committed_state.commit(); + try state.commit(); var upgraded = try T.TreeView.fromValue(allocator, pool, &T.default_value); errdefer upgraded.deinit(); @@ -868,11 +862,11 @@ pub const AnyBeaconState = union(ForkSeq) { if (comptime isBasicType(f.type)) { // For basic fields, get() returns a copy, so we can directly set it. - try upgraded.set(f.name, try committed_state.get(f.name)); + try upgraded.set(f.name, try state.get(f.name)); } else { - // For composite fields, get() returns a borrowed TreeView backed by committed_state caches. + // For composite fields, get() returns a borrowed *TreeView backed by state caches. // Clone it to create an owned view, then transfer ownership to upgraded. - var field_view = try committed_state.get(f.name); + var field_view = try state.get(f.name); var owned_field_view = try field_view.clone(.{ .transfer_cache = true }); errdefer owned_field_view.deinit(); try upgraded.set(f.name, owned_field_view); @@ -895,8 +889,8 @@ pub const AnyBeaconState = union(ForkSeq) { .altair = try populateFields( ct.phase0.BeaconState, ct.altair.BeaconState, - state.base_view.allocator, - state.base_view.pool, + state.allocator, + state.pool, state, ), }, @@ -904,8 +898,8 @@ pub const AnyBeaconState = union(ForkSeq) { .bellatrix = try populateFields( ct.altair.BeaconState, ct.bellatrix.BeaconState, - state.base_view.allocator, - state.base_view.pool, + state.allocator, + state.pool, state, ), }, @@ -913,8 +907,8 @@ pub const AnyBeaconState = union(ForkSeq) { .capella = try populateFields( ct.bellatrix.BeaconState, ct.capella.BeaconState, - state.base_view.allocator, - state.base_view.pool, + state.allocator, + state.pool, state, ), }, @@ -922,8 +916,8 @@ pub const AnyBeaconState = union(ForkSeq) { .deneb = try populateFields( ct.capella.BeaconState, ct.deneb.BeaconState, - state.base_view.allocator, - state.base_view.pool, + state.allocator, + state.pool, state, ), }, @@ -931,8 +925,8 @@ pub const AnyBeaconState = union(ForkSeq) { .electra = try populateFields( ct.deneb.BeaconState, ct.electra.BeaconState, - state.base_view.allocator, - state.base_view.pool, + state.allocator, + state.pool, state, ), }, @@ -940,8 +934,8 @@ pub const AnyBeaconState = union(ForkSeq) { .fulu = try populateFields( ct.electra.BeaconState, ct.fulu.BeaconState, - state.base_view.allocator, - state.base_view.pool, + state.allocator, + state.pool, state, ), }, diff --git a/src/fork_types/beacon_state.zig b/src/fork_types/beacon_state.zig index 202f0f446..0b7b1191f 100644 --- a/src/fork_types/beacon_state.zig +++ b/src/fork_types/beacon_state.zig @@ -3,7 +3,7 @@ const preset = @import("preset").preset; const ForkSeq = @import("config").ForkSeq; const Node = @import("persistent_merkle_tree").Node; const isBasicType = @import("ssz").isBasicType; -const BaseTreeView = @import("ssz").BaseTreeView; +const CloneOpts = @import("ssz").CloneOpts; const ct = @import("consensus_types"); const ForkTypes = @import("./fork_types.zig").ForkTypes; @@ -12,23 +12,11 @@ pub fn BeaconState(comptime f: ForkSeq) type { return struct { const Self = @This(); - inner: ForkTypes(f).BeaconState.TreeView, + inner: *ForkTypes(f).BeaconState.TreeView, pub const fork_seq = f; - pub fn fromBaseView(base_view: BaseTreeView) Self { - return .{ - .inner = ForkTypes(f).BeaconState.TreeView{ - .base_view = base_view, - }, - }; - } - - pub fn baseView(self: *Self) BaseTreeView { - return self.inner.base_view; - } - - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { + pub fn clone(self: *Self, opts: CloneOpts) !Self { return .{ .inner = try self.inner.clone(opts) }; } @@ -49,7 +37,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { } pub fn genesisValidatorsRoot(self: *Self) !*const [32]u8 { - return try self.inner.getRoot("genesis_validators_root"); + return try self.inner.getFieldRoot("genesis_validators_root"); } pub fn slot(self: *Self) !u64 { @@ -60,13 +48,13 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.set("slot", s); } - pub fn fork(self: *Self) !ForkTypes(f).Fork.TreeView { + pub fn fork(self: *Self) !*ForkTypes(f).Fork.TreeView { return try self.inner.get("fork"); } pub fn forkCurrentVersion(self: *Self) ![4]u8 { var fork_view = try self.inner.getReadonly("fork"); - const current_version_root = try fork_view.getRoot("current_version"); + const current_version_root = try fork_view.getFieldRoot("current_version"); var version: [4]u8 = undefined; @memcpy(&version, current_version_root[0..4]); return version; @@ -76,7 +64,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.setValue("fork", new_fork); } - pub fn latestBlockHeader(self: *Self) !ForkTypes(f).BeaconBlockHeader.TreeView { + pub fn latestBlockHeader(self: *Self) !*ForkTypes(f).BeaconBlockHeader.TreeView { return try self.inner.get("latest_block_header"); } @@ -84,27 +72,27 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.setValue("latest_block_header", header); } - pub fn blockRoots(self: *Self) !ForkTypes(f).HistoricalBlockRoots.TreeView { + pub fn blockRoots(self: *Self) !*ForkTypes(f).HistoricalBlockRoots.TreeView { return try self.inner.get("block_roots"); } pub fn blockRootsRoot(self: *Self) !*const [32]u8 { - return try self.inner.getRoot("block_roots"); + return try self.inner.getFieldRoot("block_roots"); } - pub fn stateRoots(self: *Self) !ForkTypes(f).HistoricalStateRoots.TreeView { + pub fn stateRoots(self: *Self) !*ForkTypes(f).HistoricalStateRoots.TreeView { return try self.inner.get("state_roots"); } pub fn stateRootsRoot(self: *Self) !*const [32]u8 { - return try self.inner.getRoot("state_roots"); + return try self.inner.getFieldRoot("state_roots"); } - pub fn historicalRoots(self: *Self) !ct.phase0.HistoricalRoots.TreeView { + pub fn historicalRoots(self: *Self) !*ct.phase0.HistoricalRoots.TreeView { return try self.inner.get("historical_roots"); } - pub fn eth1Data(self: *Self) !ForkTypes(f).Eth1Data.TreeView { + pub fn eth1Data(self: *Self) !*ForkTypes(f).Eth1Data.TreeView { return try self.inner.get("eth1_data"); } @@ -112,7 +100,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.setValue("eth1_data", eth1_data); } - pub fn eth1DataVotes(self: *Self) !ForkTypes(f).Eth1DataVotes.TreeView { + pub fn eth1DataVotes(self: *Self) !*ForkTypes(f).Eth1DataVotes.TreeView { return try self.inner.get("eth1_data_votes"); } @@ -141,7 +129,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.setEth1DepositIndex(try self.eth1DepositIndex() + 1); } - pub fn validators(self: *Self) !ForkTypes(f).Validators.TreeView { + pub fn validators(self: *Self) !*ForkTypes(f).Validators.TreeView { return try self.inner.get("validators"); } @@ -155,7 +143,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { return validators_view.getAllReadonlyValues(allocator); } - pub fn balances(self: *Self) !ForkTypes(f).Balances.TreeView { + pub fn balances(self: *Self) !*ForkTypes(f).Balances.TreeView { return try self.inner.get("balances"); } @@ -169,7 +157,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.setValue("balances", b); } - pub fn randaoMixes(self: *Self) !ForkTypes(f).RandaoMixes.TreeView { + pub fn randaoMixes(self: *Self) !*ForkTypes(f).RandaoMixes.TreeView { return try self.inner.get("randao_mixes"); } @@ -178,16 +166,16 @@ pub fn BeaconState(comptime f: ForkSeq) type { try mixes.setValue(epoch % preset.EPOCHS_PER_HISTORICAL_VECTOR, randao_mix); } - pub fn slashings(self: *Self) !ForkTypes(f).Slashings.TreeView { + pub fn slashings(self: *Self) !*ForkTypes(f).Slashings.TreeView { return try self.inner.get("slashings"); } - pub fn previousEpochPendingAttestations(self: *Self) !ForkTypes(.phase0).EpochAttestations.TreeView { + pub fn previousEpochPendingAttestations(self: *Self) !*ForkTypes(.phase0).EpochAttestations.TreeView { if (comptime f != .phase0) return error.InvalidAtFork; return try self.inner.get("previous_epoch_attestations"); } - pub fn currentEpochPendingAttestations(self: *Self) !ForkTypes(.phase0).EpochAttestations.TreeView { + pub fn currentEpochPendingAttestations(self: *Self) !*ForkTypes(.phase0).EpochAttestations.TreeView { if (comptime f != .phase0) return error.InvalidAtFork; return try self.inner.get("current_epoch_attestations"); } @@ -199,7 +187,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.setValue("current_epoch_attestations", &ForkTypes(.phase0).EpochAttestations.default_value); } - pub fn previousEpochParticipation(self: *Self) !ForkTypes(.altair).EpochParticipation.TreeView { + pub fn previousEpochParticipation(self: *Self) !*ForkTypes(.altair).EpochParticipation.TreeView { if (comptime f == .phase0) return error.InvalidAtFork; return try self.inner.get("previous_epoch_participation"); } @@ -209,7 +197,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.setValue("previous_epoch_participation", participations); } - pub fn currentEpochParticipation(self: *Self) !ForkTypes(.altair).EpochParticipation.TreeView { + pub fn currentEpochParticipation(self: *Self) !*ForkTypes(.altair).EpochParticipation.TreeView { if (comptime f == .phase0) return error.InvalidAtFork; return try self.inner.get("current_epoch_participation"); } @@ -223,22 +211,24 @@ pub fn BeaconState(comptime f: ForkSeq) type { if (comptime f == .phase0) return error.InvalidAtFork; var current_epoch_participation = try self.inner.get("current_epoch_participation"); - try current_epoch_participation.commit(); + // try current_epoch_participation.commit(); const length = try current_epoch_participation.length(); - try self.inner.set( - "previous_epoch_participation", - try current_epoch_participation.clone(.{ .transfer_cache = true }), - ); + + // Clone the view to preserve any uncommitted in-memory updates while avoiding pointer aliasing + // between previous/current fields. + var current_epoch_participation_copy = try current_epoch_participation.clone(.{ .transfer_cache = true }); + errdefer current_epoch_participation_copy.deinit(); + try self.inner.set("previous_epoch_participation", current_epoch_participation_copy); const new_current_root = try ForkTypes(.altair).EpochParticipation.tree.zeros( - self.inner.base_view.pool, + self.inner.pool, length, ); - errdefer self.inner.base_view.pool.unref(new_current_root); + errdefer self.inner.pool.unref(new_current_root); try self.inner.setRootNode("current_epoch_participation", new_current_root); } - pub fn justificationBits(self: *Self) !ct.phase0.JustificationBits.TreeView { + pub fn justificationBits(self: *Self) !*ct.phase0.JustificationBits.TreeView { return try self.inner.get("justification_bits"); } @@ -275,12 +265,12 @@ pub fn BeaconState(comptime f: ForkSeq) type { return try checkpoint_view.get("epoch"); } - pub fn inactivityScores(self: *Self) !ForkTypes(.altair).InactivityScores.TreeView { + pub fn inactivityScores(self: *Self) !*ForkTypes(.altair).InactivityScores.TreeView { if (comptime f == .phase0) return error.InvalidAtFork; return try self.inner.get("inactivity_scores"); } - pub fn currentSyncCommittee(self: *Self) !ForkTypes(.altair).SyncCommittee.TreeView { + pub fn currentSyncCommittee(self: *Self) !*ForkTypes(.altair).SyncCommittee.TreeView { if (comptime f == .phase0) return error.InvalidAtFork; return try self.inner.get("current_sync_committee"); } @@ -290,7 +280,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.setValue("current_sync_committee", sync_committee); } - pub fn nextSyncCommittee(self: *Self) !ForkTypes(.altair).SyncCommittee.TreeView { + pub fn nextSyncCommittee(self: *Self) !*ForkTypes(.altair).SyncCommittee.TreeView { if (comptime f == .phase0) return error.InvalidAtFork; return try self.inner.get("next_sync_committee"); } @@ -302,8 +292,10 @@ pub fn BeaconState(comptime f: ForkSeq) type { pub fn rotateSyncCommittees(self: *Self, next_sync_committee: *const ForkTypes(.altair).SyncCommittee.Type) !void { if (comptime f == .phase0) return error.InvalidAtFork; - const next_sync_committee_root = try self.inner.getRootNode("next_sync_committee"); - try self.inner.setRootNode("current_sync_committee", next_sync_committee_root); + var next_sync_committee_view = try self.inner.get("next_sync_committee"); + var next_sync_committee_copy = try next_sync_committee_view.clone(.{ .transfer_cache = true }); + errdefer next_sync_committee_copy.deinit(); + try self.inner.set("current_sync_committee", next_sync_committee_copy); try self.inner.setValue("next_sync_committee", next_sync_committee); } @@ -315,7 +307,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { pub fn latestExecutionPayloadHeaderBlockHash(self: *Self) !*const [32]u8 { if (comptime (f.lt(.bellatrix))) return error.InvalidAtFork; var header = try self.inner.get("latest_execution_payload_header"); - return try header.getRoot("block_hash"); + return try header.getFieldRoot("block_hash"); } pub fn setLatestExecutionPayloadHeader(self: *Self, header: *const ForkTypes(f).ExecutionPayloadHeader.Type) !void { @@ -343,7 +335,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.set("next_withdrawal_validator_index", next_withdrawal_validator_index); } - pub fn historicalSummaries(self: *Self) !ForkTypes(.capella).HistoricalSummaries.TreeView { + pub fn historicalSummaries(self: *Self) !*ForkTypes(.capella).HistoricalSummaries.TreeView { if (comptime (f == .phase0 or f == .altair or f == .bellatrix)) return error.InvalidAtFork; return try self.inner.get("historical_summaries"); } @@ -408,37 +400,37 @@ pub fn BeaconState(comptime f: ForkSeq) type { try self.inner.set("earliest_consolidation_epoch", epoch); } - pub fn pendingDeposits(self: *Self) !ForkTypes(.electra).PendingDeposits.TreeView { + pub fn pendingDeposits(self: *Self) !*ForkTypes(.electra).PendingDeposits.TreeView { if (comptime (f == .phase0 or f == .altair or f == .bellatrix or f == .capella or f == .deneb)) return error.InvalidAtFork; return try self.inner.get("pending_deposits"); } - pub fn setPendingDeposits(self: *Self, deposits: ForkTypes(.electra).PendingDeposits.TreeView) !void { + pub fn setPendingDeposits(self: *Self, deposits: *ForkTypes(.electra).PendingDeposits.TreeView) !void { if (comptime (f == .phase0 or f == .altair or f == .bellatrix or f == .capella or f == .deneb)) return error.InvalidAtFork; try self.inner.set("pending_deposits", deposits); } - pub fn pendingPartialWithdrawals(self: *Self) !ForkTypes(.electra).PendingPartialWithdrawals.TreeView { + pub fn pendingPartialWithdrawals(self: *Self) !*ForkTypes(.electra).PendingPartialWithdrawals.TreeView { if (comptime (f == .phase0 or f == .altair or f == .bellatrix or f == .capella or f == .deneb)) return error.InvalidAtFork; return try self.inner.get("pending_partial_withdrawals"); } - pub fn setPendingPartialWithdrawals(self: *Self, pending_partial_withdrawals: ForkTypes(.electra).PendingPartialWithdrawals.TreeView) !void { + pub fn setPendingPartialWithdrawals(self: *Self, pending_partial_withdrawals: *ForkTypes(.electra).PendingPartialWithdrawals.TreeView) !void { if (comptime (f == .phase0 or f == .altair or f == .bellatrix or f == .capella or f == .deneb)) return error.InvalidAtFork; try self.inner.set("pending_partial_withdrawals", pending_partial_withdrawals); } - pub fn pendingConsolidations(self: *Self) !ForkTypes(.electra).PendingConsolidations.TreeView { + pub fn pendingConsolidations(self: *Self) !*ForkTypes(.electra).PendingConsolidations.TreeView { if (comptime (f == .phase0 or f == .altair or f == .bellatrix or f == .capella or f == .deneb)) return error.InvalidAtFork; return try self.inner.get("pending_consolidations"); } - pub fn setPendingConsolidations(self: *Self, consolidations: ForkTypes(.electra).PendingConsolidations.TreeView) !void { + pub fn setPendingConsolidations(self: *Self, consolidations: *ForkTypes(.electra).PendingConsolidations.TreeView) !void { if (comptime (f == .phase0 or f == .altair or f == .bellatrix or f == .capella or f == .deneb)) return error.InvalidAtFork; try self.inner.set("pending_consolidations", consolidations); } - pub fn proposerLookahead(self: *Self) !ForkTypes(.fulu).ProposerLookahead.TreeView { + pub fn proposerLookahead(self: *Self) !*ForkTypes(.fulu).ProposerLookahead.TreeView { if (comptime (f == .phase0 or f == .altair or f == .bellatrix or f == .capella or f == .deneb or f == .electra)) return error.InvalidAtFork; return try self.inner.get("proposer_lookahead"); } @@ -458,8 +450,8 @@ pub fn BeaconState(comptime f: ForkSeq) type { comptime T: type, allocator: std.mem.Allocator, pool: *Node.Pool, - state: F.TreeView, - ) !T.TreeView { + state: *F.TreeView, + ) !*T.TreeView { var committed_state = state; try committed_state.commit(); @@ -495,8 +487,8 @@ pub fn BeaconState(comptime f: ForkSeq) type { .fulu => .fulu, }) { const cur = self.inner; - const allocator = cur.base_view.allocator; - const pool = cur.base_view.pool; + const allocator = cur.allocator; + const pool = cur.pool; return switch (comptime f) { .phase0 => .{ .inner = try populateFields(ForkTypes(.phase0).BeaconState, ForkTypes(.altair).BeaconState, allocator, pool, cur) }, diff --git a/src/ssz/root.zig b/src/ssz/root.zig index f49da017c..4c6b9237c 100644 --- a/src/ssz/root.zig +++ b/src/ssz/root.zig @@ -41,13 +41,12 @@ pub const Hasher = hasher.Hasher; pub const HasherData = hasher.HasherData; const tree_view = @import("tree_view/root.zig"); -pub const TreeViewData = tree_view.TreeViewData; -pub const BaseTreeView = tree_view.BaseTreeView; pub const ContainerTreeView = tree_view.ContainerTreeView; pub const ArrayBasicTreeView = tree_view.ArrayBasicTreeView; pub const ArrayCompositeTreeView = tree_view.ArrayCompositeTreeView; pub const ListBasicTreeView = tree_view.ListBasicTreeView; pub const ListCompositeTreeView = tree_view.ListCompositeTreeView; +pub const CloneOpts = @import("tree_view/utils/clone_opts.zig").CloneOpts; test { testing.refAllDecls(@This()); diff --git a/src/ssz/tree_view/array_basic.zig b/src/ssz/tree_view/array_basic.zig index bd2d31749..80dd39cb9 100644 --- a/src/ssz/tree_view/array_basic.zig +++ b/src/ssz/tree_view/array_basic.zig @@ -9,8 +9,9 @@ const type_root = @import("../type/root.zig"); const itemsPerChunk = type_root.itemsPerChunk; const chunkDepth = type_root.chunkDepth; -const BaseTreeView = @import("root.zig").BaseTreeView; const BasicPackedChunks = @import("chunks.zig").BasicPackedChunks; +const assertTreeViewType = @import("utils/assert.zig").assertTreeViewType; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// A specialized tree view for SSZ vector types with basic element types. /// Elements are packed into chunks (multiple elements per leaf node). @@ -24,8 +25,9 @@ pub fn ArrayBasicTreeView(comptime ST: type) type { } } - return struct { - base_view: BaseTreeView, + const TreeView = struct { + allocator: Allocator, + chunks: Chunks, pub const SszType = ST; pub const Element = ST.Element.Type; @@ -38,69 +40,95 @@ pub fn ArrayBasicTreeView(comptime ST: type) type { const items_per_chunk: usize = itemsPerChunk(ST.Element); const Chunks = BasicPackedChunks(ST, chunk_depth, items_per_chunk); - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !Self { - return Self{ - .base_view = try BaseTreeView.init(allocator, pool, root), - }; + pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self { + const ptr = try allocator.create(Self); + errdefer allocator.destroy(ptr); + + try Chunks.init(&ptr.chunks, allocator, pool, root); + ptr.allocator = allocator; + return ptr; } - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { - return Self{ .base_view = try self.base_view.clone(opts) }; + pub fn clone(self: *Self, opts: CloneOpts) !*Self { + const ptr = try self.allocator.create(Self); + errdefer self.allocator.destroy(ptr); + + try Chunks.clone(&self.chunks, opts, &ptr.chunks); + ptr.allocator = self.allocator; + return ptr; } pub fn deinit(self: *Self) void { - self.base_view.deinit(); + self.chunks.deinit(); + self.allocator.destroy(self); } pub fn commit(self: *Self) !void { - try self.base_view.commit(); + try self.chunks.commit(); } pub fn clearCache(self: *Self) void { - self.base_view.clearCache(); + self.chunks.clearCache(); + } + + pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { + try self.commit(); + out.* = self.chunks.root.getRoot(self.chunks.pool).*; } - /// Return the root hash of the tree. - /// The returned array is owned by the internal pool and must not be modified. pub fn hashTreeRoot(self: *Self) !*const [32]u8 { - return try self.base_view.hashTreeRoot(); + try self.commit(); + return self.chunks.root.getRoot(self.chunks.pool); + } + + pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { + const root = try ST.tree.fromValue(pool, value); + errdefer pool.unref(root); + return try Self.init(allocator, pool, root); + } + + pub fn toValue(self: *Self, _: Allocator, out: *ST.Type) !void { + try self.commit(); + try ST.tree.toValue(self.chunks.root, self.chunks.pool, out); + } + + pub fn getRoot(self: *const Self) Node.Id { + return self.chunks.root; } pub fn get(self: *Self, index: usize) !Element { if (index >= length) return error.IndexOutOfBounds; - return try Chunks.get(&self.base_view, index); + return self.chunks.get(index); } pub fn set(self: *Self, index: usize, value: Element) !void { if (index >= length) return error.IndexOutOfBounds; - try Chunks.set(&self.base_view, index, value); + try self.chunks.set(index, value); } - pub fn getAll(self: *Self, allocator: Allocator) ![]Element { - return try Chunks.getAll(&self.base_view, allocator, length); + pub fn getAll(self: *Self, allocator: ?Allocator) ![]Element { + return try self.chunks.getAll(allocator orelse self.allocator, length); } pub fn getAllInto(self: *Self, values: []Element) ![]Element { - return try Chunks.getAllInto(&self.base_view, length, values); + return try self.chunks.getAllInto(length, values); } /// Serialize the tree view into a provided buffer. /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.base_view.data.root, self.base_view.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); } /// Get the serialized size of this tree view. pub fn serializedSize(_: *Self) usize { return ST.fixed_size; } - - pub fn toValue(self: *Self, _: Allocator, out: *ST.Type) !void { - try self.commit(); - try ST.tree.toValue(self.base_view.data.root, self.base_view.pool, out); - } }; + + assertTreeViewType(TreeView); + return TreeView; } const UintType = @import("../type/uint.zig").UintType; @@ -135,12 +163,13 @@ test "TreeView vector element roundtrip" { var expected_root: [32]u8 = undefined; try VectorType.hashTreeRoot(&expected, &expected_root); - const actual_root = try view.hashTreeRoot(); + var actual_root: [32]u8 = undefined; + try view.hashTreeRootInto(&actual_root); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); var roundtrip: VectorType.Type = undefined; - try VectorType.tree.toValue(view.base_view.data.root, &pool, &roundtrip); + try VectorType.tree.toValue(view.getRoot(), &pool, &roundtrip); try std.testing.expectEqualSlices(u64, &expected, &roundtrip); } @@ -183,7 +212,7 @@ test "TreeView vector getAllAlloc roundtrip" { var view = try VectorType.TreeView.init(allocator, &pool, root_node); defer view.deinit(); - const filled = try view.getAll(allocator); + const filled = try view.getAll(null); defer allocator.free(filled); try std.testing.expectEqualSlices(u16, values[0..], filled); @@ -202,14 +231,13 @@ test "TreeView vector getAllAlloc repeat reflects updates" { var view = try VectorType.TreeView.init(allocator, &pool, root_node); defer view.deinit(); - const first = try view.getAll(allocator); + const first = try view.getAll(null); defer allocator.free(first); try std.testing.expectEqualSlices(u32, values[0..], first); try view.set(3, 99); - try view.commit(); - const second = try view.getAll(allocator); + const second = try view.getAll(null); defer allocator.free(second); values[3] = 99; try std.testing.expectEqualSlices(u32, values[0..], second); @@ -301,13 +329,13 @@ test "TreeView vector clone(true) does not transfer cache" { defer v.deinit(); _ = try v.get(0); - try std.testing.expect(v.base_view.data.children_nodes.count() > 0); + try std.testing.expect(v.chunks.children_nodes.count() > 0); var cloned_no_cache = try v.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(v.base_view.data.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.base_view.data.children_nodes.count()); + try std.testing.expect(v.chunks.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.children_nodes.count()); } test "TreeView vector clone(false) transfers cache and clears source" { @@ -325,13 +353,13 @@ test "TreeView vector clone(false) transfers cache and clears source" { defer v.deinit(); _ = try v.get(0); - try std.testing.expect(v.base_view.data.children_nodes.count() > 0); + try std.testing.expect(v.chunks.children_nodes.count() > 0); var cloned = try v.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), v.base_view.data.children_nodes.count()); - try std.testing.expect(cloned.base_view.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), v.chunks.children_nodes.count()); + try std.testing.expect(cloned.chunks.children_nodes.count() > 0); } // Tests ported from TypeScript ssz packages/ssz/test/unit/byType/vector/tree.test.ts @@ -382,8 +410,9 @@ test "ArrayBasicTreeView - serialize (uint64 vector)" { const view_size = view.serializedSize(); try std.testing.expectEqual(tc.expected_serialized.len, view_size); - const hash_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &tc.expected_root, hash_root); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); + try std.testing.expectEqualSlices(u8, &tc.expected_root, &hash_root); } } diff --git a/src/ssz/tree_view/array_composite.zig b/src/ssz/tree_view/array_composite.zig index d80919c7e..a28fc4e92 100644 --- a/src/ssz/tree_view/array_composite.zig +++ b/src/ssz/tree_view/array_composite.zig @@ -11,8 +11,9 @@ const type_root = @import("../type/root.zig"); const chunkDepth = type_root.chunkDepth; const tree_view_root = @import("root.zig"); -const BaseTreeView = tree_view_root.BaseTreeView; const CompositeChunks = @import("chunks.zig").CompositeChunks; +const assertTreeViewType = @import("utils/assert.zig").assertTreeViewType; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// A specialized tree view for SSZ vector types with composite element types. /// Each element occupies its own subtree. @@ -24,13 +25,16 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { if (!@hasDecl(ST, "Element") or isBasicType(ST.Element)) { @compileError("ArrayCompositeTreeView can only be used with Vector of composite element types"); } + + assertTreeViewType(ST.Element.TreeView); } - return struct { - base_view: BaseTreeView, + const TreeView = struct { + allocator: Allocator, + chunks: Chunks, pub const SszType = ST; - pub const Element = ST.Element.TreeView; + pub const Element = *ST.Element.TreeView; pub const length = ST.length; const Self = @This(); @@ -39,88 +43,114 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { const chunk_depth: Depth = chunkDepth(Depth, base_chunk_depth, ST); const Chunks = CompositeChunks(ST, chunk_depth); - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !Self { - return .{ - .base_view = try BaseTreeView.init(allocator, pool, root), - }; + pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self { + const ptr = try allocator.create(Self); + errdefer allocator.destroy(ptr); + + try Chunks.init(&ptr.chunks, allocator, pool, root); + ptr.allocator = allocator; + return ptr; } - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { - return Self{ .base_view = try self.base_view.clone(opts) }; + pub fn clone(self: *Self, opts: CloneOpts) !*Self { + const ptr = try self.allocator.create(Self); + errdefer self.allocator.destroy(ptr); + + try Chunks.clone(&self.chunks, opts, &ptr.chunks); + ptr.allocator = self.allocator; + return ptr; } pub fn deinit(self: *Self) void { - self.base_view.deinit(); + self.chunks.deinit(); + self.allocator.destroy(self); } pub fn commit(self: *Self) !void { - try self.base_view.commit(); + try self.chunks.commit(); } pub fn clearCache(self: *Self) void { - self.base_view.clearCache(); + self.chunks.clearCache(); + } + + pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { + try self.commit(); + out.* = self.chunks.root.getRoot(self.chunks.pool).*; } - /// Return the root hash of the tree. - /// The returned array is owned by the internal pool and must not be modified. pub fn hashTreeRoot(self: *Self) !*const [32]u8 { - return try self.base_view.hashTreeRoot(); + try self.commit(); + return self.chunks.root.getRoot(self.chunks.pool); } - pub fn getRoot(self: *Self, index: usize) !*const [32]u8 { - if (index >= length) return error.IndexOutOfBounds; - const field_data = try self.base_view.getChildData(Gindex.fromDepth(chunk_depth, index)); - try field_data.commit(self.base_view.allocator, self.base_view.pool); - return field_data.root.getRoot(self.base_view.pool); + pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { + const root = if (comptime isFixedType(ST)) + try ST.tree.fromValue(pool, value) + else + try ST.tree.fromValue(allocator, pool, value); + errdefer pool.unref(root); + return try Self.init(allocator, pool, root); + } + + pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { + try self.commit(); + if (comptime isFixedType(ST)) { + try ST.tree.toValue(self.chunks.root, self.chunks.pool, out); + } else { + try ST.tree.toValue(allocator, self.chunks.root, self.chunks.pool, out); + } + } + + pub fn getRoot(self: *const Self) Node.Id { + return self.chunks.root; } pub fn get(self: *Self, index: usize) !Element { if (index >= length) return error.IndexOutOfBounds; - return try Chunks.get(&self.base_view, index); + return self.chunks.get(index); } pub fn getReadonly(self: *Self, index: usize) !Element { if (index >= length) return error.IndexOutOfBounds; - return try Chunks.getReadonly(&self.base_view, index); + return self.chunks.getReadonly(index); } pub fn getValue(self: *Self, allocator: Allocator, index: usize, out: *ST.Element.Type) !void { if (index >= length) return error.IndexOutOfBounds; - return try Chunks.getValue(&self.base_view, allocator, index, out); + return self.chunks.getValue(allocator, index, out); } - pub fn set(self: *Self, index: usize, value: Element) !void { + pub fn setValue(self: *Self, index: usize, value: *const ST.Element.Type) !void { if (index >= length) return error.IndexOutOfBounds; - try Chunks.set(&self.base_view, index, value); + try self.chunks.setValue(index, value); } - pub fn setValue(self: *Self, index: usize, value: *const ST.Element.Type) !void { + pub fn getFieldRoot(self: *Self, index: usize) !*const [32]u8 { + if (index >= length) return error.IndexOutOfBounds; + const elem = try self.chunks.get(index); + try elem.commit(); + return elem.getRoot().getRoot(self.chunks.pool); + } + + pub fn set(self: *Self, index: usize, value: Element) !void { if (index >= length) return error.IndexOutOfBounds; - try Chunks.setValue(&self.base_view, index, value); + try self.chunks.set(index, value); } pub fn getAllReadonly(self: *Self, allocator: Allocator) ![]Element { - // TODO: Implement bulk read-only access after other PRs land. - _ = self; - _ = allocator; - return error.NotImplemented; + return self.chunks.getAllReadonly(allocator, length); } - /// Get all element values in a single traversal. - /// - /// WARNING: Returns all committed changes. If there are any pending changes, - /// commit them beforehand. - /// - /// Caller owns the returned slice and must free it with the same allocator. pub fn getAllReadonlyValues(self: *Self, allocator: Allocator) ![]ST.Element.Type { - return try Chunks.getAllValues(&self.base_view, allocator, length); + return self.chunks.getAllValues(allocator, length); } /// Serialize the tree view into a provided buffer. /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.base_view.data.root, self.base_view.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); } /// Get the serialized size of this tree view. @@ -129,19 +159,13 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { if (comptime isFixedType(ST)) { return ST.fixed_size; } else { - return try ST.tree.serializedSize(self.base_view.data.root, self.base_view.pool); - } - } - - pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { - try self.commit(); - if (comptime isFixedType(ST)) { - try ST.tree.toValue(self.base_view.data.root, self.base_view.pool, out); - } else { - try ST.tree.toValue(allocator, self.base_view.data.root, self.base_view.pool, out); + return ST.tree.serializedSize(self.chunks.root, self.chunks.pool); } } }; + + assertTreeViewType(TreeView); + return TreeView; } const UintType = @import("../type/uint.zig").UintType; @@ -171,28 +195,29 @@ test "TreeView vector composite element set/get/commit" { const e0_view = try view.get(0); var e0_value: Inner.Type = undefined; - try Inner.tree.toValue(e0_view.base_view.data.root, &pool, &e0_value); + try Inner.tree.toValue(e0_view.getRoot(), &pool, &e0_value); try std.testing.expectEqual(@as(u32, 1), e0_value.a); try std.testing.expectEqualSlices(u8, &[_]u8{ 1, 1, 1, 1 }, e0_value.b[0..]); const replacement: Inner.Type = .{ .a = 9, .b = [_]u8{ 9, 9, 9, 9 } }; const replacement_root = try Inner.tree.fromValue(&pool, &replacement); - var replacement_view: ?Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v| v.deinit(); + var replacement_view: ?*Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v| v.deinit(); try view.set(1, replacement_view.?); replacement_view = null; try view.commit(); - const actual_root = try view.hashTreeRoot(); + var actual_root: [32]u8 = undefined; + try view.hashTreeRootInto(&actual_root); var expected: VectorType.Type = .{ v0, replacement }; var expected_root: [32]u8 = undefined; try VectorType.hashTreeRoot(&expected, &expected_root); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); var roundtrip: VectorType.Type = undefined; - try VectorType.tree.toValue(view.base_view.data.root, &pool, &roundtrip); + try VectorType.tree.toValue(view.getRoot(), &pool, &roundtrip); try std.testing.expectEqual(@as(u32, 1), roundtrip[0].a); try std.testing.expectEqual(@as(u32, 9), roundtrip[1].a); try std.testing.expectEqualSlices(u8, &[_]u8{ 9, 9, 9, 9 }, roundtrip[1].b[0..]); @@ -215,8 +240,8 @@ test "TreeView vector composite index bounds" { const replacement: Inner.Type = .{ .x = 3 }; const replacement_root = try Inner.tree.fromValue(&pool, &replacement); - var replacement_view: ?Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v| v.deinit(); + const replacement_view: ?*Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v| v.deinit(); try std.testing.expectError(error.IndexOutOfBounds, view.set(2, replacement_view.?)); } @@ -245,17 +270,18 @@ test "TreeView vector composite clearCache does not break subsequent commits" { const replacement: Inner.Type = .{ .id = 1, .vec = [_]u32{ 0, 9 } }; const replacement_root = try Inner.tree.fromValue(&pool, &replacement); - var replacement_view: ?Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v| v.deinit(); + var replacement_view: ?*Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v| v.deinit(); try view.set(0, replacement_view.?); replacement_view = null; - const actual_root = try view.hashTreeRoot(); + var actual_root: [32]u8 = undefined; + try view.hashTreeRootInto(&actual_root); var expected: VectorType.Type = .{ replacement, v1 }; var expected_root: [32]u8 = undefined; try VectorType.hashTreeRoot(&expected, &expected_root); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); } test "TreeView vector composite clone isolates updates" { @@ -278,8 +304,8 @@ test "TreeView vector composite clone isolates updates" { const replacement: Inner.Type = .{ .a = 9 }; const replacement_root = try Inner.tree.fromValue(&pool, &replacement); - var replacement_view: ?Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v| v.deinit(); + var replacement_view: ?*Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v| v.deinit(); try v2.set(1, replacement_view.?); replacement_view = null; @@ -287,11 +313,11 @@ test "TreeView vector composite clone isolates updates" { const v1_e1 = try v1.get(1); var v1_e1_value: Inner.Type = undefined; - try Inner.tree.toValue(v1_e1.base_view.data.root, &pool, &v1_e1_value); + try Inner.tree.toValue(v1_e1.getRoot(), &pool, &v1_e1_value); const v2_e1 = try v2.get(1); var v2_e1_value: Inner.Type = undefined; - try Inner.tree.toValue(v2_e1.base_view.data.root, &pool, &v2_e1_value); + try Inner.tree.toValue(v2_e1.getRoot(), &pool, &v2_e1_value); try std.testing.expectEqual(@as(u32, 2), v1_e1_value.a); try std.testing.expectEqual(@as(u32, 9), v2_e1_value.a); @@ -314,8 +340,8 @@ test "TreeView vector composite clone reads committed state" { const replacement: Inner.Type = .{ .a = 9 }; const replacement_root = try Inner.tree.fromValue(&pool, &replacement); - var replacement_view: ?Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v| v.deinit(); + var replacement_view: ?*Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v| v.deinit(); try v1.set(1, replacement_view.?); replacement_view = null; try v1.commit(); @@ -325,7 +351,7 @@ test "TreeView vector composite clone reads committed state" { const v2_e1 = try v2.get(1); var v2_e1_value: Inner.Type = undefined; - try Inner.tree.toValue(v2_e1.base_view.data.root, &pool, &v2_e1_value); + try Inner.tree.toValue(v2_e1.getRoot(), &pool, &v2_e1_value); try std.testing.expectEqual(@as(u32, 9), v2_e1_value.a); } @@ -347,14 +373,14 @@ test "TreeView vector composite clone drops uncommitted changes" { const replacement: Inner.Type = .{ .a = 9 }; const replacement_root = try Inner.tree.fromValue(&pool, &replacement); - var replacement_view: ?Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v0| v0.deinit(); + var replacement_view: ?*Inner.TreeView = try Inner.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v0| v0.deinit(); try v.set(1, replacement_view.?); replacement_view = null; const v_e1_before = try v.get(1); var v_e1_before_value: Inner.Type = undefined; - try Inner.tree.toValue(v_e1_before.base_view.data.root, &pool, &v_e1_before_value); + try Inner.tree.toValue(v_e1_before.getRoot(), &pool, &v_e1_before_value); try std.testing.expectEqual(@as(u32, 9), v_e1_before_value.a); var dropped = try v.clone(.{}); @@ -362,11 +388,11 @@ test "TreeView vector composite clone drops uncommitted changes" { const v_e1_after = try v.get(1); var v_e1_after_value: Inner.Type = undefined; - try Inner.tree.toValue(v_e1_after.base_view.data.root, &pool, &v_e1_after_value); + try Inner.tree.toValue(v_e1_after.getRoot(), &pool, &v_e1_after_value); const dropped_e1 = try dropped.get(1); var dropped_e1_value: Inner.Type = undefined; - try Inner.tree.toValue(dropped_e1.base_view.data.root, &pool, &dropped_e1_value); + try Inner.tree.toValue(dropped_e1.getRoot(), &pool, &dropped_e1_value); try std.testing.expectEqual(@as(u32, 2), v_e1_after_value.a); try std.testing.expectEqual(@as(u32, 2), dropped_e1_value.a); @@ -391,13 +417,13 @@ test "TreeView vector composite clone(true) does not transfer cache" { _ = try view.get(0); try view.commit(); - try std.testing.expect(view.base_view.data.children_data.count() > 0); + try std.testing.expect(view.chunks.children_data.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.base_view.data.children_data.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.base_view.data.children_data.count()); + try std.testing.expect(view.chunks.children_data.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.children_data.count()); } test "TreeView vector composite clone(false) transfers cache and clears source" { @@ -419,13 +445,13 @@ test "TreeView vector composite clone(false) transfers cache and clears source" _ = try view.get(0); try view.commit(); - try std.testing.expect(view.base_view.data.children_data.count() > 0); + try std.testing.expect(view.chunks.children_data.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.base_view.data.children_data.count()); - try std.testing.expect(cloned.base_view.data.children_data.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.chunks.children_data.count()); + try std.testing.expect(cloned.chunks.children_data.count() > 0); } // Tests ported from TypeScript ssz packages/ssz/test/unit/byType/vector/tree.test.ts @@ -510,10 +536,11 @@ test "ArrayCompositeTreeView - serialize (Container vector)" { }; try std.testing.expectEqualSlices(u8, &expected, &view_serialized); - const actual_root = try view.hashTreeRoot(); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); // 0xb1a797eb50654748ba239010edccea7b46b55bf740730b700684f48b0c478372 const expected_root = [_]u8{ 0xb1, 0xa7, 0x97, 0xeb, 0x50, 0x65, 0x47, 0x48, 0xba, 0x23, 0x90, 0x10, 0xed, 0xcc, 0xea, 0x7b, 0x46, 0xb5, 0x5b, 0xf7, 0x40, 0x73, 0x0b, 0x70, 0x06, 0x84, 0xf4, 0x8b, 0x0c, 0x47, 0x83, 0x72 }; - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + try std.testing.expectEqualSlices(u8, &expected_root, &hash_root); } test "ArrayCompositeTreeView - get and set" { @@ -537,6 +564,7 @@ test "ArrayCompositeTreeView - get and set" { defer view.deinit(); var elem0 = try view.get(0); + // no need to deinit elem0 as it's borrowed from view var bytes0: [Root32.fixed_size]u8 = undefined; const bytes0_written = try elem0.serializeIntoBytes(&bytes0); try std.testing.expectEqual(bytes0.len, bytes0_written); @@ -548,6 +576,7 @@ test "ArrayCompositeTreeView - get and set" { try view.set(1, new_elem); var elem1 = try view.get(1); + // no need to deinit elem1 as it's borrowed from view var bytes1: [Root32.fixed_size]u8 = undefined; const bytes1_written = try elem1.serializeIntoBytes(&bytes1); try std.testing.expectEqual(bytes1.len, bytes1_written); diff --git a/src/ssz/tree_view/base.zig b/src/ssz/tree_view/base.zig deleted file mode 100644 index 92f6cba8c..000000000 --- a/src/ssz/tree_view/base.zig +++ /dev/null @@ -1,275 +0,0 @@ -const std = @import("std"); -const Allocator = std.mem.Allocator; -const Node = @import("persistent_merkle_tree").Node; -const Gindex = @import("persistent_merkle_tree").Gindex; - -/// Represents the internal state of a tree view. -/// -/// This struct manages the root node of the tree, caches child nodes and sub-data for efficient access, -/// and tracks which child indices have been modified since the last commit. -/// -/// It enables fast (re)access of children and batched updates to the merkle tree structure. -pub const TreeViewData = struct { - root: Node.Id, - - /// cached nodes for faster access of already-visited children - children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), - - /// cached data for faster access of already-visited children - children_data: std.AutoHashMapUnmanaged(Gindex, *TreeViewData), - - /// whether the corresponding child node/data has changed since the last update of the root - changed: std.AutoArrayHashMapUnmanaged(Gindex, void), - - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*TreeViewData { - const data = try allocator.create(TreeViewData); - errdefer allocator.destroy(data); - try pool.ref(root); - data.* = TreeViewData{ - .root = root, - .children_nodes = .empty, - .children_data = .empty, - .changed = .empty, - }; - return data; - } - - /// Deinitialize the Data and free all associated resources. - /// This also deinits all child Data recursively. - pub fn deinit(self: *TreeViewData, allocator: Allocator, pool: *Node.Pool) void { - pool.unref(self.root); - self.clearChildrenNodesCache(pool); - self.children_nodes.deinit(allocator); - self.clearChildrenDataCache(allocator, pool); - self.children_data.deinit(allocator); - self.changed.deinit(allocator); - allocator.destroy(self); - } - - pub fn clearChildrenNodesCache(self: *TreeViewData, pool: *Node.Pool) void { - var value_iter = self.children_nodes.valueIterator(); - while (value_iter.next()) |node_id_ptr| { - const node_id = node_id_ptr.*; - if (node_id.getState(pool).getRefCount() == 0) { - pool.unref(node_id); - } - } - self.children_nodes.clearRetainingCapacity(); - } - - pub fn clearChildrenDataCache(self: *TreeViewData, allocator: Allocator, pool: *Node.Pool) void { - var value_iter = self.children_data.valueIterator(); - while (value_iter.next()) |child_data| { - child_data.*.deinit(allocator, pool); - } - self.children_data.clearRetainingCapacity(); - } - - pub fn commit(self: *TreeViewData, allocator: Allocator, pool: *Node.Pool) !void { - if (self.changed.count() == 0) { - return; - } - - const nodes = try allocator.alloc(Node.Id, self.changed.count()); - defer allocator.free(nodes); - - const SortCtx = struct { - keys: []Gindex, - pub fn lessThan(ctx: @This(), a_index: usize, b_index: usize) bool { - return @intFromEnum(ctx.keys[a_index]) < @intFromEnum(ctx.keys[b_index]); - } - }; - self.changed.sortUnstable(SortCtx{ .keys = self.changed.keys() }); - const gindices_sorted = self.changed.keys(); - - for (gindices_sorted, 0..) |gindex, i| { - if (self.children_data.get(gindex)) |child_data| { - try child_data.commit(allocator, pool); - nodes[i] = child_data.root; - } else if (self.children_nodes.get(gindex)) |child_node| { - nodes[i] = child_node; - } else { - return error.ChildNotFound; - } - } - - const new_root = try self.root.setNodesGrouped(pool, gindices_sorted, nodes); - try pool.ref(new_root); - pool.unref(self.root); - self.root = new_root; - - self.changed.clearRetainingCapacity(); - - // The tree root has changed and any cached child nodes may now be stale (e.g. for - // ancestor gindices of the modified nodes). Clear cached nodes to avoid returning - // nodes from the previous root in subsequent reads/writes. - self.clearChildrenNodesCache(pool); - } -}; - -/// Provides the foundational implementation for tree views. -/// -/// `BaseTreeView` manages and owns a `TreeViewData` struct, -/// enabling fast (re)access of children and batched updates to the merkle tree structure. -/// -/// It supports operations such as get/set of child nodes and data, committing changes, computing hash tree roots. -/// -/// This struct serves as the base for specialized tree views like `ContainerTreeView` and array/list tree views. -pub const BaseTreeView = struct { - allocator: Allocator, - pool: *Node.Pool, - data: *TreeViewData, - - pub const CloneOpts = struct { - /// When true, transfer *safe* cache entries from `self` into the clone. - /// When false, the clone starts with an empty cache and `self` keeps its caches. - transfer_cache: bool = true, - }; - - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !BaseTreeView { - return BaseTreeView{ - .allocator = allocator, - .pool = pool, - .data = try TreeViewData.init(allocator, pool, root), - }; - } - - /// Create a new, independent BaseTreeView referencing the same current root node. - /// - /// - `transfer_cache = true`: transfers *safe* cache entries from `self` into the clone. - /// This is a best-effort transfer: only cache entries that are not marked as changed are moved. - /// After transferring, this instance is reset to a committed-only state by clearing its caches. - /// - `transfer_cache = false`: clone starts with an empty cache; this instance keeps its caches. - /// - /// Notes: - /// - Any uncommitted changes in this instance are not included in the clone. Call `commit()` first if needed. - pub fn clone(self: *BaseTreeView, opts: CloneOpts) !BaseTreeView { - var out = try BaseTreeView.init(self.allocator, self.pool, self.data.root); - errdefer out.deinit(); - if (!opts.transfer_cache) { - return out; - } - - try self.transferSafeCache(&out); - self.clearCache(); - return out; - } - - fn transferSafeCache(self: *BaseTreeView, out: *BaseTreeView) !void { - var safe_node_keys = std.ArrayList(Gindex).init(self.allocator); - defer safe_node_keys.deinit(); - - var nodes_it = self.data.children_nodes.iterator(); - while (nodes_it.next()) |entry| { - const gindex = entry.key_ptr.*; - if (!self.data.changed.contains(gindex)) { - try safe_node_keys.append(gindex); - } - } - - var safe_data_keys = std.ArrayList(Gindex).init(self.allocator); - defer safe_data_keys.deinit(); - - var data_it = self.data.children_data.iterator(); - while (data_it.next()) |entry| { - const gindex = entry.key_ptr.*; - if (!self.data.changed.contains(gindex)) { - try safe_data_keys.append(gindex); - } - } - - try out.data.children_nodes.ensureUnusedCapacity(self.allocator, @intCast(safe_node_keys.items.len)); - try out.data.children_data.ensureUnusedCapacity(self.allocator, @intCast(safe_data_keys.items.len)); - - for (safe_node_keys.items) |gindex| { - const removed = self.data.children_nodes.fetchRemove(gindex) orelse continue; - out.data.children_nodes.putAssumeCapacity(gindex, removed.value); - } - - for (safe_data_keys.items) |gindex| { - const removed = self.data.children_data.fetchRemove(gindex) orelse continue; - out.data.children_data.putAssumeCapacity(gindex, removed.value); - } - } - - pub fn deinit(self: *BaseTreeView) void { - self.data.deinit(self.allocator, self.pool); - } - - pub fn commit(self: *BaseTreeView) !void { - try self.data.commit(self.allocator, self.pool); - } - - pub fn clearCache(self: *BaseTreeView) void { - self.data.clearChildrenNodesCache(self.pool); - self.data.clearChildrenDataCache(self.allocator, self.pool); - self.data.changed.clearRetainingCapacity(); - } - - pub fn hashTreeRoot(self: *BaseTreeView) !*const [32]u8 { - try self.commit(); - return self.data.root.getRoot(self.pool); - } - - pub fn getChildNode(self: *BaseTreeView, gindex: Gindex) !Node.Id { - const gop = try self.data.children_nodes.getOrPut(self.allocator, gindex); - if (gop.found_existing) { - return gop.value_ptr.*; - } - const child_node = try self.data.root.getNode(self.pool, gindex); - gop.value_ptr.* = child_node; - return child_node; - } - - pub fn setChildNode(self: *BaseTreeView, gindex: Gindex, node: Node.Id) !void { - try self.data.changed.put(self.allocator, gindex, {}); - - const opt_old_node = try self.data.children_nodes.fetchPut( - self.allocator, - gindex, - node, - ); - if (opt_old_node) |old_node| { - // Multiple set() calls before commit() leave our previous temp nodes cached with refcount 0. - // Tree-owned nodes already have a refcount, so skip unref in that case. - if (old_node.value.getState(self.pool).getRefCount() == 0) { - self.pool.unref(old_node.value); - } - } - } - - pub fn getChildData(self: *BaseTreeView, gindex: Gindex) !*TreeViewData { - const child_data = try self.getChildDataReadonly(gindex); - try self.data.changed.put(self.allocator, gindex, {}); - return child_data; - } - - pub fn getChildDataReadonly(self: *BaseTreeView, gindex: Gindex) !*TreeViewData { - const gop = try self.data.children_data.getOrPut(self.allocator, gindex); - if (gop.found_existing) { - return gop.value_ptr.*; - } - errdefer _ = self.data.children_data.remove(gindex); - const child_node = try self.data.root.getNode(self.pool, gindex); - const child_data = try TreeViewData.init(self.allocator, self.pool, child_node); - gop.value_ptr.* = child_data; - - return child_data; - } - - pub fn setChildData(self: *BaseTreeView, gindex: Gindex, child_data: *TreeViewData) !void { - try self.data.changed.put(self.allocator, gindex, {}); - - const opt_old_data = try self.data.children_data.fetchPut( - self.allocator, - gindex, - child_data, - ); - if (opt_old_data) |old_data| { - if (old_data.value == child_data) { - return; - } - old_data.value.deinit(self.allocator, self.pool); - } - } -}; diff --git a/src/ssz/tree_view/bit_array.zig b/src/ssz/tree_view/bit_array.zig index 5c070373e..3ec8bf81d 100644 --- a/src/ssz/tree_view/bit_array.zig +++ b/src/ssz/tree_view/bit_array.zig @@ -1,16 +1,63 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; + const hashing = @import("hashing"); const Depth = hashing.Depth; +const Node = @import("persistent_merkle_tree").Node; const Gindex = @import("persistent_merkle_tree").Gindex; - -const BaseTreeView = @import("root.zig").BaseTreeView; +const ChildNodes = @import("utils/child_nodes.zig").ChildNodes; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// Provides common bit array operations for both BitVectorTreeView and BitListTreeView. pub fn BitArray(comptime chunk_depth: Depth) type { return struct { const bits_per_chunk: usize = 256; + allocator: Allocator, + pool: *Node.Pool, + root: Node.Id, + + /// cached nodes for faster access of already-visited children + children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), + + /// whether the corresponding child node/data has changed since the last update of the root + changed: std.AutoArrayHashMapUnmanaged(Gindex, void), + + const Self = @This(); + + pub fn init(self: *Self, allocator: Allocator, pool: *Node.Pool, root: Node.Id) !void { + try pool.ref(root); + errdefer pool.unref(root); + self.* = .{ + .allocator = allocator, + .pool = pool, + .root = root, + .children_nodes = .empty, + .changed = .empty, + }; + } + + pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { + try ChildNodes.Change.clone(Self, self, opts, out); + } + + pub fn deinit(self: *Self) void { + self.pool.unref(self.root); + self.clearChildrenNodesCache(); + self.children_nodes.deinit(self.allocator); + self.changed.deinit(self.allocator); + } + + pub fn commit(self: *Self) !void { + try ChildNodes.Change.commit(self); + } - pub fn get(base_view: *BaseTreeView, index: usize, len: usize) !bool { + pub fn clearCache(self: *Self) void { + self.clearChildrenNodesCache(); + self.changed.clearRetainingCapacity(); + } + + pub fn get(self: *Self, index: usize, len: usize) !bool { if (index >= len) return error.IndexOutOfBounds; const chunk_index = index / bits_per_chunk; @@ -18,13 +65,13 @@ pub fn BitArray(comptime chunk_depth: Depth) type { const byte_in_chunk = bit_in_chunk / 8; const bit_in_byte: u3 = @intCast(bit_in_chunk % 8); - const leaf_node = try base_view.getChildNode(Gindex.fromDepth(chunk_depth, chunk_index)); - const leaf = leaf_node.getRoot(base_view.pool); + const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, chunk_index)); + const leaf = leaf_node.getRoot(self.pool); const mask = @as(u8, 1) << bit_in_byte; return (leaf[byte_in_chunk] & mask) != 0; } - pub fn set(base_view: *BaseTreeView, index: usize, value: bool, len: usize) !void { + pub fn set(self: *Self, index: usize, value: bool, len: usize) !void { if (index >= len) return error.IndexOutOfBounds; const chunk_index = index / bits_per_chunk; @@ -33,8 +80,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { const bit_in_byte: u3 = @intCast(bit_in_chunk % 8); const gindex = Gindex.fromDepth(chunk_depth, chunk_index); - const leaf_node = try base_view.getChildNode(gindex); - var leaf_bytes = leaf_node.getRoot(base_view.pool).*; + const leaf_node = try self.getChildNode(gindex); + var leaf_bytes = leaf_node.getRoot(self.pool).*; const mask = @as(u8, 1) << bit_in_byte; if (value) { @@ -43,11 +90,11 @@ pub fn BitArray(comptime chunk_depth: Depth) type { leaf_bytes[byte_in_chunk] &= ~mask; } - const new_leaf = try base_view.pool.createLeaf(&leaf_bytes); - try base_view.setChildNode(gindex, new_leaf); + const new_leaf = try self.pool.createLeaf(&leaf_bytes); + try self.setChildNode(gindex, new_leaf); } - pub fn fillBools(base_view: *BaseTreeView, values: []bool, len: usize) !void { + pub fn fillBools(self: *Self, values: []bool, len: usize) !void { if (values.len != len) return error.InvalidSize; if (len == 0) return; @@ -56,8 +103,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { var dest = values; for (0..full_chunks) |chunk_idx| { - const leaf_node = try base_view.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); - const leaf = leaf_node.getRoot(base_view.pool); + const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); + const leaf = leaf_node.getRoot(self.pool); for (leaf) |b| { inline for (0..8) |j| { @@ -68,8 +115,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { } if (remainder_bits != 0) { - const leaf_node = try base_view.getChildNode(Gindex.fromDepth(chunk_depth, full_chunks)); - const leaf = leaf_node.getRoot(base_view.pool); + const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, full_chunks)); + const leaf = leaf_node.getRoot(self.pool); const full_bytes = remainder_bits / 8; const tail_bits = remainder_bits % 8; @@ -89,5 +136,17 @@ pub fn BitArray(comptime chunk_depth: Depth) type { } } } + + pub fn getChildNode(self: *Self, gindex: Gindex) !Node.Id { + return ChildNodes.getChildNode(self, gindex); + } + + pub fn setChildNode(self: *Self, gindex: Gindex, node: Node.Id) !void { + try ChildNodes.setChildNode(self, gindex, node); + } + + pub fn clearChildrenNodesCache(self: *Self) void { + ChildNodes.clearChildrenNodesCache(self, self.pool); + } }; } diff --git a/src/ssz/tree_view/bit_list.zig b/src/ssz/tree_view/bit_list.zig index 1bcc6a442..873f5fe46 100644 --- a/src/ssz/tree_view/bit_list.zig +++ b/src/ssz/tree_view/bit_list.zig @@ -9,8 +9,9 @@ const Node = @import("persistent_merkle_tree").Node; const type_root = @import("../type/root.zig"); const chunkDepth = type_root.chunkDepth; -const BaseTreeView = @import("root.zig").BaseTreeView; const BitArray = @import("bit_array.zig").BitArray; +const assertTreeViewType = @import("utils/assert.zig").assertTreeViewType; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; pub fn BitListTreeView(comptime ST: type) type { comptime { @@ -22,8 +23,9 @@ pub fn BitListTreeView(comptime ST: type) type { } } - return struct { - base_view: BaseTreeView, + const TreeView = struct { + allocator: Allocator, + data: BitOps, pub const SszType = ST; pub const Element = bool; @@ -34,46 +36,60 @@ pub fn BitListTreeView(comptime ST: type) type { const chunk_depth: Depth = chunkDepth(Depth, base_chunk_depth, ST); const BitOps = BitArray(chunk_depth); - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !Self { - return Self{ .base_view = try BaseTreeView.init(allocator, pool, root) }; + pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self { + const ptr = try allocator.create(Self); + errdefer allocator.destroy(ptr); + + try BitOps.init(&ptr.data, allocator, pool, root); + ptr.allocator = allocator; + return ptr; } - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { - return Self{ .base_view = try self.base_view.clone(opts) }; + pub fn clone(self: *Self, opts: CloneOpts) !*Self { + const ptr = try self.allocator.create(Self); + errdefer self.allocator.destroy(ptr); + + try self.data.clone(opts, &ptr.data); + ptr.allocator = self.allocator; + return ptr; } pub fn deinit(self: *Self) void { - self.base_view.deinit(); + self.data.deinit(); + self.allocator.destroy(self); } pub fn commit(self: *Self) !void { - try self.base_view.commit(); + try self.data.commit(); } pub fn clearCache(self: *Self) void { - self.base_view.clearCache(); + self.data.clearCache(); } - /// Return the root hash of the tree. - /// The returned array is owned by the internal pool and must not be modified. - pub fn hashTreeRoot(self: *Self) !*const [32]u8 { - return try self.base_view.hashTreeRoot(); + pub fn hashTreeRoot(self: *Self, out: *[32]u8) !void { + try self.commit(); + out.* = self.data.root.getRoot(self.data.pool).*; + } + + pub fn getRoot(self: *const Self) Node.Id { + return self.data.root; } fn readLength(self: *Self) !usize { - const length_node = try self.base_view.getChildNode(@enumFromInt(3)); - const length_chunk = length_node.getRoot(self.base_view.pool); + const length_node = try self.data.getChildNode(@enumFromInt(3)); + const length_chunk = length_node.getRoot(self.data.pool); return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); } pub fn get(self: *Self, index: usize) !Element { const list_length = try self.readLength(); - return BitOps.get(&self.base_view, index, list_length); + return try self.data.get(index, list_length); } pub fn set(self: *Self, index: usize, value: Element) !void { const list_length = try self.readLength(); - return BitOps.set(&self.base_view, index, value, list_length); + try self.data.set(index, value, list_length); } /// Caller must free the returned slice. @@ -81,16 +97,19 @@ pub fn BitListTreeView(comptime ST: type) type { const list_length = try self.readLength(); const values = try allocator.alloc(bool, list_length); errdefer allocator.free(values); - try BitOps.fillBools(&self.base_view, values, list_length); + try self.data.fillBools(values, list_length); return values; } pub fn toBoolArrayInto(self: *Self, out: []bool) !void { const list_length = try self.readLength(); if (out.len != list_length) return error.InvalidSize; - try BitOps.fillBools(&self.base_view, out, list_length); + try self.data.fillBools(out, list_length); } }; + + assertTreeViewType(TreeView); + return TreeView; } const BitListType = @import("../type/bit_list.zig").BitListType; @@ -148,13 +167,13 @@ test "BitListTreeView clone(true) does not transfer cache" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.children_nodes.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.base_view.data.children_nodes.count()); + try std.testing.expect(view.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.data.children_nodes.count()); } test "BitListTreeView clone(false) transfers cache and clears source" { @@ -174,13 +193,13 @@ test "BitListTreeView clone(false) transfers cache and clears source" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.children_nodes.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.base_view.data.children_nodes.count()); - try std.testing.expect(cloned.base_view.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.data.children_nodes.count()); + try std.testing.expect(cloned.data.children_nodes.count() > 0); } test "BitListTreeView clone isolates updates" { diff --git a/src/ssz/tree_view/bit_vector.zig b/src/ssz/tree_view/bit_vector.zig index cdec46be9..362cd11c8 100644 --- a/src/ssz/tree_view/bit_vector.zig +++ b/src/ssz/tree_view/bit_vector.zig @@ -6,8 +6,9 @@ const Depth = hashing.Depth; const Node = @import("persistent_merkle_tree").Node; -const BaseTreeView = @import("root.zig").BaseTreeView; const BitArray = @import("bit_array.zig").BitArray; +const assertTreeViewType = @import("utils/assert.zig").assertTreeViewType; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; pub fn BitVectorTreeView(comptime ST: type) type { comptime { @@ -19,8 +20,9 @@ pub fn BitVectorTreeView(comptime ST: type) type { } } - return struct { - base_view: BaseTreeView, + const TreeView = struct { + allocator: Allocator, + data: BitOps, pub const SszType = ST; pub const Element = bool; @@ -31,55 +33,80 @@ pub fn BitVectorTreeView(comptime ST: type) type { const chunk_depth: Depth = @intCast(ST.chunk_depth); const BitOps = BitArray(chunk_depth); - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !Self { - return Self{ .base_view = try BaseTreeView.init(allocator, pool, root) }; + pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self { + const ptr = try allocator.create(Self); + errdefer allocator.destroy(ptr); + + try BitOps.init(&ptr.data, allocator, pool, root); + ptr.allocator = allocator; + return ptr; } - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { - return Self{ .base_view = try self.base_view.clone(opts) }; + pub fn clone(self: *Self, opts: CloneOpts) !*Self { + const ptr = try self.allocator.create(Self); + errdefer self.allocator.destroy(ptr); + + try self.data.clone(opts, &ptr.data); + ptr.allocator = self.allocator; + return ptr; } pub fn deinit(self: *Self) void { - self.base_view.deinit(); + self.data.deinit(); + self.allocator.destroy(self); } pub fn commit(self: *Self) !void { - try self.base_view.commit(); + try self.data.commit(); } pub fn clearCache(self: *Self) void { - self.base_view.clearCache(); + self.data.clearCache(); } - /// Return the root hash of the tree. - /// The returned array is owned by the internal pool and must not be modified. - pub fn hashTreeRoot(self: *Self) !*const [32]u8 { - return try self.base_view.hashTreeRoot(); + pub fn hashTreeRoot(self: *Self, out: *[32]u8) !void { + try self.commit(); + out.* = self.data.root.getRoot(self.data.pool).*; } - pub fn get(self: *Self, index: usize) !Element { - return BitOps.get(&self.base_view, index, length); + pub fn getRoot(self: *const Self) Node.Id { + return self.data.root; } - pub fn set(self: *Self, index: usize, value: Element) !void { - return BitOps.set(&self.base_view, index, value, length); + pub fn get(self: *Self, index: usize) !Element { + return try self.data.get(index, length); } - pub fn toBoolArray(self: *Self) ![length]bool { - var values: [length]bool = undefined; - try self.toBoolArrayInto(&values); - return values; + pub fn set(self: *Self, index: usize, value: Element) !void { + return try self.data.set(index, value, length); } - pub fn toBoolArrayInto(self: *Self, out: []bool) !void { - try BitOps.fillBools(&self.base_view, out, length); + pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { + const root = try ST.tree.fromValue(pool, value); + errdefer pool.unref(root); + return try Self.init(allocator, pool, root); } pub fn toValue(self: *Self, _: Allocator, out: *ST.Type) !void { try self.commit(); - try ST.tree.toValue(self.base_view.data.root, self.base_view.pool, out); + try ST.tree.toValue(self.data.root, self.data.pool, out); + } + + /// Caller must free the returned slice. + pub fn toBoolArray(self: *Self, allocator: Allocator) ![]bool { + const values = try allocator.alloc(bool, length); + errdefer allocator.free(values); + try self.toBoolArrayInto(values); + return values; + } + + pub fn toBoolArrayInto(self: *Self, out: []bool) !void { + try self.data.fillBools(out, length); } }; + + assertTreeViewType(TreeView); + return TreeView; } const BitVectorType = @import("../type/bit_vector.zig").BitVectorType; @@ -137,13 +164,13 @@ test "BitVectorTreeView clone(true) does not transfer cache" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.children_nodes.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.base_view.data.children_nodes.count()); + try std.testing.expect(view.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.data.children_nodes.count()); } test "BitVectorTreeView clone(false) transfers cache and clears source" { @@ -163,13 +190,13 @@ test "BitVectorTreeView clone(false) transfers cache and clears source" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.children_nodes.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.base_view.data.children_nodes.count()); - try std.testing.expect(cloned.base_view.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.data.children_nodes.count()); + try std.testing.expect(cloned.data.children_nodes.count() > 0); } test "BitVectorTreeView clone isolates updates" { diff --git a/src/ssz/tree_view/chunks.zig b/src/ssz/tree_view/chunks.zig index 5a6d4b028..f9d4320c1 100644 --- a/src/ssz/tree_view/chunks.zig +++ b/src/ssz/tree_view/chunks.zig @@ -10,7 +10,8 @@ const Gindex = @import("persistent_merkle_tree").Gindex; const isFixedType = @import("../type/type_kind.zig").isFixedType; const tree_view_root = @import("root.zig"); -const BaseTreeView = tree_view_root.BaseTreeView; +const ChildNodes = @import("utils/child_nodes.zig").ChildNodes; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// Shared helpers for basic element types packed into chunks. pub fn BasicPackedChunks( @@ -19,59 +20,105 @@ pub fn BasicPackedChunks( comptime items_per_chunk: usize, ) type { return struct { + allocator: Allocator, + pool: *Node.Pool, + root: Node.Id, + + /// cached nodes for faster access of already-visited children + children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), + + /// whether the corresponding child node/data has changed since the last update of the root + changed: std.AutoArrayHashMapUnmanaged(Gindex, void), + pub const Element = ST.Element.Type; - pub fn get(base_view: *BaseTreeView, index: usize) !Element { + const Self = @This(); + + pub fn init(self: *Self, allocator: Allocator, pool: *Node.Pool, root: Node.Id) !void { + try pool.ref(root); + errdefer pool.unref(root); + self.* = .{ + .allocator = allocator, + .pool = pool, + .root = root, + .children_nodes = .empty, + .changed = .empty, + }; + } + + pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { + try ChildNodes.Change.clone(Self, self, opts, out); + } + + pub fn deinit(self: *Self) void { + self.pool.unref(self.root); + self.clearChildrenNodesCache(); + self.children_nodes.deinit(self.allocator); + self.changed.deinit(self.allocator); + } + + pub fn commit(self: *Self) !void { + try ChildNodes.Change.commit(self); + } + + pub fn clearCache(self: *Self) void { + self.clearChildrenNodesCache(); + self.changed.clearRetainingCapacity(); + } + + pub fn get(self: *Self, index: usize) !Element { var value: Element = undefined; - const child_node = try base_view.getChildNode(Gindex.fromDepth(chunk_depth, index / items_per_chunk)); - try ST.Element.tree.toValuePacked(child_node, base_view.pool, index, &value); + const child_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, index / items_per_chunk)); + try ST.Element.tree.toValuePacked(child_node, self.pool, index, &value); return value; } - pub fn set(base_view: *BaseTreeView, index: usize, value: Element) !void { + pub fn set(self: *Self, index: usize, value: Element) !void { const gindex = Gindex.fromDepth(chunk_depth, index / items_per_chunk); - const child_node = try base_view.getChildNode(gindex); - try base_view.setChildNode( + try self.changed.put(self.allocator, gindex, {}); + const child_node = try self.getChildNode(gindex); + const opt_old_node = try self.children_nodes.fetchPut( + self.allocator, gindex, - try ST.Element.tree.fromValuePacked(child_node, base_view.pool, index, &value), + try ST.Element.tree.fromValuePacked(child_node, self.pool, index, &value), ); + if (opt_old_node) |old_node| { + if (old_node.value.getState(self.pool).getRefCount() == 0) { + self.pool.unref(old_node.value); + } + } } pub fn getAll( - base_view: *BaseTreeView, + self: *Self, allocator: Allocator, len: usize, ) ![]Element { const values = try allocator.alloc(Element, len); errdefer allocator.free(values); - return try getAllInto(base_view, len, values); + return try self.getAllInto(len, values); } pub fn getAllInto( - base_view: *BaseTreeView, + self: *Self, len: usize, values: []Element, ) ![]Element { if (values.len != len) return error.InvalidSize; if (len == 0) return values; - // TODO revisit this restriction later - if (base_view.data.changed.count() != 0) { - return error.MustCommitBeforeBulkRead; - } - const len_full_chunks = len / items_per_chunk; const remainder = len % items_per_chunk; const chunk_count = len_full_chunks + @intFromBool(remainder != 0); - try populateAllNodes(base_view, chunk_count); + try self.populateAllNodes(chunk_count); for (0..len_full_chunks) |chunk_idx| { - const leaf_node = try base_view.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); + const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); for (0..items_per_chunk) |i| { try ST.Element.tree.toValuePacked( leaf_node, - base_view.pool, + self.pool, i, &values[chunk_idx * items_per_chunk + i], ); @@ -79,11 +126,11 @@ pub fn BasicPackedChunks( } if (remainder > 0) { - const leaf_node = try base_view.getChildNode(Gindex.fromDepth(chunk_depth, len_full_chunks)); + const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, len_full_chunks)); for (0..remainder) |i| { try ST.Element.tree.toValuePacked( leaf_node, - base_view.pool, + self.pool, i, &values[len_full_chunks * items_per_chunk + i], ); @@ -93,22 +140,42 @@ pub fn BasicPackedChunks( return values; } - fn populateAllNodes(base_view: *BaseTreeView, chunk_count: usize) !void { + fn populateAllNodes(self: *Self, chunk_count: usize) !void { if (chunk_count == 0) return; - const nodes = try base_view.allocator.alloc(Node.Id, chunk_count); - defer base_view.allocator.free(nodes); + const nodes = try self.allocator.alloc(Node.Id, chunk_count); + defer self.allocator.free(nodes); - try base_view.data.root.getNodesAtDepth(base_view.pool, chunk_depth, 0, nodes); + try self.root.getNodesAtDepth(self.pool, chunk_depth, 0, nodes); for (nodes, 0..) |node, chunk_idx| { const gindex = Gindex.fromDepth(chunk_depth, chunk_idx); - const gop = try base_view.data.children_nodes.getOrPut(base_view.allocator, gindex); + const gop = try self.children_nodes.getOrPut(self.allocator, gindex); if (!gop.found_existing) { gop.value_ptr.* = node; } } } + + pub fn getChildNode(self: *Self, gindex: Gindex) !Node.Id { + return ChildNodes.getChildNode(self, gindex); + } + + pub fn setChildNode(self: *Self, gindex: Gindex, node: Node.Id) !void { + try ChildNodes.setChildNode(self, gindex, node); + } + + fn clearChildrenNodesCache(self: *Self) void { + ChildNodes.clearChildrenNodesCache(self, self.pool); + } + + pub fn getLength(self: *Self) !usize { + return try ChildNodes.getLength(self); + } + + pub fn setLength(self: *Self, length: usize) !void { + try ChildNodes.setLength(self, length); + } }; } @@ -118,87 +185,204 @@ pub fn CompositeChunks( comptime chunk_depth: Depth, ) type { return struct { - pub const Element = ST.Element.TreeView; - pub const Value = ST.Element.Type; - - pub fn get(base_view: *BaseTreeView, index: usize) !Element { - const child_data = try base_view.getChildData(Gindex.fromDepth(chunk_depth, index)); - return .{ - .base_view = .{ - .allocator = base_view.allocator, - .pool = base_view.pool, - .data = child_data, - }, + allocator: Allocator, + pool: *Node.Pool, + root: Node.Id, + + /// cached nodes for faster access of already-visited children + children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), + + /// cached data for faster access of already-visited children + children_data: std.AutoHashMapUnmanaged(Gindex, ElementPtr), + + /// whether the corresponding child node/data has changed since the last update of the root + changed: std.AutoArrayHashMapUnmanaged(Gindex, void), + + const Element = ST.Element.TreeView; + pub const ElementPtr = *Element; + + const Self = @This(); + + pub fn init(self: *Self, allocator: Allocator, pool: *Node.Pool, root: Node.Id) !void { + try pool.ref(root); + errdefer pool.unref(root); + self.* = .{ + .allocator = allocator, + .pool = pool, + .root = root, + .children_nodes = .empty, + .children_data = .empty, + .changed = .empty, }; } - pub fn getReadonly(base_view: *BaseTreeView, index: usize) !Element { - const child_data = try base_view.getChildDataReadonly(Gindex.fromDepth(chunk_depth, index)); - return .{ - .base_view = .{ - .allocator = base_view.allocator, - .pool = base_view.pool, - .data = child_data, - }, - }; + pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { + try init(out, self.allocator, self.pool, self.root); + + if (!opts.transfer_cache) { + return; + } + + out.children_nodes = self.children_nodes; + out.children_data = self.children_data; + + // Removing while iterating can invalidate the iterator. + for (self.changed.keys()) |gindex| { + if (out.children_data.fetchRemove(gindex)) |entry| { + entry.value.deinit(); + } + } + + // clear self's caches + self.children_nodes = .empty; + self.children_data = .empty; + self.changed.clearRetainingCapacity(); + } + + /// Deinitialize the Data and free all associated resources. + /// This also deinits all child Data recursively. + pub fn deinit(self: *Self) void { + self.pool.unref(self.root); + self.clearChildrenNodesCache(); + self.children_nodes.deinit(self.allocator); + self.clearChildrenDataCache(); + self.children_data.deinit(self.allocator); + self.changed.deinit(self.allocator); + } + + pub fn commit(self: *Self) !void { + if (self.changed.count() == 0) { + return; + } + + const nodes = try self.allocator.alloc(Node.Id, self.changed.count()); + defer self.allocator.free(nodes); + + const gindices = self.changed.keys(); + Gindex.sortAsc(gindices); + + for (gindices, 0..) |gindex, i| { + if (self.children_data.get(gindex)) |child_ptr| { + // TODO: compare with child_nodes to avoid unnecessary rebind + try child_ptr.commit(); + nodes[i] = child_ptr.getRoot(); + } else if (self.children_nodes.get(gindex)) |child_node| { + nodes[i] = child_node; + } else { + return error.ChildNotFound; + } + } + + const new_root = try self.root.setNodesGrouped(self.pool, gindices, nodes); + try self.pool.ref(new_root); + self.pool.unref(self.root); + self.root = new_root; + + self.changed.clearRetainingCapacity(); } - pub fn getValue(base_view: *BaseTreeView, allocator: Allocator, index: usize, out: *ST.Element.Type) !void { - var child_view = try getReadonly(base_view, index); - try child_view.toValue(allocator, out); + pub fn clearCache(self: *Self) void { + self.clearChildrenNodesCache(); + self.clearChildrenDataCache(); + self.changed.clearRetainingCapacity(); } - pub fn set(base_view: *BaseTreeView, index: usize, value: Element) !void { + pub fn get(self: *Self, index: usize) !ElementPtr { const gindex = Gindex.fromDepth(chunk_depth, index); - try base_view.setChildData(gindex, value.base_view.data); + // Always mark as changed - the child may have been previously cached + // via getReadonly() without being tracked in changed. + try self.changed.put(self.allocator, gindex, {}); + const gop = try self.children_data.getOrPut(self.allocator, gindex); + if (gop.found_existing) { + return gop.value_ptr.*; + } + const child_node = try self.getChildNode(gindex); + const child_ptr = try Element.init(self.allocator, self.pool, child_node); + gop.value_ptr.* = child_ptr; + return child_ptr; } - pub fn setValue(base_view: *BaseTreeView, index: usize, value: *const ST.Element.Type) !void { - const root = try ST.Element.tree.fromValue(base_view.pool, value); - errdefer base_view.pool.unref(root); - var child_view = try ST.Element.TreeView.init( - base_view.allocator, - base_view.pool, - root, + pub fn set(self: *Self, index: usize, value: ElementPtr) !void { + const gindex = Gindex.fromDepth(chunk_depth, index); + try self.changed.put(self.allocator, gindex, {}); + const opt_old_data = try self.children_data.fetchPut( + self.allocator, + gindex, + value, ); + if (opt_old_data) |old_data_value| { + var child_ptr: ElementPtr = @constCast(&old_data_value.value.*); + if (child_ptr != value) { + child_ptr.deinit(); + } + } + } + + /// Get a child view without tracking changes (read-only access). + pub fn getReadonly(self: *Self, index: usize) !ElementPtr { + const gindex = Gindex.fromDepth(chunk_depth, index); + if (self.children_data.get(gindex)) |child_ptr| { + return child_ptr; + } + const child_node = try self.getChildNode(gindex); + const child_ptr = try Element.init(self.allocator, self.pool, child_node); + try self.children_data.put(self.allocator, gindex, child_ptr); + // Do NOT add to self.changed (read-only) + return child_ptr; + } + + /// Get all child views without tracking changes (read-only). + pub fn getAllReadonly(self: *Self, allocator: Allocator, len: usize) ![]ElementPtr { + const views = try allocator.alloc(ElementPtr, len); + errdefer allocator.free(views); + for (0..len) |i| { + views[i] = try self.getReadonly(i); + } + return views; + } + + pub const Value = ST.Element.Type; + + /// Get a child value as an SSZ value type. + pub fn getValue(self: *Self, allocator: Allocator, index: usize, out: *Value) !void { + var child_view = try self.getReadonly(index); + if (comptime isFixedType(ST.Element)) { + try child_view.toValue(undefined, out); + } else { + try child_view.toValue(allocator, out); + } + } + + /// Set a child from an SSZ value type. + pub fn setValue(self: *Self, index: usize, value: *const Value) !void { + const root = try ST.Element.tree.fromValue(self.pool, value); + errdefer self.pool.unref(root); + const child_view = try Element.init(self.allocator, self.pool, root); errdefer child_view.deinit(); - try set(base_view, index, child_view); + try self.set(index, child_view); } /// Get all element values in a single traversal. - /// - /// WARNING: Returns all committed changes. If there are any pending changes, - /// commit them beforehand. - /// /// Caller owns the returned slice and must free it with the same allocator. - pub fn getAllValues( - base_view: *BaseTreeView, - allocator: Allocator, - len: usize, - ) ![]Value { + pub fn getAllValues(self: *Self, allocator: Allocator, len: usize) ![]Value { const values = try allocator.alloc(Value, len); errdefer allocator.free(values); - return try getAllValuesInto(base_view, allocator, values); + return try self.getAllValuesInto(allocator, values); } - /// Fills `values` with all element values in a single traversal. - /// `values.len` determines the number of elements read. - pub fn getAllValuesInto( - base_view: *BaseTreeView, - allocator: Allocator, - values: []Value, - ) ![]Value { + /// Fills `values` with all element values. + pub fn getAllValuesInto(self: *Self, allocator: Allocator, values: []Value) ![]Value { const len = values.len; if (len == 0) return values; - if (base_view.data.changed.count() != 0) { + if (self.changed.count() != 0) { return error.MustCommitBeforeBulkRead; } const nodes = try allocator.alloc(Node.Id, len); defer allocator.free(nodes); - try base_view.data.root.getNodesAtDepth(base_view.pool, chunk_depth, 0, nodes); + try self.root.getNodesAtDepth(self.pool, chunk_depth, 0, nodes); for (nodes, 0..) |node, i| { if (comptime @hasDecl(ST.Element, "deinit")) { @@ -208,22 +392,49 @@ pub fn CompositeChunks( } } } - - // Some variable-size value types (e.g. BitList) expect the output value to start in a valid - // initialized state because `toValue()` may call methods like `resize()` which assume internal - // buffers/sentinels are well-formed. Initialize with `default_value` to avoid mutating - // uninitialized memory during bulk reads. - if (comptime @hasDecl(ST.Element, "default_value")) { - values[i] = ST.Element.default_value; - } if (comptime isFixedType(ST.Element)) { - try ST.Element.tree.toValue(node, base_view.pool, &values[i]); + try ST.Element.tree.toValue(node, self.pool, &values[i]); } else { - try ST.Element.tree.toValue(allocator, node, base_view.pool, &values[i]); + // Initialize value to default before toValue for variable types + // (e.g. BitList fields need initialized ArrayListUnmanaged) + if (comptime @hasDecl(ST.Element, "default_value")) { + values[i] = ST.Element.default_value; + } else { + values[i] = std.mem.zeroes(Value); + } + try ST.Element.tree.toValue(allocator, node, self.pool, &values[i]); } } return values; } + + pub fn getChildNode(self: *Self, gindex: Gindex) !Node.Id { + return ChildNodes.getChildNode(self, gindex); + } + + pub fn setChildNode(self: *Self, gindex: Gindex, node: Node.Id) !void { + try ChildNodes.setChildNode(self, gindex, node); + } + + fn clearChildrenNodesCache(self: *Self) void { + ChildNodes.clearChildrenNodesCache(self, self.pool); + } + + pub fn getLength(self: *Self) !usize { + return try ChildNodes.getLength(self); + } + + pub fn setLength(self: *Self, length: usize) !void { + try ChildNodes.setLength(self, length); + } + + fn clearChildrenDataCache(self: *Self) void { + var value_iter = self.children_data.valueIterator(); + while (value_iter.next()) |child_ptr| { + child_ptr.*.deinit(); + } + self.children_data.clearRetainingCapacity(); + } }; } diff --git a/src/ssz/tree_view/container.zig b/src/ssz/tree_view/container.zig index 1c3bc448d..3f9b9d61a 100644 --- a/src/ssz/tree_view/container.zig +++ b/src/ssz/tree_view/container.zig @@ -3,164 +3,249 @@ const Allocator = std.mem.Allocator; const Node = @import("persistent_merkle_tree").Node; const Gindex = @import("persistent_merkle_tree").Gindex; const isBasicType = @import("../type/type_kind.zig").isBasicType; +const assertTreeViewType = @import("utils/assert.zig").assertTreeViewType; const isFixedType = @import("../type/type_kind.zig").isFixedType; -const tree_view_root = @import("root.zig"); -const TreeViewData = tree_view_root.TreeViewData; -const BaseTreeView = tree_view_root.BaseTreeView; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// A specialized tree view for SSZ container types, enabling efficient access and modification of container fields, given a backing merkle tree. /// -/// This struct wraps a `BaseTreeView` and provides methods to get and set fields by name. +/// This struct stores a tuples of either reference to child TreeView or basic type and provides methods to get and set fields by name. /// -/// For basic-type fields, it returns or accepts values directly; for complex fields, it returns or accepts corresponding tree views. +/// For basic-type fields, it returns or accepts values directly; for complex fields, it returns or accepts corresponding tree view references. pub fn ContainerTreeView(comptime ST: type) type { - return struct { - base_view: BaseTreeView, + comptime var opt_treeview_fields: [ST.fields.len]std.builtin.Type.StructField = undefined; + inline for (ST.fields, 0..) |field, i| { + opt_treeview_fields[i] = .{ + .name = std.fmt.comptimePrint("{}", .{i}), + .type = if (isBasicType(field.type)) @Type(.{ + .optional = .{ + .child = field.type.Type, + }, + }) else blk: { + assertTreeViewType(field.type.TreeView); + break :blk @Type(.{ + .optional = .{ + .child = *field.type.TreeView, + }, + }); + }, + .default_value_ptr = null, + .is_comptime = false, + .alignment = if (isBasicType(field.type)) @alignOf(field.type.Type) else @alignOf(*field.type.TreeView), + }; + } + + const TreeViewData = @Type(.{ + .@"struct" = .{ + .layout = .auto, + .backing_integer = null, + .fields = opt_treeview_fields[0..], + // TODO: do we need to assign this value? + .decls = &[_]std.builtin.Type.Declaration{}, + .is_tuple = true, + }, + }); + const TreeView = struct { + allocator: Allocator, + pool: *Node.Pool, + root: Node.Id, + + /// specific fields for this TreeView + /// a tuple of either Optional(Value) for basic type or Optional(ChildTreeView) for composite type + child_data: TreeViewData, + /// whether the corresponding child node/data has changed since the last update of the root + changed: std.AutoArrayHashMapUnmanaged(usize, void), + original_nodes: [ST.chunk_count]?Node.Id, pub const SszType = ST; const Self = @This(); - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !Self { - return .{ - .base_view = try BaseTreeView.init(allocator, pool, root), + pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self { + try pool.ref(root); + errdefer pool.unref(root); + + const ptr = try allocator.create(Self); + ptr.* = .{ + .allocator = allocator, + .pool = pool, + .child_data = .{null} ** ST.chunk_count, + .original_nodes = .{null} ** ST.chunk_count, + .root = root, + .changed = .empty, }; + return ptr; } - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { - return Self{ .base_view = try self.base_view.clone(opts) }; + pub fn clone(self: *Self, opts: CloneOpts) !*Self { + const ptr = try init(self.allocator, self.pool, self.root); + if (!opts.transfer_cache) { + return ptr; + } + + ptr.child_data = self.child_data; + ptr.original_nodes = self.original_nodes; + + inline for (0..ST.fields.len) |i| { + if (self.changed.contains(i)) { + if (ptr.child_data[i]) |child_view_ptr| { + if (!comptime isBasicType(ST.fields[i].type)) { + @constCast(child_view_ptr).deinit(); + } + } + ptr.child_data[i] = null; + } + } + + // clear self's caches + self.child_data = .{null} ** ST.chunk_count; + self.original_nodes = .{null} ** ST.chunk_count; + self.changed.clearRetainingCapacity(); + + return ptr; } pub fn deinit(self: *Self) void { - self.base_view.deinit(); + self.clearChildrenDataCache(); + self.pool.unref(self.root); + self.allocator.destroy(self); } - pub fn commit(self: *Self) !void { - try self.base_view.commit(); + fn clearChildrenDataCache(self: *Self) void { + inline for (self.child_data, 0..) |child_opt, i| { + if (child_opt) |child| { + if (!comptime isBasicType(ST.fields[i].type)) { + @constCast(child).deinit(); + } + self.child_data[i] = null; + } + } + inline for (0..ST.chunk_count) |i| { + // these nodes are unref by root + self.original_nodes[i] = null; + } + self.changed.deinit(self.allocator); } - /// Return the root hash of the tree. - /// The returned array is owned by the internal pool and must not be modified. - pub fn hashTreeRoot(self: *Self) !*const [32]u8 { - return try self.base_view.hashTreeRoot(); - } + pub fn commit(self: *Self) !void { + if (self.changed.count() == 0) { + return; + } - pub fn Field(comptime field_name: []const u8) type { - comptime { - @setEvalBranchQuota(20000); + var nodes: [ST.chunk_count]Node.Id = undefined; + var indices: [ST.chunk_count]usize = undefined; + + var changed_idx: usize = 0; + inline for (ST.fields, 0..) |field, i| { + if (self.changed.get(i) != null) { + const ChildST = ST.getFieldType(field.name); + if (comptime isBasicType(ChildST)) { + const child_value = self.child_data[i] orelse return error.MissingChildValue; + const child_node = try ChildST.tree.fromValue( + self.pool, + &child_value, + ); + nodes[changed_idx] = child_node; + indices[changed_idx] = i; + self.original_nodes[i] = child_node; + changed_idx += 1; + } else { + var child_view = self.child_data[i] orelse return error.MissingChildView; + try child_view.commit(); + const child_changed = if (self.original_nodes[i]) |orig_node| blk: { + break :blk orig_node != child_view.getRoot(); + } else true; + if (child_changed) { + nodes[changed_idx] = child_view.getRoot(); + self.original_nodes[i] = child_view.getRoot(); + indices[changed_idx] = i; + changed_idx += 1; + } + // else child_view is not changed + } + } } - const ChildST = ST.getFieldType(field_name); - if (comptime isBasicType(ChildST)) { - return ChildST.Type; - } else { - return ChildST.TreeView; + + self.changed.clearRetainingCapacity(); + if (changed_idx == 0) { + return; } + const new_root = try self.root.setNodesAtDepth(self.pool, ST.chunk_depth, indices[0..changed_idx], nodes[0..changed_idx]); + try self.pool.ref(new_root); + self.pool.unref(self.root); + self.root = new_root; } - pub fn FieldValue(comptime field_name: []const u8) type { - const ChildST = ST.getFieldType(field_name); - return ChildST.Type; + pub fn getRoot(self: *const Self) Node.Id { + return self.root; } - pub fn getGindex(comptime field_name: []const u8) Gindex { - const field_index = comptime ST.getFieldIndex(field_name); - return Gindex.fromDepth(ST.chunk_depth, field_index); + pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { + try self.commit(); + out.* = self.root.getRoot(self.pool).*; } pub fn getRootNode(self: *Self, comptime field_name: []const u8) !Node.Id { - const ChildST = ST.getFieldType(field_name); - const field_gindex = Self.getGindex(field_name); - if (comptime isBasicType(ChildST)) { - return try self.base_view.getChildNode(field_gindex); + const field_index = comptime ST.getFieldIndex(field_name); + const existing = self.original_nodes[field_index]; + if (existing) |node| { + return node; } else { - const field_data = try self.base_view.getChildDataReadonly(field_gindex); - try field_data.commit(self.base_view.allocator, self.base_view.pool); - return field_data.root; + const node = try self.root.getNodeAtDepth(self.pool, ST.chunk_depth, field_index); + self.original_nodes[field_index] = node; + return node; } } pub fn setRootNode(self: *Self, comptime field_name: []const u8, root: Node.Id) !void { const ChildST = ST.getFieldType(field_name); - const field_gindex = Self.getGindex(field_name); if (comptime isBasicType(ChildST)) { - return try self.base_view.setChildNode(field_gindex, root); - } else { - const field_data = try TreeViewData.init( - self.base_view.allocator, - self.base_view.pool, - root, - ); - errdefer field_data.deinit(self.base_view.allocator, self.base_view.pool); - try self.base_view.setChildData(field_gindex, field_data); + // TODO: should support this? in this implement it uses value for basic type + return error.InvalidRootNodeForBasicType; } - } - pub fn getRoot(self: *Self, comptime field_name: []const u8) !*const [32]u8 { - const field_node = try self.getRootNode(field_name); - return field_node.getRoot(self.base_view.pool); + const field_data = try ChildST.TreeView.init(self.allocator, self.pool, root); + try self.set(field_name, field_data); } - /// Get a field by name. If the field is a basic type, returns the value directly. - /// Caller borrows a copy of the value so there is no need to deinit it. - pub fn get(self: *Self, comptime field_name: []const u8) !Field(field_name) { - comptime { - @setEvalBranchQuota(20000); - } - const field_index = comptime ST.getFieldIndex(field_name); - const ChildST = ST.getFieldType(field_name); - const child_gindex = Gindex.fromDepth(ST.chunk_depth, field_index); - if (comptime isBasicType(ChildST)) { - var value: ChildST.Type = undefined; - const child_node = try self.base_view.getChildNode(child_gindex); - try ChildST.tree.toValue(child_node, self.base_view.pool, &value); - return value; - } else { - const child_data = try self.base_view.getChildData(child_gindex); - - return .{ - .base_view = .{ - .allocator = self.base_view.allocator, - .pool = self.base_view.pool, - .data = child_data, - }, - }; - } - } - - pub fn getValue(self: *Self, allocator: Allocator, comptime field_name: []const u8, out: *FieldValue(field_name)) !void { + pub fn Field(comptime field_name: []const u8) type { const ChildST = ST.getFieldType(field_name); if (comptime isBasicType(ChildST)) { - out.* = try self.getReadonly(field_name); + return ChildST.Type; } else { - var child_view = try self.getReadonly(field_name); - try child_view.toValue(allocator, out); + return *ChildST.TreeView; } } /// Get a field by name. If the field is a basic type, returns the value directly. - /// Caller borrows a copy of the value so there is no need to deinit it. - pub fn getReadonly(self: *Self, comptime field_name: []const u8) !Field(field_name) { - comptime { - @setEvalBranchQuota(20000); - } + /// Caller borrows a reference to child value so there is no need to deinit it. + pub fn get(self: *Self, comptime field_name: []const u8) !Field(field_name) { const field_index = comptime ST.getFieldIndex(field_name); const ChildST = ST.getFieldType(field_name); - const child_gindex = Gindex.fromDepth(ST.chunk_depth, field_index); if (comptime isBasicType(ChildST)) { - var value: ChildST.Type = undefined; - const child_node = try self.base_view.getChildNode(child_gindex); - try ChildST.tree.toValue(child_node, self.base_view.pool, &value); - return value; + const existing = self.child_data[field_index]; + if (existing) |child_value| { + return child_value; + } else { + const node = try self.root.getNodeAtDepth(self.pool, ST.chunk_depth, field_index); + var child_value: ChildST.Type = undefined; + try ChildST.tree.toValue(node, self.pool, &child_value); + self.original_nodes[field_index] = node; + self.child_data[field_index] = child_value; + return child_value; + } } else { - const child_data = try self.base_view.getChildDataReadonly(child_gindex); - - return .{ - .base_view = .{ - .allocator = self.base_view.allocator, - .pool = self.base_view.pool, - .data = child_data, - }, - }; + try self.changed.put(self.allocator, field_index, {}); + + const existing_ptr = self.child_data[field_index]; + if (existing_ptr) |child_view_ptr| { + return child_view_ptr; + } else { + const node = try self.root.getNodeAtDepth(self.pool, ST.chunk_depth, field_index); + self.original_nodes[field_index] = node; + self.child_data[field_index] = try ChildST.TreeView.init(self.allocator, self.pool, node); + return self.child_data[field_index].?; + } } } @@ -169,30 +254,38 @@ pub fn ContainerTreeView(comptime ST: type) type { /// The caller transfers ownership of the `value` TreeView to this parent view. /// The existing TreeView, if any, will be deinited by this function. pub fn set(self: *Self, comptime field_name: []const u8, value: Field(field_name)) !void { - comptime { - @setEvalBranchQuota(20000); - } const field_index = comptime ST.getFieldIndex(field_name); const ChildST = ST.getFieldType(field_name); - const child_gindex = Gindex.fromDepth(ST.chunk_depth, field_index); + if (comptime isBasicType(ChildST)) { - try self.base_view.setChildNode( - child_gindex, - try ChildST.tree.fromValue( - self.base_view.pool, - &value, - ), - ); + const existing = self.child_data[field_index]; + if (existing) |child_value| { + if (child_value == value) { + // if consumer keeps setting a new value, do nothing + return; + } + } + + self.child_data[field_index] = value; } else { - try self.base_view.setChildData(child_gindex, value.base_view.data); + const existing_ptr = self.child_data[field_index]; + if (existing_ptr) |old_ptr| { + if (old_ptr != value) { + old_ptr.deinit(); + } + } + + self.child_data[field_index] = value; } + + try self.changed.put(self.allocator, field_index, {}); } /// Serialize the tree view into a provided buffer. /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.base_view.data.root, self.base_view.pool, out); + return try ST.tree.serializeIntoBytes(self.root, self.pool, out); } /// Get the serialized size of this tree view. @@ -201,7 +294,7 @@ pub fn ContainerTreeView(comptime ST: type) type { if (comptime isFixedType(ST)) { return ST.fixed_size; } else { - return try ST.tree.serializedSize(self.base_view.data.root, self.base_view.pool); + return ST.tree.serializedSize(self.root, self.pool); } } @@ -210,38 +303,202 @@ pub fn ContainerTreeView(comptime ST: type) type { return try Self.init(allocator, pool, root); } - pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !Self { + pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { const root = try ST.tree.fromValue(pool, value); errdefer pool.unref(root); - return try Self.init(allocator, pool, root); + const self = try Self.init(allocator, pool, root); + return self; } pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { try self.commit(); if (comptime isFixedType(ST)) { - try ST.tree.toValue(self.base_view.data.root, self.base_view.pool, out); + try ST.tree.toValue(self.root, self.pool, out); + } else { + try ST.tree.toValue(allocator, self.root, self.pool, out); + } + } + + /// Return the SSZ value type for a given field name. + pub fn FieldValue(comptime field_name: []const u8) type { + const ChildST = ST.getFieldType(field_name); + return ChildST.Type; + } + + /// Return the root hash of the tree. + /// The returned array is owned by the internal pool and must not be modified. + pub fn hashTreeRoot(self: *Self) !*const [32]u8 { + try self.commit(); + return self.root.getRoot(self.pool); + } + + /// Get the hash tree root of a specific field by name. + /// For composite fields, commits the child view first if it has changes. + pub fn getFieldRoot(self: *Self, comptime field_name: []const u8) !*const [32]u8 { + comptime { + @setEvalBranchQuota(20000); + } + const field_index = comptime ST.getFieldIndex(field_name); + const ChildST = ST.getFieldType(field_name); + if (comptime isBasicType(ChildST)) { + // For basic types, get the node at the field's position and return its root + const node = if (self.child_data[field_index]) |child_value| blk: { + break :blk try ChildST.tree.fromValue(self.pool, &child_value); + } else blk: { + break :blk try self.root.getNodeAtDepth(self.pool, ST.chunk_depth, field_index); + }; + return node.getRoot(self.pool); + } else { + // For composite types, if we have a cached view, commit it and return its root + if (self.child_data[field_index]) |child_view_ptr| { + try child_view_ptr.commit(); + return child_view_ptr.getRoot().getRoot(self.pool); + } else { + const node = try self.root.getNodeAtDepth(self.pool, ST.chunk_depth, field_index); + return node.getRoot(self.pool); + } + } + } + + /// Get a field by name without tracking changes (read-only access). + /// For basic types, returns the value. For composite types, returns a borrowed *TreeView. + pub fn getReadonly(self: *Self, comptime field_name: []const u8) !Field(field_name) { + comptime { + @setEvalBranchQuota(20000); + } + const field_index = comptime ST.getFieldIndex(field_name); + const ChildST = ST.getFieldType(field_name); + if (comptime isBasicType(ChildST)) { + const existing = self.child_data[field_index]; + if (existing) |child_value| { + return child_value; + } else { + const node = try self.root.getNodeAtDepth(self.pool, ST.chunk_depth, field_index); + var child_value: ChildST.Type = undefined; + try ChildST.tree.toValue(node, self.pool, &child_value); + return child_value; + } + } else { + // Unlike get(), do NOT add to self.changed + const existing_ptr = self.child_data[field_index]; + if (existing_ptr) |child_view_ptr| { + return child_view_ptr; + } else { + const node = try self.root.getNodeAtDepth(self.pool, ST.chunk_depth, field_index); + const child_view = try ChildST.TreeView.init(self.allocator, self.pool, node); + self.child_data[field_index] = child_view; + return child_view; + } + } + } + + /// Get a field value as an SSZ value type (copied out). + pub fn getValue(self: *Self, allocator: Allocator, comptime field_name: []const u8, out: *FieldValue(field_name)) !void { + comptime { + @setEvalBranchQuota(20000); + } + const ChildST = ST.getFieldType(field_name); + if (comptime isBasicType(ChildST)) { + out.* = try self.getReadonly(field_name); } else { - try ST.tree.toValue(allocator, self.base_view.data.root, self.base_view.pool, out); + var child_view = try self.getReadonly(field_name); + try child_view.toValue(allocator, out); } } + /// Set a field from an SSZ value type. + /// For basic types, sets the value directly. For composite types, creates a TreeView from the value. pub fn setValue(self: *Self, comptime field_name: []const u8, value: *const FieldValue(field_name)) !void { + comptime { + @setEvalBranchQuota(20000); + } const ChildST = ST.getFieldType(field_name); if (comptime isBasicType(ChildST)) { try self.set(field_name, value.*); } else { - const root = try ChildST.tree.fromValue(self.base_view.pool, value); - errdefer self.base_view.pool.unref(root); - var child_view = try ChildST.TreeView.init( - self.base_view.allocator, - self.base_view.pool, - root, - ); + const child_view = try ChildST.TreeView.fromValue(self.allocator, self.pool, value); errdefer child_view.deinit(); try self.set(field_name, child_view); } } }; + + assertTreeViewType(TreeView); + return TreeView; +} + +test "ContainerTreeView" { + const Foo = FixedContainerType(struct { + a: UintType(64), + b: UintType(64), + }); + + var pool = try Node.Pool.init(std.testing.allocator, 1000); + defer pool.deinit(); + + const foo_value: Foo.Type = .{ + .a = 123, + .b = 456, + }; + const root_node = try Foo.tree.fromValue(&pool, &foo_value); + var foo_view = try ContainerTreeView(Foo).init(std.testing.allocator, &pool, root_node); + defer foo_view.deinit(); + + // test get() and set() and commit() + try std.testing.expectEqual(123, try foo_view.get("a")); + try std.testing.expectEqual(456, try foo_view.get("b")); + try foo_view.set("a", 1230); + try std.testing.expectEqual(1230, try foo_view.get("a")); + try foo_view.commit(); + try std.testing.expectEqual(1230, try foo_view.get("a")); + + // test hashTreeRoot() + var value_root: [32]u8 = undefined; + var expected_foo_value: Foo.Type = .{ .a = 1230, .b = 456 }; + try Foo.hashTreeRoot(&expected_foo_value, &value_root); + var view_root: [32]u8 = undefined; + try foo_view.hashTreeRootInto(&view_root); + try std.testing.expectEqualSlices(u8, value_root[0..], view_root[0..]); + + const Bar = FixedContainerType(struct { + foo: Foo, + c: UintType(32), + }); + + const bar_value: Bar.Type = .{ + .foo = foo_value, + .c = 789, + }; + const bar_root_node = try Bar.tree.fromValue(&pool, &bar_value); + var bar_view = try ContainerTreeView(Bar).init(std.testing.allocator, &pool, bar_root_node); + defer bar_view.deinit(); + + // test nested get() and set() and commit() + var foo_field_view = try bar_view.get("foo"); + try std.testing.expectEqual(123, try foo_field_view.get("a")); + try std.testing.expectEqual(456, try foo_field_view.get("b")); + try std.testing.expectEqual(789, try bar_view.get("c")); + + try foo_field_view.set("a", 1230); + try std.testing.expectEqual(1230, try foo_field_view.get("a")); + try bar_view.commit(); + try std.testing.expectEqual(1230, try foo_field_view.get("a")); + + // test hashTreeRoot() after nested modification + const expected_bar_value: Bar.Type = .{ + .foo = .{ .a = 1230, .b = 456 }, + .c = 789, + }; + try Bar.hashTreeRoot(&expected_bar_value, &value_root); + try bar_view.hashTreeRootInto(&view_root); + try std.testing.expectEqualSlices(u8, value_root[0..], view_root[0..]); + + const cloned_foo_view_node = try Foo.tree.fromValue(&pool, &expected_foo_value); + const cloned_foo_view = try ContainerTreeView(Foo).init(std.testing.allocator, &pool, cloned_foo_view_node); + // do not deinit cloned_foo_view, it will be transferred + try bar_view.set("foo", cloned_foo_view); + try bar_view.hashTreeRootInto(&view_root); + try std.testing.expectEqualSlices(u8, value_root[0..], view_root[0..]); } const FixedContainerType = @import("../type/container.zig").FixedContainerType; @@ -276,8 +533,8 @@ test "TreeView container field roundtrip" { // get field "root" var root_view = try cp_view.get("root"); var root = [_]u8{0} ** 32; - const RootView = Checkpoint.TreeView.Field("root"); - try RootView.SszType.tree.toValue(root_view.base_view.data.root, &pool, root[0..]); + const RootView = @typeInfo(Checkpoint.TreeView.Field("root")).pointer.child; + try RootView.SszType.tree.toValue(root_view.getRoot(), &pool, root[0..]); try std.testing.expectEqualSlices(u8, ([_]u8{1} ** 32)[0..], root[0..]); // modify field "epoch" @@ -292,7 +549,7 @@ test "TreeView container field roundtrip" { // confirm "root" has been modified root_view = try cp_view.get("root"); - try RootView.SszType.tree.toValue(root_view.base_view.data.root, &pool, root[0..]); + try RootView.SszType.tree.toValue(root_view.getRoot(), &pool, root[0..]); try std.testing.expectEqualSlices(u8, ([_]u8{2} ** 32)[0..], root[0..]); // commit and check hash_tree_root @@ -304,8 +561,14 @@ test "TreeView container field roundtrip" { }; try Checkpoint.hashTreeRoot(&expected_checkpoint, &htr_from_value); - const htr_from_tree = try cp_view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &htr_from_value, htr_from_tree); + var htr_from_tree: [32]u8 = undefined; + try cp_view.hashTreeRootInto(&htr_from_tree); + + try std.testing.expectEqualSlices( + u8, + &htr_from_value, + &htr_from_tree, + ); } test "TreeView container nested types set/get/commit" { @@ -360,9 +623,8 @@ test "TreeView container nested types set/get/commit" { try bytes_view.push(@as(u8, 0xAA)); try bytes_view.push(@as(u8, 0xBB)); try bytes_view.set(1, @as(u8, 0xCC)); - try bytes_view.commit(); - const all = try bytes_view.getAll(allocator); + const all = try bytes_view.getAll(null); defer allocator.free(all); try std.testing.expectEqualSlices(u8, &[_]u8{ 0xAA, 0xCC }, all); @@ -377,9 +639,8 @@ test "TreeView container nested types set/get/commit" { try std.testing.expectEqual(@as(u16, 0), try basic_vec_view.get(0)); try basic_vec_view.set(0, @as(u16, 1)); try basic_vec_view.set(3, @as(u16, 4)); - try basic_vec_view.commit(); - const all = try basic_vec_view.getAll(allocator); + const all = try basic_vec_view.getAll(null); defer allocator.free(all); try std.testing.expectEqual(@as(usize, 4), all.len); try std.testing.expectEqual(@as(u16, 1), all[0]); @@ -397,15 +658,15 @@ test "TreeView container nested types set/get/commit" { const e0: InnerFixed.Type = .{ .a = 11, .b = [_]u8{ 1, 2, 3, 4 } }; const e0_root = try InnerFixed.tree.fromValue(&pool, &e0); - var e0_view: ?InnerFixed.TreeView = try InnerFixed.TreeView.init(allocator, &pool, e0_root); - defer if (e0_view) |*v| v.deinit(); + var e0_view: ?*InnerFixed.TreeView = try InnerFixed.TreeView.init(allocator, &pool, e0_root); + defer if (e0_view) |v| v.deinit(); try comp_vec_view.set(0, e0_view.?); e0_view = null; const e1: InnerFixed.Type = .{ .a = 22, .b = [_]u8{ 4, 3, 2, 1 } }; const e1_root = try InnerFixed.tree.fromValue(&pool, &e1); - var e1_view: ?InnerFixed.TreeView = try InnerFixed.TreeView.init(allocator, &pool, e1_root); - defer if (e1_view) |*v| v.deinit(); + var e1_view: ?*InnerFixed.TreeView = try InnerFixed.TreeView.init(allocator, &pool, e1_root); + defer if (e1_view) |v| v.deinit(); try comp_vec_view.set(1, e1_view.?); e1_view = null; @@ -421,16 +682,18 @@ test "TreeView container nested types set/get/commit" { var inner_value: InnerVar.Type = InnerVar.default_value; defer InnerVar.deinit(allocator, &inner_value); const inner_root = try InnerVar.tree.fromValue(&pool, &inner_value); - var inner_view: ?InnerVar.TreeView = try InnerVar.TreeView.init(allocator, &pool, inner_root); - defer if (inner_view) |*v| v.deinit(); - const inner = &inner_view.?; + var inner_view: ?*InnerVar.TreeView = try InnerVar.TreeView.init(allocator, &pool, inner_root); + defer if (inner_view) |v| v.deinit(); + const inner = inner_view.?; try inner.set("id", @as(u32, 99)); - var payload_value: InnerVar.TreeView.Field("payload").SszType.Type = InnerVar.TreeView.Field("payload").SszType.default_value; + const payload_value_ssz_type = @typeInfo(InnerVar.TreeView.Field("payload")).pointer.child.SszType; + var payload_value = payload_value_ssz_type.default_value; defer payload_value.deinit(allocator); - const payload_root = try InnerVar.TreeView.Field("payload").SszType.tree.fromValue(&pool, &payload_value); - var payload_view = try InnerVar.TreeView.Field("payload").init(allocator, &pool, payload_root); + const payload_root = try payload_value_ssz_type.tree.fromValue(&pool, &payload_value); + var payload_view = try payload_value_ssz_type.TreeView.init(allocator, &pool, payload_root); + try payload_view.push(@as(u8, 0x5A)); try inner.set("payload", payload_view); @@ -444,7 +707,7 @@ test "TreeView container nested types set/get/commit" { var roundtrip: Outer.Type = Outer.default_value; defer Outer.deinit(allocator, &roundtrip); - try Outer.tree.toValue(allocator, view.base_view.data.root, &pool, &roundtrip); + try Outer.tree.toValue(allocator, view.getRoot(), &pool, &roundtrip); try std.testing.expectEqual(@as(u64, 7), roundtrip.n); try std.testing.expectEqualSlices(u8, &[_]u8{ 0xAA, 0xCC }, roundtrip.bytes.items); @@ -527,13 +790,13 @@ test "TreeView container clone(true) does not transfer cache" { defer v.deinit(); _ = try v.get("n"); - try std.testing.expect(v.base_view.data.children_nodes.count() > 0); + try std.testing.expect(v.child_data[0] != null); var cloned_no_cache = try v.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(v.base_view.data.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.base_view.data.children_nodes.count()); + try std.testing.expect(v.child_data[0] != null); + try std.testing.expect(cloned_no_cache.child_data[0] == null); } test "TreeView container clone(false) transfers cache and clears source" { @@ -553,13 +816,13 @@ test "TreeView container clone(false) transfers cache and clears source" { defer v.deinit(); _ = try v.get("n"); - try std.testing.expect(v.base_view.data.children_nodes.count() > 0); + try std.testing.expect(v.child_data[0] != null); var cloned = try v.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), v.base_view.data.children_nodes.count()); - try std.testing.expect(cloned.base_view.data.children_nodes.count() > 0); + try std.testing.expect(v.child_data[0] == null); + try std.testing.expect(cloned.child_data[0] != null); } // Tests ported from TypeScript ssz packages/ssz/test/unit/byType/container/tree.test.ts @@ -625,8 +888,9 @@ test "ContainerTreeView - serialize (basic fields)" { const view_size = try view.serializedSize(); try std.testing.expectEqual(tc.expected_serialized.len, view_size); - const hash_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &tc.expected_root, hash_root); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); + try std.testing.expectEqualSlices(u8, &tc.expected_root, &hash_root); } } @@ -704,8 +968,9 @@ test "ContainerTreeView - serialize (with nested list)" { try std.testing.expectEqualSlices(u8, &expected_serialized, view_serialized); try std.testing.expectEqualSlices(u8, value_serialized, view_serialized); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); // 0xdc3619cbbc5ef0e0a3b38e3ca5d31c2b16868eacb6e4bcf8b4510963354315f5 const expected_root = [_]u8{ 0xdc, 0x36, 0x19, 0xcb, 0xbc, 0x5e, 0xf0, 0xe0, 0xa3, 0xb3, 0x8e, 0x3c, 0xa5, 0xd3, 0x1c, 0x2b, 0x16, 0x86, 0x8e, 0xac, 0xb6, 0xe4, 0xbc, 0xf8, 0xb4, 0x51, 0x09, 0x63, 0x35, 0x43, 0x15, 0xf5 }; - const hash_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, hash_root); + try std.testing.expectEqualSlices(u8, &expected_root, &hash_root); } diff --git a/src/ssz/tree_view/list_basic.zig b/src/ssz/tree_view/list_basic.zig index d162d2b6a..7a05fcf9d 100644 --- a/src/ssz/tree_view/list_basic.zig +++ b/src/ssz/tree_view/list_basic.zig @@ -10,8 +10,9 @@ const BYTES_PER_CHUNK = type_root.BYTES_PER_CHUNK; const itemsPerChunk = type_root.itemsPerChunk; const chunkDepth = type_root.chunkDepth; -const BaseTreeView = @import("root.zig").BaseTreeView; const BasicPackedChunks = @import("chunks.zig").BasicPackedChunks; +const assertTreeViewType = @import("utils/assert.zig").assertTreeViewType; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// A specialized tree view for SSZ list types with basic element types. /// Elements are packed into chunks (multiple elements per leaf node). @@ -25,8 +26,13 @@ pub fn ListBasicTreeView(comptime ST: type) type { } } - return struct { - base_view: BaseTreeView, + const TreeView = struct { + allocator: Allocator, + chunks: Chunks, + // the original length, before any modifications + _orig_len: usize, + // the current length, may differ from original until committed + _len: usize, pub const SszType = ST; pub const Element = ST.Element.Type; @@ -38,65 +44,138 @@ pub fn ListBasicTreeView(comptime ST: type) type { const items_per_chunk: usize = itemsPerChunk(ST.Element); const Chunks = BasicPackedChunks(ST, chunk_depth, items_per_chunk); - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !Self { - return Self{ - .base_view = try BaseTreeView.init(allocator, pool, root), - }; + pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self { + const ptr = try allocator.create(Self); + errdefer allocator.destroy(ptr); + + try Chunks.init(&ptr.chunks, allocator, pool, root); + ptr.allocator = allocator; + ptr._orig_len = try ptr.chunks.getLength(); + ptr._len = ptr._orig_len; + return ptr; } - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { - return Self{ .base_view = try self.base_view.clone(opts) }; + pub fn clone(self: *Self, opts: CloneOpts) !*Self { + const ptr = try self.allocator.create(Self); + errdefer self.allocator.destroy(ptr); + + try self.chunks.clone(opts, &ptr.chunks); + ptr.allocator = self.allocator; + ptr._orig_len = self._orig_len; + ptr._len = self._len; + return ptr; } pub fn deinit(self: *Self) void { - self.base_view.deinit(); + self.chunks.deinit(); + self.allocator.destroy(self); } pub fn commit(self: *Self) !void { - try self.base_view.commit(); + try self.updateListLength(); + try self.chunks.commit(); + self._orig_len = self._len; } pub fn clearCache(self: *Self) void { - self.base_view.clearCache(); + self.chunks.clearCache(); + } + + pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { + try self.commit(); + out.* = self.chunks.root.getRoot(self.chunks.pool).*; } - /// Return the root hash of the tree. - /// The returned array is owned by the internal pool and must not be modified. pub fn hashTreeRoot(self: *Self) !*const [32]u8 { - return try self.base_view.hashTreeRoot(); + try self.commit(); + return self.chunks.root.getRoot(self.chunks.pool); + } + + pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { + const root = try ST.tree.fromValue(pool, value); + errdefer pool.unref(root); + return try Self.init(allocator, pool, root); } - pub fn length(self: *Self) !usize { - const length_node = try self.base_view.getChildNode(@enumFromInt(3)); - const length_chunk = length_node.getRoot(self.base_view.pool); - return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); + pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { + try self.commit(); + try ST.tree.toValue(allocator, self.chunks.root, self.chunks.pool, out); } pub fn setLength(self: *Self, new_length: usize) !void { - try self.updateListLength(new_length); + self._len = new_length; + } + + pub fn iteratorReadonly(self: *const Self, start_index: usize) ReadonlyIterator { + return ReadonlyIterator.init(self, start_index); + } + + pub const ReadonlyIterator = struct { + tree_view: *const Self, + depth_iterator: Node.DepthIterator, + elem_index: usize, + elem_node: ?Node.Id, + + pub fn init(tree_view: *const Self, start_index: usize) ReadonlyIterator { + return .{ + .tree_view = tree_view, + .depth_iterator = Node.DepthIterator.init( + tree_view.chunks.pool, + tree_view.chunks.root, + ST.chunk_depth + 1, + ST.chunkIndex(start_index), + ), + .elem_index = start_index, + .elem_node = null, + }; + } + + pub fn next(self: *ReadonlyIterator) !Element { + const elem_index = self.elem_index; + const n = if (self.elem_node) |node| + node + else + try self.depth_iterator.next(); + self.elem_node = n; + var value: Element = undefined; + try ST.Element.tree.toValuePacked(n, self.tree_view.chunks.pool, elem_index, &value); + self.elem_index += 1; + if (self.elem_index % items_per_chunk == 0) { + self.elem_node = null; + } + return value; + } + }; + + pub fn getRoot(self: *const Self) Node.Id { + return self.chunks.root; + } + + pub fn length(self: *const Self) !usize { + return self._len; } pub fn get(self: *Self, index: usize) !Element { const list_length = try self.length(); if (index >= list_length) return error.IndexOutOfBounds; - return try Chunks.get(&self.base_view, index); + return self.chunks.get(index); } pub fn set(self: *Self, index: usize, value: Element) !void { const list_length = try self.length(); if (index >= list_length) return error.IndexOutOfBounds; - try Chunks.set(&self.base_view, index, value); + try self.chunks.set(index, value); } - /// Caller must free the returned slice. - pub fn getAll(self: *Self, allocator: Allocator) ![]Element { + /// Caller must free the returned slice with the same allocator. + pub fn getAll(self: *Self, allocator: ?Allocator) ![]Element { const list_length = try self.length(); - return try Chunks.getAll(&self.base_view, allocator, list_length); + return try self.chunks.getAll(allocator orelse self.allocator, list_length); } pub fn getAllInto(self: *Self, values: []Element) ![]Element { const list_length = try self.length(); - return try Chunks.getAllInto(&self.base_view, list_length, values); + return self.chunks.getAllInto(list_length, values); } pub fn push(self: *Self, value: Element) !void { @@ -104,18 +183,18 @@ pub fn ListBasicTreeView(comptime ST: type) type { if (list_length >= ST.limit) { return error.LengthOverLimit; } - try self.updateListLength(list_length + 1); + self._len += 1; try self.set(list_length, value); } /// Return a new view containing all elements up to and including `index`. /// Caller must call `deinit()` on the returned view to avoid memory leaks. - pub fn sliceTo(self: *Self, index: usize) !Self { + pub fn sliceTo(self: *Self, index: usize) !*Self { try self.commit(); const list_length = try self.length(); if (list_length == 0 or index >= list_length - 1) { - return try Self.init(self.base_view.allocator, self.base_view.pool, self.base_view.data.root); + return try Self.init(self.allocator, self.chunks.pool, self.chunks.root); } const new_length = index + 1; @@ -125,122 +204,66 @@ pub fn ListBasicTreeView(comptime ST: type) type { const chunk_index = index / items_per_chunk; const chunk_offset = index % items_per_chunk; - const chunk_node = try Node.Id.getNodeAtDepth(self.base_view.data.root, self.base_view.pool, chunk_depth, chunk_index); + const chunk_node = try Node.Id.getNodeAtDepth(self.chunks.root, self.chunks.pool, chunk_depth, chunk_index); - var chunk_bytes = chunk_node.getRoot(self.base_view.pool).*; + var chunk_bytes = chunk_node.getRoot(self.chunks.pool).*; const keep_bytes = (chunk_offset + 1) * ST.Element.fixed_size; if (keep_bytes < BYTES_PER_CHUNK) { @memset(chunk_bytes[keep_bytes..], 0); } - var truncated_chunk_node: ?Node.Id = try self.base_view.pool.createLeaf(&chunk_bytes); - defer if (truncated_chunk_node) |id| self.base_view.pool.unref(id); + var truncated_chunk_node: ?Node.Id = try self.chunks.pool.createLeaf(&chunk_bytes); + defer if (truncated_chunk_node) |id| self.chunks.pool.unref(id); var updated: ?Node.Id = try Node.Id.setNodeAtDepth( - self.base_view.data.root, - self.base_view.pool, + self.chunks.root, + self.chunks.pool, chunk_depth, chunk_index, truncated_chunk_node.?, ); - defer if (updated) |id| self.base_view.pool.unref(id); + defer if (updated) |id| self.chunks.pool.unref(id); truncated_chunk_node = null; - var new_root: ?Node.Id = try Node.Id.truncateAfterIndex(updated.?, self.base_view.pool, chunk_depth, chunk_index); - defer if (new_root) |id| self.base_view.pool.unref(id); + var new_root: ?Node.Id = try Node.Id.truncateAfterIndex(updated.?, self.chunks.pool, chunk_depth, chunk_index); + defer if (new_root) |id| self.chunks.pool.unref(id); updated = null; - var length_node: ?Node.Id = try self.base_view.pool.createLeafFromUint(@intCast(new_length)); - defer if (length_node) |id| self.base_view.pool.unref(id); - const root_with_length = try Node.Id.setNode(new_root.?, self.base_view.pool, @enumFromInt(3), length_node.?); - errdefer self.base_view.pool.unref(root_with_length); + var length_node: ?Node.Id = try self.chunks.pool.createLeafFromUint(@intCast(new_length)); + defer if (length_node) |id| self.chunks.pool.unref(id); + const root_with_length = try Node.Id.setNode(new_root.?, self.chunks.pool, @enumFromInt(3), length_node.?); + errdefer self.chunks.pool.unref(root_with_length); length_node = null; new_root = null; - return try Self.init(self.base_view.allocator, self.base_view.pool, root_with_length); - } - - fn updateListLength(self: *Self, new_length: usize) !void { - if (new_length > ST.limit) { - return error.LengthOverLimit; - } - const length_node = try self.base_view.pool.createLeafFromUint(@intCast(new_length)); - errdefer self.base_view.pool.unref(length_node); - try self.base_view.setChildNode(@enumFromInt(3), length_node); + return try Self.init(self.allocator, self.chunks.pool, root_with_length); } /// Serialize the tree view into a provided buffer. /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.base_view.data.root, self.base_view.pool, out); - } - - pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { - try self.commit(); - try ST.tree.toValue(allocator, self.base_view.data.root, self.base_view.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); } /// Get the serialized size of this tree view. pub fn serializedSize(self: *Self) !usize { try self.commit(); - return try ST.tree.serializedSize(self.base_view.data.root, self.base_view.pool); + return try ST.tree.serializedSize(self.chunks.root, self.chunks.pool); } - /// Get a read-only iterator over the elements of the list. - /// This only iterates over committed elements. - /// It is up to the caller to ensure that the iterator doesn't run past the end of the list. - /// - /// Convenience wrapper around `ReadonlyIterator.init`. - pub fn iteratorReadonly(self: *const Self, start_index: usize) ReadonlyIterator { - return ReadonlyIterator.init(self, start_index); - } - - /// Get a read-only iterator over the elements of the list. - /// This only iterates over committed elements. - /// It is up to the caller to ensure that the iterator doesn't run past the end of the list. - pub const ReadonlyIterator = struct { - tree_view: *const Self, - depth_iterator: Node.DepthIterator, - elem_index: usize, - elem_node: ?Node.Id, - - pub fn init(tree_view: *const Self, start_index: usize) ReadonlyIterator { - return .{ - .tree_view = tree_view, - .depth_iterator = Node.DepthIterator.init( - tree_view.base_view.pool, - tree_view.base_view.data.root, - ST.chunk_depth + 1, - ST.chunkIndex(start_index), - ), - .elem_index = start_index, - .elem_node = null, - }; + fn updateListLength(self: *Self) !void { + if (self._len == self._orig_len) { + return; } - pub fn next(self: *ReadonlyIterator) !Element { - const elem_index = self.elem_index; - const n = if (self.elem_node) |node| - if (ST.chunkIndex(self.elem_index) != (self.depth_iterator.index - 1)) - try self.depth_iterator.next() - else - node - else - try self.depth_iterator.next(); - self.elem_node = n; - self.elem_index += 1; - var out = ST.Element.default_value; - try ST.Element.tree.toValuePacked( - n, - self.tree_view.base_view.pool, - elem_index, - &out, - ); - return out; - } - }; + std.debug.assert(self._len <= ST.limit); + try self.chunks.setLength(self._len); + } }; + + assertTreeViewType(TreeView); + return TreeView; } const UintType = @import("../type/uint.zig").UintType; @@ -281,12 +304,14 @@ test "TreeView list element roundtrip" { var expected_root: [32]u8 = undefined; try ListType.hashTreeRoot(allocator, &expected_list, &expected_root); - const actual_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try view.hashTreeRootInto(&actual_root); + + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); var roundtrip: ListType.Type = .empty; defer roundtrip.deinit(allocator); - try ListType.tree.toValue(allocator, view.base_view.data.root, &pool, &roundtrip); + try ListType.tree.toValue(allocator, view.getRoot(), &pool, &roundtrip); try std.testing.expectEqual(roundtrip.items.len, expected_list.items.len); try std.testing.expectEqualSlices(u32, expected_list.items, roundtrip.items); } @@ -325,8 +350,10 @@ test "TreeView list push updates cached length" { var expected_root: [32]u8 = undefined; try ListType.hashTreeRoot(allocator, &expected, &expected_root); - const actual_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try view.hashTreeRootInto(&actual_root); + + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); } test "TreeView list getAllAlloc handles zero length" { @@ -344,7 +371,7 @@ test "TreeView list getAllAlloc handles zero length" { var view = try ListType.TreeView.init(allocator, &pool, root_node); defer view.deinit(); - const filled = try view.getAll(allocator); + const filled = try view.getAll(null); defer allocator.free(filled); try std.testing.expectEqual(@as(usize, 0), filled.len); @@ -371,7 +398,7 @@ test "TreeView list getAllAlloc spans multiple chunks" { var view = try ListType.TreeView.init(allocator, &pool, root_node); defer view.deinit(); - const filled = try view.getAll(allocator); + const filled = try view.getAll(null); defer allocator.free(filled); try std.testing.expectEqualSlices(u16, values[0..], filled); @@ -413,8 +440,9 @@ test "TreeView list push batches before commit" { var expected_root: [32]u8 = undefined; try ListType.hashTreeRoot(allocator, &expected, &expected_root); - const actual_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try view.hashTreeRootInto(&actual_root); + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); } test "TreeView list push across chunk boundary resets prefetch" { @@ -433,7 +461,7 @@ test "TreeView list push across chunk boundary resets prefetch" { var view = try ListType.TreeView.init(allocator, &pool, root_node); defer view.deinit(); - const initial = try view.getAll(allocator); + const initial = try view.getAll(null); defer allocator.free(initial); try std.testing.expectEqual(@as(usize, 8), initial.len); @@ -443,8 +471,7 @@ test "TreeView list push across chunk boundary resets prefetch" { try std.testing.expectEqual(@as(usize, 10), try view.length()); try std.testing.expectEqual(@as(u32, 9), try view.get(9)); - try view.commit(); - const filled = try view.getAll(allocator); + const filled = try view.getAll(null); defer allocator.free(filled); var expected: [10]u32 = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; try std.testing.expectEqualSlices(u32, expected[0..], filled); @@ -564,13 +591,13 @@ test "TreeView list basic clone(true) does not transfer cache" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); + try std.testing.expect(view.chunks.children_nodes.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.base_view.data.children_nodes.count()); + try std.testing.expect(view.chunks.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.children_nodes.count()); } test "TreeView list basic clone(false) transfers cache and clears source" { @@ -590,13 +617,13 @@ test "TreeView list basic clone(false) transfers cache and clears source" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.base_view.data.children_nodes.count() > 0); + try std.testing.expect(view.chunks.children_nodes.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.base_view.data.children_nodes.count()); - try std.testing.expect(cloned.base_view.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.chunks.children_nodes.count()); + try std.testing.expect(cloned.chunks.children_nodes.count() > 0); } // Refer to https://github.com/ChainSafe/ssz/blob/7f5580c2ea69f9307300ddb6010a8bc7ce2fc471/packages/ssz/test/unit/byType/listBasic/tree.test.ts#L180-L203 @@ -632,7 +659,7 @@ test "TreeView basic list getAll reflects pushes" { } try view.commit(); - const filled = try view.getAll(allocator); + const filled = try view.getAll(null); defer allocator.free(filled); try std.testing.expectEqualSlices(u64, expected[0..], filled); } @@ -663,8 +690,10 @@ test "TreeView list sliceTo returns original when truncation unnecessary" { var expected_root: [32]u8 = undefined; try ListType.hashTreeRoot(allocator, &list, &expected_root); - const actual_root = try sliced.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try sliced.hashTreeRootInto(&actual_root); + + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); } // Refer to https://github.com/ChainSafe/ssz/blob/7f5580c2ea69f9307300ddb6010a8bc7ce2fc471/packages/ssz/test/unit/byType/listBasic/tree.test.ts#L219-L247 @@ -706,7 +735,7 @@ test "TreeView basic list sliceTo matches incremental snapshots" { var actual: ListType.Type = .empty; defer actual.deinit(allocator); - try ListType.tree.toValue(allocator, sliced.base_view.data.root, &pool, &actual); + try ListType.tree.toValue(allocator, sliced.getRoot(), &pool, &actual); try std.testing.expectEqual(expected_len, actual.items.len); try std.testing.expectEqualSlices(u64, expected.items, actual.items); @@ -724,8 +753,10 @@ test "TreeView basic list sliceTo matches incremental snapshots" { var expected_root: [32]u8 = undefined; try ListType.hashTreeRoot(allocator, &expected, &expected_root); - const actual_root = try sliced.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try sliced.hashTreeRootInto(&actual_root); + + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); } } @@ -754,7 +785,7 @@ test "TreeView list sliceTo truncates tail elements" { try std.testing.expectEqual(@as(usize, 3), try sliced.length()); - const filled = try sliced.getAll(allocator); + const filled = try sliced.getAll(null); defer allocator.free(filled); try std.testing.expectEqualSlices(u32, values[0..3], filled); @@ -766,8 +797,10 @@ test "TreeView list sliceTo truncates tail elements" { var expected_root: [32]u8 = undefined; try ListType.hashTreeRoot(allocator, &expected, &expected_root); - const actual_root = try sliced.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try sliced.hashTreeRootInto(&actual_root); + + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); } // Tests ported from TypeScript ssz packages/ssz/test/unit/byType/listBasic/tree.test.ts @@ -828,8 +861,9 @@ test "ListBasicTreeView - serialize (uint8 list)" { try std.testing.expectEqual(tc.expected_serialized.len, view_size); - const actual_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &tc.expected_root, actual_root); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); + try std.testing.expectEqualSlices(u8, &tc.expected_root, &hash_root); } } @@ -891,8 +925,9 @@ test "ListBasicTreeView - serialize (uint64 list)" { try std.testing.expectEqual(tc.expected_serialized.len, view_size); - const actual_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &tc.expected_root, actual_root); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); + try std.testing.expectEqualSlices(u8, &tc.expected_root, &hash_root); } } @@ -928,9 +963,10 @@ test "ListBasicTreeView - push and serialize" { const len = try view.length(); try std.testing.expectEqual(@as(usize, 4), len); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); const expected_root = [_]u8{ 0xba, 0xc5, 0x11, 0xd1, 0xf6, 0x41, 0xd6, 0xb8, 0x82, 0x32, 0x00, 0xbb, 0x4b, 0x3c, 0xce, 0xd3, 0xbd, 0x47, 0x20, 0x70, 0x1f, 0x18, 0x57, 0x1d, 0xff, 0x35, 0xa5, 0xd2, 0xa4, 0x01, 0x90, 0xfa }; - const actual_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + try std.testing.expectEqualSlices(u8, &expected_root, &hash_root); } test "ListBasicTreeView - sliceTo and serialize" { @@ -965,30 +1001,3 @@ test "ListBasicTreeView - sliceTo and serialize" { try std.testing.expectEqualSlices(u8, &[_]u8{ 1, 2 }, serialized); try std.testing.expectEqual(@as(usize, 2), try sliced.length()); } - -test "ListBasicTreeView - ReadonlyIterator" { - const allocator = std.testing.allocator; - - const Uint16 = UintType(16); - const ListU16Type = FixedListType(Uint16, 64); - - var pool = try Node.Pool.init(allocator, 1024); - defer pool.deinit(); - - var value: ListU16Type.Type = ListU16Type.default_value; - defer value.deinit(allocator); - const test_values = &[_]u16{ 10, 20, 30, 40, 50 }; - for (test_values) |v| { - try value.append(allocator, v); - } - - const tree_node = try ListU16Type.tree.fromValue(&pool, &value); - var view = try ListU16Type.TreeView.init(allocator, &pool, tree_node); - defer view.deinit(); - - var iter = view.iteratorReadonly(0); - for (test_values) |expected| { - const val = try iter.next(); - try std.testing.expectEqual(expected, val); - } -} diff --git a/src/ssz/tree_view/list_composite.zig b/src/ssz/tree_view/list_composite.zig index 45d184d7a..6fa19ccd2 100644 --- a/src/ssz/tree_view/list_composite.zig +++ b/src/ssz/tree_view/list_composite.zig @@ -11,8 +11,9 @@ const type_root = @import("../type/root.zig"); const chunkDepth = type_root.chunkDepth; const tree_view_root = @import("root.zig"); -const BaseTreeView = tree_view_root.BaseTreeView; const CompositeChunks = @import("chunks.zig").CompositeChunks; +const assertTreeViewType = @import("utils/assert.zig").assertTreeViewType; +const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// A specialized tree view for SSZ list types with composite element types. /// Each element occupies its own subtree. @@ -24,13 +25,19 @@ pub fn ListCompositeTreeView(comptime ST: type) type { if (!@hasDecl(ST, "Element") or isBasicType(ST.Element)) { @compileError("ListCompositeTreeView can only be used with List of composite element types"); } + assertTreeViewType(ST.Element.TreeView); } - return struct { - base_view: BaseTreeView, + const TreeView = struct { + allocator: Allocator, + chunks: Chunks, + // the original length, before any modifications + _orig_len: usize, + // the current length, may differ from original until committed + _len: usize, pub const SszType = ST; - pub const Element = ST.Element.TreeView; + pub const Element = *ST.Element.TreeView; const Self = @This(); @@ -38,96 +45,122 @@ pub fn ListCompositeTreeView(comptime ST: type) type { const chunk_depth: Depth = chunkDepth(Depth, base_chunk_depth, ST); const Chunks = CompositeChunks(ST, chunk_depth); - pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !Self { - return Self{ - .base_view = try BaseTreeView.init(allocator, pool, root), - }; + pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self { + const ptr = try allocator.create(Self); + errdefer allocator.destroy(ptr); + + try Chunks.init(&ptr.chunks, allocator, pool, root); + ptr.allocator = allocator; + ptr._orig_len = try ptr.chunks.getLength(); + ptr._len = ptr._orig_len; + return ptr; } - pub fn clone(self: *Self, opts: BaseTreeView.CloneOpts) !Self { - return Self{ .base_view = try self.base_view.clone(opts) }; + pub fn clone(self: *Self, opts: CloneOpts) !*Self { + const ptr = try self.allocator.create(Self); + errdefer self.allocator.destroy(ptr); + + try self.chunks.clone(opts, &ptr.chunks); + ptr.allocator = self.allocator; + ptr._orig_len = self._orig_len; + ptr._len = self._len; + return ptr; } pub fn deinit(self: *Self) void { - self.base_view.deinit(); + self.chunks.deinit(); + self.allocator.destroy(self); } pub fn commit(self: *Self) !void { - try self.base_view.commit(); + try self.updateListLength(); + try self.chunks.commit(); + self._orig_len = self._len; } pub fn clearCache(self: *Self) void { - self.base_view.clearCache(); + self.chunks.clearCache(); + } + + pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { + try self.commit(); + out.* = self.chunks.root.getRoot(self.chunks.pool).*; } - /// Return the root hash of the tree. - /// The returned array is owned by the internal pool and must not be modified. pub fn hashTreeRoot(self: *Self) !*const [32]u8 { - return try self.base_view.hashTreeRoot(); + try self.commit(); + return self.chunks.root.getRoot(self.chunks.pool); + } + + pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { + const root = try ST.tree.fromValue(pool, value); + errdefer pool.unref(root); + return try Self.init(allocator, pool, root); } - pub fn length(self: *Self) !usize { - const length_node = try self.base_view.getChildNode(@enumFromInt(3)); - const length_chunk = length_node.getRoot(self.base_view.pool); - return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); + pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { + try self.commit(); + try ST.tree.toValue(allocator, self.chunks.root, self.chunks.pool, out); } pub fn setLength(self: *Self, new_length: usize) !void { - try self.updateListLength(new_length); + self._len = new_length; } - pub fn getRoot(self: *Self, index: usize) !*const [32]u8 { - const field_data = try self.base_view.getChildData(Gindex.fromDepth(chunk_depth, index)); - try field_data.commit(self.base_view.allocator, self.base_view.pool); - return field_data.root.getRoot(self.base_view.pool); + pub fn getRoot(self: *const Self) Node.Id { + return self.chunks.root; + } + + pub fn length(self: *const Self) !usize { + return self._len; } pub fn get(self: *Self, index: usize) !Element { const list_length = try self.length(); if (index >= list_length) return error.IndexOutOfBounds; - return try Chunks.get(&self.base_view, index); + return self.chunks.get(index); } pub fn getReadonly(self: *Self, index: usize) !Element { const list_length = try self.length(); if (index >= list_length) return error.IndexOutOfBounds; - return try Chunks.getReadonly(&self.base_view, index); + return self.chunks.getReadonly(index); } pub fn getValue(self: *Self, allocator: Allocator, index: usize, out: *ST.Element.Type) !void { const list_length = try self.length(); if (index >= list_length) return error.IndexOutOfBounds; - return try Chunks.getValue(&self.base_view, allocator, index, out); + return self.chunks.getValue(allocator, index, out); } - pub fn set(self: *Self, index: usize, value: Element) !void { + pub fn setValue(self: *Self, index: usize, value: *const ST.Element.Type) !void { const list_length = try self.length(); if (index >= list_length) return error.IndexOutOfBounds; - try Chunks.set(&self.base_view, index, value); + try self.chunks.setValue(index, value); } - pub fn setValue(self: *Self, index: usize, value: *const ST.Element.Type) !void { + pub fn getFieldRoot(self: *Self, index: usize) !*const [32]u8 { const list_length = try self.length(); if (index >= list_length) return error.IndexOutOfBounds; - try Chunks.setValue(&self.base_view, index, value); + const elem = try self.chunks.get(index); + try elem.commit(); + return elem.getRoot().getRoot(self.chunks.pool); + } + + pub fn set(self: *Self, index: usize, value: Element) !void { + const list_length = try self.length(); + if (index >= list_length) return error.IndexOutOfBounds; + try self.chunks.set(index, value); } pub fn getAllReadonly(self: *Self, allocator: Allocator) ![]Element { - // TODO: Implement bulk read-only access after other PRs land. - _ = self; - _ = allocator; - return error.NotImplemented; + const list_length = try self.length(); + return self.chunks.getAllReadonly(allocator, list_length); } - /// Get all element values in a single traversal. - /// - /// WARNING: Returns all committed changes. If there are any pending changes, - /// commit them beforehand. - /// - /// Caller owns the returned slice and must free it with the same allocator. pub fn getAllReadonlyValues(self: *Self, allocator: Allocator) ![]ST.Element.Type { const list_length = try self.length(); - return try Chunks.getAllValues(&self.base_view, allocator, list_length); + return self.chunks.getAllValues(allocator, list_length); } /// Appends an element to the end of the list. @@ -137,32 +170,85 @@ pub fn ListCompositeTreeView(comptime ST: type) type { /// as it is now owned by the list. pub fn push(self: *Self, value: Element) !void { const list_length = try self.length(); - if (list_length >= ST.limit) return error.LengthOverLimit; + if (list_length >= ST.limit) { + return error.LengthOverLimit; + } - try self.updateListLength(list_length + 1); - try Chunks.set(&self.base_view, list_length, value); + self._len += 1; + try self.set(list_length, value); } + /// Push an SSZ value type, creating a TreeView internally. pub fn pushValue(self: *Self, value: *const ST.Element.Type) !void { - const root = try ST.Element.tree.fromValue(self.base_view.pool, value); - errdefer self.base_view.pool.unref(root); - var child_view = try ST.Element.TreeView.init( - self.base_view.allocator, - self.base_view.pool, - root, - ); + const root = try ST.Element.tree.fromValue(self.chunks.pool, value); + errdefer self.chunks.pool.unref(root); + const child_view = try ST.Element.TreeView.init(self.allocator, self.chunks.pool, root); errdefer child_view.deinit(); try self.push(child_view); } + pub fn iteratorReadonly(self: *const Self, start_index: usize) ReadonlyIterator { + return ReadonlyIterator.init(self, start_index); + } + + pub const ReadonlyIterator = struct { + tree_view: *const Self, + depth_iterator: Node.DepthIterator, + elem_index: usize, + + pub fn init(tree_view: *const Self, start_index: usize) ReadonlyIterator { + return .{ + .tree_view = tree_view, + .depth_iterator = Node.DepthIterator.init( + tree_view.chunks.pool, + tree_view.chunks.root, + chunk_depth, + start_index, + ), + .elem_index = start_index, + }; + } + + pub fn next(self: *ReadonlyIterator) !Element { + const node = try self.depth_iterator.next(); + const child_view = try ST.Element.TreeView.init( + self.tree_view.allocator, + self.tree_view.chunks.pool, + node, + ); + self.elem_index += 1; + return child_view; + } + + /// Get the hash tree root of the next element without constructing a TreeView. + pub fn nextRoot(self: *ReadonlyIterator) !*const [32]u8 { + const node = try self.depth_iterator.next(); + self.elem_index += 1; + return node.getRoot(self.tree_view.chunks.pool); + } + + /// Get the next element as an SSZ value type. + pub fn nextValue(self: *ReadonlyIterator, allocator: Allocator) !ST.Element.Type { + const node = try self.depth_iterator.next(); + self.elem_index += 1; + var value: ST.Element.Type = undefined; + if (comptime isFixedType(ST.Element)) { + try ST.Element.tree.toValue(node, self.tree_view.chunks.pool, &value); + } else { + try ST.Element.tree.toValue(allocator, node, self.tree_view.chunks.pool, &value); + } + return value; + } + }; + /// Return a new view containing all elements up to and including `index`. /// The caller **must** call `deinit()` on the returned view to avoid memory leaks. - pub fn sliceTo(self: *Self, index: usize) !Self { + pub fn sliceTo(self: *Self, index: usize) !*Self { try self.commit(); const list_length = try self.length(); if (list_length == 0 or index >= list_length - 1) { - return try Self.init(self.base_view.allocator, self.base_view.pool, self.base_view.data.root); + return try Self.init(self.allocator, self.chunks.pool, self.chunks.root); } const new_length = index + 1; @@ -170,149 +256,81 @@ pub fn ListCompositeTreeView(comptime ST: type) type { return error.LengthOverLimit; } - var chunk_root: ?Node.Id = try Node.Id.truncateAfterIndex(self.base_view.data.root, self.base_view.pool, chunk_depth, index); - defer if (chunk_root) |id| self.base_view.pool.unref(id); + var chunk_root: ?Node.Id = try Node.Id.truncateAfterIndex(self.chunks.root, self.chunks.pool, chunk_depth, index); + defer if (chunk_root) |id| self.chunks.pool.unref(id); - var length_node: ?Node.Id = try self.base_view.pool.createLeafFromUint(@intCast(new_length)); - defer if (length_node) |id| self.base_view.pool.unref(id); - const root_with_length = try Node.Id.setNode(chunk_root.?, self.base_view.pool, @enumFromInt(3), length_node.?); - errdefer self.base_view.pool.unref(root_with_length); + var length_node: ?Node.Id = try self.chunks.pool.createLeafFromUint(@intCast(new_length)); + defer if (length_node) |id| self.chunks.pool.unref(id); + const root_with_length = try Node.Id.setNode(chunk_root.?, self.chunks.pool, @enumFromInt(3), length_node.?); + errdefer self.chunks.pool.unref(root_with_length); length_node = null; chunk_root = null; - return try Self.init(self.base_view.allocator, self.base_view.pool, root_with_length); + return try Self.init(self.allocator, self.chunks.pool, root_with_length); } /// Return a new view containing all elements from `index` to the end. /// The returned view must be deinitialized by the caller using `deinit()` to avoid memory leaks. - pub fn sliceFrom(self: *Self, index: usize) !Self { + pub fn sliceFrom(self: *Self, index: usize) !*Self { try self.commit(); const list_length = try self.length(); if (index == 0) { - return try Self.init(self.base_view.allocator, self.base_view.pool, self.base_view.data.root); + return try Self.init(self.allocator, self.chunks.pool, self.chunks.root); } const target_length = if (index >= list_length) 0 else list_length - index; var chunk_root: ?Node.Id = null; - defer if (chunk_root) |id| self.base_view.pool.unref(id); + defer if (chunk_root) |id| self.chunks.pool.unref(id); if (target_length == 0) { chunk_root = @enumFromInt(base_chunk_depth); } else { - const nodes = try self.base_view.allocator.alloc(Node.Id, target_length); - defer self.base_view.allocator.free(nodes); - try self.base_view.data.root.getNodesAtDepth(self.base_view.pool, chunk_depth, index, nodes); + const nodes = try self.allocator.alloc(Node.Id, target_length); + defer self.allocator.free(nodes); + try self.chunks.root.getNodesAtDepth(self.chunks.pool, chunk_depth, index, nodes); - chunk_root = try Node.fillWithContents(self.base_view.pool, nodes, base_chunk_depth); + chunk_root = try Node.fillWithContents(self.chunks.pool, nodes, base_chunk_depth); } - var length_node: ?Node.Id = try self.base_view.pool.createLeafFromUint(@intCast(target_length)); - defer if (length_node) |id| self.base_view.pool.unref(id); + var length_node: ?Node.Id = try self.chunks.pool.createLeafFromUint(@intCast(target_length)); + defer if (length_node) |id| self.chunks.pool.unref(id); - const new_root = try self.base_view.pool.createBranch(chunk_root.?, length_node.?); - errdefer self.base_view.pool.unref(new_root); + const new_root = try self.chunks.pool.createBranch(chunk_root.?, length_node.?); + errdefer self.chunks.pool.unref(new_root); length_node = null; chunk_root = null; - return try Self.init(self.base_view.allocator, self.base_view.pool, new_root); - } - - fn updateListLength(self: *Self, new_length: usize) !void { - if (new_length > ST.limit) { - return error.LengthOverLimit; - } - const length_node = try self.base_view.pool.createLeafFromUint(@intCast(new_length)); - errdefer self.base_view.pool.unref(length_node); - try self.base_view.setChildNode(@enumFromInt(3), length_node); + return try Self.init(self.allocator, self.chunks.pool, new_root); } /// Serialize the tree view into a provided buffer. /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.base_view.data.root, self.base_view.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); } /// Get the serialized size of this tree view. pub fn serializedSize(self: *Self) !usize { try self.commit(); - return try ST.tree.serializedSize(self.base_view.data.root, self.base_view.pool); - } - - pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !Self { - const root = try ST.tree.fromValue(pool, value); - errdefer pool.unref(root); - return try Self.init(allocator, pool, root); - } - - pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { - try self.commit(); - try ST.tree.toValue(allocator, self.base_view.data.root, self.base_view.pool, out); - } - - /// Get a read-only iterator over the elements of the list. - /// This only iterates over committed elements. - /// It is up to the caller to ensure that the iterator doesn't run past the end of the list. - /// - /// Convenience wrapper around `ReadonlyIterator.init`. - pub fn iteratorReadonly(self: *const Self, start_index: usize) ReadonlyIterator { - return ReadonlyIterator.init(self, start_index); + return try ST.tree.serializedSize(self.chunks.root, self.chunks.pool); } - /// Get a read-only iterator over the elements of the list. - /// This only iterates over committed elements. - /// It is up to the caller to ensure that the iterator doesn't run past the end of the list. - pub const ReadonlyIterator = struct { - tree_view: *const Self, - depth_iterator: Node.DepthIterator, - - pub fn init(tree_view: *const Self, start_index: usize) ReadonlyIterator { - return .{ - .tree_view = tree_view, - .depth_iterator = Node.DepthIterator.init( - tree_view.base_view.pool, - tree_view.base_view.data.root, - ST.chunk_depth + 1, - start_index, - ), - }; + fn updateListLength(self: *Self) !void { + if (self._len == self._orig_len) { + return; } - /// Return the next element of the iterator as a TreeView. - /// Caller owns the returned TreeView. - pub fn next(self: *ReadonlyIterator) !Element { - const node = try self.depth_iterator.next(); - return try ST.Element.TreeView.init( - self.tree_view.base_view.allocator, - self.tree_view.base_view.pool, - node, - ); - } - - /// Return the root of the next element of the iterator - /// Caller must not modify the returned root. - pub fn nextRoot(self: *ReadonlyIterator) !*const [32]u8 { - const node = try self.depth_iterator.next(); - return node.getRoot(self.tree_view.base_view.pool); - } - - /// Return the next element of the iterator as a value. - /// Caller owns the returned value. - pub fn nextValue(self: *ReadonlyIterator, allocator: Allocator) !ST.Element.Type { - const node = try self.depth_iterator.next(); - var out = ST.Element.default_value; - if (comptime isFixedType(ST.Element)) { - try ST.Element.tree.toValue(node, self.tree_view.base_view.pool, &out); - } else { - try ST.Element.tree.toValue(allocator, node, self.tree_view.base_view.pool, &out); - } + std.debug.assert(self._len <= ST.limit); - return out; - } - }; + try self.chunks.setLength(self._len); + } }; + + assertTreeViewType(TreeView); + return TreeView; } const FixedContainerType = @import("../type/container.zig").FixedContainerType; @@ -358,7 +376,7 @@ test "TreeView composite list sliceTo truncates elements" { var roundtrip: ListType.Type = .empty; defer roundtrip.deinit(allocator); - try ListType.tree.toValue(allocator, sliced.base_view.data.root, &pool, &roundtrip); + try ListType.tree.toValue(allocator, sliced.getRoot(), &pool, &roundtrip); try std.testing.expectEqual(@as(usize, 2), roundtrip.items.len); try std.testing.expectEqual(checkpoints[0].epoch, roundtrip.items[0].epoch); @@ -394,7 +412,7 @@ test "TreeView composite list sliceFrom returns suffix" { var roundtrip: ListType.Type = .empty; defer roundtrip.deinit(allocator); - try ListType.tree.toValue(allocator, suffix.base_view.data.root, &pool, &roundtrip); + try ListType.tree.toValue(allocator, suffix.getRoot(), &pool, &roundtrip); try std.testing.expectEqual(@as(usize, 2), roundtrip.items.len); try std.testing.expectEqual(checkpoints[2].epoch, roundtrip.items[0].epoch); @@ -452,7 +470,7 @@ test "TreeView composite list sliceFrom handles boundary conditions" { var actual: ListType.Type = .empty; defer actual.deinit(allocator); - try ListType.tree.toValue(allocator, sliced.base_view.data.root, &pool, &actual); + try ListType.tree.toValue(allocator, sliced.getRoot(), &pool, &actual); var expected: ListType.Type = .empty; defer expected.deinit(allocator); @@ -470,8 +488,10 @@ test "TreeView composite list sliceFrom handles boundary conditions" { var expected_root: [32]u8 = expected_node.getRoot(&pool).*; defer pool.unref(expected_node); - const actual_root = try sliced.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try sliced.hashTreeRootInto(&actual_root); + + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); } } } @@ -508,7 +528,7 @@ test "TreeView composite list push appends element" { var roundtrip: ListType.Type = .empty; defer roundtrip.deinit(allocator); - try ListType.tree.toValue(allocator, view.base_view.data.root, &pool, &roundtrip); + try ListType.tree.toValue(allocator, view.getRoot(), &pool, &roundtrip); try std.testing.expectEqual(@as(usize, 2), roundtrip.items.len); try std.testing.expectEqual(next_checkpoint.epoch, roundtrip.items[1].epoch); @@ -534,19 +554,19 @@ test "TreeView composite list clone isolates updates" { const replacement = Checkpoint.Type{ .epoch = 9, .root = [_]u8{9} ** 32 }; const replacement_root = try Checkpoint.tree.fromValue(&pool, &replacement); - var replacement_view: ?Checkpoint.TreeView = try Checkpoint.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v| v.deinit(); + var replacement_view: ?*Checkpoint.TreeView = try Checkpoint.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v| v.deinit(); try v2.set(0, replacement_view.?); replacement_view = null; try v2.commit(); const v1_e0 = try v1.get(0); var v1_e0_value: Checkpoint.Type = undefined; - try Checkpoint.tree.toValue(v1_e0.base_view.data.root, &pool, &v1_e0_value); + try Checkpoint.tree.toValue(v1_e0.getRoot(), &pool, &v1_e0_value); const v2_e0 = try v2.get(0); var v2_e0_value: Checkpoint.Type = undefined; - try Checkpoint.tree.toValue(v2_e0.base_view.data.root, &pool, &v2_e0_value); + try Checkpoint.tree.toValue(v2_e0.getRoot(), &pool, &v2_e0_value); try std.testing.expectEqual(@as(u64, 1), v1_e0_value.epoch); try std.testing.expectEqual(@as(u64, 9), v2_e0_value.epoch); @@ -569,8 +589,8 @@ test "TreeView composite list clone reads committed state" { const replacement = Checkpoint.Type{ .epoch = 9, .root = [_]u8{9} ** 32 }; const replacement_root = try Checkpoint.tree.fromValue(&pool, &replacement); - var replacement_view: ?Checkpoint.TreeView = try Checkpoint.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v| v.deinit(); + var replacement_view: ?*Checkpoint.TreeView = try Checkpoint.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v| v.deinit(); try v1.set(0, replacement_view.?); replacement_view = null; try v1.commit(); @@ -580,7 +600,7 @@ test "TreeView composite list clone reads committed state" { const v2_e0 = try v2.get(0); var v2_e0_value: Checkpoint.Type = undefined; - try Checkpoint.tree.toValue(v2_e0.base_view.data.root, &pool, &v2_e0_value); + try Checkpoint.tree.toValue(v2_e0.getRoot(), &pool, &v2_e0_value); try std.testing.expectEqual(@as(u64, 9), v2_e0_value.epoch); } @@ -602,14 +622,14 @@ test "TreeView composite list clone drops uncommitted changes" { const replacement = Checkpoint.Type{ .epoch = 9, .root = [_]u8{9} ** 32 }; const replacement_root = try Checkpoint.tree.fromValue(&pool, &replacement); - var replacement_view: ?Checkpoint.TreeView = try Checkpoint.TreeView.init(allocator, &pool, replacement_root); - defer if (replacement_view) |*v0| v0.deinit(); + var replacement_view: ?*Checkpoint.TreeView = try Checkpoint.TreeView.init(allocator, &pool, replacement_root); + defer if (replacement_view) |v0| v0.deinit(); try v.set(0, replacement_view.?); replacement_view = null; const v_e0_before = try v.get(0); var v_e0_before_value: Checkpoint.Type = undefined; - try Checkpoint.tree.toValue(v_e0_before.base_view.data.root, &pool, &v_e0_before_value); + try Checkpoint.tree.toValue(v_e0_before.getRoot(), &pool, &v_e0_before_value); try std.testing.expectEqual(@as(u64, 9), v_e0_before_value.epoch); var dropped = try v.clone(.{}); @@ -617,11 +637,11 @@ test "TreeView composite list clone drops uncommitted changes" { const v_e0_after = try v.get(0); var v_e0_after_value: Checkpoint.Type = undefined; - try Checkpoint.tree.toValue(v_e0_after.base_view.data.root, &pool, &v_e0_after_value); + try Checkpoint.tree.toValue(v_e0_after.getRoot(), &pool, &v_e0_after_value); const dropped_e0 = try dropped.get(0); var dropped_e0_value: Checkpoint.Type = undefined; - try Checkpoint.tree.toValue(dropped_e0.base_view.data.root, &pool, &dropped_e0_value); + try Checkpoint.tree.toValue(dropped_e0.getRoot(), &pool, &dropped_e0_value); try std.testing.expectEqual(@as(u64, 1), v_e0_after_value.epoch); try std.testing.expectEqual(@as(u64, 1), dropped_e0_value.epoch); @@ -645,13 +665,13 @@ test "TreeView composite list clone(true) does not transfer cache" { _ = try view.get(0); try view.commit(); - try std.testing.expect(view.base_view.data.children_data.count() > 0); + try std.testing.expect(view.chunks.children_data.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.base_view.data.children_data.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.base_view.data.children_data.count()); + try std.testing.expect(view.chunks.children_data.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.children_data.count()); } test "TreeView composite list clone(false) transfers cache and clears source" { @@ -672,13 +692,13 @@ test "TreeView composite list clone(false) transfers cache and clears source" { _ = try view.get(0); try view.commit(); - try std.testing.expect(view.base_view.data.children_data.count() > 0); + try std.testing.expect(view.chunks.children_data.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.base_view.data.children_data.count()); - try std.testing.expect(cloned.base_view.data.children_data.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.chunks.children_data.count()); + try std.testing.expect(cloned.chunks.children_data.count() > 0); } test "TreeView list of list commits inner length updates" { @@ -715,9 +735,9 @@ test "TreeView list of list commits inner length updates" { var e1_value: InnerElement.Type = InnerElement.default_value; defer InnerElement.deinit(allocator, &e1_value); const e1_root = try InnerElement.tree.fromValue(&pool, &e1_value); - var e1_view: ?InnerElement.TreeView = try InnerElement.TreeView.init(allocator, &pool, e1_root); - defer if (e1_view) |*view| view.deinit(); - const e1 = &e1_view.?; + var e1_view: ?*InnerElement.TreeView = try InnerElement.TreeView.init(allocator, &pool, e1_root); + defer if (e1_view) |view| view.deinit(); + const e1 = e1_view.?; try e1.set("id", @as(u32, 11)); @@ -725,16 +745,15 @@ test "TreeView list of list commits inner length updates" { var payload_value: Bytes.Type = Bytes.default_value; defer payload_value.deinit(allocator); const payload_root = try Bytes.tree.fromValue(&pool, &payload_value); - var payload_view: ?Bytes.TreeView = try Bytes.TreeView.init(allocator, &pool, payload_root); - defer if (payload_view) |*view| view.deinit(); - const payload = &payload_view.?; + var payload_view: ?*Bytes.TreeView = try Bytes.TreeView.init(allocator, &pool, payload_root); + defer if (payload_view) |view| view.deinit(); + const payload = payload_view.?; try payload.push(@as(u8, 0xAA)); try payload.push(@as(u8, 0xAB)); try payload.set(1, @as(u8, 0xAC)); - try payload.commit(); { - const all = try payload.getAll(allocator); + const all = try payload.getAll(null); defer allocator.free(all); try std.testing.expectEqualSlices(u8, &[_]u8{ 0xAA, 0xAC }, all); @@ -749,16 +768,15 @@ test "TreeView list of list commits inner length updates" { var numbers_value: Numbers.Type = .empty; defer numbers_value.deinit(allocator); const numbers_root = try Numbers.tree.fromValue(&pool, &numbers_value); - var numbers_view: ?Numbers.TreeView = try Numbers.TreeView.init(allocator, &pool, numbers_root); - defer if (numbers_view) |*view| view.deinit(); - const numbers = &numbers_view.?; + var numbers_view: ?*Numbers.TreeView = try Numbers.TreeView.init(allocator, &pool, numbers_root); + defer if (numbers_view) |view| view.deinit(); + const numbers = numbers_view.?; try numbers.push(@as(u32, 1)); try numbers.push(@as(u32, 2)); try numbers.set(0, @as(u32, 3)); - try numbers.commit(); { - const all = try numbers.getAll(allocator); + const all = try numbers.getAll(null); defer allocator.free(all); try std.testing.expectEqual(@as(usize, 2), all.len); try std.testing.expectEqual(@as(u32, 3), all[0]); @@ -775,15 +793,14 @@ test "TreeView list of list commits inner length updates" { var vec_value: Vec2.Type = [_]u32{ 0, 0 }; const vec_root = try Vec2.tree.fromValue(&pool, &vec_value); - var vec_view: ?Vec2.TreeView = try Vec2.TreeView.init(allocator, &pool, vec_root); - defer if (vec_view) |*view| view.deinit(); - const vec = &vec_view.?; + var vec_view: ?*Vec2.TreeView = try Vec2.TreeView.init(allocator, &pool, vec_root); + defer if (vec_view) |view| view.deinit(); + const vec = vec_view.?; try vec.set(0, @as(u32, 9)); try vec.set(1, @as(u32, 10)); - try vec.commit(); { - const all = try vec.getAll(allocator); + const all = try vec.getAll(null); defer allocator.free(all); try std.testing.expectEqual(@as(usize, 2), all.len); try std.testing.expectEqual(@as(u32, 9), all[0]); @@ -804,18 +821,18 @@ test "TreeView list of list commits inner length updates" { var e2_value: InnerElement.Type = InnerElement.default_value; defer InnerElement.deinit(allocator, &e2_value); const e2_root = try InnerElement.tree.fromValue(&pool, &e2_value); - var e2_view: ?InnerElement.TreeView = try InnerElement.TreeView.init(allocator, &pool, e2_root); - defer if (e2_view) |*view| view.deinit(); - const e2 = &e2_view.?; + var e2_view: ?*InnerElement.TreeView = try InnerElement.TreeView.init(allocator, &pool, e2_root); + defer if (e2_view) |view| view.deinit(); + const e2 = e2_view.?; try e2.set("id", @as(u32, 22)); var e2_payload_value: Bytes.Type = Bytes.default_value; defer e2_payload_value.deinit(allocator); const e2_payload_root = try Bytes.tree.fromValue(&pool, &e2_payload_value); - var e2_payload_view: ?Bytes.TreeView = try Bytes.TreeView.init(allocator, &pool, e2_payload_root); - defer if (e2_payload_view) |*view| view.deinit(); - const e2_payload = &e2_payload_view.?; + var e2_payload_view: ?*Bytes.TreeView = try Bytes.TreeView.init(allocator, &pool, e2_payload_root); + defer if (e2_payload_view) |view| view.deinit(); + const e2_payload = e2_payload_view.?; try e2_payload.push(@as(u8, 0xBB)); try e2.set("payload", e2_payload_view.?); e2_payload_view = null; @@ -827,9 +844,9 @@ test "TreeView list of list commits inner length updates" { var e3_value: InnerElement.Type = InnerElement.default_value; defer InnerElement.deinit(allocator, &e3_value); const e3_root = try InnerElement.tree.fromValue(&pool, &e3_value); - var e3_view: ?InnerElement.TreeView = try InnerElement.TreeView.init(allocator, &pool, e3_root); - defer if (e3_view) |*view| view.deinit(); - const e3 = &e3_view.?; + var e3_view: ?*InnerElement.TreeView = try InnerElement.TreeView.init(allocator, &pool, e3_root); + defer if (e3_view) |view| view.deinit(); + const e3 = e3_view.?; try e3.set("id", @as(u32, 33)); try inner_view.set(1, e3_view.?); e3_view = null; @@ -845,7 +862,7 @@ test "TreeView list of list commits inner length updates" { // Roundtrip and verify nested lengths and values. var roundtrip: OuterListType.Type = .empty; defer OuterListType.deinit(allocator, &roundtrip); - try OuterListType.tree.toValue(allocator, outer_view.base_view.data.root, &pool, &roundtrip); + try OuterListType.tree.toValue(allocator, outer_view.getRoot(), &pool, &roundtrip); try std.testing.expectEqual(@as(usize, 1), roundtrip.items.len); try std.testing.expectEqual(@as(usize, 2), roundtrip.items[0].items.len); @@ -897,7 +914,7 @@ test "TreeView composite list sliceTo matches incremental snapshots" { var actual: ListType.Type = .empty; defer actual.deinit(allocator); - try ListType.tree.toValue(allocator, sliced.base_view.data.root, &pool, &actual); + try ListType.tree.toValue(allocator, sliced.getRoot(), &pool, &actual); var expected: ListType.Type = .empty; defer expected.deinit(allocator); @@ -912,8 +929,10 @@ test "TreeView composite list sliceTo matches incremental snapshots" { var expected_root: [32]u8 = undefined; try ListType.hashTreeRoot(allocator, &expected, &expected_root); - const actual_root = try sliced.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, actual_root); + var actual_root: [32]u8 = undefined; + try sliced.hashTreeRootInto(&actual_root); + + try std.testing.expectEqualSlices(u8, &expected_root, &actual_root); const serialized_len = ListType.serializedSize(&expected); const expected_bytes = try allocator.alloc(u8, serialized_len); @@ -986,8 +1005,9 @@ test "ListCompositeTreeView - serialize (ByteVector32 list)" { try std.testing.expectEqualSlices(u8, value_serialized, view_serialized); try std.testing.expectEqual(value_serialized.len, view_size); - const hash_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &tc.expected_root, hash_root); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); + try std.testing.expectEqualSlices(u8, &tc.expected_root, &hash_root); } } @@ -1061,8 +1081,9 @@ test "ListCompositeTreeView - serialize (Container list)" { try std.testing.expectEqualSlices(u8, tc.expected_serialized, view_serialized); try std.testing.expectEqualSlices(u8, value_serialized, view_serialized); - const hash_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &tc.expected_root, hash_root); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); + try std.testing.expectEqualSlices(u8, &tc.expected_root, &hash_root); } } @@ -1105,54 +1126,8 @@ test "ListCompositeTreeView - push and serialize" { try std.testing.expectEqualSlices(u8, &val1, serialized[0..32]); try std.testing.expectEqualSlices(u8, &val2, serialized[32..64]); + var hash_root: [32]u8 = undefined; + try view.hashTreeRootInto(&hash_root); const expected_root = [_]u8{ 0x0c, 0xb9, 0x47, 0x37, 0x7e, 0x17, 0x7f, 0x77, 0x47, 0x19, 0xea, 0xd8, 0xd2, 0x10, 0xaf, 0x9c, 0x64, 0x61, 0xf4, 0x1b, 0xaf, 0x5b, 0x40, 0x82, 0xf8, 0x6a, 0x39, 0x11, 0x45, 0x48, 0x31, 0xb8 }; - const hash_root = try view.hashTreeRoot(); - try std.testing.expectEqualSlices(u8, &expected_root, hash_root); -} - -test "ListCompositeTreeView - ReadonlyIterator" { - const allocator = std.testing.allocator; - - const Root32 = ByteVectorType(32); - const ListRootsType = FixedListType(Root32, 128); - - var pool = try Node.Pool.init(allocator, 1024); - defer pool.deinit(); - - var value: ListRootsType.Type = ListRootsType.default_value; - defer value.deinit(allocator); - - const data = [_][32]u8{ - [_]u8{0xaa} ** 32, - [_]u8{0xbb} ** 32, - [_]u8{0xcc} ** 32, - [_]u8{0xdd} ** 32, - [_]u8{0xee} ** 32, - [_]u8{0xff} ** 32, - }; - for (data) |d| { - try value.append(allocator, d); - } - - const tree_node = try ListRootsType.tree.fromValue(&pool, &value); - var view = try ListRootsType.TreeView.init(allocator, &pool, tree_node); - defer view.deinit(); - - var iter = view.iteratorReadonly(0); - - for (data) |expected| { - var elem = try iter.next(); - defer elem.deinit(); - var elem_value: [32]u8 = undefined; - - try Root32.tree.toValue(elem.base_view.data.root, &pool, &elem_value); - try std.testing.expectEqualSlices(u8, &expected, &elem_value); - } - - iter = view.iteratorReadonly(0); - for (data) |expected| { - const elem_value = try iter.nextValue(undefined); - - try std.testing.expectEqualSlices(u8, &expected, &elem_value); - } + try std.testing.expectEqualSlices(u8, &expected_root, &hash_root); } diff --git a/src/ssz/tree_view/root.zig b/src/ssz/tree_view/root.zig index bb1c3a924..99fa4da5d 100644 --- a/src/ssz/tree_view/root.zig +++ b/src/ssz/tree_view/root.zig @@ -1,5 +1,5 @@ -pub const TreeViewData = @import("base.zig").TreeViewData; -pub const BaseTreeView = @import("base.zig").BaseTreeView; +const std = @import("std"); + pub const ContainerTreeView = @import("container.zig").ContainerTreeView; pub const ArrayBasicTreeView = @import("array_basic.zig").ArrayBasicTreeView; pub const ArrayCompositeTreeView = @import("array_composite.zig").ArrayCompositeTreeView; diff --git a/src/ssz/tree_view/utils/assert.zig b/src/ssz/tree_view/utils/assert.zig new file mode 100644 index 000000000..cfc432c40 --- /dev/null +++ b/src/ssz/tree_view/utils/assert.zig @@ -0,0 +1,53 @@ +/// To implement a TreeView type, you must implement the following functions: +/// pub fn init(allocator: Allocator, pool: *Node.Pool, root: Node.Id) !*Self +/// pub fn deinit(self: *Self) void +/// pub fn commit(self: *Self) !void +/// pub fn getRoot(self: *const Self) Node.Id +/// pub fn hashTreeRoot(self: *Self, out: *[32]u8) !void +/// +/// it usually also contains these fields: +/// allocator: Allocator +/// pool: *Node.Pool +/// root: Node.Id +pub fn assertTreeViewType(comptime TV: type) void { + if (!@hasDecl(TV, "init")) { + @compileError("TreeView type must implement 'init' function"); + } + + const init_fn_info = @typeInfo(@TypeOf(TV.init)); + if (init_fn_info != .@"fn") { + @compileError("TreeView 'init' must be a function"); + } + + const return_type = init_fn_info.@"fn".return_type orelse @compileError("TreeView 'init' must have a return type"); + + const return_payload_type = switch (@typeInfo(return_type)) { + .error_union => |eu| eu.payload, + else => @compileError("TreeView 'init' must return an error union"), + }; + + const Self = switch (@typeInfo(return_payload_type)) { + .pointer => |ptr_info| ptr_info.child, + else => @compileError("TreeView 'init' must return a pointer to TreeView type"), + }; + + if (Self != TV) { + @compileError("TreeView 'init' must return pointer to Self type"); + } + + if (!@hasDecl(TV, "deinit")) { + @compileError("TreeView type must implement 'deinit' function"); + } + + if (!@hasDecl(TV, "commit")) { + @compileError("TreeView type must implement 'commit' function"); + } + + if (!@hasDecl(TV, "getRoot")) { + @compileError("TreeView type must implement 'getRoot' function"); + } + + if (!@hasDecl(TV, "hashTreeRoot")) { + @compileError("TreeView type must implement 'hashTreeRoot' function"); + } +} diff --git a/src/ssz/tree_view/utils/child_nodes.zig b/src/ssz/tree_view/utils/child_nodes.zig new file mode 100644 index 000000000..324b107b3 --- /dev/null +++ b/src/ssz/tree_view/utils/child_nodes.zig @@ -0,0 +1,106 @@ +const std = @import("std"); +const Node = @import("persistent_merkle_tree").Node; +const Gindex = @import("persistent_merkle_tree").Gindex; +const CloneOpts = @import("clone_opts.zig").CloneOpts; + +/// Common functions for `TreeView`s dealing with `children_nodes`. +pub const ChildNodes = struct { + pub fn getChildNode(self: anytype, gindex: Gindex) !Node.Id { + const gop = try self.children_nodes.getOrPut(self.allocator, gindex); + if (gop.found_existing) { + return gop.value_ptr.*; + } + const child_node = try self.root.getNode(self.pool, gindex); + gop.value_ptr.* = child_node; + return child_node; + } + + pub fn setChildNode(self: anytype, gindex: Gindex, node: Node.Id) !void { + try self.changed.put(self.allocator, gindex, {}); + const opt_old_node = try self.children_nodes.fetchPut( + self.allocator, + gindex, + node, + ); + if (opt_old_node) |old_node| { + // Multiple set() calls before commit() leave our previous temp nodes cached with refcount 0. + // Tree-owned nodes already have a refcount, so skip unref in that case. + if (old_node.value.getState(self.pool).getRefCount() == 0) { + self.pool.unref(old_node.value); + } + } + } + + pub fn clearChildrenNodesCache(self: anytype, pool: *Node.Pool) void { + var value_iter = self.children_nodes.valueIterator(); + while (value_iter.next()) |node_id_ptr| { + const node_id = node_id_ptr.*; + if (node_id.getState(pool).getRefCount() == 0) { + pool.unref(node_id); + } + } + self.children_nodes.clearRetainingCapacity(); + } + + pub fn getLength(self: anytype) !usize { + const length_node = try getChildNode(self, @enumFromInt(3)); + const length_chunk = length_node.getRoot(self.pool); + return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); + } + + pub fn setLength(self: anytype, length: usize) !void { + const length_node = try self.pool.createLeafFromUint(@intCast(length)); + errdefer self.pool.unref(length_node); + try self.setChildNode(@enumFromInt(3), length_node); + } + + /// Common functions for TreeViews deal with `children_nodes` + `changed` + pub const Change = struct { + pub fn commit(self: anytype) !void { + if (self.changed.count() == 0) { + return; + } + + const nodes = try self.allocator.alloc(Node.Id, self.changed.count()); + defer self.allocator.free(nodes); + + const gindices = self.changed.keys(); + Gindex.sortAsc(gindices); + + for (gindices, 0..) |gindex, i| { + if (self.children_nodes.get(gindex)) |child_node| { + nodes[i] = child_node; + } else { + return error.ChildNotFound; + } + } + + const new_root = try self.root.setNodesGrouped(self.pool, gindices, nodes); + try self.pool.ref(new_root); + self.pool.unref(self.root); + self.root = new_root; + + self.changed.clearRetainingCapacity(); + } + + pub fn clone(comptime T: type, self: *T, opts: CloneOpts, out: *T) !void { + try T.init(out, self.allocator, self.pool, self.root); + + if (!opts.transfer_cache) { + return; + } + + out.children_nodes = self.children_nodes; + + // Removing entries while iterating the same map can invalidate the iterator. + // Remove by traversing `self.changed` keys instead. + for (self.changed.keys()) |gindex| { + _ = out.children_nodes.remove(gindex); + } + + // clear self's caches + self.children_nodes = .empty; + self.changed.clearRetainingCapacity(); + } + }; +}; diff --git a/src/ssz/tree_view/utils/clone_opts.zig b/src/ssz/tree_view/utils/clone_opts.zig new file mode 100644 index 000000000..71f082968 --- /dev/null +++ b/src/ssz/tree_view/utils/clone_opts.zig @@ -0,0 +1,5 @@ +pub const CloneOpts = struct { + /// When true, transfer *safe* cache entries from `self` into the clone. + /// When false, the clone starts with an empty cache and `self` keeps its caches. + transfer_cache: bool = true, +}; diff --git a/src/ssz/type/container.zig b/src/ssz/type/container.zig index 82329da94..e4315b22f 100644 --- a/src/ssz/type/container.zig +++ b/src/ssz/type/container.zig @@ -512,6 +512,7 @@ pub fn VariableContainerType(comptime ST: type) type { } pub fn getFieldType(comptime name: []const u8) type { + @setEvalBranchQuota(20000); inline for (fields) |field| { if (std.mem.eql(u8, name, field.name)) { return field.type; diff --git a/src/state_transition/block/process_attestation_phase0.zig b/src/state_transition/block/process_attestation_phase0.zig index fbab02d77..c5e40c865 100644 --- a/src/state_transition/block/process_attestation_phase0.zig +++ b/src/state_transition/block/process_attestation_phase0.zig @@ -35,7 +35,7 @@ pub fn processAttestationPhase0( }; var justified_checkpoint: types.phase0.Checkpoint.Type = undefined; - var epoch_pending_attestations: types.phase0.EpochAttestations.TreeView = undefined; + var epoch_pending_attestations: *types.phase0.EpochAttestations.TreeView = undefined; if (data.target.epoch == epoch_cache.epoch) { try state.currentJustifiedCheckpoint(&justified_checkpoint); epoch_pending_attestations = try state.currentEpochPendingAttestations(); diff --git a/src/state_transition/block/process_bls_to_execution_change.zig b/src/state_transition/block/process_bls_to_execution_change.zig index 452aa3769..599fff4c9 100644 --- a/src/state_transition/block/process_bls_to_execution_change.zig +++ b/src/state_transition/block/process_bls_to_execution_change.zig @@ -46,7 +46,7 @@ pub fn isValidBlsToExecutionChange( } var validator = try validators.get(@intCast(validator_index)); - const withdrawal_credentials = try validator.getRoot("withdrawal_credentials"); + const withdrawal_credentials = try validator.getFieldRoot("withdrawal_credentials"); if (withdrawal_credentials[0] != c.BLS_WITHDRAWAL_PREFIX) { return error.InvalidWithdrawalCredentialsPrefix; } diff --git a/src/state_transition/block/process_consolidation_request.zig b/src/state_transition/block/process_consolidation_request.zig index 7efe81744..18373a03e 100644 --- a/src/state_transition/block/process_consolidation_request.zig +++ b/src/state_transition/block/process_consolidation_request.zig @@ -63,8 +63,8 @@ pub fn processConsolidationRequest( var validators = try state.validators(); var source_validator = try validators.get(@intCast(source_index)); var target_validator = try validators.get(@intCast(target_index)); - const source_withdrawal_credentials = try source_validator.getRoot("withdrawal_credentials"); - const target_withdrawal_credentials = try target_validator.getRoot("withdrawal_credentials"); + const source_withdrawal_credentials = try source_validator.getFieldRoot("withdrawal_credentials"); + const target_withdrawal_credentials = try target_validator.getFieldRoot("withdrawal_credentials"); const source_withdrawal_address = source_withdrawal_credentials[12..]; const current_epoch = epoch_cache.epoch; @@ -81,7 +81,7 @@ pub fn processConsolidationRequest( } // Verify the source and the target are active - if (!(try isActiveValidatorView(&source_validator, current_epoch)) or !(try isActiveValidatorView(&target_validator, current_epoch))) { + if (!(try isActiveValidatorView(source_validator, current_epoch)) or !(try isActiveValidatorView(target_validator, current_epoch))) { return; } @@ -134,7 +134,7 @@ fn isValidSwitchToCompoundRequest( var validators = try state.validators(); var source_validator = try validators.get(@intCast(source_index)); - const source_withdrawal_credentials = try source_validator.getRoot("withdrawal_credentials"); + const source_withdrawal_credentials = try source_validator.getFieldRoot("withdrawal_credentials"); const source_withdrawal_address = source_withdrawal_credentials[12..]; // Verify request has been authorized @@ -148,7 +148,7 @@ fn isValidSwitchToCompoundRequest( } // Verify the source is active - if (!try isActiveValidatorView(&source_validator, epoch_cache.epoch)) { + if (!try isActiveValidatorView(source_validator, epoch_cache.epoch)) { return false; } diff --git a/src/state_transition/block/process_deposit.zig b/src/state_transition/block/process_deposit.zig index 7f762ee29..c84dea151 100644 --- a/src/state_transition/block/process_deposit.zig +++ b/src/state_transition/block/process_deposit.zig @@ -69,7 +69,7 @@ pub fn processDeposit( try types.phase0.DepositData.hashTreeRoot(&deposit.data, &deposit_data_root); var eth1_data = try state.eth1Data(); - const deposit_root = try eth1_data.getRoot("deposit_root"); + const deposit_root = try eth1_data.getFieldRoot("deposit_root"); if (!verifyMerkleBranch( deposit_data_root, &deposit.proof, diff --git a/src/state_transition/block/process_voluntary_exit.zig b/src/state_transition/block/process_voluntary_exit.zig index a965a2df0..e8ca67969 100644 --- a/src/state_transition/block/process_voluntary_exit.zig +++ b/src/state_transition/block/process_voluntary_exit.zig @@ -25,8 +25,8 @@ pub fn processVoluntaryExit( } var validators = try state.validators(); - var validator = try validators.get(@intCast(signed_voluntary_exit.message.validator_index)); - try initiateValidatorExit(fork, config, epoch_cache, state, &validator); + const validator = try validators.get(@intCast(signed_voluntary_exit.message.validator_index)); + try initiateValidatorExit(fork, config, epoch_cache, state, validator); } pub fn isValidVoluntaryExit( @@ -70,7 +70,7 @@ pub fn getVoluntaryExitValidity( const current_epoch = epoch_cache.epoch; // verify the validator is active - if (!try isActiveValidatorView(&validator, current_epoch)) { + if (!try isActiveValidatorView(validator, current_epoch)) { return .inactive; } diff --git a/src/state_transition/block/process_withdrawal_request.zig b/src/state_transition/block/process_withdrawal_request.zig index e77778063..c8b4504cf 100644 --- a/src/state_transition/block/process_withdrawal_request.zig +++ b/src/state_transition/block/process_withdrawal_request.zig @@ -42,11 +42,11 @@ pub fn processWithdrawalRequest( var validators = try state.validators(); if (validator_index >= try validators.length()) return; - var validator = try validators.get(@intCast(validator_index)); + const validator = try validators.get(@intCast(validator_index)); if (!(try isValidatorEligibleForWithdrawOrExit( config, epoch_cache.epoch, - &validator, + validator, &withdrawal_request.source_address, ))) { return; @@ -60,14 +60,14 @@ pub fn processWithdrawalRequest( if (is_full_exit_request) { // only exit validator if it has no pending withdrawals in the queue if (pending_balance_to_withdraw == 0) { - try initiateValidatorExit(fork, config, epoch_cache, state, &validator); + try initiateValidatorExit(fork, config, epoch_cache, state, validator); } return; } // partial withdrawal request const effective_balance = try validator.get("effective_balance"); - const withdrawal_credentials = try validator.getRoot("withdrawal_credentials"); + const withdrawal_credentials = try validator.getFieldRoot("withdrawal_credentials"); const has_sufficient_effective_balance = effective_balance >= preset.MIN_ACTIVATION_BALANCE; const has_excess_balance = validator_balance > preset.MIN_ACTIVATION_BALANCE + pending_balance_to_withdraw; @@ -96,7 +96,7 @@ fn isValidatorEligibleForWithdrawOrExit( validator: *types.phase0.Validator.TreeView, source_address: []const u8, ) !bool { - const withdrawal_credentials = try validator.getRoot("withdrawal_credentials"); + const withdrawal_credentials = try validator.getFieldRoot("withdrawal_credentials"); const address = withdrawal_credentials[12..]; const activation_epoch = try validator.get("activation_epoch"); diff --git a/src/state_transition/block/process_withdrawals.zig b/src/state_transition/block/process_withdrawals.zig index d7a6cdc57..1030bbe51 100644 --- a/src/state_transition/block/process_withdrawals.zig +++ b/src/state_transition/block/process_withdrawals.zig @@ -166,7 +166,7 @@ pub fn getExpectedWithdrawals( val_balance; const withdrawable_epoch = try validator.get("withdrawable_epoch"); - const withdrawal_credentials = try validator.getRoot("withdrawal_credentials"); + const withdrawal_credentials = try validator.getFieldRoot("withdrawal_credentials"); const effective_balance = try validator.get("effective_balance"); const has_withdrawable_credentials = if (comptime fork.gte(.electra)) hasExecutionWithdrawalCredential(withdrawal_credentials) else hasEth1WithdrawalCredential(withdrawal_credentials); // early skip for balance = 0 as its now more likely that validator has exited/slashed with diff --git a/src/state_transition/block/slash_validator.zig b/src/state_transition/block/slash_validator.zig index 0d601db99..46dad3e9f 100644 --- a/src/state_transition/block/slash_validator.zig +++ b/src/state_transition/block/slash_validator.zig @@ -34,7 +34,7 @@ pub fn slashValidator( var validator = try validators.get(@intCast(slashed_index)); // TODO: Bellatrix initiateValidatorExit validators.update() with the one below - try initiateValidatorExit(fork, config, epoch_cache, state, &validator); + try initiateValidatorExit(fork, config, epoch_cache, state, validator); try validator.set("slashed", true); var latest_block_header = try state.latestBlockHeader(); @@ -96,8 +96,8 @@ pub fn slashValidator( if (fork.gte(.altair)) { const previous_epoch = computePreviousEpoch(epoch); - const is_active_previous_epoch = try isActiveValidatorView(&validator, previous_epoch); - const is_active_current_epoch = try isActiveValidatorView(&validator, epoch); + const is_active_previous_epoch = try isActiveValidatorView(validator, previous_epoch); + const is_active_current_epoch = try isActiveValidatorView(validator, epoch); var previous_participation = try state.previousEpochParticipation(); if (is_active_previous_epoch and (try previous_participation.get(@intCast(slashed_index))) & TIMELY_TARGET == TIMELY_TARGET) { diff --git a/src/state_transition/cache/state_cache.zig b/src/state_transition/cache/state_cache.zig index 8f2d56c5b..51d9e8a68 100644 --- a/src/state_transition/cache/state_cache.zig +++ b/src/state_transition/cache/state_cache.zig @@ -8,7 +8,9 @@ const EpochCacheImmutableData = @import("./epoch_cache.zig").EpochCacheImmutable const EpochCacheOpts = @import("./epoch_cache.zig").EpochCacheOpts; const AnyBeaconState = @import("fork_types").AnyBeaconState; const ValidatorIndex = types.primitive.ValidatorIndex.Type; -const CloneOpts = @import("ssz").BaseTreeView.CloneOpts; +const PubkeyIndexMap = @import("pubkey_cache.zig").PubkeyIndexMap(ValidatorIndex); +const Index2PubkeyCache = @import("pubkey_cache.zig").Index2PubkeyCache; +const CloneOpts = @import("ssz").CloneOpts; const SlashingsCache = @import("./slashings_cache.zig").SlashingsCache; const Node = @import("persistent_merkle_tree").Node; diff --git a/src/state_transition/epoch/process_effective_balance_updates.zig b/src/state_transition/epoch/process_effective_balance_updates.zig index 9a94c9313..fd1365a53 100644 --- a/src/state_transition/epoch/process_effective_balance_updates.zig +++ b/src/state_transition/epoch/process_effective_balance_updates.zig @@ -42,8 +42,8 @@ pub fn processEffectiveBalanceUpdates( }; const is_compounding_validator_arr = cache.is_compounding_validator_arr.items; - var previous_epoch_participation: types.altair.EpochParticipation.TreeView = undefined; - var current_epoch_participation: types.altair.EpochParticipation.TreeView = undefined; + var previous_epoch_participation: *types.altair.EpochParticipation.TreeView = undefined; + var current_epoch_participation: *types.altair.EpochParticipation.TreeView = undefined; if (comptime fork.gte(.altair)) { previous_epoch_participation = try state.previousEpochParticipation(); current_epoch_participation = try state.currentEpochParticipation(); diff --git a/src/state_transition/epoch/process_justification_and_finalization.zig b/src/state_transition/epoch/process_justification_and_finalization.zig index 52eb04fbf..1707aedd8 100644 --- a/src/state_transition/epoch/process_justification_and_finalization.zig +++ b/src/state_transition/epoch/process_justification_and_finalization.zig @@ -52,7 +52,8 @@ pub fn weighJustificationAndFinalization( // Process justifications try state.setPreviousJustifiedCheckpoint(&old_current_justified_checkpoint); var justification_bits = try state.justificationBits(); - var bits = try justification_bits.toBoolArray(); + var bits: [types.phase0.JustificationBits.length]bool = undefined; + try justification_bits.toBoolArrayInto(&bits); // Rotate bits var idx: usize = bits.len - 1; diff --git a/src/state_transition/epoch/process_registry_updates.zig b/src/state_transition/epoch/process_registry_updates.zig index b58da136b..45183ddce 100644 --- a/src/state_transition/epoch/process_registry_updates.zig +++ b/src/state_transition/epoch/process_registry_updates.zig @@ -23,8 +23,8 @@ pub fn processRegistryUpdates( for (cache.indices_to_eject.items) |i| { // set validator exit epoch and withdrawable epoch // TODO: Figure out a way to quickly set properties on the validators tree - var validator = try validators.get(i); - try initiateValidatorExit(fork, config, epoch_cache, state, &validator); + const validator = try validators.get(i); + try initiateValidatorExit(fork, config, epoch_cache, state, validator); } // set new activation eligibilities diff --git a/src/state_transition/epoch/process_slashings.zig b/src/state_transition/epoch/process_slashings.zig index b37d4066c..29b07429f 100644 --- a/src/state_transition/epoch/process_slashings.zig +++ b/src/state_transition/epoch/process_slashings.zig @@ -73,7 +73,7 @@ pub fn getTotalSlashingsByIncrement( ) !u64 { var total_slashings_by_increment: u64 = 0; var slashings = try state.slashings(); - const slashings_len = @TypeOf(slashings).length; + const slashings_len = @TypeOf(slashings.*).length; for (0..slashings_len) |i| { const slashing = try slashings.get(i); total_slashings_by_increment += @divFloor(slashing, preset.EFFECTIVE_BALANCE_INCREMENT); diff --git a/src/state_transition/slot/process_slot.zig b/src/state_transition/slot/process_slot.zig index 3b8034843..17652306c 100644 --- a/src/state_transition/slot/process_slot.zig +++ b/src/state_transition/slot/process_slot.zig @@ -12,7 +12,7 @@ pub fn processSlot(state: *AnyBeaconState) !void { // Cache latest block header state root var latest_block_header = try state.latestBlockHeader(); - var latest_header_state_root = try latest_block_header.getRoot("state_root"); + var latest_header_state_root = try latest_block_header.getFieldRoot("state_root"); if (std.mem.eql(u8, latest_header_state_root[0..], ZERO_HASH[0..])) { try latest_block_header.setValue("state_root", previous_state_root); diff --git a/src/state_transition/slot/upgrade_state_to_altair.zig b/src/state_transition/slot/upgrade_state_to_altair.zig index 69685bd4a..5733440e5 100644 --- a/src/state_transition/slot/upgrade_state_to_altair.zig +++ b/src/state_transition/slot/upgrade_state_to_altair.zig @@ -90,9 +90,9 @@ fn translateParticipation( epoch_cache: *const EpochCache, root_cache: *RootCache(.phase0), validators_count: usize, - pending_attestations_tree: types.phase0.EpochAttestations.TreeView, + pending_attestations_tree: *types.phase0.EpochAttestations.TreeView, ) !types.altair.EpochParticipation.Type { - const pending_attestations = try @constCast(&pending_attestations_tree).getAllReadonlyValues(allocator); + const pending_attestations = try pending_attestations_tree.getAllReadonlyValues(allocator); defer { for (pending_attestations) |*attestation| { types.phase0.PendingAttestation.deinit(allocator, attestation); diff --git a/src/state_transition/utils/block_root.zig b/src/state_transition/utils/block_root.zig index 7f5553d60..06d639831 100644 --- a/src/state_transition/utils/block_root.zig +++ b/src/state_transition/utils/block_root.zig @@ -20,7 +20,7 @@ pub fn getBlockRootAtSlot(comptime fork: ForkSeq, state: *BeaconState(fork), slo } var block_roots = try state.blockRoots(); - return try block_roots.getRoot(slot % SLOTS_PER_HISTORICAL_ROOT); + return try block_roots.getFieldRoot(slot % SLOTS_PER_HISTORICAL_ROOT); } pub fn getBlockRoot(comptime fork: ForkSeq, state: *BeaconState(fork), epoch: Epoch) !*const [32]u8 { diff --git a/src/state_transition/utils/electra.zig b/src/state_transition/utils/electra.zig index cddb591a3..fda7f4ed0 100644 --- a/src/state_transition/utils/electra.zig +++ b/src/state_transition/utils/electra.zig @@ -25,7 +25,7 @@ pub fn hasExecutionWithdrawalCredential(withdrawal_credentials: *const Withdrawa pub fn switchToCompoundingValidator(comptime fork: ForkSeq, state: *BeaconState(fork), index: ValidatorIndex) !void { var validators = try state.validators(); var validator = try validators.get(index); - const old_withdrawal_credentials = try validator.getRoot("withdrawal_credentials"); + const old_withdrawal_credentials = try validator.getFieldRoot("withdrawal_credentials"); var new_withdrawal_credentials: [32]u8 = undefined; @memcpy(new_withdrawal_credentials[0..], old_withdrawal_credentials[0..]); diff --git a/src/state_transition/utils/seed.zig b/src/state_transition/utils/seed.zig index e94751840..abd7638e9 100644 --- a/src/state_transition/utils/seed.zig +++ b/src/state_transition/utils/seed.zig @@ -79,7 +79,7 @@ pub fn getNextSyncCommitteeIndices(comptime fork: ForkSeq, allocator: Allocator, pub fn getRandaoMix(comptime fork: ForkSeq, state: *BeaconState(fork), epoch: Epoch) !*const [32]u8 { var randao_mixes = try state.randaoMixes(); - return try randao_mixes.getRoot(epoch % EPOCHS_PER_HISTORICAL_VECTOR); + return try randao_mixes.getFieldRoot(epoch % EPOCHS_PER_HISTORICAL_VECTOR); } pub fn getSeed(comptime fork: ForkSeq, state: *BeaconState(fork), epoch: Epoch, domain_type: DomainType, out: *[32]u8) !void { diff --git a/test/spec/test_case.zig b/test/spec/test_case.zig index b204bf231..89194b9bc 100644 --- a/test/spec/test_case.zig +++ b/test/spec/test_case.zig @@ -277,13 +277,13 @@ pub fn expectEqualBeaconStates(expected: *AnyBeaconState, actual: *AnyBeaconStat try actual.hashTreeRoot(), )) { const Debug = struct { - fn printDiff(comptime StateST: type, expected_state: *AnyBeaconState, actual_state: *AnyBeaconState) !void { - var expected_view = StateST.TreeView{ .base_view = expected_state.baseView() }; - var actual_view = StateST.TreeView{ .base_view = actual_state.baseView() }; + fn printDiff(comptime StateST: type, comptime fork: ForkSeq, expected_state: *AnyBeaconState, actual_state: *AnyBeaconState) !void { + const expected_view: *StateST.TreeView = expected_state.castToFork(fork).inner; + const actual_view: *StateST.TreeView = actual_state.castToFork(fork).inner; inline for (StateST.fields) |field| { - const expected_field_root = try expected_view.getRoot(field.name); - const actual_field_root = try actual_view.getRoot(field.name); + const expected_field_root = try expected_view.getFieldRoot(field.name); + const actual_field_root = try actual_view.getFieldRoot(field.name); if (!std.mem.eql(u8, expected_field_root, actual_field_root)) { std.debug.print( "field: {s}\n expected_root: {s}\n actual_root: {s}\n", @@ -294,58 +294,20 @@ pub fn expectEqualBeaconStates(expected: *AnyBeaconState, actual: *AnyBeaconStat }, ); - @setEvalBranchQuota(100000); - const FieldST = StateST.getFieldType(field.name); - const allocator = std.testing.allocator; - { - var expected_field_view = try expected_view.get(field.name); - if (comptime @hasDecl(FieldST, "TreeView") and @hasDecl(FieldST.TreeView, "length") and @typeInfo(@TypeOf(FieldST.TreeView.length)) == .@"fn") { - std.debug.print( - " expected_value_length: {any}\n", - .{try expected_field_view.length()}, - ); - } - var expected_field_value: FieldST.Type = undefined; - try expected_view.getValue(allocator, field.name, &expected_field_value); - defer if (@hasDecl(FieldST, "deinit")) - FieldST.deinit(allocator, &expected_field_value); - - std.debug.print( - " expected_value: {any}\n", - .{expected_field_value}, - ); - } - { - var actual_field_view = try actual_view.get(field.name); - if (comptime @hasDecl(FieldST, "TreeView") and @hasDecl(FieldST.TreeView, "length") and @typeInfo(@TypeOf(FieldST.TreeView.length)) == .@"fn") { - std.debug.print( - " actual_value_length: {any}\n", - .{try actual_field_view.length()}, - ); - } - var actual_field_value: FieldST.Type = undefined; - try actual_view.getValue(allocator, field.name, &actual_field_value); - defer if (@hasDecl(FieldST, "deinit")) - FieldST.deinit(allocator, &actual_field_value); - - std.debug.print( - " actual_value: {any}\n", - .{actual_field_value}, - ); - } + // Value-level diff printing omitted to avoid crashes in toValue path } } } }; switch (expected.forkSeq()) { - .phase0 => try Debug.printDiff(types.phase0.BeaconState, expected, actual), - .altair => try Debug.printDiff(types.altair.BeaconState, expected, actual), - .bellatrix => try Debug.printDiff(types.bellatrix.BeaconState, expected, actual), - .capella => try Debug.printDiff(types.capella.BeaconState, expected, actual), - .deneb => try Debug.printDiff(types.deneb.BeaconState, expected, actual), - .electra => try Debug.printDiff(types.electra.BeaconState, expected, actual), - .fulu => try Debug.printDiff(types.fulu.BeaconState, expected, actual), + .phase0 => try Debug.printDiff(types.phase0.BeaconState, .phase0, expected, actual), + .altair => try Debug.printDiff(types.altair.BeaconState, .altair, expected, actual), + .bellatrix => try Debug.printDiff(types.bellatrix.BeaconState, .bellatrix, expected, actual), + .capella => try Debug.printDiff(types.capella.BeaconState, .capella, expected, actual), + .deneb => try Debug.printDiff(types.deneb.BeaconState, .deneb, expected, actual), + .electra => try Debug.printDiff(types.electra.BeaconState, .electra, expected, actual), + .fulu => try Debug.printDiff(types.fulu.BeaconState, .fulu, expected, actual), } return error.NotEqual; } From 65eb1a93079071b7c0c63b96d7a589d5a577dbe0 Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Tue, 3 Mar 2026 19:33:38 +0700 Subject: [PATCH 02/11] fix(ssz): return pointer from ContainerTreeView.deserialize --- src/ssz/tree_view/container.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ssz/tree_view/container.zig b/src/ssz/tree_view/container.zig index 3f9b9d61a..38ad244e2 100644 --- a/src/ssz/tree_view/container.zig +++ b/src/ssz/tree_view/container.zig @@ -298,7 +298,7 @@ pub fn ContainerTreeView(comptime ST: type) type { } } - pub fn deserialize(allocator: Allocator, pool: *Node.Pool, bytes: []const u8) !Self { + pub fn deserialize(allocator: Allocator, pool: *Node.Pool, bytes: []const u8) !*Self { const root = try ST.tree.deserializeFromBytes(pool, bytes); return try Self.init(allocator, pool, root); } From d7f6a6d79bd72cf087de39f7359ac3e2089edb07 Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Tue, 3 Mar 2026 19:42:55 +0700 Subject: [PATCH 03/11] fix bindings build for updated container tree view API --- bindings/napi/BeaconStateView.zig | 6 +++--- src/fork_types/any_beacon_state.zig | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/bindings/napi/BeaconStateView.zig b/bindings/napi/BeaconStateView.zig index 93c174a12..a92dd04cd 100644 --- a/bindings/napi/BeaconStateView.zig +++ b/bindings/napi/BeaconStateView.zig @@ -778,7 +778,7 @@ pub fn BeaconStateView_createMultiProof(env: napi.Env, cb: napi.CallbackInfo(1)) // Get the root node from the state try cached_state.state.commit(); const root_node = switch (cached_state.state.*) { - inline else => |*state| state.base_view.data.root, + inline else => |state| state.root, }; // Create proof input for compact multi-proof @@ -880,7 +880,7 @@ pub fn BeaconStateView_serialize(env: napi.Env, cb: napi.CallbackInfo(0)) !napi. pub fn BeaconStateView_serializedSize(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value { const cached_state = try env.unwrap(CachedBeaconState, cb.this()); const size = switch (cached_state.state.*) { - inline else => |*state| try state.serializedSize(), + inline else => |state| try state.serializedSize(), }; return try env.createInt64(@intCast(size)); } @@ -902,7 +902,7 @@ pub fn BeaconStateView_serializeToBytes(env: napi.Env, cb: napi.CallbackInfo(2)) const output_slice = output_info.data[offset..]; const bytes_written = switch (cached_state.state.*) { - inline else => |*state| try state.serializeIntoBytes(output_slice), + inline else => |state| try state.serializeIntoBytes(output_slice), }; return try env.createInt64(@intCast(bytes_written)); diff --git a/src/fork_types/any_beacon_state.zig b/src/fork_types/any_beacon_state.zig index 36198891b..91ca8bcdb 100644 --- a/src/fork_types/any_beacon_state.zig +++ b/src/fork_types/any_beacon_state.zig @@ -168,10 +168,10 @@ pub const AnyBeaconState = union(ForkSeq) { try self.commit(); const gindex: Gindex = @enumFromInt(gindex_value); return switch (self.*) { - inline else => |*state| try createSingleProof( + inline else => |state| try createSingleProof( allocator, - state.base_view.pool, - state.base_view.data.root, + state.pool, + state.root, gindex, ), }; From ff4063525f38f8c1bad6363d946f455239adcecb Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Tue, 3 Mar 2026 19:56:45 +0700 Subject: [PATCH 04/11] fix: rotateEpochPendingAttestations() --- src/fork_types/any_beacon_state.zig | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/fork_types/any_beacon_state.zig b/src/fork_types/any_beacon_state.zig index 91ca8bcdb..fc5577a40 100644 --- a/src/fork_types/any_beacon_state.zig +++ b/src/fork_types/any_beacon_state.zig @@ -440,10 +440,8 @@ pub const AnyBeaconState = union(ForkSeq) { pub fn rotateEpochPendingAttestations(self: *AnyBeaconState) !void { return switch (self.*) { .phase0 => |state| { - // const current_root = try state.getRootNode("current_epoch_attestations"); - // try state.setRootNode("previous_epoch_attestations", current_root); - // TODO - treeview - try state.set("previous_epoch_attestations", try state.get("current_epoch_attestations")); + const current_root = try state.getRootNode("current_epoch_attestations"); + try state.setRootNode("previous_epoch_attestations", current_root); try state.setValue("current_epoch_attestations", &ct.phase0.EpochAttestations.default_value); }, else => error.InvalidAtFork, From 5d91b622715598d3005a5c3598b77f11a6a19e3b Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Tue, 3 Mar 2026 20:05:04 +0700 Subject: [PATCH 05/11] fix: BeaconState.roteSyncCommittees() to use getRootNode setRootNode --- src/fork_types/beacon_state.zig | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/fork_types/beacon_state.zig b/src/fork_types/beacon_state.zig index 0b7b1191f..cf8608743 100644 --- a/src/fork_types/beacon_state.zig +++ b/src/fork_types/beacon_state.zig @@ -292,10 +292,8 @@ pub fn BeaconState(comptime f: ForkSeq) type { pub fn rotateSyncCommittees(self: *Self, next_sync_committee: *const ForkTypes(.altair).SyncCommittee.Type) !void { if (comptime f == .phase0) return error.InvalidAtFork; - var next_sync_committee_view = try self.inner.get("next_sync_committee"); - var next_sync_committee_copy = try next_sync_committee_view.clone(.{ .transfer_cache = true }); - errdefer next_sync_committee_copy.deinit(); - try self.inner.set("current_sync_committee", next_sync_committee_copy); + const next_sync_committee_root = try self.inner.getRootNode("next_sync_committee"); + try self.inner.setRootNode("current_sync_committee", next_sync_committee_root); try self.inner.setValue("next_sync_committee", next_sync_committee); } From 2a17051fe51dd2abfa4a40ff68601f91470b506f Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Tue, 3 Mar 2026 20:08:48 +0700 Subject: [PATCH 06/11] fix: rotateEpochParticipation commit current_epoch_participation --- src/fork_types/beacon_state.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fork_types/beacon_state.zig b/src/fork_types/beacon_state.zig index cf8608743..bc1e8aa02 100644 --- a/src/fork_types/beacon_state.zig +++ b/src/fork_types/beacon_state.zig @@ -211,7 +211,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { if (comptime f == .phase0) return error.InvalidAtFork; var current_epoch_participation = try self.inner.get("current_epoch_participation"); - // try current_epoch_participation.commit(); + try current_epoch_participation.commit(); const length = try current_epoch_participation.length(); // Clone the view to preserve any uncommitted in-memory updates while avoiding pointer aliasing From bd92d55cfde38cfb8e6caa9a71e3f9b629926e2d Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Tue, 3 Mar 2026 20:13:07 +0700 Subject: [PATCH 07/11] chore: polish populateFields() --- src/fork_types/beacon_state.zig | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/fork_types/beacon_state.zig b/src/fork_types/beacon_state.zig index bc1e8aa02..c6bd8412b 100644 --- a/src/fork_types/beacon_state.zig +++ b/src/fork_types/beacon_state.zig @@ -450,8 +450,7 @@ pub fn BeaconState(comptime f: ForkSeq) type { pool: *Node.Pool, state: *F.TreeView, ) !*T.TreeView { - var committed_state = state; - try committed_state.commit(); + try state.commit(); var upgraded = try T.TreeView.fromValue(allocator, pool, &T.default_value); errdefer upgraded.deinit(); @@ -461,9 +460,9 @@ pub fn BeaconState(comptime f: ForkSeq) type { if (T.getFieldType(fld.name) != fld.type) continue; if (comptime isBasicType(fld.type)) { - try upgraded.set(fld.name, try committed_state.get(fld.name)); + try upgraded.set(fld.name, try state.get(fld.name)); } else { - var field_view = try committed_state.get(fld.name); + var field_view = try state.get(fld.name); var owned_field_view = try field_view.clone(.{ .transfer_cache = true }); errdefer owned_field_view.deinit(); try upgraded.set(fld.name, owned_field_view); From cec956d8aec20431b0ec9e0861cdc7f61b6fd50f Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Sat, 7 Mar 2026 08:31:11 +0700 Subject: [PATCH 08/11] fix: bench process_epoch --- bench/state_transition/process_epoch.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bench/state_transition/process_epoch.zig b/bench/state_transition/process_epoch.zig index bf5223ffb..d42362a77 100644 --- a/bench/state_transition/process_epoch.zig +++ b/bench/state_transition/process_epoch.zig @@ -698,11 +698,11 @@ fn runBenchmark( const validators = try beacon_state.?.validatorsSlice(allocator); defer allocator.free(validators); - try state_transition.syncPubkeys(validators, &pubkey_index_map, &index_pubkey_cache); + try state_transition.syncPubkeys(validators, &pubkey_index_map, index_pubkey_cache); const immutable_data = state_transition.EpochCacheImmutableData{ .config = &beacon_config, - .index_to_pubkey = &index_pubkey_cache, + .index_to_pubkey = index_pubkey_cache, .pubkey_to_index = &pubkey_index_map, }; From 2acaeaedaf90f1a1f317814de642261d42262310 Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Fri, 13 Mar 2026 16:16:43 +0700 Subject: [PATCH 09/11] fix: require allocator in ArrayBasicTreeView.getAll() --- src/ssz/tree_view/array_basic.zig | 11 ++++++----- src/ssz/tree_view/container.zig | 2 +- src/ssz/tree_view/list_composite.zig | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/ssz/tree_view/array_basic.zig b/src/ssz/tree_view/array_basic.zig index 80dd39cb9..b4ed34a02 100644 --- a/src/ssz/tree_view/array_basic.zig +++ b/src/ssz/tree_view/array_basic.zig @@ -106,8 +106,9 @@ pub fn ArrayBasicTreeView(comptime ST: type) type { try self.chunks.set(index, value); } - pub fn getAll(self: *Self, allocator: ?Allocator) ![]Element { - return try self.chunks.getAll(allocator orelse self.allocator, length); + /// Caller is responsible for freeing the returned slice using the same allocator. + pub fn getAll(self: *Self, allocator: Allocator) ![]Element { + return try self.chunks.getAll(allocator, length); } pub fn getAllInto(self: *Self, values: []Element) ![]Element { @@ -212,7 +213,7 @@ test "TreeView vector getAllAlloc roundtrip" { var view = try VectorType.TreeView.init(allocator, &pool, root_node); defer view.deinit(); - const filled = try view.getAll(null); + const filled = try view.getAll(allocator); defer allocator.free(filled); try std.testing.expectEqualSlices(u16, values[0..], filled); @@ -231,13 +232,13 @@ test "TreeView vector getAllAlloc repeat reflects updates" { var view = try VectorType.TreeView.init(allocator, &pool, root_node); defer view.deinit(); - const first = try view.getAll(null); + const first = try view.getAll(allocator); defer allocator.free(first); try std.testing.expectEqualSlices(u32, values[0..], first); try view.set(3, 99); - const second = try view.getAll(null); + const second = try view.getAll(allocator); defer allocator.free(second); values[3] = 99; try std.testing.expectEqualSlices(u32, values[0..], second); diff --git a/src/ssz/tree_view/container.zig b/src/ssz/tree_view/container.zig index 38ad244e2..6c23a4c4c 100644 --- a/src/ssz/tree_view/container.zig +++ b/src/ssz/tree_view/container.zig @@ -640,7 +640,7 @@ test "TreeView container nested types set/get/commit" { try basic_vec_view.set(0, @as(u16, 1)); try basic_vec_view.set(3, @as(u16, 4)); - const all = try basic_vec_view.getAll(null); + const all = try basic_vec_view.getAll(allocator); defer allocator.free(all); try std.testing.expectEqual(@as(usize, 4), all.len); try std.testing.expectEqual(@as(u16, 1), all[0]); diff --git a/src/ssz/tree_view/list_composite.zig b/src/ssz/tree_view/list_composite.zig index 6fa19ccd2..536400f95 100644 --- a/src/ssz/tree_view/list_composite.zig +++ b/src/ssz/tree_view/list_composite.zig @@ -800,7 +800,7 @@ test "TreeView list of list commits inner length updates" { try vec.set(0, @as(u32, 9)); try vec.set(1, @as(u32, 10)); { - const all = try vec.getAll(null); + const all = try vec.getAll(allocator); defer allocator.free(all); try std.testing.expectEqual(@as(usize, 2), all.len); try std.testing.expectEqual(@as(u32, 9), all[0]); From 1bd37a51d5ce2f1a2bdaa5f5867f6ab6e6d1850f Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Fri, 13 Mar 2026 16:20:10 +0700 Subject: [PATCH 10/11] refactor: rename clone -> cloneAndTransferCache --- src/ssz/tree_view/bit_array.zig | 2 +- src/ssz/tree_view/chunks.zig | 2 +- src/ssz/tree_view/utils/child_nodes.zig | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ssz/tree_view/bit_array.zig b/src/ssz/tree_view/bit_array.zig index 3ec8bf81d..aefcaff1b 100644 --- a/src/ssz/tree_view/bit_array.zig +++ b/src/ssz/tree_view/bit_array.zig @@ -38,7 +38,7 @@ pub fn BitArray(comptime chunk_depth: Depth) type { } pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { - try ChildNodes.Change.clone(Self, self, opts, out); + try ChildNodes.Change.cloneAndTransferCache(Self, self, opts, out); } pub fn deinit(self: *Self) void { diff --git a/src/ssz/tree_view/chunks.zig b/src/ssz/tree_view/chunks.zig index f9d4320c1..4272eadf0 100644 --- a/src/ssz/tree_view/chunks.zig +++ b/src/ssz/tree_view/chunks.zig @@ -47,7 +47,7 @@ pub fn BasicPackedChunks( } pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { - try ChildNodes.Change.clone(Self, self, opts, out); + try ChildNodes.Change.cloneAndTransferCache(Self, self, opts, out); } pub fn deinit(self: *Self) void { diff --git a/src/ssz/tree_view/utils/child_nodes.zig b/src/ssz/tree_view/utils/child_nodes.zig index 324b107b3..e38ff9863 100644 --- a/src/ssz/tree_view/utils/child_nodes.zig +++ b/src/ssz/tree_view/utils/child_nodes.zig @@ -83,7 +83,7 @@ pub const ChildNodes = struct { self.changed.clearRetainingCapacity(); } - pub fn clone(comptime T: type, self: *T, opts: CloneOpts, out: *T) !void { + pub fn cloneAndTransferCache(comptime T: type, self: *T, opts: CloneOpts, out: *T) !void { try T.init(out, self.allocator, self.pool, self.root); if (!opts.transfer_cache) { From fdab8c6bbb01875fa6171f15676d30c8a097a63f Mon Sep 17 00:00:00 2001 From: Cayman Date: Tue, 17 Mar 2026 04:23:01 -0400 Subject: [PATCH 11/11] refactor(ssz): review tree views (#245) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary The tree view refactor in #139 correctly killed the heap-allocated `BaseTreeView` indirection, but it overcorrected — it scattered five fields (`allocator`, `pool`, `root`, `children_nodes`, `changed`) into every view type and recovered sharing through `ChildNodes`, a set of free functions that take `anytype` and duck-type their way to the right field names. This PR fixes the abstraction: - **`TreeViewState`** — a concrete struct embedded by value in each chunk-based view (`BasicPackedChunks`, `CompositeChunks`, `BitArray`). Not a pointer, not a trait — just a struct with typed methods. When you see `state: TreeViewState`, you know what state it carries and what operations exist. The compiler gives real errors at the call site, not inside a generic utility that reconstructs the interface from field names. - **`StaticBitSet`** for `ContainerTreeView.changed` — the field count is comptime-known, so the dirty-tracking hashmap (`AutoArrayHashMapUnmanaged(usize, void)`) becomes a zero-allocation bitset. No hashmap init, no hashmap deinit, no allocator needed for dirty tracking. `ContainerTreeView` does **not** use `TreeViewState` — its comptime tuple + fixed arrays are a genuinely different storage shape, and the bitset is the right dirty tracker for it. The split is now explicit in the type system rather than implicit in "which types happen to have the right field names." ### What changed | Before | After | |---|---| | `ChildNodes.getChildNode(self, gindex)` — anytype dispatch | `self.state.getChildNode(gindex)` — concrete method on `TreeViewState` | | `ChildNodes.Change.commit(self)` — anytype dispatch | `self.state.commitNodes()` — concrete method | | `CompositeChunks.commit()` duplicated sort/setNodesGrouped/ref/unref | Flushes child views into `children_nodes`, delegates to `commitNodes()` | | `getLength`/`setLength` on generic `TreeViewState` | Inlined into `BasicPackedChunks`/`CompositeChunks` (list-specific) | | `changed: AutoArrayHashMapUnmanaged(usize, void)` in ContainerTreeView | `changed: StaticBitSet(N)` — zero allocation | ## Test plan - [x] `zig build test:ssz` — all 194 tests pass - [ ] `zig build test:spec_tests -Dpreset=minimal` 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) --- src/ssz/tree_view/array_basic.zig | 22 +- src/ssz/tree_view/array_composite.zig | 16 +- src/ssz/tree_view/bit_array.zig | 60 ++---- src/ssz/tree_view/bit_list.zig | 18 +- src/ssz/tree_view/bit_vector.zig | 18 +- src/ssz/tree_view/chunks.zig | 221 +++++++------------- src/ssz/tree_view/container.zig | 18 +- src/ssz/tree_view/list_basic.zig | 60 +++--- src/ssz/tree_view/list_composite.zig | 66 +++--- src/ssz/tree_view/utils/child_nodes.zig | 106 ---------- src/ssz/tree_view/utils/tree_view_state.zig | 123 +++++++++++ 11 files changed, 332 insertions(+), 396 deletions(-) delete mode 100644 src/ssz/tree_view/utils/child_nodes.zig create mode 100644 src/ssz/tree_view/utils/tree_view_state.zig diff --git a/src/ssz/tree_view/array_basic.zig b/src/ssz/tree_view/array_basic.zig index b4ed34a02..9ec2bba61 100644 --- a/src/ssz/tree_view/array_basic.zig +++ b/src/ssz/tree_view/array_basic.zig @@ -73,12 +73,12 @@ pub fn ArrayBasicTreeView(comptime ST: type) type { pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { try self.commit(); - out.* = self.chunks.root.getRoot(self.chunks.pool).*; + out.* = self.chunks.state.root.getRoot(self.chunks.state.pool).*; } pub fn hashTreeRoot(self: *Self) !*const [32]u8 { try self.commit(); - return self.chunks.root.getRoot(self.chunks.pool); + return self.chunks.state.root.getRoot(self.chunks.state.pool); } pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { @@ -89,11 +89,11 @@ pub fn ArrayBasicTreeView(comptime ST: type) type { pub fn toValue(self: *Self, _: Allocator, out: *ST.Type) !void { try self.commit(); - try ST.tree.toValue(self.chunks.root, self.chunks.pool, out); + try ST.tree.toValue(self.chunks.state.root, self.chunks.state.pool, out); } pub fn getRoot(self: *const Self) Node.Id { - return self.chunks.root; + return self.chunks.state.root; } pub fn get(self: *Self, index: usize) !Element { @@ -119,7 +119,7 @@ pub fn ArrayBasicTreeView(comptime ST: type) type { /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.state.root, self.chunks.state.pool, out); } /// Get the serialized size of this tree view. @@ -330,13 +330,13 @@ test "TreeView vector clone(true) does not transfer cache" { defer v.deinit(); _ = try v.get(0); - try std.testing.expect(v.chunks.children_nodes.count() > 0); + try std.testing.expect(v.chunks.state.children_nodes.count() > 0); var cloned_no_cache = try v.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(v.chunks.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.children_nodes.count()); + try std.testing.expect(v.chunks.state.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.state.children_nodes.count()); } test "TreeView vector clone(false) transfers cache and clears source" { @@ -354,13 +354,13 @@ test "TreeView vector clone(false) transfers cache and clears source" { defer v.deinit(); _ = try v.get(0); - try std.testing.expect(v.chunks.children_nodes.count() > 0); + try std.testing.expect(v.chunks.state.children_nodes.count() > 0); var cloned = try v.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), v.chunks.children_nodes.count()); - try std.testing.expect(cloned.chunks.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), v.chunks.state.children_nodes.count()); + try std.testing.expect(cloned.chunks.state.children_nodes.count() > 0); } // Tests ported from TypeScript ssz packages/ssz/test/unit/byType/vector/tree.test.ts diff --git a/src/ssz/tree_view/array_composite.zig b/src/ssz/tree_view/array_composite.zig index a28fc4e92..eb8c86a30 100644 --- a/src/ssz/tree_view/array_composite.zig +++ b/src/ssz/tree_view/array_composite.zig @@ -76,12 +76,12 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { try self.commit(); - out.* = self.chunks.root.getRoot(self.chunks.pool).*; + out.* = self.chunks.state.root.getRoot(self.chunks.state.pool).*; } pub fn hashTreeRoot(self: *Self) !*const [32]u8 { try self.commit(); - return self.chunks.root.getRoot(self.chunks.pool); + return self.chunks.state.root.getRoot(self.chunks.state.pool); } pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { @@ -96,14 +96,14 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { try self.commit(); if (comptime isFixedType(ST)) { - try ST.tree.toValue(self.chunks.root, self.chunks.pool, out); + try ST.tree.toValue(self.chunks.state.root, self.chunks.state.pool, out); } else { - try ST.tree.toValue(allocator, self.chunks.root, self.chunks.pool, out); + try ST.tree.toValue(allocator, self.chunks.state.root, self.chunks.state.pool, out); } } pub fn getRoot(self: *const Self) Node.Id { - return self.chunks.root; + return self.chunks.state.root; } pub fn get(self: *Self, index: usize) !Element { @@ -130,7 +130,7 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { if (index >= length) return error.IndexOutOfBounds; const elem = try self.chunks.get(index); try elem.commit(); - return elem.getRoot().getRoot(self.chunks.pool); + return elem.getRoot().getRoot(self.chunks.state.pool); } pub fn set(self: *Self, index: usize, value: Element) !void { @@ -150,7 +150,7 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.state.root, self.chunks.state.pool, out); } /// Get the serialized size of this tree view. @@ -159,7 +159,7 @@ pub fn ArrayCompositeTreeView(comptime ST: type) type { if (comptime isFixedType(ST)) { return ST.fixed_size; } else { - return ST.tree.serializedSize(self.chunks.root, self.chunks.pool); + return ST.tree.serializedSize(self.chunks.state.root, self.chunks.state.pool); } } }; diff --git a/src/ssz/tree_view/bit_array.zig b/src/ssz/tree_view/bit_array.zig index aefcaff1b..70dec220c 100644 --- a/src/ssz/tree_view/bit_array.zig +++ b/src/ssz/tree_view/bit_array.zig @@ -6,55 +6,35 @@ const Depth = hashing.Depth; const Node = @import("persistent_merkle_tree").Node; const Gindex = @import("persistent_merkle_tree").Gindex; -const ChildNodes = @import("utils/child_nodes.zig").ChildNodes; +const TreeViewState = @import("utils/tree_view_state.zig").TreeViewState; const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// Provides common bit array operations for both BitVectorTreeView and BitListTreeView. pub fn BitArray(comptime chunk_depth: Depth) type { return struct { const bits_per_chunk: usize = 256; - allocator: Allocator, - pool: *Node.Pool, - root: Node.Id, - - /// cached nodes for faster access of already-visited children - children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), - - /// whether the corresponding child node/data has changed since the last update of the root - changed: std.AutoArrayHashMapUnmanaged(Gindex, void), + state: TreeViewState, const Self = @This(); pub fn init(self: *Self, allocator: Allocator, pool: *Node.Pool, root: Node.Id) !void { - try pool.ref(root); - errdefer pool.unref(root); - self.* = .{ - .allocator = allocator, - .pool = pool, - .root = root, - .children_nodes = .empty, - .changed = .empty, - }; + try self.state.init(allocator, pool, root); } pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { - try ChildNodes.Change.cloneAndTransferCache(Self, self, opts, out); + try self.state.clone(opts, &out.state); } pub fn deinit(self: *Self) void { - self.pool.unref(self.root); - self.clearChildrenNodesCache(); - self.children_nodes.deinit(self.allocator); - self.changed.deinit(self.allocator); + self.state.deinit(); } pub fn commit(self: *Self) !void { - try ChildNodes.Change.commit(self); + try self.state.commitNodes(); } pub fn clearCache(self: *Self) void { - self.clearChildrenNodesCache(); - self.changed.clearRetainingCapacity(); + self.state.clearCache(); } pub fn get(self: *Self, index: usize, len: usize) !bool { @@ -65,8 +45,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { const byte_in_chunk = bit_in_chunk / 8; const bit_in_byte: u3 = @intCast(bit_in_chunk % 8); - const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, chunk_index)); - const leaf = leaf_node.getRoot(self.pool); + const leaf_node = try self.state.getChildNode(Gindex.fromDepth(chunk_depth, chunk_index)); + const leaf = leaf_node.getRoot(self.state.pool); const mask = @as(u8, 1) << bit_in_byte; return (leaf[byte_in_chunk] & mask) != 0; } @@ -80,8 +60,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { const bit_in_byte: u3 = @intCast(bit_in_chunk % 8); const gindex = Gindex.fromDepth(chunk_depth, chunk_index); - const leaf_node = try self.getChildNode(gindex); - var leaf_bytes = leaf_node.getRoot(self.pool).*; + const leaf_node = try self.state.getChildNode(gindex); + var leaf_bytes = leaf_node.getRoot(self.state.pool).*; const mask = @as(u8, 1) << bit_in_byte; if (value) { @@ -90,8 +70,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { leaf_bytes[byte_in_chunk] &= ~mask; } - const new_leaf = try self.pool.createLeaf(&leaf_bytes); - try self.setChildNode(gindex, new_leaf); + const new_leaf = try self.state.pool.createLeaf(&leaf_bytes); + try self.state.setChildNode(gindex, new_leaf); } pub fn fillBools(self: *Self, values: []bool, len: usize) !void { @@ -103,8 +83,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { var dest = values; for (0..full_chunks) |chunk_idx| { - const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); - const leaf = leaf_node.getRoot(self.pool); + const leaf_node = try self.state.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); + const leaf = leaf_node.getRoot(self.state.pool); for (leaf) |b| { inline for (0..8) |j| { @@ -115,8 +95,8 @@ pub fn BitArray(comptime chunk_depth: Depth) type { } if (remainder_bits != 0) { - const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, full_chunks)); - const leaf = leaf_node.getRoot(self.pool); + const leaf_node = try self.state.getChildNode(Gindex.fromDepth(chunk_depth, full_chunks)); + const leaf = leaf_node.getRoot(self.state.pool); const full_bytes = remainder_bits / 8; const tail_bits = remainder_bits % 8; @@ -138,15 +118,15 @@ pub fn BitArray(comptime chunk_depth: Depth) type { } pub fn getChildNode(self: *Self, gindex: Gindex) !Node.Id { - return ChildNodes.getChildNode(self, gindex); + return self.state.getChildNode(gindex); } pub fn setChildNode(self: *Self, gindex: Gindex, node: Node.Id) !void { - try ChildNodes.setChildNode(self, gindex, node); + try self.state.setChildNode(gindex, node); } pub fn clearChildrenNodesCache(self: *Self) void { - ChildNodes.clearChildrenNodesCache(self, self.pool); + self.state.clearChildrenNodesCache(); } }; } diff --git a/src/ssz/tree_view/bit_list.zig b/src/ssz/tree_view/bit_list.zig index 873f5fe46..5f27c28c8 100644 --- a/src/ssz/tree_view/bit_list.zig +++ b/src/ssz/tree_view/bit_list.zig @@ -69,16 +69,16 @@ pub fn BitListTreeView(comptime ST: type) type { pub fn hashTreeRoot(self: *Self, out: *[32]u8) !void { try self.commit(); - out.* = self.data.root.getRoot(self.data.pool).*; + out.* = self.data.state.root.getRoot(self.data.state.pool).*; } pub fn getRoot(self: *const Self) Node.Id { - return self.data.root; + return self.data.state.root; } fn readLength(self: *Self) !usize { const length_node = try self.data.getChildNode(@enumFromInt(3)); - const length_chunk = length_node.getRoot(self.data.pool); + const length_chunk = length_node.getRoot(self.data.state.pool); return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); } @@ -167,13 +167,13 @@ test "BitListTreeView clone(true) does not transfer cache" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.state.children_nodes.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.data.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.data.children_nodes.count()); + try std.testing.expect(view.data.state.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.data.state.children_nodes.count()); } test "BitListTreeView clone(false) transfers cache and clears source" { @@ -193,13 +193,13 @@ test "BitListTreeView clone(false) transfers cache and clears source" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.state.children_nodes.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.data.children_nodes.count()); - try std.testing.expect(cloned.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.data.state.children_nodes.count()); + try std.testing.expect(cloned.data.state.children_nodes.count() > 0); } test "BitListTreeView clone isolates updates" { diff --git a/src/ssz/tree_view/bit_vector.zig b/src/ssz/tree_view/bit_vector.zig index 362cd11c8..228639d4e 100644 --- a/src/ssz/tree_view/bit_vector.zig +++ b/src/ssz/tree_view/bit_vector.zig @@ -66,11 +66,11 @@ pub fn BitVectorTreeView(comptime ST: type) type { pub fn hashTreeRoot(self: *Self, out: *[32]u8) !void { try self.commit(); - out.* = self.data.root.getRoot(self.data.pool).*; + out.* = self.data.state.root.getRoot(self.data.state.pool).*; } pub fn getRoot(self: *const Self) Node.Id { - return self.data.root; + return self.data.state.root; } pub fn get(self: *Self, index: usize) !Element { @@ -89,7 +89,7 @@ pub fn BitVectorTreeView(comptime ST: type) type { pub fn toValue(self: *Self, _: Allocator, out: *ST.Type) !void { try self.commit(); - try ST.tree.toValue(self.data.root, self.data.pool, out); + try ST.tree.toValue(self.data.state.root, self.data.state.pool, out); } /// Caller must free the returned slice. @@ -164,13 +164,13 @@ test "BitVectorTreeView clone(true) does not transfer cache" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.state.children_nodes.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.data.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.data.children_nodes.count()); + try std.testing.expect(view.data.state.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.data.state.children_nodes.count()); } test "BitVectorTreeView clone(false) transfers cache and clears source" { @@ -190,13 +190,13 @@ test "BitVectorTreeView clone(false) transfers cache and clears source" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.data.children_nodes.count() > 0); + try std.testing.expect(view.data.state.children_nodes.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.data.children_nodes.count()); - try std.testing.expect(cloned.data.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.data.state.children_nodes.count()); + try std.testing.expect(cloned.data.state.children_nodes.count() > 0); } test "BitVectorTreeView clone isolates updates" { diff --git a/src/ssz/tree_view/chunks.zig b/src/ssz/tree_view/chunks.zig index 4272eadf0..82cd72df7 100644 --- a/src/ssz/tree_view/chunks.zig +++ b/src/ssz/tree_view/chunks.zig @@ -10,7 +10,7 @@ const Gindex = @import("persistent_merkle_tree").Gindex; const isFixedType = @import("../type/type_kind.zig").isFixedType; const tree_view_root = @import("root.zig"); -const ChildNodes = @import("utils/child_nodes.zig").ChildNodes; +const TreeViewState = @import("utils/tree_view_state.zig").TreeViewState; const CloneOpts = @import("utils/clone_opts.zig").CloneOpts; /// Shared helpers for basic element types packed into chunks. @@ -20,73 +20,44 @@ pub fn BasicPackedChunks( comptime items_per_chunk: usize, ) type { return struct { - allocator: Allocator, - pool: *Node.Pool, - root: Node.Id, - - /// cached nodes for faster access of already-visited children - children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), - - /// whether the corresponding child node/data has changed since the last update of the root - changed: std.AutoArrayHashMapUnmanaged(Gindex, void), + state: TreeViewState, pub const Element = ST.Element.Type; const Self = @This(); pub fn init(self: *Self, allocator: Allocator, pool: *Node.Pool, root: Node.Id) !void { - try pool.ref(root); - errdefer pool.unref(root); - self.* = .{ - .allocator = allocator, - .pool = pool, - .root = root, - .children_nodes = .empty, - .changed = .empty, - }; + try self.state.init(allocator, pool, root); } pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { - try ChildNodes.Change.cloneAndTransferCache(Self, self, opts, out); + try self.state.clone(opts, &out.state); } pub fn deinit(self: *Self) void { - self.pool.unref(self.root); - self.clearChildrenNodesCache(); - self.children_nodes.deinit(self.allocator); - self.changed.deinit(self.allocator); + self.state.deinit(); } pub fn commit(self: *Self) !void { - try ChildNodes.Change.commit(self); + try self.state.commitNodes(); } pub fn clearCache(self: *Self) void { - self.clearChildrenNodesCache(); - self.changed.clearRetainingCapacity(); + self.state.clearCache(); } pub fn get(self: *Self, index: usize) !Element { var value: Element = undefined; - const child_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, index / items_per_chunk)); - try ST.Element.tree.toValuePacked(child_node, self.pool, index, &value); + const child_node = try self.state.getChildNode(Gindex.fromDepth(chunk_depth, index / items_per_chunk)); + try ST.Element.tree.toValuePacked(child_node, self.state.pool, index, &value); return value; } pub fn set(self: *Self, index: usize, value: Element) !void { const gindex = Gindex.fromDepth(chunk_depth, index / items_per_chunk); - try self.changed.put(self.allocator, gindex, {}); - const child_node = try self.getChildNode(gindex); - const opt_old_node = try self.children_nodes.fetchPut( - self.allocator, - gindex, - try ST.Element.tree.fromValuePacked(child_node, self.pool, index, &value), - ); - if (opt_old_node) |old_node| { - if (old_node.value.getState(self.pool).getRefCount() == 0) { - self.pool.unref(old_node.value); - } - } + const child_node = try self.state.getChildNode(gindex); + const new_node = try ST.Element.tree.fromValuePacked(child_node, self.state.pool, index, &value); + try self.state.setChildNode(gindex, new_node); } pub fn getAll( @@ -114,11 +85,11 @@ pub fn BasicPackedChunks( try self.populateAllNodes(chunk_count); for (0..len_full_chunks) |chunk_idx| { - const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); + const leaf_node = try self.state.getChildNode(Gindex.fromDepth(chunk_depth, chunk_idx)); for (0..items_per_chunk) |i| { try ST.Element.tree.toValuePacked( leaf_node, - self.pool, + self.state.pool, i, &values[chunk_idx * items_per_chunk + i], ); @@ -126,11 +97,11 @@ pub fn BasicPackedChunks( } if (remainder > 0) { - const leaf_node = try self.getChildNode(Gindex.fromDepth(chunk_depth, len_full_chunks)); + const leaf_node = try self.state.getChildNode(Gindex.fromDepth(chunk_depth, len_full_chunks)); for (0..remainder) |i| { try ST.Element.tree.toValuePacked( leaf_node, - self.pool, + self.state.pool, i, &values[len_full_chunks * items_per_chunk + i], ); @@ -143,14 +114,14 @@ pub fn BasicPackedChunks( fn populateAllNodes(self: *Self, chunk_count: usize) !void { if (chunk_count == 0) return; - const nodes = try self.allocator.alloc(Node.Id, chunk_count); - defer self.allocator.free(nodes); + const nodes = try self.state.allocator.alloc(Node.Id, chunk_count); + defer self.state.allocator.free(nodes); - try self.root.getNodesAtDepth(self.pool, chunk_depth, 0, nodes); + try self.state.root.getNodesAtDepth(self.state.pool, chunk_depth, 0, nodes); for (nodes, 0..) |node, chunk_idx| { const gindex = Gindex.fromDepth(chunk_depth, chunk_idx); - const gop = try self.children_nodes.getOrPut(self.allocator, gindex); + const gop = try self.state.children_nodes.getOrPut(self.state.allocator, gindex); if (!gop.found_existing) { gop.value_ptr.* = node; } @@ -158,23 +129,23 @@ pub fn BasicPackedChunks( } pub fn getChildNode(self: *Self, gindex: Gindex) !Node.Id { - return ChildNodes.getChildNode(self, gindex); + return self.state.getChildNode(gindex); } pub fn setChildNode(self: *Self, gindex: Gindex, node: Node.Id) !void { - try ChildNodes.setChildNode(self, gindex, node); - } - - fn clearChildrenNodesCache(self: *Self) void { - ChildNodes.clearChildrenNodesCache(self, self.pool); + try self.state.setChildNode(gindex, node); } pub fn getLength(self: *Self) !usize { - return try ChildNodes.getLength(self); + const length_node = try self.state.getChildNode(@enumFromInt(3)); + const length_chunk = length_node.getRoot(self.state.pool); + return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); } pub fn setLength(self: *Self, length: usize) !void { - try ChildNodes.setLength(self, length); + const length_node = try self.state.pool.createLeafFromUint(@intCast(length)); + errdefer self.state.pool.unref(length_node); + try self.state.setChildNode(@enumFromInt(3), length_node); } }; } @@ -185,128 +156,96 @@ pub fn CompositeChunks( comptime chunk_depth: Depth, ) type { return struct { - allocator: Allocator, - pool: *Node.Pool, - root: Node.Id, - - /// cached nodes for faster access of already-visited children - children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), + state: TreeViewState, /// cached data for faster access of already-visited children children_data: std.AutoHashMapUnmanaged(Gindex, ElementPtr), - /// whether the corresponding child node/data has changed since the last update of the root - changed: std.AutoArrayHashMapUnmanaged(Gindex, void), - const Element = ST.Element.TreeView; pub const ElementPtr = *Element; const Self = @This(); pub fn init(self: *Self, allocator: Allocator, pool: *Node.Pool, root: Node.Id) !void { - try pool.ref(root); - errdefer pool.unref(root); - self.* = .{ - .allocator = allocator, - .pool = pool, - .root = root, - .children_nodes = .empty, - .children_data = .empty, - .changed = .empty, - }; + try self.state.init(allocator, pool, root); + self.children_data = .empty; } pub fn clone(self: *Self, opts: CloneOpts, out: *Self) !void { - try init(out, self.allocator, self.pool, self.root); - if (!opts.transfer_cache) { + try self.state.clone(opts, &out.state); + out.children_data = .empty; return; } - out.children_nodes = self.children_nodes; + // Transfer children_data, removing uncommitted entries. out.children_data = self.children_data; - - // Removing while iterating can invalidate the iterator. - for (self.changed.keys()) |gindex| { - if (out.children_data.fetchRemove(gindex)) |entry| { - entry.value.deinit(); + { + const changed_keys = self.state.changed.keys(); + for (changed_keys) |gindex| { + if (out.children_data.fetchRemove(gindex)) |entry| { + entry.value.deinit(); + } } } + // changed_keys borrow is now out of scope. - // clear self's caches - self.children_nodes = .empty; + // Clone state (transfers children_nodes, clears self caches). + try self.state.clone(opts, &out.state); self.children_data = .empty; - self.changed.clearRetainingCapacity(); } /// Deinitialize the Data and free all associated resources. /// This also deinits all child Data recursively. pub fn deinit(self: *Self) void { - self.pool.unref(self.root); - self.clearChildrenNodesCache(); - self.children_nodes.deinit(self.allocator); + const allocator = self.state.allocator; self.clearChildrenDataCache(); - self.children_data.deinit(self.allocator); - self.changed.deinit(self.allocator); + self.children_data.deinit(allocator); + self.state.deinit(); } pub fn commit(self: *Self) !void { - if (self.changed.count() == 0) { + if (self.state.changed.count() == 0) { return; } - const nodes = try self.allocator.alloc(Node.Id, self.changed.count()); - defer self.allocator.free(nodes); - - const gindices = self.changed.keys(); - Gindex.sortAsc(gindices); - - for (gindices, 0..) |gindex, i| { + // Flush child views into children_nodes so commitNodes can handle them uniformly. + for (self.state.changed.keys()) |gindex| { if (self.children_data.get(gindex)) |child_ptr| { - // TODO: compare with child_nodes to avoid unnecessary rebind try child_ptr.commit(); - nodes[i] = child_ptr.getRoot(); - } else if (self.children_nodes.get(gindex)) |child_node| { - nodes[i] = child_node; - } else { - return error.ChildNotFound; + const gop = try self.state.children_nodes.getOrPut(self.state.allocator, gindex); + gop.value_ptr.* = child_ptr.getRoot(); } } - const new_root = try self.root.setNodesGrouped(self.pool, gindices, nodes); - try self.pool.ref(new_root); - self.pool.unref(self.root); - self.root = new_root; - - self.changed.clearRetainingCapacity(); + try self.state.commitNodes(); } pub fn clearCache(self: *Self) void { - self.clearChildrenNodesCache(); + self.state.clearCache(); self.clearChildrenDataCache(); - self.changed.clearRetainingCapacity(); } pub fn get(self: *Self, index: usize) !ElementPtr { const gindex = Gindex.fromDepth(chunk_depth, index); // Always mark as changed - the child may have been previously cached // via getReadonly() without being tracked in changed. - try self.changed.put(self.allocator, gindex, {}); - const gop = try self.children_data.getOrPut(self.allocator, gindex); + try self.state.changed.put(self.state.allocator, gindex, {}); + const gop = try self.children_data.getOrPut(self.state.allocator, gindex); if (gop.found_existing) { return gop.value_ptr.*; } - const child_node = try self.getChildNode(gindex); - const child_ptr = try Element.init(self.allocator, self.pool, child_node); + const child_node = try self.state.getChildNode(gindex); + const child_ptr = try Element.init(self.state.allocator, self.state.pool, child_node); gop.value_ptr.* = child_ptr; return child_ptr; } pub fn set(self: *Self, index: usize, value: ElementPtr) !void { const gindex = Gindex.fromDepth(chunk_depth, index); - try self.changed.put(self.allocator, gindex, {}); + try self.state.changed.put(self.state.allocator, gindex, {}); const opt_old_data = try self.children_data.fetchPut( - self.allocator, + self.state.allocator, gindex, value, ); @@ -324,10 +263,10 @@ pub fn CompositeChunks( if (self.children_data.get(gindex)) |child_ptr| { return child_ptr; } - const child_node = try self.getChildNode(gindex); - const child_ptr = try Element.init(self.allocator, self.pool, child_node); - try self.children_data.put(self.allocator, gindex, child_ptr); - // Do NOT add to self.changed (read-only) + const child_node = try self.state.getChildNode(gindex); + const child_ptr = try Element.init(self.state.allocator, self.state.pool, child_node); + try self.children_data.put(self.state.allocator, gindex, child_ptr); + // Do NOT add to self.state.changed (read-only) return child_ptr; } @@ -355,9 +294,9 @@ pub fn CompositeChunks( /// Set a child from an SSZ value type. pub fn setValue(self: *Self, index: usize, value: *const Value) !void { - const root = try ST.Element.tree.fromValue(self.pool, value); - errdefer self.pool.unref(root); - const child_view = try Element.init(self.allocator, self.pool, root); + const root = try ST.Element.tree.fromValue(self.state.pool, value); + errdefer self.state.pool.unref(root); + const child_view = try Element.init(self.state.allocator, self.state.pool, root); errdefer child_view.deinit(); try self.set(index, child_view); } @@ -375,25 +314,25 @@ pub fn CompositeChunks( const len = values.len; if (len == 0) return values; - if (self.changed.count() != 0) { + if (self.state.changed.count() != 0) { return error.MustCommitBeforeBulkRead; } const nodes = try allocator.alloc(Node.Id, len); defer allocator.free(nodes); - try self.root.getNodesAtDepth(self.pool, chunk_depth, 0, nodes); + try self.state.root.getNodesAtDepth(self.state.pool, chunk_depth, 0, nodes); for (nodes, 0..) |node, i| { if (comptime @hasDecl(ST.Element, "deinit")) { errdefer { - for (values[0..i]) |*value| { - ST.Element.deinit(allocator, value); + for (values[0..i]) |*v| { + ST.Element.deinit(allocator, v); } } } if (comptime isFixedType(ST.Element)) { - try ST.Element.tree.toValue(node, self.pool, &values[i]); + try ST.Element.tree.toValue(node, self.state.pool, &values[i]); } else { // Initialize value to default before toValue for variable types // (e.g. BitList fields need initialized ArrayListUnmanaged) @@ -402,7 +341,7 @@ pub fn CompositeChunks( } else { values[i] = std.mem.zeroes(Value); } - try ST.Element.tree.toValue(allocator, node, self.pool, &values[i]); + try ST.Element.tree.toValue(allocator, node, self.state.pool, &values[i]); } } @@ -410,23 +349,23 @@ pub fn CompositeChunks( } pub fn getChildNode(self: *Self, gindex: Gindex) !Node.Id { - return ChildNodes.getChildNode(self, gindex); + return self.state.getChildNode(gindex); } pub fn setChildNode(self: *Self, gindex: Gindex, node: Node.Id) !void { - try ChildNodes.setChildNode(self, gindex, node); - } - - fn clearChildrenNodesCache(self: *Self) void { - ChildNodes.clearChildrenNodesCache(self, self.pool); + try self.state.setChildNode(gindex, node); } pub fn getLength(self: *Self) !usize { - return try ChildNodes.getLength(self); + const length_node = try self.state.getChildNode(@enumFromInt(3)); + const length_chunk = length_node.getRoot(self.state.pool); + return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); } pub fn setLength(self: *Self, length: usize) !void { - try ChildNodes.setLength(self, length); + const length_node = try self.state.pool.createLeafFromUint(@intCast(length)); + errdefer self.state.pool.unref(length_node); + try self.state.setChildNode(@enumFromInt(3), length_node); } fn clearChildrenDataCache(self: *Self) void { diff --git a/src/ssz/tree_view/container.zig b/src/ssz/tree_view/container.zig index 6c23a4c4c..1e6cedd88 100644 --- a/src/ssz/tree_view/container.zig +++ b/src/ssz/tree_view/container.zig @@ -55,7 +55,7 @@ pub fn ContainerTreeView(comptime ST: type) type { /// a tuple of either Optional(Value) for basic type or Optional(ChildTreeView) for composite type child_data: TreeViewData, /// whether the corresponding child node/data has changed since the last update of the root - changed: std.AutoArrayHashMapUnmanaged(usize, void), + changed: std.StaticBitSet(ST.chunk_count), original_nodes: [ST.chunk_count]?Node.Id, pub const SszType = ST; @@ -72,7 +72,7 @@ pub fn ContainerTreeView(comptime ST: type) type { .child_data = .{null} ** ST.chunk_count, .original_nodes = .{null} ** ST.chunk_count, .root = root, - .changed = .empty, + .changed = std.StaticBitSet(ST.chunk_count).initEmpty(), }; return ptr; } @@ -87,7 +87,7 @@ pub fn ContainerTreeView(comptime ST: type) type { ptr.original_nodes = self.original_nodes; inline for (0..ST.fields.len) |i| { - if (self.changed.contains(i)) { + if (self.changed.isSet(i)) { if (ptr.child_data[i]) |child_view_ptr| { if (!comptime isBasicType(ST.fields[i].type)) { @constCast(child_view_ptr).deinit(); @@ -100,7 +100,7 @@ pub fn ContainerTreeView(comptime ST: type) type { // clear self's caches self.child_data = .{null} ** ST.chunk_count; self.original_nodes = .{null} ** ST.chunk_count; - self.changed.clearRetainingCapacity(); + self.changed = std.StaticBitSet(ST.chunk_count).initEmpty(); return ptr; } @@ -124,7 +124,7 @@ pub fn ContainerTreeView(comptime ST: type) type { // these nodes are unref by root self.original_nodes[i] = null; } - self.changed.deinit(self.allocator); + self.changed = std.StaticBitSet(ST.chunk_count).initEmpty(); } pub fn commit(self: *Self) !void { @@ -137,7 +137,7 @@ pub fn ContainerTreeView(comptime ST: type) type { var changed_idx: usize = 0; inline for (ST.fields, 0..) |field, i| { - if (self.changed.get(i) != null) { + if (self.changed.isSet(i)) { const ChildST = ST.getFieldType(field.name); if (comptime isBasicType(ChildST)) { const child_value = self.child_data[i] orelse return error.MissingChildValue; @@ -166,7 +166,7 @@ pub fn ContainerTreeView(comptime ST: type) type { } } - self.changed.clearRetainingCapacity(); + self.changed = std.StaticBitSet(ST.chunk_count).initEmpty(); if (changed_idx == 0) { return; } @@ -235,7 +235,7 @@ pub fn ContainerTreeView(comptime ST: type) type { return child_value; } } else { - try self.changed.put(self.allocator, field_index, {}); + self.changed.set(field_index); const existing_ptr = self.child_data[field_index]; if (existing_ptr) |child_view_ptr| { @@ -278,7 +278,7 @@ pub fn ContainerTreeView(comptime ST: type) type { self.child_data[field_index] = value; } - try self.changed.put(self.allocator, field_index, {}); + self.changed.set(field_index); } /// Serialize the tree view into a provided buffer. diff --git a/src/ssz/tree_view/list_basic.zig b/src/ssz/tree_view/list_basic.zig index 7a05fcf9d..18b30ca38 100644 --- a/src/ssz/tree_view/list_basic.zig +++ b/src/ssz/tree_view/list_basic.zig @@ -83,12 +83,12 @@ pub fn ListBasicTreeView(comptime ST: type) type { pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { try self.commit(); - out.* = self.chunks.root.getRoot(self.chunks.pool).*; + out.* = self.chunks.state.root.getRoot(self.chunks.state.pool).*; } pub fn hashTreeRoot(self: *Self) !*const [32]u8 { try self.commit(); - return self.chunks.root.getRoot(self.chunks.pool); + return self.chunks.state.root.getRoot(self.chunks.state.pool); } pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { @@ -99,7 +99,7 @@ pub fn ListBasicTreeView(comptime ST: type) type { pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { try self.commit(); - try ST.tree.toValue(allocator, self.chunks.root, self.chunks.pool, out); + try ST.tree.toValue(allocator, self.chunks.state.root, self.chunks.state.pool, out); } pub fn setLength(self: *Self, new_length: usize) !void { @@ -120,8 +120,8 @@ pub fn ListBasicTreeView(comptime ST: type) type { return .{ .tree_view = tree_view, .depth_iterator = Node.DepthIterator.init( - tree_view.chunks.pool, - tree_view.chunks.root, + tree_view.chunks.state.pool, + tree_view.chunks.state.root, ST.chunk_depth + 1, ST.chunkIndex(start_index), ), @@ -138,7 +138,7 @@ pub fn ListBasicTreeView(comptime ST: type) type { try self.depth_iterator.next(); self.elem_node = n; var value: Element = undefined; - try ST.Element.tree.toValuePacked(n, self.tree_view.chunks.pool, elem_index, &value); + try ST.Element.tree.toValuePacked(n, self.tree_view.chunks.state.pool, elem_index, &value); self.elem_index += 1; if (self.elem_index % items_per_chunk == 0) { self.elem_node = null; @@ -148,7 +148,7 @@ pub fn ListBasicTreeView(comptime ST: type) type { }; pub fn getRoot(self: *const Self) Node.Id { - return self.chunks.root; + return self.chunks.state.root; } pub fn length(self: *const Self) !usize { @@ -194,7 +194,7 @@ pub fn ListBasicTreeView(comptime ST: type) type { const list_length = try self.length(); if (list_length == 0 or index >= list_length - 1) { - return try Self.init(self.allocator, self.chunks.pool, self.chunks.root); + return try Self.init(self.allocator, self.chunks.state.pool, self.chunks.state.root); } const new_length = index + 1; @@ -204,52 +204,52 @@ pub fn ListBasicTreeView(comptime ST: type) type { const chunk_index = index / items_per_chunk; const chunk_offset = index % items_per_chunk; - const chunk_node = try Node.Id.getNodeAtDepth(self.chunks.root, self.chunks.pool, chunk_depth, chunk_index); + const chunk_node = try Node.Id.getNodeAtDepth(self.chunks.state.root, self.chunks.state.pool, chunk_depth, chunk_index); - var chunk_bytes = chunk_node.getRoot(self.chunks.pool).*; + var chunk_bytes = chunk_node.getRoot(self.chunks.state.pool).*; const keep_bytes = (chunk_offset + 1) * ST.Element.fixed_size; if (keep_bytes < BYTES_PER_CHUNK) { @memset(chunk_bytes[keep_bytes..], 0); } - var truncated_chunk_node: ?Node.Id = try self.chunks.pool.createLeaf(&chunk_bytes); - defer if (truncated_chunk_node) |id| self.chunks.pool.unref(id); + var truncated_chunk_node: ?Node.Id = try self.chunks.state.pool.createLeaf(&chunk_bytes); + defer if (truncated_chunk_node) |id| self.chunks.state.pool.unref(id); var updated: ?Node.Id = try Node.Id.setNodeAtDepth( - self.chunks.root, - self.chunks.pool, + self.chunks.state.root, + self.chunks.state.pool, chunk_depth, chunk_index, truncated_chunk_node.?, ); - defer if (updated) |id| self.chunks.pool.unref(id); + defer if (updated) |id| self.chunks.state.pool.unref(id); truncated_chunk_node = null; - var new_root: ?Node.Id = try Node.Id.truncateAfterIndex(updated.?, self.chunks.pool, chunk_depth, chunk_index); - defer if (new_root) |id| self.chunks.pool.unref(id); + var new_root: ?Node.Id = try Node.Id.truncateAfterIndex(updated.?, self.chunks.state.pool, chunk_depth, chunk_index); + defer if (new_root) |id| self.chunks.state.pool.unref(id); updated = null; - var length_node: ?Node.Id = try self.chunks.pool.createLeafFromUint(@intCast(new_length)); - defer if (length_node) |id| self.chunks.pool.unref(id); - const root_with_length = try Node.Id.setNode(new_root.?, self.chunks.pool, @enumFromInt(3), length_node.?); - errdefer self.chunks.pool.unref(root_with_length); + var length_node: ?Node.Id = try self.chunks.state.pool.createLeafFromUint(@intCast(new_length)); + defer if (length_node) |id| self.chunks.state.pool.unref(id); + const root_with_length = try Node.Id.setNode(new_root.?, self.chunks.state.pool, @enumFromInt(3), length_node.?); + errdefer self.chunks.state.pool.unref(root_with_length); length_node = null; new_root = null; - return try Self.init(self.allocator, self.chunks.pool, root_with_length); + return try Self.init(self.allocator, self.chunks.state.pool, root_with_length); } /// Serialize the tree view into a provided buffer. /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.state.root, self.chunks.state.pool, out); } /// Get the serialized size of this tree view. pub fn serializedSize(self: *Self) !usize { try self.commit(); - return try ST.tree.serializedSize(self.chunks.root, self.chunks.pool); + return try ST.tree.serializedSize(self.chunks.state.root, self.chunks.state.pool); } fn updateListLength(self: *Self) !void { @@ -591,13 +591,13 @@ test "TreeView list basic clone(true) does not transfer cache" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.chunks.children_nodes.count() > 0); + try std.testing.expect(view.chunks.state.children_nodes.count() > 0); var cloned_no_cache = try view.clone(.{ .transfer_cache = false }); defer cloned_no_cache.deinit(); - try std.testing.expect(view.chunks.children_nodes.count() > 0); - try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.children_nodes.count()); + try std.testing.expect(view.chunks.state.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), cloned_no_cache.chunks.state.children_nodes.count()); } test "TreeView list basic clone(false) transfers cache and clears source" { @@ -617,13 +617,13 @@ test "TreeView list basic clone(false) transfers cache and clears source" { defer view.deinit(); _ = try view.get(0); - try std.testing.expect(view.chunks.children_nodes.count() > 0); + try std.testing.expect(view.chunks.state.children_nodes.count() > 0); var cloned = try view.clone(.{}); defer cloned.deinit(); - try std.testing.expectEqual(@as(usize, 0), view.chunks.children_nodes.count()); - try std.testing.expect(cloned.chunks.children_nodes.count() > 0); + try std.testing.expectEqual(@as(usize, 0), view.chunks.state.children_nodes.count()); + try std.testing.expect(cloned.chunks.state.children_nodes.count() > 0); } // Refer to https://github.com/ChainSafe/ssz/blob/7f5580c2ea69f9307300ddb6010a8bc7ce2fc471/packages/ssz/test/unit/byType/listBasic/tree.test.ts#L180-L203 diff --git a/src/ssz/tree_view/list_composite.zig b/src/ssz/tree_view/list_composite.zig index 536400f95..aec5786ef 100644 --- a/src/ssz/tree_view/list_composite.zig +++ b/src/ssz/tree_view/list_composite.zig @@ -84,12 +84,12 @@ pub fn ListCompositeTreeView(comptime ST: type) type { pub fn hashTreeRootInto(self: *Self, out: *[32]u8) !void { try self.commit(); - out.* = self.chunks.root.getRoot(self.chunks.pool).*; + out.* = self.chunks.state.root.getRoot(self.chunks.state.pool).*; } pub fn hashTreeRoot(self: *Self) !*const [32]u8 { try self.commit(); - return self.chunks.root.getRoot(self.chunks.pool); + return self.chunks.state.root.getRoot(self.chunks.state.pool); } pub fn fromValue(allocator: Allocator, pool: *Node.Pool, value: *const ST.Type) !*Self { @@ -100,7 +100,7 @@ pub fn ListCompositeTreeView(comptime ST: type) type { pub fn toValue(self: *Self, allocator: Allocator, out: *ST.Type) !void { try self.commit(); - try ST.tree.toValue(allocator, self.chunks.root, self.chunks.pool, out); + try ST.tree.toValue(allocator, self.chunks.state.root, self.chunks.state.pool, out); } pub fn setLength(self: *Self, new_length: usize) !void { @@ -108,7 +108,7 @@ pub fn ListCompositeTreeView(comptime ST: type) type { } pub fn getRoot(self: *const Self) Node.Id { - return self.chunks.root; + return self.chunks.state.root; } pub fn length(self: *const Self) !usize { @@ -144,7 +144,7 @@ pub fn ListCompositeTreeView(comptime ST: type) type { if (index >= list_length) return error.IndexOutOfBounds; const elem = try self.chunks.get(index); try elem.commit(); - return elem.getRoot().getRoot(self.chunks.pool); + return elem.getRoot().getRoot(self.chunks.state.pool); } pub fn set(self: *Self, index: usize, value: Element) !void { @@ -180,9 +180,9 @@ pub fn ListCompositeTreeView(comptime ST: type) type { /// Push an SSZ value type, creating a TreeView internally. pub fn pushValue(self: *Self, value: *const ST.Element.Type) !void { - const root = try ST.Element.tree.fromValue(self.chunks.pool, value); - errdefer self.chunks.pool.unref(root); - const child_view = try ST.Element.TreeView.init(self.allocator, self.chunks.pool, root); + const root = try ST.Element.tree.fromValue(self.chunks.state.pool, value); + errdefer self.chunks.state.pool.unref(root); + const child_view = try ST.Element.TreeView.init(self.allocator, self.chunks.state.pool, root); errdefer child_view.deinit(); try self.push(child_view); } @@ -200,8 +200,8 @@ pub fn ListCompositeTreeView(comptime ST: type) type { return .{ .tree_view = tree_view, .depth_iterator = Node.DepthIterator.init( - tree_view.chunks.pool, - tree_view.chunks.root, + tree_view.chunks.state.pool, + tree_view.chunks.state.root, chunk_depth, start_index, ), @@ -213,7 +213,7 @@ pub fn ListCompositeTreeView(comptime ST: type) type { const node = try self.depth_iterator.next(); const child_view = try ST.Element.TreeView.init( self.tree_view.allocator, - self.tree_view.chunks.pool, + self.tree_view.chunks.state.pool, node, ); self.elem_index += 1; @@ -224,7 +224,7 @@ pub fn ListCompositeTreeView(comptime ST: type) type { pub fn nextRoot(self: *ReadonlyIterator) !*const [32]u8 { const node = try self.depth_iterator.next(); self.elem_index += 1; - return node.getRoot(self.tree_view.chunks.pool); + return node.getRoot(self.tree_view.chunks.state.pool); } /// Get the next element as an SSZ value type. @@ -233,9 +233,9 @@ pub fn ListCompositeTreeView(comptime ST: type) type { self.elem_index += 1; var value: ST.Element.Type = undefined; if (comptime isFixedType(ST.Element)) { - try ST.Element.tree.toValue(node, self.tree_view.chunks.pool, &value); + try ST.Element.tree.toValue(node, self.tree_view.chunks.state.pool, &value); } else { - try ST.Element.tree.toValue(allocator, node, self.tree_view.chunks.pool, &value); + try ST.Element.tree.toValue(allocator, node, self.tree_view.chunks.state.pool, &value); } return value; } @@ -248,7 +248,7 @@ pub fn ListCompositeTreeView(comptime ST: type) type { const list_length = try self.length(); if (list_length == 0 or index >= list_length - 1) { - return try Self.init(self.allocator, self.chunks.pool, self.chunks.root); + return try Self.init(self.allocator, self.chunks.state.pool, self.chunks.state.root); } const new_length = index + 1; @@ -256,17 +256,17 @@ pub fn ListCompositeTreeView(comptime ST: type) type { return error.LengthOverLimit; } - var chunk_root: ?Node.Id = try Node.Id.truncateAfterIndex(self.chunks.root, self.chunks.pool, chunk_depth, index); - defer if (chunk_root) |id| self.chunks.pool.unref(id); + var chunk_root: ?Node.Id = try Node.Id.truncateAfterIndex(self.chunks.state.root, self.chunks.state.pool, chunk_depth, index); + defer if (chunk_root) |id| self.chunks.state.pool.unref(id); - var length_node: ?Node.Id = try self.chunks.pool.createLeafFromUint(@intCast(new_length)); - defer if (length_node) |id| self.chunks.pool.unref(id); - const root_with_length = try Node.Id.setNode(chunk_root.?, self.chunks.pool, @enumFromInt(3), length_node.?); - errdefer self.chunks.pool.unref(root_with_length); + var length_node: ?Node.Id = try self.chunks.state.pool.createLeafFromUint(@intCast(new_length)); + defer if (length_node) |id| self.chunks.state.pool.unref(id); + const root_with_length = try Node.Id.setNode(chunk_root.?, self.chunks.state.pool, @enumFromInt(3), length_node.?); + errdefer self.chunks.state.pool.unref(root_with_length); length_node = null; chunk_root = null; - return try Self.init(self.allocator, self.chunks.pool, root_with_length); + return try Self.init(self.allocator, self.chunks.state.pool, root_with_length); } /// Return a new view containing all elements from `index` to the end. @@ -276,46 +276,46 @@ pub fn ListCompositeTreeView(comptime ST: type) type { const list_length = try self.length(); if (index == 0) { - return try Self.init(self.allocator, self.chunks.pool, self.chunks.root); + return try Self.init(self.allocator, self.chunks.state.pool, self.chunks.state.root); } const target_length = if (index >= list_length) 0 else list_length - index; var chunk_root: ?Node.Id = null; - defer if (chunk_root) |id| self.chunks.pool.unref(id); + defer if (chunk_root) |id| self.chunks.state.pool.unref(id); if (target_length == 0) { chunk_root = @enumFromInt(base_chunk_depth); } else { const nodes = try self.allocator.alloc(Node.Id, target_length); defer self.allocator.free(nodes); - try self.chunks.root.getNodesAtDepth(self.chunks.pool, chunk_depth, index, nodes); + try self.chunks.state.root.getNodesAtDepth(self.chunks.state.pool, chunk_depth, index, nodes); - chunk_root = try Node.fillWithContents(self.chunks.pool, nodes, base_chunk_depth); + chunk_root = try Node.fillWithContents(self.chunks.state.pool, nodes, base_chunk_depth); } - var length_node: ?Node.Id = try self.chunks.pool.createLeafFromUint(@intCast(target_length)); - defer if (length_node) |id| self.chunks.pool.unref(id); + var length_node: ?Node.Id = try self.chunks.state.pool.createLeafFromUint(@intCast(target_length)); + defer if (length_node) |id| self.chunks.state.pool.unref(id); - const new_root = try self.chunks.pool.createBranch(chunk_root.?, length_node.?); - errdefer self.chunks.pool.unref(new_root); + const new_root = try self.chunks.state.pool.createBranch(chunk_root.?, length_node.?); + errdefer self.chunks.state.pool.unref(new_root); length_node = null; chunk_root = null; - return try Self.init(self.allocator, self.chunks.pool, new_root); + return try Self.init(self.allocator, self.chunks.state.pool, new_root); } /// Serialize the tree view into a provided buffer. /// Returns the number of bytes written. pub fn serializeIntoBytes(self: *Self, out: []u8) !usize { try self.commit(); - return try ST.tree.serializeIntoBytes(self.chunks.root, self.chunks.pool, out); + return try ST.tree.serializeIntoBytes(self.chunks.state.root, self.chunks.state.pool, out); } /// Get the serialized size of this tree view. pub fn serializedSize(self: *Self) !usize { try self.commit(); - return try ST.tree.serializedSize(self.chunks.root, self.chunks.pool); + return try ST.tree.serializedSize(self.chunks.state.root, self.chunks.state.pool); } fn updateListLength(self: *Self) !void { diff --git a/src/ssz/tree_view/utils/child_nodes.zig b/src/ssz/tree_view/utils/child_nodes.zig deleted file mode 100644 index e38ff9863..000000000 --- a/src/ssz/tree_view/utils/child_nodes.zig +++ /dev/null @@ -1,106 +0,0 @@ -const std = @import("std"); -const Node = @import("persistent_merkle_tree").Node; -const Gindex = @import("persistent_merkle_tree").Gindex; -const CloneOpts = @import("clone_opts.zig").CloneOpts; - -/// Common functions for `TreeView`s dealing with `children_nodes`. -pub const ChildNodes = struct { - pub fn getChildNode(self: anytype, gindex: Gindex) !Node.Id { - const gop = try self.children_nodes.getOrPut(self.allocator, gindex); - if (gop.found_existing) { - return gop.value_ptr.*; - } - const child_node = try self.root.getNode(self.pool, gindex); - gop.value_ptr.* = child_node; - return child_node; - } - - pub fn setChildNode(self: anytype, gindex: Gindex, node: Node.Id) !void { - try self.changed.put(self.allocator, gindex, {}); - const opt_old_node = try self.children_nodes.fetchPut( - self.allocator, - gindex, - node, - ); - if (opt_old_node) |old_node| { - // Multiple set() calls before commit() leave our previous temp nodes cached with refcount 0. - // Tree-owned nodes already have a refcount, so skip unref in that case. - if (old_node.value.getState(self.pool).getRefCount() == 0) { - self.pool.unref(old_node.value); - } - } - } - - pub fn clearChildrenNodesCache(self: anytype, pool: *Node.Pool) void { - var value_iter = self.children_nodes.valueIterator(); - while (value_iter.next()) |node_id_ptr| { - const node_id = node_id_ptr.*; - if (node_id.getState(pool).getRefCount() == 0) { - pool.unref(node_id); - } - } - self.children_nodes.clearRetainingCapacity(); - } - - pub fn getLength(self: anytype) !usize { - const length_node = try getChildNode(self, @enumFromInt(3)); - const length_chunk = length_node.getRoot(self.pool); - return std.mem.readInt(usize, length_chunk[0..@sizeOf(usize)], .little); - } - - pub fn setLength(self: anytype, length: usize) !void { - const length_node = try self.pool.createLeafFromUint(@intCast(length)); - errdefer self.pool.unref(length_node); - try self.setChildNode(@enumFromInt(3), length_node); - } - - /// Common functions for TreeViews deal with `children_nodes` + `changed` - pub const Change = struct { - pub fn commit(self: anytype) !void { - if (self.changed.count() == 0) { - return; - } - - const nodes = try self.allocator.alloc(Node.Id, self.changed.count()); - defer self.allocator.free(nodes); - - const gindices = self.changed.keys(); - Gindex.sortAsc(gindices); - - for (gindices, 0..) |gindex, i| { - if (self.children_nodes.get(gindex)) |child_node| { - nodes[i] = child_node; - } else { - return error.ChildNotFound; - } - } - - const new_root = try self.root.setNodesGrouped(self.pool, gindices, nodes); - try self.pool.ref(new_root); - self.pool.unref(self.root); - self.root = new_root; - - self.changed.clearRetainingCapacity(); - } - - pub fn cloneAndTransferCache(comptime T: type, self: *T, opts: CloneOpts, out: *T) !void { - try T.init(out, self.allocator, self.pool, self.root); - - if (!opts.transfer_cache) { - return; - } - - out.children_nodes = self.children_nodes; - - // Removing entries while iterating the same map can invalidate the iterator. - // Remove by traversing `self.changed` keys instead. - for (self.changed.keys()) |gindex| { - _ = out.children_nodes.remove(gindex); - } - - // clear self's caches - self.children_nodes = .empty; - self.changed.clearRetainingCapacity(); - } - }; -}; diff --git a/src/ssz/tree_view/utils/tree_view_state.zig b/src/ssz/tree_view/utils/tree_view_state.zig new file mode 100644 index 000000000..26ac24fee --- /dev/null +++ b/src/ssz/tree_view/utils/tree_view_state.zig @@ -0,0 +1,123 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const Node = @import("persistent_merkle_tree").Node; +const Gindex = @import("persistent_merkle_tree").Gindex; +const CloneOpts = @import("clone_opts.zig").CloneOpts; + +/// Common state for tree views that use runtime gindex-based child caching. +/// +/// Used by list, array, bitvector, and bitlist views (chunk-based). +/// NOT used by ContainerTreeView (which uses comptime field-indexed tuples). +pub const TreeViewState = struct { + allocator: Allocator, + pool: *Node.Pool, + root: Node.Id, + + /// cached nodes for faster access of already-visited children + children_nodes: std.AutoHashMapUnmanaged(Gindex, Node.Id), + + /// whether the corresponding child node/data has changed since the last update of the root + changed: std.AutoArrayHashMapUnmanaged(Gindex, void), + + pub fn init(self: *TreeViewState, allocator: Allocator, pool: *Node.Pool, root: Node.Id) !void { + try pool.ref(root); + self.* = .{ + .allocator = allocator, + .pool = pool, + .root = root, + .children_nodes = .empty, + .changed = .empty, + }; + } + + pub fn deinit(self: *TreeViewState) void { + self.clearChildrenNodesCache(); + self.children_nodes.deinit(self.allocator); + self.changed.deinit(self.allocator); + self.pool.unref(self.root); + } + + pub fn getChildNode(self: *TreeViewState, gindex: Gindex) !Node.Id { + const gop = try self.children_nodes.getOrPut(self.allocator, gindex); + if (gop.found_existing) { + return gop.value_ptr.*; + } + const child_node = try self.root.getNode(self.pool, gindex); + gop.value_ptr.* = child_node; + return child_node; + } + + pub fn setChildNode(self: *TreeViewState, gindex: Gindex, node: Node.Id) !void { + try self.changed.put(self.allocator, gindex, {}); + const opt_old_node = try self.children_nodes.fetchPut( + self.allocator, + gindex, + node, + ); + if (opt_old_node) |old_node| { + if (old_node.value.getState(self.pool).getRefCount() == 0) { + self.pool.unref(old_node.value); + } + } + } + + pub fn commitNodes(self: *TreeViewState) !void { + if (self.changed.count() == 0) { + return; + } + + const nodes = try self.allocator.alloc(Node.Id, self.changed.count()); + defer self.allocator.free(nodes); + + const gindices = self.changed.keys(); + Gindex.sortAsc(gindices); + + for (gindices, 0..) |gindex, i| { + if (self.children_nodes.get(gindex)) |child_node| { + nodes[i] = child_node; + } else { + return error.ChildNotFound; + } + } + + const new_root = try self.root.setNodesGrouped(self.pool, gindices, nodes); + try self.pool.ref(new_root); + self.pool.unref(self.root); + self.root = new_root; + + self.changed.clearRetainingCapacity(); + } + + pub fn clearChildrenNodesCache(self: *TreeViewState) void { + var value_iter = self.children_nodes.valueIterator(); + while (value_iter.next()) |node_id_ptr| { + const node_id = node_id_ptr.*; + if (node_id.getState(self.pool).getRefCount() == 0) { + self.pool.unref(node_id); + } + } + self.children_nodes.clearRetainingCapacity(); + } + + pub fn clearCache(self: *TreeViewState) void { + self.clearChildrenNodesCache(); + self.changed.clearRetainingCapacity(); + } + + pub fn clone(self: *TreeViewState, opts: CloneOpts, out: *TreeViewState) !void { + try out.init(self.allocator, self.pool, self.root); + + if (!opts.transfer_cache) { + return; + } + + out.children_nodes = self.children_nodes; + + for (self.changed.keys()) |gindex| { + _ = out.children_nodes.remove(gindex); + } + + self.children_nodes = .empty; + self.changed.clearRetainingCapacity(); + } +};