ethrex_common/seeded_hash.rs
1//! A seeded hasher for maps whose keys a block can choose.
2//!
3//! rustc-hash 2.x is unseeded and hashes a key of 17 to 32 bytes as
4//! `multiply_mix(SEED2 ^ word(bytes[len - 16..len - 8]), ..) ^ len`, where `SEED2` is a
5//! public constant and `multiply_mix(0, _) == 0`. Keys carrying `SEED2` in that word all hash
6//! to `len` and share one hashbrown bucket, so storage slots, touched addresses or calldata
7//! crafted that way turn every lookup into a scan, at flat opcode gas. [`SeededState`] hashes
8//! with foldhash instead, seeded per process and per map, with one twist: a 32- or 20-byte
9//! key (`H256`, `U256`, `Address`) is fed to foldhash as words rather than as a byte string.
10//! foldhash's byte path spends four folded multiplies on 32 bytes where its integer path
11//! spends two, which shows on storage-heavy code; the word path resists the same attacks,
12//! since every multiply still mixes in a seed the key does not know.
13//!
14//! It is foldhash's quality variant, which ends with one more folded multiply than the fast
15//! one. hashbrown picks a key's bucket from the low bits of its hash, and with the fast
16//! variant those came out of a single multiply: for some seeds, keys that differ only in a
17//! short word, such as addresses differing in their last four bytes, crowded a few buckets.
18//!
19//! A keccak output is no safer as a key than the preimage behind it. Whoever picks the
20//! preimage (a CREATE2 salt, the trailing bytes of deployed code) can grind it until the hash
21//! lands in a chosen bucket, at about one keccak per bucket of the table for each key. What
22//! keeps such a map on FxHash safe is the gas a block pays for each key it adds or looks up.
23//! Code hashes are seeded: a contract deployed once can be called again for 100 gas, and every
24//! call looks its code up by hash. Created and self-destructed accounts stay on FxHash, since
25//! each entry costs the block a CREATE or a SELFDESTRUCT.
26//!
27//! A seeded map iterates in a different order in every process and every map. Whatever carries
28//! that order out of the process (a list another program replays, a report, the offender an
29//! error names) has to be sorted, as the prover's host and the guest sort a block's account
30//! updates before applying them to the state trie.
31//!
32//! Inside a zkVM guest foldhash finds no clock and no address randomization, so its seeds
33//! follow from the guest program and its input. Crafting keys against a guest then takes
34//! replaying it up to the map under attack, which is harder than against FxHash but possible.
35
36use std::hash::{BuildHasher, Hasher};
37
38/// A `std::collections::HashMap` hashed with [`SeededState`].
39pub type SeededHashMap<K, V> = std::collections::HashMap<K, V, SeededState>;
40/// A `std::collections::HashSet` hashed with [`SeededState`].
41pub type SeededHashSet<K> = std::collections::HashSet<K, SeededState>;
42
43/// A foldhash quality `RandomState`, seeded per process and per map, whose hasher takes
44/// fixed-size keys through foldhash's integer path. See the module docs.
45#[derive(Clone, Debug, Default)]
46pub struct SeededState(foldhash::quality::RandomState);
47
48impl BuildHasher for SeededState {
49 type Hasher = SeededHasher;
50
51 #[inline]
52 fn build_hasher(&self) -> SeededHasher {
53 SeededHasher(self.0.build_hasher())
54 }
55}
56
57/// The hasher built by [`SeededState`].
58pub struct SeededHasher(foldhash::quality::FoldHasher<'static>);
59
60impl Hasher for SeededHasher {
61 /// `H256` and `Address` hash as one 32- or 20-byte write, and `U256` as a length prefix
62 /// plus one 32-byte write. Those go through `write_u128`, which folds 16 bytes per
63 /// multiply; every other length takes foldhash's byte path.
64 #[inline]
65 fn write(&mut self, bytes: &[u8]) {
66 if let Some((lo, rest)) = bytes.split_first_chunk::<16>() {
67 if let Ok(hi) = <[u8; 16]>::try_from(rest) {
68 self.0.write_u128(u128::from_ne_bytes(*lo));
69 self.0.write_u128(u128::from_ne_bytes(hi));
70 return;
71 }
72 if let Ok(hi) = <[u8; 4]>::try_from(rest) {
73 self.0.write_u128(u128::from_ne_bytes(*lo));
74 self.0.write_u32(u32::from_ne_bytes(hi));
75 return;
76 }
77 }
78 self.0.write(bytes);
79 }
80
81 #[inline]
82 fn write_u8(&mut self, i: u8) {
83 self.0.write_u8(i);
84 }
85
86 #[inline]
87 fn write_u16(&mut self, i: u16) {
88 self.0.write_u16(i);
89 }
90
91 #[inline]
92 fn write_u32(&mut self, i: u32) {
93 self.0.write_u32(i);
94 }
95
96 #[inline]
97 fn write_u64(&mut self, i: u64) {
98 self.0.write_u64(i);
99 }
100
101 #[inline]
102 fn write_u128(&mut self, i: u128) {
103 self.0.write_u128(i);
104 }
105
106 #[inline]
107 fn write_usize(&mut self, i: usize) {
108 self.0.write_usize(i);
109 }
110
111 #[inline]
112 fn finish(&self) -> u64 {
113 self.0.finish()
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120 use crate::{Address, H256, U256};
121 use std::hash::Hash;
122
123 /// Keys per test, hashed into as many buckets.
124 const KEYS: u64 = 4096;
125 /// Hashing 4096 keys uniformly into 4096 buckets fills the fullest one to about 6; a
126 /// hasher that ignores the part of the key that varies puts them all in one.
127 const MAX_BUCKET_LOAD: usize = 16;
128 /// The word FxHash 2.x XORs into a 17- to 32-byte key right before a multiply, which
129 /// makes keys carrying it hash alike there. Kept as a hostile key shape; nothing here
130 /// relies on rustc-hash still behaving that way.
131 const ZEROING_WORD: u64 = 0x13198a2e03707344;
132
133 /// The load of the fullest bucket once `keys` are spread over `KEYS` buckets by the low
134 /// bits of their hash, as hashbrown picks a key's first bucket.
135 fn fullest_bucket<K: Hash>(keys: impl Iterator<Item = K>) -> usize {
136 let state = SeededState::default();
137 let mut loads = vec![0usize; KEYS as usize];
138 for key in keys {
139 let bucket = state.hash_one(key) % KEYS;
140 if let Some(load) = loads.get_mut(bucket as usize) {
141 *load += 1;
142 }
143 }
144 loads.into_iter().max().unwrap_or_default()
145 }
146
147 /// An address whose bytes `at..at + 8` hold `word` and whose bytes 4..12 hold the zeroing
148 /// word, so only one region of the key varies.
149 fn address_with(at: usize, word: u64) -> Address {
150 let mut bytes = [0u8; 20];
151 for (byte, value) in bytes.iter_mut().skip(4).zip(ZEROING_WORD.to_le_bytes()) {
152 *byte = value;
153 }
154 for (byte, value) in bytes.iter_mut().skip(at).zip(word.to_le_bytes()) {
155 *byte = value;
156 }
157 Address::from(bytes)
158 }
159
160 #[test]
161 fn spreads_h256_keys_that_differ_in_either_half() {
162 let low = (0..KEYS).map(|i| H256::from(U256([i, 0, ZEROING_WORD, 0]).to_little_endian()));
163 assert!(fullest_bucket(low) <= MAX_BUCKET_LOAD);
164 let high = (0..KEYS).map(|i| H256::from(U256([0, 0, ZEROING_WORD, i]).to_little_endian()));
165 assert!(fullest_bucket(high) <= MAX_BUCKET_LOAD);
166 }
167
168 #[test]
169 fn spreads_u256_keys_that_differ_in_either_half() {
170 let low = (0..KEYS).map(|i| U256([i, 0, ZEROING_WORD, 0]));
171 assert!(fullest_bucket(low) <= MAX_BUCKET_LOAD);
172 let high = (0..KEYS).map(|i| U256([0, 0, ZEROING_WORD, i]));
173 assert!(fullest_bucket(high) <= MAX_BUCKET_LOAD);
174 }
175
176 #[test]
177 fn spreads_addresses_that_differ_in_either_part() {
178 // Bytes 12..20 straddle the 16-byte word and the 4-byte tail; 16..20 is the tail alone.
179 assert!(fullest_bucket((0..KEYS).map(|i| address_with(12, i))) <= MAX_BUCKET_LOAD);
180 assert!(fullest_bucket((0..KEYS).map(|i| address_with(16, i))) <= MAX_BUCKET_LOAD);
181 }
182
183 #[test]
184 fn spreads_byte_strings_on_both_paths() {
185 // 32-byte calldata takes the word path; 40 bytes takes foldhash's byte path.
186 let short = (0..KEYS).map(|i| U256([i, 0, ZEROING_WORD, 0]).to_little_endian().to_vec());
187 assert!(fullest_bucket(short) <= MAX_BUCKET_LOAD);
188 let long = (0..KEYS).map(|i| {
189 let mut bytes = vec![0u8; 40];
190 for (byte, value) in bytes.iter_mut().skip(32).zip(i.to_le_bytes()) {
191 *byte = value;
192 }
193 bytes
194 });
195 assert!(fullest_bucket(long) <= MAX_BUCKET_LOAD);
196 }
197
198 #[test]
199 fn two_maps_hash_the_same_key_apart() {
200 // Each map draws its own seed, so a key crafted against one map's buckets says
201 // nothing about another's.
202 let key = H256::repeat_byte(0x5a);
203 assert_ne!(
204 SeededState::default().hash_one(key),
205 SeededState::default().hash_one(key)
206 );
207 }
208
209 #[test]
210 fn equal_keys_hash_equal_on_both_paths() {
211 let state = SeededState::default();
212 let key = H256::from_low_u64_be(7);
213 assert_eq!(state.hash_one(key), state.hash_one(key));
214 let bytes = vec![1u8; 40];
215 assert_eq!(state.hash_one(&bytes), state.hash_one(&bytes));
216 }
217}