Skip to main content

reth_snap_sync/bytecode/
store.rs

1//! Persists contract code ahead of the account range that commits to it.
2//!
3//! Code is content addressed, so a blob is authenticated by its hash alone and stays valid however
4//! far the pivot moves. Accounts sharing a code hash therefore need it downloaded and stored once.
5
6use crate::{SnapAttemptStore, SnapSyncError, SnapWrite};
7use alloy_primitives::{keccak256, Bytes, B256};
8use reth_db_api::{
9    tables,
10    transaction::{DbTx, DbTxMut},
11    RawKey, RawTable,
12};
13use reth_storage_api::{DBProvider, MetadataProvider, StateWriter};
14use revm::{bytecode::Bytecode, database::states::StateChangeset};
15
16/// Persistence for the code an attempt's accounts reference.
17///
18/// Blanket-implemented over the node's writers, so code joins the caller's transaction and commits
19/// with whatever else that transaction carries.
20pub trait SnapBytecodeStore {
21    /// Returns the first `limit` of `hashes` that are not stored yet, so the scan a request costs
22    /// is bounded by what it can ask for.
23    fn missing_code(
24        &self,
25        write: SnapWrite,
26        hashes: &[B256],
27        limit: usize,
28    ) -> Result<Vec<B256>, SnapSyncError>
29    where
30        Self: DBProvider;
31
32    /// Persists `codes`, each checked against the hash it was downloaded under, and returns how
33    /// many were written.
34    fn commit_bytecodes(
35        &self,
36        write: SnapWrite,
37        codes: Vec<(B256, Bytes)>,
38    ) -> Result<usize, SnapSyncError>
39    where
40        Self: StateWriter + DBProvider<Tx: DbTxMut>;
41}
42
43impl<T: MetadataProvider> SnapBytecodeStore for T {
44    fn missing_code(
45        &self,
46        write: SnapWrite,
47        hashes: &[B256],
48        limit: usize,
49    ) -> Result<Vec<B256>, SnapSyncError>
50    where
51        Self: DBProvider,
52    {
53        self.authorize_snap_write(write)?;
54        let mut missing = Vec::new();
55        for hash in hashes {
56            if missing.len() == limit {
57                break
58            }
59            // Only presence matters, so stored code is not decoded.
60            if self.tx_ref().get::<RawTable<tables::Bytecodes>>(RawKey::new(*hash))?.is_none() {
61                missing.push(*hash);
62            }
63        }
64        Ok(missing)
65    }
66
67    // Every check runs before the first write, so a refused response changes nothing.
68    fn commit_bytecodes(
69        &self,
70        write: SnapWrite,
71        codes: Vec<(B256, Bytes)>,
72    ) -> Result<usize, SnapSyncError>
73    where
74        Self: StateWriter + DBProvider<Tx: DbTxMut>,
75    {
76        self.authorize_snap_write(write)?;
77        let contracts = codes
78            .into_iter()
79            .map(|(hash, code)| {
80                let got = keccak256(&code);
81                if got != hash {
82                    return Err(SnapSyncError::CodeMismatch { expected: hash, got })
83                }
84                // Code deployed before EIP-3541 can carry the delegation prefix without being
85                // one, so authenticated bytes that do not parse as a delegation are legacy code.
86                let code = Bytecode::new_raw_checked(code.clone())
87                    .unwrap_or_else(|_| Bytecode::new_legacy(code));
88                Ok((hash, code))
89            })
90            .collect::<Result<Vec<_>, SnapSyncError>>()?;
91
92        let written = contracts.len();
93        self.write_state_changes(StateChangeset { contracts, ..Default::default() })?;
94        Ok(written)
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::test_utils::{
102        account, generation, hashed_factory_with_roots, key, state_root, verified_range,
103    };
104    use alloy_primitives::bytes;
105    use reth_provider::{
106        test_utils::MockNodeTypesWithDB, DatabaseProviderFactory, ProviderFactory,
107    };
108    use reth_trie_common::TrieAccount;
109
110    type Factory = ProviderFactory<MockNodeTypesWithDB>;
111
112    fn code(byte: u8) -> Bytes {
113        Bytes::from(vec![byte; 4])
114    }
115
116    // An account referencing `code`, distinguished by its nonce.
117    fn contract(nonce: u64, code: &Bytes) -> TrieAccount {
118        let mut contract = account(nonce);
119        contract.code_hash = keccak256(code);
120        contract
121    }
122
123    fn started(accounts: &[(B256, TrieAccount)]) -> (Factory, SnapWrite) {
124        let factory = hashed_factory_with_roots(&[state_root(accounts); 3]);
125        let provider = factory.database_provider_rw().unwrap();
126        let write = provider.start_snap_attempt(generation(1, state_root(accounts))).unwrap();
127        provider.commit().unwrap();
128        (factory, write)
129    }
130
131    fn is_stored(provider: &impl DBProvider, code: &Bytes) -> bool {
132        provider.tx_ref().get::<tables::Bytecodes>(keccak256(code)).unwrap().is_some()
133    }
134
135    #[test]
136    fn one_blob_answers_every_account_sharing_its_hash() {
137        let shared = code(1);
138        let accounts = vec![
139            (key(1), contract(1, &shared)),
140            (key(2), account(2)),
141            (key(3), contract(3, &shared)),
142            (key(4), contract(4, &code(2))),
143        ];
144        let (factory, write) = started(&accounts);
145        let provider = factory.database_provider_rw().unwrap();
146        let referenced =
147            verified_range(&accounts, 0..accounts.len(), B256::ZERO, &[]).code_hashes();
148
149        let missing = provider.missing_code(write, &referenced, usize::MAX).unwrap();
150
151        assert_eq!(missing, [keccak256(&shared), keccak256(code(2))]);
152        assert_eq!(
153            provider.commit_bytecodes(write, vec![(missing[0], shared.clone())]).unwrap(),
154            1
155        );
156        // The shared blob answers both accounts, leaving only the other contract's code.
157        assert_eq!(
158            provider.missing_code(write, &referenced, usize::MAX).unwrap(),
159            [keccak256(code(2))]
160        );
161        assert!(is_stored(&provider, &shared));
162    }
163
164    #[test]
165    fn code_that_does_not_hash_to_its_requested_hash_is_refused() {
166        let wanted = code(1);
167        let accounts = vec![(key(1), contract(1, &wanted))];
168        let (factory, write) = started(&accounts);
169        let provider = factory.database_provider_rw().unwrap();
170        let hash = keccak256(&wanted);
171
172        let refused = provider.commit_bytecodes(write, vec![(hash, code(2))]);
173
174        assert!(
175            matches!(refused, Err(SnapSyncError::CodeMismatch { expected, .. }) if expected == hash)
176        );
177        assert_eq!(provider.missing_code(write, &[hash], usize::MAX).unwrap(), [hash]);
178        assert!(!is_stored(&provider, &wanted));
179    }
180
181    // A delegation is exactly 23 bytes, but EIP-3541 only bars the prefix from London onwards, so
182    // an older account can reference shorter code that starts with it.
183    #[test]
184    fn delegation_shaped_code_that_predates_eip_3541_is_kept_as_legacy_code() {
185        let historical = bytes!("ef0100");
186        let accounts = vec![(key(1), contract(1, &historical))];
187        let (factory, write) = started(&accounts);
188        let provider = factory.database_provider_rw().unwrap();
189
190        let hash = keccak256(&historical);
191        assert_eq!(provider.commit_bytecodes(write, vec![(hash, historical.clone())]).unwrap(), 1);
192
193        let stored = provider.tx_ref().get::<tables::Bytecodes>(hash).unwrap().unwrap();
194        assert_eq!(stored.original_bytes(), historical);
195        assert!(provider.missing_code(write, &[hash], usize::MAX).unwrap().is_empty());
196    }
197
198    #[test]
199    fn code_is_refused_once_the_attempt_no_longer_owns_the_state() {
200        let wanted = code(1);
201        let accounts = vec![(key(1), contract(1, &wanted))];
202        let (factory, write) = started(&accounts);
203        let provider = factory.database_provider_rw().unwrap();
204        provider.advance_snap_pivot(write, generation(2, state_root(&accounts))).unwrap();
205
206        let refused = provider.commit_bytecodes(write, vec![(keccak256(&wanted), wanted.clone())]);
207
208        assert!(matches!(refused, Err(SnapSyncError::StaleWrite { .. })));
209        assert!(matches!(
210            provider.missing_code(write, &[keccak256(&wanted)], usize::MAX),
211            Err(SnapSyncError::StaleWrite { .. })
212        ));
213        assert!(!is_stored(&provider, &wanted));
214    }
215}