Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
The original diagrams are retained and may contain Japanese labels.
Blocks and the Four Core Tries
Changing a number stored in a contract from 42 to 43 also changes the hash representing the resulting state. A hash is a fixed-length value computed from data; a root hash commits to the contents of an entire tree.
Ethereum uses a tree structure that locates a value by following a path from the beginning of its key, linking balances and storage values to the tree's root hash. This structure is called a trie. All accounts, each account's storage, transactions, and execution results correspond to trees with distinct roles.

Suppose an application wants to read a contract's x and verify that its value is 42.
To verify that 42 belongs to the state of a specific block rather than merely accepting a node's response, the application needs a path linking the account to its storage value.
Distinguishing the logical tree that commits values to a root from the node's physical storage scheme helps determine what data is required for retrieval and verification.
Accounts and Individual Storage
The state trie represents the state of all accounts, mapping keys derived from addresses to account records.
Alongside an account counter and ETH balance, each record contains two hashes referring to storage and code.
Instead of listing every contract variable in this record, Ethereum uses storageRoot to refer to the account's own storage trie.
This two-level structure ultimately reflects changes to any account's storage in a single stateRoot.

The state trie represents the state of all accounts after a block has been executed.
The storage trie is specific to each account, so slot 0 of different contracts does not occupy the same location in one shared storage trie.
Even for an identical slot number, the storageRoot being traversed depends on which account was retrieved first.
The Four Account Fields
The nonce is an account counter used for transaction sequencing and contract creation.
The balance is an integer representing the ETH balance in wei; ERC-20 balances usually reside in the token contract's storage.
The storageRoot is the root of the storage trie, and codeHash is the hash of the code.
These fields are encoded into the account value in this order using Recursive Length Prefix (RLP), a common encoding for byte strings and lists that includes their lengths.
RLP([nonce, balance, storageRoot, codeHash])The Keccak-256 hash of the 20-byte address is the state trie key. The RLP-encoded sequence of the four account fields is the value corresponding to that key. The terminal leaf node containing this account value is itself RLP-encoded as a node with a path and value.
| Data | Account field |
|---|---|
| Account counter | nonce |
| ETH balance | balance |
| Persistent storage values | storageRoot |
| Code | codeHash |
Code delegation specifies that code at another address should execute in the context of one's own account.
The nonce is used not only to sequence outgoing transactions but also in contract creation and code-delegation authorizations. It is therefore not always simply the number of transactions sent by an account.
RLP encodes integers without unnecessary leading zeros, and empty storage and code have predefined empty hashes.
Ordinary EOAs and Code Delegation
An externally owned account (EOA) submits transactions signed using a private key.
An ordinary EOA without code delegation starts with empty code and storage.
However, EOAs can also configure code delegation, so the designation EOA alone does not establish that codeHash or storageRoot is empty.
When investigating the storage structure, inspect the four account fields at the relevant block.
Transactions and Execution Results
The transaction trie and receipts trie both use the position within a block as their key. A transaction and receipt at the same position correspond to each other: one contains the input to be executed, and the other the execution result, including success or failure and logs. The RLP-encoded key for position 0 is 0x80, and for position 1 it is 0x01. Nodes support lookup by transaction ID because they maintain a separate search index.

The transaction and receipts tries are constructed from the lists for that block. Their key derivation differs from that of the state trie, which derives keys by hashing addresses with Keccak-256.
| Trie | Key | Value |
|---|---|---|
| State trie | keccak256(address) |
RLP-encoded account |
| Storage trie | keccak256(32-byte storage slot) | RLP encoding of the minimal integer representation |
| Transaction trie | RLP(block position) | Consensus transaction bytes |
| Receipts trie | RLP(block position) | Consensus receipt bytes |
Replacing position 0 with the single integer byte 0x00 would produce an incorrect root. RLP encodes the integer zero using an empty integer byte string, so its key is 0x80.
Transaction Encoding
Transaction input binds the details of an ETH transfer or contract call to a signature.
The nonce checks sequencing for the sender account; it is distinct from the transaction's position within the block.
The legacy consensus byte representation uses RLP encoding in the following order.
RLP([nonce, gasPrice, gasLimit, to, value, data, v, r, s])A type 2 dynamic-fee transaction is represented by prefixing the following RLP structure with the type byte 0x02.
0x02 || RLP([
chainId, nonce, maxPriorityFeePerGas, maxFeePerGas,
gasLimit, to, value, data, accessList, yParity, r, s
])maxPriorityFeePerGas and maxFeePerGas specify the priority fee cap and total fee cap per unit of gas.
The accessList specifies addresses and storage locations to access in advance, while yParity, r, and s form the signature.
The leading type byte determines how the remaining bytes are interpreted.
Geth v1.17.10 supports transaction types 0 through 4. Type 3 supports large accompanying data objects called blobs. The consensus payload includes references to cryptographic commitments to the blob contents; the blobs themselves travel as separate accompanying data.
Type 4, used for code delegation, adds an authorizationList of signed authorizations specifying the EOA's delegation target.
In the legacy format, gasPrice is the price per unit of gas and gasLimit is the maximum gas that the transaction may consume.
value specifies the amount of ETH transferred, and data contains the encoded function and arguments.
For example, a token transfer encodes the token amount in the data used to call the token contract.
The value field specifies the ETH sent along with that call.
| Type | Main additions or changes |
|---|---|
| 0 | Legacy input and signature |
| 1 | chainId and accessList |
| 2 | Two fee caps replacing gasPrice |
| 3 | maxFeePerBlobGas and blobVersionedHashes |
| 4 | Code-delegation authorizationList |
The transaction type determines how the leaf value is interpreted. Regardless of type, the transaction trie key remains the RLP representation of the block position.
Results Stored in Receipts
A receipt records whether execution in the Ethereum Virtual Machine (EVM) succeeded or failed, along with its logs. Failed transactions also have receipts. The consensus receipt contains the following fields.
| Field | Contents |
|---|---|
status |
EVM execution success or failure |
cumulativeGasUsed |
Cumulative gas used since the start of the block |
logsBloom |
Bloom filter for narrowing log search candidates |
logs |
Logs emitted during execution |
Because cumulativeGasUsed is cumulative through that position, the gas used by one transaction is calculated from the difference between adjacent receipts.
Transaction IDs and block numbers returned to applications through RPC are fields that the node supplements from other information.
For example, if cumulativeGasUsed at position 0 is 21000 and at position 1 is 71000, the transaction at position 1 has a gasUsed of 50000.
Receipts also record failed EVM call execution.
In this case, storage changes and logs produced by the failed call are rolled back.
Even when status is 0, the sender's nonce increment and gas payment remain.
Code delegation configured before execution of a type 4 transaction also remains in effect.
Pre-Byzantium receipts use the post-execution state root rather than status, so very old block data must not be decoded exclusively using the current format.
Log Contents and the Search Bloom Filter
Logs contain the emitting address, topics, and data.
For a conventional Transfer event, the topics contain the event signature and indexed arguments, and the data contains the transfer amount.
The 2048-bit Bloom filter includes the address and topics, but not the data.
Three bits are set using the Keccak-256 hash of each value. This allows candidates to be excluded, but a match alone does not prove that a log exists.

Inspect the actual logs in blocks that remain candidates.
Consider a single non-anonymous Transfer event with a transfer amount of 1000. The amount is expressed in the token's smallest unit.
event Transfer(address indexed from, address indexed to, uint256 value);With this declaration, recording a transfer of 1000 maps the emitter, signature, and arguments to the following bytes.
address = <イベントを発行したトークンコントラクト>
topics[0] = keccak256("Transfer(address,address,uint256)")
topics[1] = pad32(<送付元の20バイトaddress>)
topics[2] = pad32(<送付先の20バイトaddress>)
data = pad32(1000)The actual event signature topic is 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef.
Addresses are prefixed with 12 zero bytes, while value is encoded into data as a 32-byte integer.
The topics array has three elements in this example: the signature topic and the two indexed arguments.
The log itself belongs to the receipt, separately from variables in the contract's storage trie.
The bit positions set in the Bloom filter are calculated from three pairs of bytes taken from the first six bytes of the value's Keccak-256 hash.
h = keccak256(address_or_topic)
p0 = ((h[0] << 8) | h[1]) & 2047
p1 = ((h[2] << 8) | h[3]) & 2047
p2 = ((h[4] << 8) | h[5]) & 2047
bloom[p0] = bloom[p1] = bloom[p2] = 1
blockBloom = receiptBloom[0] | receiptBloom[1] | ...In the formula above, p0, p1, and p2 are logical positions in the 2048-bit filter.
The actual byte-array layout must correspond to Geth's bloomValues implementation.
If any bit required by the search condition is absent, there cannot be a log with that address or topic.
Even when all bits are present, different values may have set overlapping bits, so inspect the actual candidate logs.
Other Header Fields and the Withdrawals Root
Besides the parent block, block number, gas, and timestamp, headers contain additional fields depending on the fork.
In execution-layer blocks containing withdrawals, withdrawalsRoot commits to the withdrawals list. Its calculation also uses a hash-verifiable Merkle Patricia trie (MPT) keyed by position in the block.
The withdrawals trie commits to a root distinct from the state, storage, transaction, and receipts tries.
It is also distinct from the root calculated using Simple Serialize (SSZ), the encoding used by consensus-layer beacon blocks.

The Header type in the examined implementation also includes optional fields for future forks. Their presence in the type does not prove that they have been activated on mainnet.
The execution-layer block body contains the transaction list and, for applicable forks, the withdrawals list. Receipts are results obtained by executing transactions, not a receipt list distributed directly in the ordinary block body.
The key used for withdrawalsRoot is the zero-based position within the withdrawals list in that block.
Distinguish the withdrawal record's global index from its position within the block.
parentBeaconBlockRoot and requestsHash cannot be classified as roots of the same kind of MPT simply because their names refer to hashes.
Inside the MPT
A Merkle Patricia trie is a tree that locates a value by traversing the key from its beginning and allows that relationship to be verified using hashes. Patricia compression combines paths that do not branch, while Merkle hashing propagates changes in children to their parents. To derive the same root from the same set of key-value pairs, path compression, value encoding, and child references must follow common rules.

If verifiers had to retrieve every value whenever one changed, large state sets would be difficult to handle. An MPT commits the relationships between nodes along a key to hashes, so the nodes needed to verify the part containing that key can be extracted. Assuming hash collisions are computationally infeasible, it is difficult to disguise different contents as belonging to the same root.
Nibbles and Compressed Paths
Splitting a byte into its high and low four bits produces two values ranging from 0 to 15. Each four-bit unit is called a nibble and corresponds to one hexadecimal digit. For example, 0xA7 is traversed in two steps, A and 7. In an illustrative trie containing A7F3, A7F8, and B012, the first branch separates A from B; the shared 7F path on the A side is compressed before branching into 3 and 8.

The actual state and storage tries traverse 32-byte hashes, or 64 nibbles.
Hashing addresses and storage slots with Keccak-256 first ensures that lookup keys are 32 bytes long. It also makes it difficult for users to select raw keys with long common prefixes to skew the trie. This is not a guarantee of equal branch lengths or I/O counts. It is a design that constructs the trie using a common input transformation.
The three example keys are deliberately short to illustrate compression. Although state and storage trie lookup keys contain 64 nibbles, shared intermediate paths are combined into extension nodes, so a lookup does not necessarily read 64 nodes.
Branch, Extension, and Leaf Nodes
A branch contains 16 references corresponding to the first unconsumed nibble, plus a value field for a key that ends there. An extension contains a shared path and a reference to the next node; a leaf pairs the remaining path with the final value. An empty reference indicates that no value exists beyond it. For A7F3 and A7F8, consuming branch 3 or 8 finishes the key, so the leaf below it has an empty remaining path.
The elements of each node can be represented as follows.
Branch = [child[0], child[1], ..., child[15], terminalValue]
Extension = [compact(sharedPath), childReference]
Leaf = [compact(remainingPath), storedValue]To look up A7F3, consume A at the first branch, 7F at the extension, and 3 at the next branch.
The remaining key is now empty, and the lookup reaches the value of a leaf with an empty remainingPath.
For B012, consume B at the first branch, then match the leaf's 012 against the remaining 012.
Lookup Termination Conditions
A branch consumes the first remaining nibble; an extension compares its entire stored path with the prefix of the remaining key. A leaf returns a value only if its entire path matches the remaining key. An empty reference or a path mismatch indicates nonexistence, whereas failure to retrieve required referenced data is a read failure. Collapsing both outcomes into one empty value makes it impossible to distinguish an absent value from a retrieval error.
The following pseudocode illustrates path consumption.
If root is the known empty-trie root, return nonexistence immediately.
Otherwise, treat empty references as nonexistence, and stop with an error if referenced data is missing or the RLP is invalid.
def lookup(reference, remaining):
while True:
if reference is Empty:
return Absent
node = resolve(reference) # 取得・復号失敗はエラー
if node is Branch:
if remaining is empty:
return node.terminalValue or Absent
reference = node.child[remaining[0]]
remaining = remaining[1:]
elif node is Extension:
if not remaining.starts_with(node.path):
return Absent
remaining = remaining.after(node.path)
reference = node.child
elif node is Leaf:
if remaining == node.path:
return node.value
return AbsentFor an embedded child, resolve uses the node structure itself. For a hash reference, it retrieves the corresponding RLP, checks the hash, and validates the decoded node.
The reference is resolved from a source determined by the implementation; cached nodes can be resolved from the cache.
Return the leaf value as an existing entry's value; do not convert retrieval failures into Absent.
For example, a lookup for A7F9 matches A and 7F. If the branch at 9 is empty, the key is absent. On the same path, if child 3 exists as a hash reference but its node data cannot be retrieved, that does not establish the absence of A7F3. Stopping with a retrieval error distinguishes pruned data or an incomplete proof from a genuinely absent value.
Byte Representations of Paths and Nodes
Even if two MPTs have the same shape, their hashes differ if their byte encodings differ. Node elements are RLP-encoded, and extension and leaf paths are compacted using hex-prefix encoding. If a child node's RLP encoding is shorter than 32 bytes, embed it directly in the parent. If it is 32 bytes or longer, reference its Keccak-256 hash. The root is always identified externally by its hash, so even a short root node is hashed.

The 32-byte threshold applies to the entire RLP-encoded child node, not just its path or value. Exactly 32 bytes also requires a hash reference. An embedded child's structure forms part of the parent's RLP, so a change to that child affects the parent's bytes and the root.
Compact Encoding Flags
The first high nibble indicates whether the path is an intermediate path or a leaf, and whether its length is even or odd. An even-length intermediate path uses 0 and an odd-length one uses 1; an even-length leaf path uses 2 and an odd-length one uses 3. For example, an intermediate path ABC becomes 0x1abc, a leaf path ABCD becomes 0x20abcd, and a leaf with an empty remaining path becomes 0x20. For an even-length path, the low nibble of the first byte is zero padding, avoiding a representation with an unmatched half-byte such as 0x00ABC.
| Path type | Even-length flag | Odd-length flag |
|---|---|---|
Extension |
0 | 1 |
Leaf |
2 | 3 |
For a leaf path ABCD, the high nibble of the first byte is 2, and its low nibble is padding zero. The two bytes AB and CD follow it, producing 0x20abcd. The flag also encodes the information identifying a leaf as terminal. Only the nibbles representing the key path are traversed during lookup.
RLP and Embedded Children
RLP distinguishes byte strings from lists and encodes nodes into unique byte representations that include element lengths. When a short child is embedded, the child node structure itself becomes part of the parent's RLP. Representing every edge as a 32-byte hash reference would obscure this distinction and misrepresent the number of reads. The hash function is Keccak-256, not SHA3-256, despite their similar names.
For example, integers from 1 to 127 are represented in RLP by their single byte. The minimal byte representation of 1000 is 0x03e8. Prefix it with 0x82, indicating a two-byte string, to obtain 0x8203e8. This representation then becomes the value element in a leaf, whose outer RLP encodes the list containing the path and value. Distinguishing the value's RLP from the entire node's RLP prevents hashing the wrong bytes.
Reading and Writing Contract Storage
The storage slot of a variable specified by an application and the MPT lookup key are determined at different stages.
Consider a minimal Solidity example with two uint256 variables, x and y, followed by a balances mapping keyed by address. Trace the process from slot calculation to the change in stateRoot.
Fixing the variable types and order before calculating their slots makes it possible to distinguish mapping hashes from trie hashes.

The following code is a minimal example for illustrating storage locations.
For the read example, assume that x equals 42 at a particular block.
Deploying the code as written initializes its value to 0.
The value 42 is a hypothetical state used to illustrate reads.
Storage Slots and Mapping Locations
In this example, x occupies slot 0, y occupies slot 1, and the base slot of balances is slot 2.
Each slot is 256 bits, but Solidity can pack smaller variables into the same slot, so one variable does not always occupy one entire slot.
For an address key k, the location L of balances[k] is the Keccak-256 hash of the concatenation of k and 2, each padded to 32 bytes.
Hashing L again with Keccak-256 as a 32-byte storage location yields the key traversed in the storage trie.

contract Example {
uint256 public x; // slot 0
uint256 public y; // slot 1
mapping(address => uint256) public balances; // base slot 2
}Calculate location L from the declared base slot 2 of balances and key k, then derive the lookup key from that location.
L = keccak256(pad32(k) + pad32(2))
trieKey = keccak256(pad32(L))Here, pad32(k) prefixes the 20-byte address with 12 zero bytes.
Pass location L to eth_getStorageAt, not the final trieKey.
The L calculated for each key is the storage location of that entry.
Consequently, reading different addresses in balances requires different locations L, even for the same contract.
Nested Mappings and Type Encoding
In another minimal example, data uses two levels of uint256 keys and has base slot 2.
Two preceding uint256 variables cause its base slot p to be 2.
contract NestedExample {
uint256 public x;
uint256 public y;
mapping(uint256 => mapping(uint256 => uint256)) public data;
}Calculate the base slot of the inner mapping using outer key 4, then calculate the final location using inner key 9.
p = 2
L1 = keccak256(pad32(4) + pad32(p))
L2 = keccak256(pad32(9) + L1)
trieKey = keccak256(L2)L1 is the base location of the inner mapping data[4], and L2 is the location of data[4][9].
Pass L2 to the RPC method.
The node hashes L2 to derive its internal trieKey.
The values of L1 and L2 in this example are already 32 bytes long, so they can be passed directly to the next calculation.
For string and bytes keys, the location formula's h(k) uses the unpadded key contents; pad32(k) for addresses or uint256 values cannot be applied to every key type.
Local calculation with these inputs produces the following storage locations.
L1 = 0xee60d0579bcffd98e668647d59fec1ff86a7fb340ce572e844f234ae73a6918f
L2 = 0xe04b399bdc055175526226949921f74c7cfa1ef4c8440f7cccae6e4ed0ae8ac4These values were verified by matching the results of cast index with cast keccak over the concatenated 32-byte inputs.
This calculation only determines storage locations; it does not query a contract.
From stateRoot to a Storage Value
Starting at the specified block's stateRoot, retrieve the account using the Keccak-256 hash of its address as the key.
Move to that account's storageRoot, then retrieve the value using the Keccak-256 hash of the 32-byte slot position.
If x equals 42, the stored value is the RLP encoding of the integer without leading zeros, while RPC returns the decoded value padded to 32 bytes.
MPT traversal is a logical procedure; not every read by a node using caches or flat state requires the same number of disk I/O operations.

Until the account is identified, the storage trie to read is not determined. A contract's value cannot therefore be read using only the hash of slot 0 without specifying its address. First identify the account, then search the storage trie committed to by that account.
Zero Values and Absent Slots
Writing zero in the storage trie removes the entry at that location. Distinguish a read that returns zero for an absent slot from one that fails because a required node cannot be retrieved. For the value 1000, the minimal integer byte representation is 0x03e8 and its RLP encoding as a trie value is 0x8203e8. The node decodes the RLP to retrieve the integer and pads it to 32 bytes for the RPC response.
| Representation stage | Representation of 1000 |
|---|---|
| EVM storage value | 256-bit integer 1000 |
| Byte string without leading zeros | 0x03e8 |
| Storage trie value | 0x8203e8 |
| RPC response | 32-byte DATA padded with leading zeros |
Omitting entries rather than retaining zeros avoids representing countless empty slots as leaves. During a read, that omission corresponds to the EVM's default value of zero.
How a Single Value Changes the Root
Updating x from 42 to 43 changes the representation of nodes on the path containing its leaf, which changes storageRoot.
The account record consequently changes, and the change propagates along the path to that account in the state trie, changing stateRoot.
Unchanged subtrees can reuse the same contents and hashes.
This logical sharing is separate from the decision of how long to retain old versions physically.
The same updated key-value set produces the same MPT under the same compression and encoding rules.
However, a real transaction that updates x may also change the sender's nonce and balances associated with gas payments.
Following the path of the update to x shows how changes propagate to the root through two levels: storage and account.
Retrieving and Proving Values
External applications typically request storage values from nodes through JSON-RPC.
To independently verify the returned value, check the account and storage proofs against a trusted block's stateRoot.
Retrieving a value, retrieving its proof, and successfully verifying that proof are distinct outcomes.

Reading through JSON-RPC
eth_getBalance, eth_getTransactionCount, and eth_getStorageAt read the account balance, nonce, and storage value, respectively.
For eth_getTransactionByHash and eth_getTransactionReceipt, the node uses its transaction lookup index to find the corresponding block and position.
When comparing storage values, specify the same block number to avoid the chain advancing between separate requests using latest.

{
"jsonrpc": "2.0",
"id": 1,
"method": "eth_getStorageAt",
"params": ["<対象コントラクトのアドレス>", "0x0", "<対象ブロック番号の16進数>"]
}The second argument, 0x0, is the storage location of x.
If the specified block is one where x equals 42, the returned DATA ends in 2a and is 32 bytes long.
The request above illustrates the format without connecting to a node; it is not a measurement from a specific deployed contract.
APIs returning quantities and APIs returning fixed-length data use different hexadecimal representations even for the same number.
eth_getStorageAt returns 32-byte DATA, whereas storageProof.value in eth_getProof is a QUANTITY without unnecessary leading zeros.
Compare the two results as integers rather than raw strings.
Example Preconditions and Verification Results
This example uses cast 1.5.1-stable to check the arguments for storage, index, and proof.
Specify the same Example contract address and block number for storage and proof.
index calculates the storage location L of balances locally.
cast storage '<対象のExampleのアドレス>' 0 --block '<対象ブロック番号>' --rpc-url '<読み取り先RPC URL>'
cast index address '<balancesのキーにするアドレス>' 2
cast proof '<対象のExampleのアドレス>' '<indexが返した位置L>' --block '<同じ対象ブロック番号>' --rpc-url '<同じ読み取り先RPC URL>'storage retrieves x at slot 0.
index calculates location L for the specified address in balances using base slot 2.
proof takes that L as input and requests the value and proof for balances.
To retrieve a proof for x as well, specify 0 instead of L.
The location calculation and command arguments were checked, but this example was not connected to a node and does not report values observed on a network. If a request for a historical block fails because its data is not retained, send the same block-specific request to a node retaining that period.
Verification Using Merkle Proofs
eth_getProof returns accountProof and a storageProof for each requested location.
Starting at a trusted stateRoot, the verifier reconstructs the account by validating node RLP encodings, hash references, embedded children, and path matches.
Using the storageRoot contained in that account, verify the storage value in the same way.
Do not unconditionally trust the separate storageHash field returned by RPC; check that it matches the root committed to by accountProof.

{
"jsonrpc": "2.0",
"id": 2,
"method": "eth_getProof",
"params": ["<同じコントラクトのアドレス>", ["0x0000000000000000000000000000000000000000000000000000000000000000"], "<同じ対象ブロック番号の16進数>"]
}In this example, the storage location is specified as 32 bytes, and one element of the returned storageProof contains the value at slot 0 and the RLP nodes along its path.
Use the same storageRoot decoded from the accountProof leaf as the root against which this storage proof is verified.
The minimal form of the response for a state in which x equals 42 is as follows.
{
"accountProof": ["<stateRootから対象アカウントへ至るRLPノード群>"],
"storageHash": "<アカウントのstorageRoot>",
"storageProof": [{
"key": "0x0000000000000000000000000000000000000000000000000000000000000000",
"value": "0x2a",
"proof": ["<storageRootからslot 0へ至るRLPノード群>"]
}]
}In practice, accountProof and each proof contain multiple nodes needed along the path.
Each element of storageProof groups a requested location, its value, and the proof leading to that value.
During verification, compare the account's storageRoot obtained from accountProof with storageHash, then connect storageProof to that root.
Decode the RLP value 0x2a obtained from the leaf for slot 0 into the integer 42, and compare it with the returned value quantity 0x2a.
If the root, path, or value does not match, stop with a verification failure rather than accepting the returned value alone.
Even if the accountProof nodes correctly connect to the root, a path for a different account does not prove the intended value.
Bind the stateRoot, address-derived key, decoded account, slot-derived key, and storage value to the same request.
These checks reject a provider's substitution of a value or mixture of proofs from different blocks.
Absent Values and Incomplete Proofs
An empty branch along the correct path or a leaf whose path differs from the remaining key can prove that a specified location does not exist. By contrast, a referenced node missing from the proof is a verification failure.
Whether the location exists remains undetermined. An empty trie has a known empty root, so do not require a nonexistent root node in the same way as for an ordinary nonempty trie. Do not substitute zero when verification fails; return the failure to the caller.
Trusted Roots and the Scope of a Proof
An MPT proof establishes that a value is committed to by a specified root. Whether the header containing that root belongs to the correct chain and is sufficiently finalized must be checked separately.
Execution clients validate state transitions, while consensus clients handle chain selection and finality. Combine the MPT proof with verification of the header containing the root to establish the value at the intended block. Light clients likewise distinguish the prerequisite of obtaining a trusted header from the retrieval of required data.
Geth's Storage Architecture
The key-value relationships and root calculations described so far are logical structures agreed upon by the network. The client implementation determines which disk keys are used to store nodes. Using pinned Geth v1.17.10 source code as an example, we will distinguish block records, trie nodes, code, search indexes, and caches.

Even nodes validating the same block need not use the same database engine or internal key layout. Consensus requires agreement on state transition results and roots; reading and writing local records is an implementation concern. The following internal key examples are also distinct from inputs sent directly to network RPC methods.
Database Keys and Storage Locations
Geth manages block headers, bodies, receipts, account state, code, and search indexes using keys specific to their purposes.
For example, the key for a header concatenates h, an eight-byte block number, and the block hash; bodies use the prefix b, and receipts use r.
Code uses the combination of c and codeHash, while the transaction lookup index uses l and the transaction ID.
These internal keys belong to Geth's storage implementation and should not be assumed to apply unchanged to other clients or future versions.

Let N8 denote the eight-byte big-endian block number, B the block hash, and T the transaction ID. The stored data is organized as follows.
The table shows the type of record associated with each key.
Stored receipts and search indexes use encodings that differ from the corresponding consensus values.
| Key structure | Referenced data |
|---|---|
h || N8 || B |
Header |
h || N8 || n |
Canonical block hash |
H || B |
Block number |
b || N8 || B |
Body |
r || N8 || B |
Receipt list in storage format |
l || T |
Transaction lookup information |
c || codeHash |
Code bytes |
A || path |
Account trie node in the path-based scheme |
O || accountHash || path |
Storage trie node in the path-based scheme |
a || accountHash |
Flat-state account record |
o || accountHash || slotHash |
Flat-state storage value |
path is the path within the trie, accountHash is the address hash, and slotHash is the hash of the storage location.
H is the prefix for block number lookup, while the suffix n identifies keys used to retrieve the canonical block hash.
For block number 18000000, N8 is 0x000000000112a880.
The header key concatenates 0x68, these eight bytes, and the 32-byte hash of the block.
0x68 is the single-byte representation of the character h.
The canonical-chain lookup key concatenates 0x68, the same eight bytes, and 0x6e. It therefore differs from the header key, which ends with the block hash itself.
Do not equate the l lookup information or the stored receipt format with values in consensus tries.
Hash-Based and Path-Based Schemes
The hash-based scheme retrieves independently stored trie nodes using hashes of their contents.
In the path-based scheme, the state trie uses A and the path, while individual storage tries use O, the account hash, and the path.
The latter scheme can compute the same MPT root from node contents, but it does not store every old and new node at the same path under distinct hash keys.
Reading the database once using stateRoot directly as a key does not necessarily retrieve the root node under every scheme.
In the hash-based scheme, nodes with identical contents can be referenced by the same hash, facilitating reuse of unchanged nodes. However, retaining content-addressed nodes referenced only by old roots requires a way to identify and remove unneeded disk records. The path-based scheme can update the node at a given location, allowing current-state management and history retention to be designed separately. Both schemes arrive at the same state root when MPT references and hashes are interpreted according to the same rules.
Memory, Flat State, and Ancients
Geth uses in-memory caches and recent diffs, and it also provides a direct read path from flat state to account records and storage values.
The flat state managed by Geth's a and o keys is a representation separate from the MPT that makes values easier to access.
Older block records and state history also use separate storage areas called ancients, so depicting everything as a single list of LevelDB nodes is inaccurate.

The following is a minimal layout when the location of ancients is not specified separately. Instance directories and internal database engine filenames vary by environment.
<datadir>/
<Gethインスタンスのディレクトリ>/
chaindata/ キーバリューDBと索引
ancient/ 古いブロック等の保存領域Configuring a separate ancients location allows the key-value database and older data to reside on different disks.
Old block records and state history are also distinct retention targets; a directory name alone does not establish that their retention periods match.
The flat-state a keys provide direct access to account records, while o keys address storage values for an account and slot pair.
To construct an MPT proof, obtain the nodes along the path in addition to the flat-state value. Maintaining a representation for fast value access alongside one for traversing nodes toward the root supports ordinary queries and proof generation respectively. If modified nodes remain in memory, the base state on disk alone does not represent the latest state.
Persistence Timing and Reconstruction
When a new state is produced, a diff layer is added using its root and parent root. When the retained diff-layer range is exceeded, older diffs are merged into lower layers, advancing the persistent state. The examined Geth version distinguishes this merging from the actual disk flush triggered by a full buffer. Recent forks are handled using in-memory diff layers. To return to a canonical state older than the persistent state, retained historical pre-change values are applied in order.
Without the history, recovery to that state is not necessarily possible.
変更前 永続状態 N 差分 N+1 差分 N+2
畳み込み 永続状態 N+1 差分 N+2This diagram simplifies the relationship between layers to two diffs. Transaction and receipt roots can be reconstructed by deriving consensus bytes from block bodies and receipt lists. Persisting every node of every trie is therefore different from being able to recompute the roots.
Validation Versus Synchronization
Execution clients execute transactions and validate state transitions. Consensus clients receive blocks, determine which chain to follow, and handle finality. Even a configuration that validates as a full node can retain different numbers of historical states depending on its retention policy. Snap sync retrieves a relatively recent state and its proofs to reconstruct the MPT, then executes new blocks once it catches up.
Archiving is a retention policy that allows historical state to be queried. Configure the synchronization method and history retention policy separately according to their purposes. Light clients verify required data against trusted headers using proofs, without assuming they store the same full dataset as ordinary full nodes.
Historical State and Retention Policies
Even if block N's stateRoot remains in its header, a node may not retain the data needed to traverse from that root.
Treat state required for current validation, historical value queries, historical proofs, and old block bodies or receipts as distinct retention targets.
This distinction is the starting point for understanding pruning and archive settings.

Suppose x equals 42 at block N and changes to 43 at N+1, and an application later queries its value at N.
A node that retains only the current value 43 cannot derive the previous value 42 from it.
It needs the state at N, history containing the pre-change value, or the information and computation required to replay up to that point.
Pruning and Archiving
Pruning removes state or history outside the configured retention range. The hash-based scheme's dirty cache tracks references between nodes not yet persisted and releases unnecessary cached data. This differs in scope and retention period from a mechanism that automatically deletes every node on disk using the same reference counts. The path-based scheme updates the same paths in the persistent layer and can retain history using reverse diffs and indexes.

In this scheme, being able to read historical values is also distinct from being able to construct proofs from historical MPT nodes.
Historical Queries in the Path-Based Scheme
Reverse diffs record the pre-change values of accounts and storage locations modified in a block. Historical value queries can find the required values through an index of blocks containing changes, avoiding the need to store a complete copy of the MPT for every block. Distinguish periods that cannot be queried until history indexing finishes from periods for which history was never retained. Enabling archive settings later does not automatically restore historical states that were already discarded.
If a value changes from 42 at N to 43 at N+1, the reverse diff contains the previous value 42. A historical query can use the index to find the subsequent block where that location changed and retrieve the recorded pre-change value. Replicating every node for each rollback and indexing change history for value queries are separate approaches.
Additional Requirements for Historical Proofs
To serve historical eth_getProof requests under Geth v1.17's path-based scheme, retain trie-node history for the relevant period as well.
The history.state setting retains value history, while history.trienode separately configures retention of the node history needed for proofs.
Determine whether historical proofs can be served only after confirming the period covered, index completion, and availability of node history.
The path-based scheme in v1.16 could not serve historical proofs; v1.17 added a configuration that retains the necessary node history.
| Setting or status | What to check |
|---|---|
history.state |
How many blocks of value history are retained |
history.trienode |
Whether the node history needed for proofs is retained |
| Archive indexing | Whether indexing is complete for the relevant period |
| Synchronization starting point | Whether the period for which state was retrieved or executed covers the required historical state |
In the examined version, history.trienode defaults to -1, disabling node history retention.
Even a node that serves historical values cannot generate historical proofs unless it retains the node history for the required period.
Changing when history retention begins is separate from recovering history that has already been lost.
Retention Requirements by Use Case
Reading current balances or storage values requires access to the current state. Investigating historical balances or contract storage requires state history covering the relevant block. Constructing a historical value proof for a bridge requires both value history and the data necessary to construct the proof. Analyzing transaction or event history depends on retention of bodies, receipts, and search indexes; the presence of a state archive alone is insufficient.

| Query objective | Required data |
|---|---|
Latest value of x |
Current state |
Value of x at block N |
State history and query indexes covering the relevant period |
Proof of x at N |
Required state and MPT node history |
| Transfer logs in block N | Receipts and data required for log searches |
Current validation, historical value analysis, bridge proofs, and historical event searches query different kinds of data. Rather than selecting an endpoint solely because it is called an archive, verify that it can respond using the required API at the target block.
Diagnosing Retrieval Failures
Distinguish incorrect input slots, an incorrect target block, missing history, incomplete indexing, and missing proof nodes. If retries cannot recover history that was never retained, query a node serving the required period or prepare a configuration capable of reacquiring it. Storage requirements and speed vary with the network, retention range, database, hardware, and synchronization starting point, so storage estimates in TB from different sources should not be presented as fixed requirements. Before switching endpoints, reproduce the failure using the same address, storage location, and block number, then inspect the returned error.
Conclusion
Balances and storage values are committed to by stateRoot through two levels of tries, while transactions and receipts are committed to by their respective roots using positions within the block.
An MPT proof verifies the relationship between a trusted root and a value.
Geth's disk keys, caches, flat state, and history retention are implementation mechanisms for reading and writing this logical structure.
Deciding whether historical values or historical proofs are needed makes it possible to specify precisely what data a node must retain.
Ethereum's official developer documentation explains MPT structure and path and node encoding. https://ethereum.org/developers/docs/data-structures-and-encoding/patricia-merkle-trie/
Geth's official documentation covers synchronization methods, node configuration, archiving, and history retention. https://geth.ethereum.org/docs
The comparison with Geth's implementation is based on the pinned v1.17.10 commit. https://github.com/ethereum/go-ethereum/tree/1df30b18d9ed35ee9d28ffd4648442c2204554ad
Solidity storage locations and event encoding are based on the official documentation for version 0.8.30. https://docs.soliditylang.org/en/v0.8.30/
Withdrawal roots, proof requests, code delegation, and token events are defined by EIP-4895, EIP-1186, EIP-7702, and ERC-20, respectively. https://eips.ethereum.org/
