Phase 5: SimpleStorageRootDeriver + resolve_storage_roots; closes UnresolvedStorageRoot gap in PR3; restore ssz doc comments
Browse files
runtime/builder/Cargo.toml
CHANGED
|
@@ -6,3 +6,4 @@ license.workspace = true
|
|
| 6 |
|
| 7 |
[dependencies]
|
| 8 |
kaysentinel-cse = { path = "../cse" }
|
|
|
|
|
|
| 6 |
|
| 7 |
[dependencies]
|
| 8 |
kaysentinel-cse = { path = "../cse" }
|
| 9 |
+
kaysentinel-hash = { path = "../hash" }
|
runtime/builder/src/lib.rs
CHANGED
|
@@ -27,3 +27,4 @@ pub use lifecycle::hydration::{
|
|
| 27 |
BackendError, CertificateAssemblyError, DerivationError, HydratedAccountState,
|
| 28 |
StorageDerivationError, StorageRootDeriver, assemble_certificates, hydrate_accounts,
|
| 29 |
};
|
|
|
|
|
|
| 27 |
BackendError, CertificateAssemblyError, DerivationError, HydratedAccountState,
|
| 28 |
StorageDerivationError, StorageRootDeriver, assemble_certificates, hydrate_accounts,
|
| 29 |
};
|
| 30 |
+
pub use lifecycle::storage_root::{SimpleStorageRootDeriver, resolve_storage_roots};
|
runtime/builder/src/lifecycle/mod.rs
CHANGED
|
@@ -6,6 +6,7 @@ pub mod hydration;
|
|
| 6 |
pub mod keys;
|
| 7 |
pub mod resolve;
|
| 8 |
pub mod semantic;
|
|
|
|
| 9 |
|
| 10 |
use std::collections::BTreeMap;
|
| 11 |
|
|
|
|
| 6 |
pub mod keys;
|
| 7 |
pub mod resolve;
|
| 8 |
pub mod semantic;
|
| 9 |
+
pub mod storage_root;
|
| 10 |
|
| 11 |
use std::collections::BTreeMap;
|
| 12 |
|
runtime/builder/src/lifecycle/storage_root.rs
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Storage root derivation — implements the `StorageRootDeriver` trait from
|
| 2 |
+
//! `lifecycle::hydration`, and wires its output into already-built certificates.
|
| 3 |
+
//!
|
| 4 |
+
//! Deliberately self-contained (depends only on `kaysentinel-hash`, not on
|
| 5 |
+
//! `runtime/ssz`): `runtime/ssz` already depends on `runtime/builder` (to encode
|
| 6 |
+
//! `CanonicalAccountCertificate`), so the reverse dependency would create a cycle.
|
| 7 |
+
//! This means the pairwise Merkle fold below is a small, independent
|
| 8 |
+
//! re-implementation of the same zero-padding convention `runtime/ssz::merkleize`
|
| 9 |
+
//! uses — not a reuse of it. If the two ever need to be unified, that has to
|
| 10 |
+
//! happen by extracting a third, lower-level crate both depend on, not by either
|
| 11 |
+
//! depending on the other.
|
| 12 |
+
//!
|
| 13 |
+
//! ## Design note: not an Ethereum-compatible storage root
|
| 14 |
+
//!
|
| 15 |
+
//! This derives a protocol-native commitment over an account's touched storage
|
| 16 |
+
//! slots, using the project's own domain-separated BLAKE3 scheme
|
| 17 |
+
//! (`Domain::TrieLeaf` / `Domain::TrieBranch`) — it does **not** attempt to
|
| 18 |
+
//! reproduce Ethereum's real Merkle-Patricia Trie root (which requires Keccak256
|
| 19 |
+
//! and RLP encoding, neither of which exist anywhere in this codebase).
|
| 20 |
+
//!
|
| 21 |
+
//! This is inferred from the available evidence, not confirmed by an explicit
|
| 22 |
+
//! spec statement:
|
| 23 |
+
//! - `docs/emes_profile.md` §5.2 confirms the Geth tracer only ever captures
|
| 24 |
+
//! per-slot (prev, new) mutation pairs (`OnStorageChange`); it never captures
|
| 25 |
+
//! Geth's real per-account MPT root, so there is no authoritative Ethereum
|
| 26 |
+
//! root flowing through this pipeline to reproduce or compare against.
|
| 27 |
+
//! - `kaysentinel-hash`'s entire domain-separation scheme is built on BLAKE3,
|
| 28 |
+
//! structurally incompatible with Ethereum's Keccak/RLP-based MPT regardless
|
| 29 |
+
//! of design intent.
|
| 30 |
+
//! If a future requirement demands real Ethereum MPT compatibility, this
|
| 31 |
+
//! implementation must be replaced, not extended — see `StorageRootDeriver`'s
|
| 32 |
+
//! trait boundary, which exists precisely so the rest of the builder doesn't
|
| 33 |
+
//! need to care which algorithm produced the root.
|
| 34 |
+
|
| 35 |
+
use std::collections::BTreeMap;
|
| 36 |
+
|
| 37 |
+
use kaysentinel_hash::{Domain, derive_commitment};
|
| 38 |
+
|
| 39 |
+
use crate::ir::timeline::CanonicalKey;
|
| 40 |
+
use crate::ir::reduced::ReducedVariant;
|
| 41 |
+
use crate::lifecycle::certificate::CanonicalAccountCertificate;
|
| 42 |
+
use crate::lifecycle::hydration::{DerivationError, StorageRootDeriver};
|
| 43 |
+
use crate::lifecycle::certificate::StorageRootState;
|
| 44 |
+
|
| 45 |
+
/// The canonical "no storage touched" root: derived the same way as any other
|
| 46 |
+
/// case (a zero-leaf Merkle fold), not a magic sentinel constant, so it's
|
| 47 |
+
/// automatically consistent if the leaf/branch hashing ever changes.
|
| 48 |
+
pub struct SimpleStorageRootDeriver;
|
| 49 |
+
|
| 50 |
+
impl StorageRootDeriver for SimpleStorageRootDeriver {
|
| 51 |
+
/// No external base state is used — this derivation only covers slots
|
| 52 |
+
/// actually touched in the current transaction batch, not an account's full
|
| 53 |
+
/// historical storage. Real Ethereum-style trie derivation would need a
|
| 54 |
+
/// `BaseState` carrying the account's prior slots; this interim design
|
| 55 |
+
/// deliberately doesn't model that yet (see module-level design note).
|
| 56 |
+
type BaseState = ();
|
| 57 |
+
|
| 58 |
+
fn derive(
|
| 59 |
+
&self,
|
| 60 |
+
_base_state: &(),
|
| 61 |
+
terminal_slots: &BTreeMap<[u8; 32], [u8; 32]>,
|
| 62 |
+
) -> Result<[u8; 32], DerivationError> {
|
| 63 |
+
let mut leaves: Vec<[u8; 32]> = terminal_slots
|
| 64 |
+
.iter() // BTreeMap iteration is key-sorted -> deterministic leaf order
|
| 65 |
+
.map(|(slot, value)| {
|
| 66 |
+
let mut canonical = Vec::with_capacity(64);
|
| 67 |
+
canonical.extend_from_slice(slot);
|
| 68 |
+
canonical.extend_from_slice(value);
|
| 69 |
+
derive_commitment(Domain::TrieLeaf, &canonical).to_bytes()
|
| 70 |
+
})
|
| 71 |
+
.collect();
|
| 72 |
+
|
| 73 |
+
if leaves.is_empty() {
|
| 74 |
+
leaves.push([0u8; 32]);
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
let mut size = 1usize;
|
| 78 |
+
while size < leaves.len() {
|
| 79 |
+
size <<= 1;
|
| 80 |
+
}
|
| 81 |
+
while leaves.len() < size {
|
| 82 |
+
leaves.push([0u8; 32]);
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
while leaves.len() > 1 {
|
| 86 |
+
let mut next = Vec::with_capacity(leaves.len() / 2);
|
| 87 |
+
for pair in leaves.chunks(2) {
|
| 88 |
+
let mut canonical = Vec::with_capacity(64);
|
| 89 |
+
canonical.extend_from_slice(&pair[0]);
|
| 90 |
+
canonical.extend_from_slice(&pair[1]);
|
| 91 |
+
next.push(derive_commitment(Domain::TrieBranch, &canonical).to_bytes());
|
| 92 |
+
}
|
| 93 |
+
leaves = next;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
Ok(leaves[0])
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
/// Mutates every certificate's `storage_root` in place, deriving it from the
|
| 101 |
+
/// account's `CanonicalKey::Storage` entries in `state_table`. Deliberately
|
| 102 |
+
/// separate from `build_canonical_certificates`/`hydrate_accounts` (an
|
| 103 |
+
/// additive post-processing pass, not a signature change to either) so
|
| 104 |
+
/// existing call sites — including the already-pushed
|
| 105 |
+
/// `runtime/builder/tests/conformance.rs` — keep working unmodified.
|
| 106 |
+
///
|
| 107 |
+
/// `CanonicalKey::Transient` entries are excluded on purpose: EIP-1153
|
| 108 |
+
/// transient storage is explicitly ephemeral (cleared at transaction end) and
|
| 109 |
+
/// is not part of an account's persistent storage root in real Ethereum
|
| 110 |
+
/// semantics either.
|
| 111 |
+
pub fn resolve_storage_roots<D: StorageRootDeriver<BaseState = ()>>(
|
| 112 |
+
certificates: &mut BTreeMap<[u8; 20], CanonicalAccountCertificate>,
|
| 113 |
+
state_table: &BTreeMap<CanonicalKey, ReducedVariant>,
|
| 114 |
+
deriver: &D,
|
| 115 |
+
) -> Result<(), DerivationError> {
|
| 116 |
+
let mut slots_by_address: BTreeMap<[u8; 20], BTreeMap<[u8; 32], [u8; 32]>> = BTreeMap::new();
|
| 117 |
+
|
| 118 |
+
for (key, variant) in state_table {
|
| 119 |
+
if let (CanonicalKey::Storage { address, slot }, ReducedVariant::Storage(t)) = (key, variant) {
|
| 120 |
+
slots_by_address.entry(*address).or_default().insert(*slot, *t.terminal());
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
for (address, cert) in certificates.iter_mut() {
|
| 125 |
+
let slots = slots_by_address.get(address).cloned().unwrap_or_default();
|
| 126 |
+
let root = deriver.derive(&(), &slots)?;
|
| 127 |
+
cert.storage_root = StorageRootState::Verified(root);
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
Ok(())
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
#[cfg(test)]
|
| 134 |
+
mod tests {
|
| 135 |
+
use super::*;
|
| 136 |
+
use crate::lifecycle::certificate::VerifiedGeneration;
|
| 137 |
+
use crate::lifecycle::keys::GenerationKey;
|
| 138 |
+
|
| 139 |
+
fn sample_cert(address: [u8; 20]) -> CanonicalAccountCertificate {
|
| 140 |
+
CanonicalAccountCertificate {
|
| 141 |
+
address,
|
| 142 |
+
generation: VerifiedGeneration {
|
| 143 |
+
key: GenerationKey { address, generation_id: 0 },
|
| 144 |
+
state_table_proof_root: [0u8; 32],
|
| 145 |
+
},
|
| 146 |
+
nonce: 0,
|
| 147 |
+
balance: [0u8; 32],
|
| 148 |
+
code_hash: [0u8; 32],
|
| 149 |
+
storage_root: StorageRootState::AwaitingDerivation,
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
#[test]
|
| 154 |
+
fn empty_storage_derives_deterministic_root() {
|
| 155 |
+
let deriver = SimpleStorageRootDeriver;
|
| 156 |
+
let empty = BTreeMap::new();
|
| 157 |
+
let root_a = deriver.derive(&(), &empty).unwrap();
|
| 158 |
+
let root_b = deriver.derive(&(), &empty).unwrap();
|
| 159 |
+
assert_eq!(root_a, root_b);
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
#[test]
|
| 163 |
+
fn nonempty_storage_differs_from_empty() {
|
| 164 |
+
let deriver = SimpleStorageRootDeriver;
|
| 165 |
+
let empty = BTreeMap::new();
|
| 166 |
+
let mut one_slot = BTreeMap::new();
|
| 167 |
+
one_slot.insert([1u8; 32], [2u8; 32]);
|
| 168 |
+
|
| 169 |
+
let empty_root = deriver.derive(&(), &empty).unwrap();
|
| 170 |
+
let nonempty_root = deriver.derive(&(), &one_slot).unwrap();
|
| 171 |
+
assert_ne!(empty_root, nonempty_root);
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
#[test]
|
| 175 |
+
fn different_slot_values_produce_different_roots() {
|
| 176 |
+
let deriver = SimpleStorageRootDeriver;
|
| 177 |
+
let mut slots_a = BTreeMap::new();
|
| 178 |
+
slots_a.insert([1u8; 32], [2u8; 32]);
|
| 179 |
+
let mut slots_b = BTreeMap::new();
|
| 180 |
+
slots_b.insert([1u8; 32], [3u8; 32]);
|
| 181 |
+
|
| 182 |
+
assert_ne!(deriver.derive(&(), &slots_a).unwrap(), deriver.derive(&(), &slots_b).unwrap());
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
#[test]
|
| 186 |
+
fn root_is_independent_of_insertion_order() {
|
| 187 |
+
let deriver = SimpleStorageRootDeriver;
|
| 188 |
+
let mut slots_a = BTreeMap::new();
|
| 189 |
+
slots_a.insert([1u8; 32], [0xAAu8; 32]);
|
| 190 |
+
slots_a.insert([2u8; 32], [0xBBu8; 32]);
|
| 191 |
+
|
| 192 |
+
let mut slots_b = BTreeMap::new();
|
| 193 |
+
slots_b.insert([2u8; 32], [0xBBu8; 32]);
|
| 194 |
+
slots_b.insert([1u8; 32], [0xAAu8; 32]);
|
| 195 |
+
|
| 196 |
+
// Both are BTreeMaps, so iteration order is identical regardless of
|
| 197 |
+
// insertion order -- this asserts that fact holds through derivation.
|
| 198 |
+
assert_eq!(deriver.derive(&(), &slots_a).unwrap(), deriver.derive(&(), &slots_b).unwrap());
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
#[test]
|
| 202 |
+
fn resolve_storage_roots_moves_every_certificate_off_awaiting_derivation() {
|
| 203 |
+
let addr_a = [0x01u8; 20];
|
| 204 |
+
let addr_b = [0x02u8; 20]; // has no storage entries at all
|
| 205 |
+
|
| 206 |
+
let mut certs = BTreeMap::new();
|
| 207 |
+
certs.insert(addr_a, sample_cert(addr_a));
|
| 208 |
+
certs.insert(addr_b, sample_cert(addr_b));
|
| 209 |
+
|
| 210 |
+
let mut state_table = BTreeMap::new();
|
| 211 |
+
state_table.insert(
|
| 212 |
+
CanonicalKey::Storage { address: addr_a, slot: [7u8; 32] },
|
| 213 |
+
ReducedVariant::Storage(crate::traits::ReducedTransition::new(
|
| 214 |
+
[0u8; 32],
|
| 215 |
+
[9u8; 32],
|
| 216 |
+
crate::ir::timeline::Provenance::new(),
|
| 217 |
+
)),
|
| 218 |
+
);
|
| 219 |
+
|
| 220 |
+
resolve_storage_roots(&mut certs, &state_table, &SimpleStorageRootDeriver).unwrap();
|
| 221 |
+
|
| 222 |
+
for cert in certs.values() {
|
| 223 |
+
assert!(matches!(cert.storage_root, StorageRootState::Verified(_)));
|
| 224 |
+
}
|
| 225 |
+
// addr_b had zero storage entries but still gets a real (empty) root,
|
| 226 |
+
// not a leftover AwaitingDerivation.
|
| 227 |
+
assert_ne!(certs[&addr_b].storage_root, StorageRootState::AwaitingDerivation);
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
#[test]
|
| 231 |
+
fn transient_storage_is_excluded_from_the_root() {
|
| 232 |
+
let addr = [0x03u8; 20];
|
| 233 |
+
let mut certs = BTreeMap::new();
|
| 234 |
+
certs.insert(addr, sample_cert(addr));
|
| 235 |
+
|
| 236 |
+
let mut state_table = BTreeMap::new();
|
| 237 |
+
state_table.insert(
|
| 238 |
+
CanonicalKey::Transient { address: addr, slot: [1u8; 32] },
|
| 239 |
+
ReducedVariant::Transient(crate::traits::ReducedTransition::new(
|
| 240 |
+
[0u8; 32],
|
| 241 |
+
[0xFFu8; 32],
|
| 242 |
+
crate::ir::timeline::Provenance::new(),
|
| 243 |
+
)),
|
| 244 |
+
);
|
| 245 |
+
|
| 246 |
+
resolve_storage_roots(&mut certs, &state_table, &SimpleStorageRootDeriver).unwrap();
|
| 247 |
+
|
| 248 |
+
// No CanonicalKey::Storage entries exist for this address (only
|
| 249 |
+
// Transient), so the root must equal the empty-storage root.
|
| 250 |
+
let empty_root = SimpleStorageRootDeriver.derive(&(), &BTreeMap::new()).unwrap();
|
| 251 |
+
match certs[&addr].storage_root {
|
| 252 |
+
StorageRootState::Verified(root) => assert_eq!(root, empty_root),
|
| 253 |
+
StorageRootState::AwaitingDerivation => panic!("expected Verified"),
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
}
|
runtime/ssz/src/certificate.rs
CHANGED
|
@@ -220,6 +220,67 @@ mod tests {
|
|
| 220 |
);
|
| 221 |
}
|
| 222 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
fn hex_encode(bytes: &[u8]) -> String {
|
| 224 |
bytes.iter().map(|b| format!("{:02x}", b)).collect()
|
| 225 |
}
|
|
|
|
| 220 |
);
|
| 221 |
}
|
| 222 |
|
| 223 |
+
/// The actual payoff of this phase: proves that a certificate produced by
|
| 224 |
+
/// the real pipeline, once its storage root is resolved, no longer hits
|
| 225 |
+
/// `UnresolvedStorageRoot` — closing the gap flagged when PR3 first shipped
|
| 226 |
+
/// (every real certificate hit that error, since nothing ever produced
|
| 227 |
+
/// `Verified` before this phase existed).
|
| 228 |
+
#[test]
|
| 229 |
+
fn full_vertical_slice_resolved_certificate_commits_successfully() {
|
| 230 |
+
use kaysentinel_builder::{SimpleStorageRootDeriver, resolve_storage_roots};
|
| 231 |
+
use kaysentinel_builder::lifecycle::certificate::{
|
| 232 |
+
AccountSnapshotSource, GenerationResolutionError, ResolvedAccountSnapshot, VerifiedGeneration,
|
| 233 |
+
build_canonical_certificates,
|
| 234 |
+
};
|
| 235 |
+
use kaysentinel_builder::lifecycle::keys::GenerationKey;
|
| 236 |
+
use kaysentinel_builder::ir::timeline::CanonicalKey;
|
| 237 |
+
use kaysentinel_builder::ir::reduced::ReducedVariant;
|
| 238 |
+
|
| 239 |
+
struct NullSnapshotSource;
|
| 240 |
+
impl AccountSnapshotSource for NullSnapshotSource {
|
| 241 |
+
fn resolve_identity_generation(&self, address: [u8; 20]) -> Result<VerifiedGeneration, GenerationResolutionError> {
|
| 242 |
+
Ok(VerifiedGeneration { key: GenerationKey { address, generation_id: 0 }, state_table_proof_root: [0u8; 32] })
|
| 243 |
+
}
|
| 244 |
+
fn recover_account_snapshot(&self, _address: [u8; 20]) -> Result<ResolvedAccountSnapshot, GenerationResolutionError> {
|
| 245 |
+
Ok(ResolvedAccountSnapshot { nonce: 0, balance: [0u8; 32], code_hash: [0u8; 32] })
|
| 246 |
+
}
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
let address = [0x55u8; 20];
|
| 250 |
+
let mut state_table = BTreeMap::new();
|
| 251 |
+
state_table.insert(
|
| 252 |
+
CanonicalKey::Storage { address, slot: [1u8; 32] },
|
| 253 |
+
ReducedVariant::Storage(kaysentinel_builder::ReducedTransition::new(
|
| 254 |
+
[0u8; 32],
|
| 255 |
+
[2u8; 32],
|
| 256 |
+
kaysentinel_builder::Provenance::new(),
|
| 257 |
+
)),
|
| 258 |
+
);
|
| 259 |
+
|
| 260 |
+
let generations = vec![kaysentinel_builder::lifecycle::canonical::CanonicalGeneration {
|
| 261 |
+
key: GenerationKey { address, generation_id: 0 },
|
| 262 |
+
begin: kaysentinel_builder::ir::timeline::TraceProvenance::default(),
|
| 263 |
+
end: None,
|
| 264 |
+
}];
|
| 265 |
+
|
| 266 |
+
// Before this phase: build_canonical_certificates alone always leaves
|
| 267 |
+
// storage_root == AwaitingDerivation, and every commit_root() call
|
| 268 |
+
// below would fail with UnresolvedStorageRoot.
|
| 269 |
+
let mut certs = build_canonical_certificates(&state_table, &generations, &NullSnapshotSource).unwrap();
|
| 270 |
+
assert!(certs.values().next().unwrap().commit_root().is_err());
|
| 271 |
+
|
| 272 |
+
// After: resolve_storage_roots closes the gap.
|
| 273 |
+
resolve_storage_roots(&mut certs, &state_table, &SimpleStorageRootDeriver).unwrap();
|
| 274 |
+
|
| 275 |
+
let cert = certs.get(&address).unwrap();
|
| 276 |
+
let encoded = cert.ssz_encode().unwrap();
|
| 277 |
+
let commitment = cert.commit_root().unwrap();
|
| 278 |
+
|
| 279 |
+
assert_eq!(encoded.len(), 180);
|
| 280 |
+
// Deterministic: re-deriving the same certificate produces the same commitment.
|
| 281 |
+
assert_eq!(commitment, cert.commit_root().unwrap());
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
fn hex_encode(bytes: &[u8]) -> String {
|
| 285 |
bytes.iter().map(|b| format!("{:02x}", b)).collect()
|
| 286 |
}
|
runtime/ssz/src/lib.rs
CHANGED
|
@@ -39,6 +39,9 @@ pub struct CanonicalEventSummary {
|
|
| 39 |
impl CanonicalEventSummary {
|
| 40 |
pub const ENCODED_LEN: usize = 8 + 8 + 20 + 32;
|
| 41 |
|
|
|
|
|
|
|
|
|
|
| 42 |
pub fn ssz_encode(&self) -> Vec<u8> {
|
| 43 |
let mut out = Vec::with_capacity(Self::ENCODED_LEN);
|
| 44 |
out.extend_from_slice(&self.block_timestamp.to_le_bytes());
|
|
@@ -49,6 +52,11 @@ impl CanonicalEventSummary {
|
|
| 49 |
}
|
| 50 |
}
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
#[derive(Debug, Clone, PartialEq, Eq)]
|
| 53 |
pub struct EpochStateSnapshot {
|
| 54 |
pub epoch_index: u64,
|
|
@@ -56,6 +64,8 @@ pub struct EpochStateSnapshot {
|
|
| 56 |
}
|
| 57 |
|
| 58 |
impl EpochStateSnapshot {
|
|
|
|
|
|
|
| 59 |
const FIXED_HEADER_LEN: usize = 8 + 4;
|
| 60 |
|
| 61 |
pub fn ssz_encode(&self) -> Result<Vec<u8>, SszError> {
|
|
@@ -78,6 +88,31 @@ impl EpochStateSnapshot {
|
|
| 78 |
}
|
| 79 |
}
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
pub fn chunkify(bytes: &[u8]) -> Vec<[u8; 32]> {
|
| 82 |
if bytes.is_empty() {
|
| 83 |
return vec![[0u8; 32]];
|
|
@@ -101,6 +136,8 @@ fn hash_pair(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
|
|
| 101 |
derive_commitment(Domain::SsrRoot, &canonical).to_bytes()
|
| 102 |
}
|
| 103 |
|
|
|
|
|
|
|
| 104 |
pub fn merkleize(chunks: &[[u8; 32]]) -> [u8; 32] {
|
| 105 |
let mut layer: Vec<[u8; 32]> = if chunks.is_empty() { vec![[0u8; 32]] } else { chunks.to_vec() };
|
| 106 |
|
|
@@ -122,6 +159,8 @@ pub fn merkleize(chunks: &[[u8; 32]]) -> [u8; 32] {
|
|
| 122 |
layer[0]
|
| 123 |
}
|
| 124 |
|
|
|
|
|
|
|
| 125 |
pub fn ssr_root(serialized_bytes: &[u8]) -> [u8; 32] {
|
| 126 |
merkleize(&chunkify(serialized_bytes))
|
| 127 |
}
|
|
@@ -146,6 +185,12 @@ mod tests {
|
|
| 146 |
assert_eq!(encoded.len(), 68);
|
| 147 |
}
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
#[test]
|
| 150 |
fn epoch_state_snapshot_matches_correctly_computed_vector() {
|
| 151 |
let snapshot = EpochStateSnapshot { epoch_index: 5, event_summaries: vec![sample_summary()] };
|
|
@@ -170,7 +215,7 @@ mod tests {
|
|
| 170 |
|
| 171 |
#[test]
|
| 172 |
fn chunkify_pads_final_chunk_with_zeros() {
|
| 173 |
-
let bytes = vec![1u8, 2, 3];
|
| 174 |
let chunks = chunkify(&bytes);
|
| 175 |
assert_eq!(chunks.len(), 1);
|
| 176 |
assert_eq!(&chunks[0][..3], &[1, 2, 3]);
|
|
@@ -179,7 +224,7 @@ mod tests {
|
|
| 179 |
|
| 180 |
#[test]
|
| 181 |
fn chunkify_exact_multiple_has_no_padding_chunk() {
|
| 182 |
-
let bytes = vec![7u8; 64];
|
| 183 |
let chunks = chunkify(&bytes);
|
| 184 |
assert_eq!(chunks.len(), 2);
|
| 185 |
}
|
|
@@ -199,11 +244,16 @@ mod tests {
|
|
| 199 |
|
| 200 |
#[test]
|
| 201 |
fn merkleize_single_chunk_equals_the_chunk_itself() {
|
|
|
|
|
|
|
| 202 |
let chunks = chunkify(&[9u8; 10]);
|
| 203 |
assert_eq!(chunks.len(), 1);
|
| 204 |
assert_eq!(merkleize(&chunks), chunks[0]);
|
| 205 |
}
|
| 206 |
|
|
|
|
|
|
|
|
|
|
| 207 |
#[test]
|
| 208 |
fn ssr_root_for_vec_ssr_rc1_001_is_pinned() {
|
| 209 |
let snapshot = EpochStateSnapshot { epoch_index: 5, event_summaries: vec![sample_summary()] };
|
|
|
|
| 39 |
impl CanonicalEventSummary {
|
| 40 |
pub const ENCODED_LEN: usize = 8 + 8 + 20 + 32;
|
| 41 |
|
| 42 |
+
/// Phase 3 (Write) for a fixed-size container: fields are simply concatenated
|
| 43 |
+
/// in declared order — there's no header/offset machinery needed since nothing
|
| 44 |
+
/// in this container is variable-length.
|
| 45 |
pub fn ssz_encode(&self) -> Vec<u8> {
|
| 46 |
let mut out = Vec::with_capacity(Self::ENCODED_LEN);
|
| 47 |
out.extend_from_slice(&self.block_timestamp.to_le_bytes());
|
|
|
|
| 52 |
}
|
| 53 |
}
|
| 54 |
|
| 55 |
+
/// `EpochStateSnapshot` — variable-size container: a fixed `epoch_index`, followed
|
| 56 |
+
/// by a 4-byte offset pointing at the `event_summaries` list payload. Since
|
| 57 |
+
/// `CanonicalEventSummary` is itself fixed-size, the list body is a plain
|
| 58 |
+
/// concatenation of encoded elements — SSZ only needs one offset for the whole
|
| 59 |
+
/// list field, not one per element.
|
| 60 |
#[derive(Debug, Clone, PartialEq, Eq)]
|
| 61 |
pub struct EpochStateSnapshot {
|
| 62 |
pub epoch_index: u64,
|
|
|
|
| 64 |
}
|
| 65 |
|
| 66 |
impl EpochStateSnapshot {
|
| 67 |
+
/// Bytes 0-7: epoch_index. Bytes 8-11: 4-byte offset to the variable payload
|
| 68 |
+
/// (always 12, since the fixed header is exactly 8 + 4 bytes).
|
| 69 |
const FIXED_HEADER_LEN: usize = 8 + 4;
|
| 70 |
|
| 71 |
pub fn ssz_encode(&self) -> Result<Vec<u8>, SszError> {
|
|
|
|
| 88 |
}
|
| 89 |
}
|
| 90 |
|
| 91 |
+
// ============================================================================
|
| 92 |
+
// Merkle Profile MP1
|
| 93 |
+
// ============================================================================
|
| 94 |
+
//
|
| 95 |
+
// Two things in the source spec were ambiguous or inconsistent with the standard
|
| 96 |
+
// SSZ convention, resolved here explicitly rather than guessed silently:
|
| 97 |
+
//
|
| 98 |
+
// 1. "If the number of leaf chunks is odd, the final leaf node is duplicated or
|
| 99 |
+
// handled strictly according to the deterministic tree packing standard" reads
|
| 100 |
+
// as offering two different, uncommitted-to alternatives. This implementation
|
| 101 |
+
// uses the real, standard SSZ approach: pad with zero chunks up to the next
|
| 102 |
+
// power of two, not duplication. Duplication (as used by some other Merkle
|
| 103 |
+
// schemes) creates second-preimage weaknesses that zero-padding to a fixed
|
| 104 |
+
// known width avoids.
|
| 105 |
+
// 2. The formula "H = BLAKE3(Left || Right)" is captioned "domain-separated" but
|
| 106 |
+
// the formula itself shows no domain prefix. To actually be domain-separated
|
| 107 |
+
// (and consistent with `kaysentinel-hash`'s own domain-separation invariant:
|
| 108 |
+
// HashInput := DomainBytes || CanonicalBytes), this implementation hashes
|
| 109 |
+
// `Domain::SsrRoot bytes || Left || Right` via `derive_commitment`, reusing
|
| 110 |
+
// `Domain::SsrRoot` since the hash crate's domain registry already documents
|
| 111 |
+
// it for exactly this purpose ("Serialization Record roots").
|
| 112 |
+
|
| 113 |
+
/// Splits a canonical byte stream into 32-byte chunks, right-padding the final
|
| 114 |
+
/// chunk with zero octets if needed. An empty input produces a single zero chunk
|
| 115 |
+
/// (there must always be at least one leaf to Merkleize).
|
| 116 |
pub fn chunkify(bytes: &[u8]) -> Vec<[u8; 32]> {
|
| 117 |
if bytes.is_empty() {
|
| 118 |
return vec![[0u8; 32]];
|
|
|
|
| 136 |
derive_commitment(Domain::SsrRoot, &canonical).to_bytes()
|
| 137 |
}
|
| 138 |
|
| 139 |
+
/// Builds the deterministic binary Merkle tree over a chunk sequence and returns
|
| 140 |
+
/// its root, per Merkle Profile MP1.
|
| 141 |
pub fn merkleize(chunks: &[[u8; 32]]) -> [u8; 32] {
|
| 142 |
let mut layer: Vec<[u8; 32]> = if chunks.is_empty() { vec![[0u8; 32]] } else { chunks.to_vec() };
|
| 143 |
|
|
|
|
| 159 |
layer[0]
|
| 160 |
}
|
| 161 |
|
| 162 |
+
/// Convenience: the full Layer 2 -> Layer 3 pipeline (chunkify + merkleize) applied
|
| 163 |
+
/// directly to an object's SSZ-encoded bytes.
|
| 164 |
pub fn ssr_root(serialized_bytes: &[u8]) -> [u8; 32] {
|
| 165 |
merkleize(&chunkify(serialized_bytes))
|
| 166 |
}
|
|
|
|
| 185 |
assert_eq!(encoded.len(), 68);
|
| 186 |
}
|
| 187 |
|
| 188 |
+
/// Regression pin for VEC-SSR-RC1-001 (single-element EpochStateSnapshot). The
|
| 189 |
+
/// source spec's own claimed hex for this vector was wrong — decoding its
|
| 190 |
+
/// `block_timestamp` field back out gives 171711, not the 171717 stated in the
|
| 191 |
+
/// same vector's input object. This pins the value this implementation
|
| 192 |
+
/// actually computes for the stated input, verified independently in Python
|
| 193 |
+
/// before being hardcoded here.
|
| 194 |
#[test]
|
| 195 |
fn epoch_state_snapshot_matches_correctly_computed_vector() {
|
| 196 |
let snapshot = EpochStateSnapshot { epoch_index: 5, event_summaries: vec![sample_summary()] };
|
|
|
|
| 215 |
|
| 216 |
#[test]
|
| 217 |
fn chunkify_pads_final_chunk_with_zeros() {
|
| 218 |
+
let bytes = vec![1u8, 2, 3]; // 3 bytes, one short chunk
|
| 219 |
let chunks = chunkify(&bytes);
|
| 220 |
assert_eq!(chunks.len(), 1);
|
| 221 |
assert_eq!(&chunks[0][..3], &[1, 2, 3]);
|
|
|
|
| 224 |
|
| 225 |
#[test]
|
| 226 |
fn chunkify_exact_multiple_has_no_padding_chunk() {
|
| 227 |
+
let bytes = vec![7u8; 64]; // exactly 2 chunks
|
| 228 |
let chunks = chunkify(&bytes);
|
| 229 |
assert_eq!(chunks.len(), 2);
|
| 230 |
}
|
|
|
|
| 244 |
|
| 245 |
#[test]
|
| 246 |
fn merkleize_single_chunk_equals_the_chunk_itself() {
|
| 247 |
+
// A single-leaf tree's root is just that leaf — no hashing needed, since
|
| 248 |
+
// there's nothing to combine it with.
|
| 249 |
let chunks = chunkify(&[9u8; 10]);
|
| 250 |
assert_eq!(chunks.len(), 1);
|
| 251 |
assert_eq!(merkleize(&chunks), chunks[0]);
|
| 252 |
}
|
| 253 |
|
| 254 |
+
/// Real, computed root for VEC-SSR-RC1-001's correctly-encoded bytes — printed
|
| 255 |
+
/// first via `cargo test -- --nocapture`, then pinned, exactly like the
|
| 256 |
+
/// hash crate's vectors. Not copied from the (incorrect) source doc.
|
| 257 |
#[test]
|
| 258 |
fn ssr_root_for_vec_ssr_rc1_001_is_pinned() {
|
| 259 |
let snapshot = EpochStateSnapshot { epoch_index: 5, event_summaries: vec![sample_summary()] };
|