kona_executor/db/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
//! This module contains an implementation of an in-memory Trie DB for [revm], that allows for
//! incremental updates through fetching node preimages on the fly during execution.
use crate::errors::{TrieDBError, TrieDBResult};
use alloc::{string::ToString, vec::Vec};
use alloy_consensus::{Header, Sealed, EMPTY_ROOT_HASH};
use alloy_primitives::{keccak256, Address, B256, U256};
use alloy_rlp::{Decodable, Encodable};
use kona_mpt::{Nibbles, TrieHinter, TrieNode, TrieNodeError};
use revm::{
db::{states::StorageSlot, BundleState},
primitives::{AccountInfo, Bytecode, HashMap, BLOCK_HASH_HISTORY},
Database,
};
mod account;
pub use account::TrieAccount;
mod traits;
pub use traits::{NoopTrieDBProvider, TrieDBProvider};
/// A Trie DB that caches open state in-memory.
///
/// When accounts that don't already exist within the cached [TrieNode] are queried, the database
/// fetches the preimages of the trie nodes on the path to the account using the `PreimageFetcher`
/// (`F` generic). This allows for data to be fetched in a verifiable manner given an initial
/// trusted state root as it is needed during execution.
///
/// The [TrieDB] is intended to be wrapped by a [State], which is then used by the [revm::Evm] to
/// capture state transitions during block execution.
///
/// **Behavior**:
/// - When an account is queried and the trie path has not already been opened by [Self::basic], we
/// fall through to the `PreimageFetcher` to fetch the preimages of the trie nodes on the path to
/// the account. After it has been fetched, the path will be cached until the next call to
/// [Self::state_root].
/// - When querying for the code hash of an account, the `CodeHashFetcher` is consulted to fetch the
/// code hash of the account.
/// - When a [BundleState] changeset is committed to the parent [State] database, the changes are
/// first applied to the [State]'s cache, then the trie hash is recomputed with
/// [Self::state_root].
/// - When the block hash of a block number is needed via [Self::block_hash], the
/// `HeaderByHashFetcher` is consulted to walk back to the desired block number by revealing the
/// parent hash of block headers until the desired block number is reached, up to a maximum of
/// [BLOCK_HASH_HISTORY] blocks back relative to the current parent block hash.
///
/// **Example Construction**:
/// ```rust
/// use alloy_consensus::{Header, Sealable};
/// use alloy_primitives::{Bytes, B256};
/// use anyhow::Result;
/// use kona_executor::{NoopTrieDBProvider, TrieDB};
/// use kona_mpt::NoopTrieHinter;
/// use revm::{db::states::bundle_state::BundleRetention, EvmBuilder, StateBuilder};
///
/// let mock_starting_root = B256::default();
/// let mock_parent_block_header = Header::default();
///
/// let trie_db = TrieDB::new(
/// mock_starting_root,
/// mock_parent_block_header.seal_slow(),
/// NoopTrieDBProvider,
/// NoopTrieHinter,
/// );
/// let mut state = StateBuilder::new_with_database(trie_db).with_bundle_update().build();
/// let evm = EvmBuilder::default().with_db(&mut state).build();
///
/// // Execute your block's transactions...
///
/// // Drop the EVM prior to merging the state transitions.
/// drop(evm);
///
/// state.merge_transitions(BundleRetention::Reverts);
/// let bundle = state.take_bundle();
/// let state_root = state.database.state_root(&bundle).expect("Failed to compute state root");
/// ```
///
/// [State]: revm::State
#[derive(Debug, Clone)]
pub struct TrieDB<F, H>
where
F: TrieDBProvider,
H: TrieHinter,
{
/// The [TrieNode] representation of the root node.
root_node: TrieNode,
/// Storage roots of accounts within the trie.
storage_roots: HashMap<Address, TrieNode>,
/// The parent block hash of the current block.
parent_block_header: Sealed<Header>,
/// The [TrieDBProvider]
fetcher: F,
/// The [TrieHinter]
hinter: H,
}
impl<F, H> TrieDB<F, H>
where
F: TrieDBProvider,
H: TrieHinter,
{
/// Creates a new [TrieDB] with the given root node.
pub fn new(root: B256, parent_block_header: Sealed<Header>, fetcher: F, hinter: H) -> Self {
Self {
root_node: TrieNode::new_blinded(root),
storage_roots: Default::default(),
parent_block_header,
fetcher,
hinter,
}
}
/// Consumes `Self` and takes the the current state root of the trie DB.
pub fn take_root_node(self) -> TrieNode {
self.root_node
}
/// Returns a shared reference to the root [TrieNode] of the trie DB.
pub const fn root(&self) -> &TrieNode {
&self.root_node
}
/// Returns the mapping of [Address]es to storage roots.
pub const fn storage_roots(&self) -> &HashMap<Address, TrieNode> {
&self.storage_roots
}
/// Returns a reference to the current parent block header of the trie DB.
pub const fn parent_block_header(&self) -> &Sealed<Header> {
&self.parent_block_header
}
/// Sets the parent block header of the trie DB. Should be called after a block has been
/// executed and the Header has been created.
///
/// ## Takes
/// - `parent_block_header`: The parent block header of the current block.
pub fn set_parent_block_header(&mut self, parent_block_header: Sealed<Header>) {
self.parent_block_header = parent_block_header;
}
/// Applies a [BundleState] changeset to the [TrieNode] and recomputes the state root hash.
///
/// ## Takes
/// - `bundle`: The [BundleState] changeset to apply to the trie DB.
///
/// ## Returns
/// - `Ok(B256)`: The new state root hash of the trie DB.
/// - `Err(_)`: If the state root hash could not be computed.
pub fn state_root(&mut self, bundle: &BundleState) -> TrieDBResult<B256> {
debug!(target: "client_executor", "Recomputing state root");
// Update the accounts in the trie with the changeset.
self.update_accounts(bundle)?;
// Recompute the root hash of the trie.
self.root_node.blind();
debug!(
target: "client_executor",
"Recomputed state root: {commitment:?}",
commitment = self.root_node.blinded_commitment()
);
// Extract the new state root from the root node.
self.root_node.blinded_commitment().ok_or(TrieDBError::RootNotBlinded)
}
/// Fetches the [TrieAccount] of an account from the trie DB.
///
/// ## Takes
/// - `address`: The address of the account.
///
/// ## Returns
/// - `Ok(Some(TrieAccount))`: The [TrieAccount] of the account.
/// - `Ok(None)`: If the account does not exist in the trie.
/// - `Err(_)`: If the account could not be fetched.
pub fn get_trie_account(&mut self, address: &Address) -> TrieDBResult<Option<TrieAccount>> {
// Send a hint to the host to fetch the account proof.
self.hinter
.hint_account_proof(*address, self.parent_block_header.number)
.map_err(|e| TrieDBError::Provider(e.to_string()))?;
// Fetch the account from the trie.
let hashed_address_nibbles = Nibbles::unpack(keccak256(address.as_slice()));
let Some(trie_account_rlp) = self.root_node.open(&hashed_address_nibbles, &self.fetcher)?
else {
return Ok(None);
};
// Decode the trie account from the RLP bytes.
TrieAccount::decode(&mut trie_account_rlp.as_ref())
.map_err(TrieNodeError::RLPError)
.map_err(Into::into)
.map(Some)
}
/// Modifies the accounts in the storage trie with the given [BundleState] changeset.
///
/// ## Takes
/// - `bundle`: The [BundleState] changeset to apply to the trie DB.
///
/// ## Returns
/// - `Ok(())` if the accounts were successfully updated.
/// - `Err(_)` if the accounts could not be updated.
fn update_accounts(&mut self, bundle: &BundleState) -> TrieDBResult<()> {
for (address, bundle_account) in bundle.state() {
if bundle_account.status.is_not_modified() {
continue;
}
// Compute the path to the account in the trie.
let account_path = Nibbles::unpack(keccak256(address.as_slice()));
// If the account was destroyed, delete it from the trie.
if bundle_account.was_destroyed() {
self.root_node.delete(&account_path, &self.fetcher, &self.hinter)?;
self.storage_roots.remove(address);
continue;
}
let account_info =
bundle_account.account_info().ok_or(TrieDBError::MissingAccountInfo)?;
let mut trie_account = TrieAccount {
balance: account_info.balance,
nonce: account_info.nonce,
code_hash: account_info.code_hash,
..Default::default()
};
// Update the account's storage root
let acc_storage_root = self
.storage_roots
.entry(*address)
.or_insert_with(|| TrieNode::new_blinded(EMPTY_ROOT_HASH));
bundle_account.storage.iter().try_for_each(|(index, value)| {
Self::change_storage(acc_storage_root, *index, value, &self.fetcher, &self.hinter)
})?;
// Recompute the account storage root.
acc_storage_root.blind();
let commitment =
acc_storage_root.blinded_commitment().ok_or(TrieDBError::RootNotBlinded)?;
trie_account.storage_root = commitment;
// RLP encode the trie account for insertion.
let mut account_buf = Vec::with_capacity(trie_account.length());
trie_account.encode(&mut account_buf);
// Insert or update the account in the trie.
self.root_node.insert(&account_path, account_buf.into(), &self.fetcher)?;
}
Ok(())
}
/// Modifies a storage slot of an account in the Merkle Patricia Trie.
///
/// ## Takes
/// - `address`: The address of the account.
/// - `index`: The index of the storage slot.
/// - `value`: The new value of the storage slot.
///
/// ## Returns
/// - `Ok(())` if the storage slot was successfully modified.
/// - `Err(_)` if the storage slot could not be modified.
fn change_storage(
storage_root: &mut TrieNode,
index: U256,
value: &StorageSlot,
fetcher: &F,
hinter: &H,
) -> TrieDBResult<()> {
if !value.is_changed() {
return Ok(());
}
// RLP encode the storage slot value.
let mut rlp_buf = Vec::with_capacity(value.present_value.length());
value.present_value.encode(&mut rlp_buf);
// Insert or update the storage slot in the trie.
let hashed_slot_key = Nibbles::unpack(keccak256(index.to_be_bytes::<32>().as_slice()));
if value.present_value.is_zero() {
// If the storage slot is being set to zero, prune it from the trie.
storage_root.delete(&hashed_slot_key, fetcher, hinter)?;
} else {
// Otherwise, update the storage slot.
storage_root.insert(&hashed_slot_key, rlp_buf.into(), fetcher)?;
}
Ok(())
}
}
impl<F, H> Database for TrieDB<F, H>
where
F: TrieDBProvider,
H: TrieHinter,
{
type Error = TrieDBError;
fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
// Fetch the account from the trie.
let Some(trie_account) = self.get_trie_account(&address)? else {
// If the account does not exist in the trie, return `Ok(None)`.
return Ok(None);
};
// Insert the account's storage root into the cache.
self.storage_roots.insert(address, TrieNode::new_blinded(trie_account.storage_root));
// Return a partial DB account. The storage and code are not loaded out-right, and are
// loaded optimistically in the `Database` + `DatabaseRef` trait implementations.
Ok(Some(AccountInfo {
balance: trie_account.balance,
nonce: trie_account.nonce,
code_hash: trie_account.code_hash,
code: None,
}))
}
fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
self.fetcher
.bytecode_by_hash(code_hash)
.map(Bytecode::new_raw)
.map_err(|e| TrieDBError::Provider(e.to_string()))
}
fn storage(&mut self, address: Address, index: U256) -> Result<U256, Self::Error> {
// Send a hint to the host to fetch the storage proof.
self.hinter
.hint_storage_proof(address, index, self.parent_block_header.number)
.map_err(|e| TrieDBError::Provider(e.to_string()))?;
// Fetch the account's storage root from the cache. If storage is being accessed, the
// account should have been loaded into the cache by the `basic` method. If the account was
// non-existing, the storage root will not be present.
match self.storage_roots.get_mut(&address) {
None => {
// If the storage root for the account does not exist, return zero.
Ok(U256::ZERO)
}
Some(storage_root) => {
// Fetch the storage slot from the trie.
let hashed_slot_key = keccak256(index.to_be_bytes::<32>().as_slice());
match storage_root.open(&Nibbles::unpack(hashed_slot_key), &self.fetcher)? {
Some(slot_value) => {
// Decode the storage slot value.
let int_slot = U256::decode(&mut slot_value.as_ref())
.map_err(TrieNodeError::RLPError)?;
Ok(int_slot)
}
None => {
// If the storage slot does not exist, return zero.
Ok(U256::ZERO)
}
}
}
}
}
fn block_hash(&mut self, block_number: u64) -> Result<B256, Self::Error> {
// Copy the current header
let mut header = self.parent_block_header.inner().clone();
// Check if the block number is in range. If not, we can fail early.
if block_number > header.number ||
header.number.saturating_sub(block_number) > BLOCK_HASH_HISTORY
{
return Ok(B256::default());
}
// Walk back the block headers to the desired block number.
while header.number > block_number {
header = self
.fetcher
.header_by_hash(header.parent_hash)
.map_err(|e| TrieDBError::Provider(e.to_string()))?;
}
Ok(header.hash_slow())
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloy_consensus::Sealable;
use alloy_primitives::b256;
use kona_mpt::NoopTrieHinter;
fn new_test_db() -> TrieDB<NoopTrieDBProvider, NoopTrieHinter> {
TrieDB::new(
B256::default(),
Header::default().seal_slow(),
NoopTrieDBProvider,
NoopTrieHinter,
)
}
#[test]
fn test_trie_db_take_root_node() {
let db = new_test_db();
let root_node = db.take_root_node();
assert_eq!(root_node.blinded_commitment(), Some(B256::default()));
}
#[test]
fn test_trie_db_root_node_ref() {
let db = new_test_db();
let root_node = db.root();
assert_eq!(root_node.blinded_commitment(), Some(B256::default()));
}
#[test]
fn test_trie_db_storage_roots() {
let db = new_test_db();
let storage_roots = db.storage_roots();
assert!(storage_roots.is_empty());
}
#[test]
fn test_block_hash_above_range() {
let mut db = new_test_db();
db.parent_block_header = Header { number: 10, ..Default::default() }.seal_slow();
let block_number = 11;
let block_hash = db.block_hash(block_number).unwrap();
assert_eq!(block_hash, B256::default());
}
#[test]
fn test_block_hash_below_range() {
let mut db = new_test_db();
db.parent_block_header =
Header { number: BLOCK_HASH_HISTORY + 10, ..Default::default() }.seal_slow();
let block_number = 0;
let block_hash = db.block_hash(block_number).unwrap();
assert_eq!(block_hash, B256::default());
}
#[test]
fn test_block_hash_provider_missing_hash() {
let mut db = new_test_db();
db.parent_block_header = Header { number: 10, ..Default::default() }.seal_slow();
let block_number = 5;
let block_hash = db.block_hash(block_number).unwrap();
assert_eq!(
block_hash,
b256!("78dec18c6d7da925bbe773c315653cdc70f6444ed6c1de9ac30bdb36cff74c3b")
);
}
}