bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 18쪽 중 13쪽
the unchanged `stateRoot`). Deriving the MSU Root slot from the key closes this gap.
***
## 6. Verification Script
A Python verification script [`spv_verify.py`](https://github.com/PharosNetwork/examples/blob/main/spv-verification/spv_verify.py) is provided to verify both existence and non-existence proofs. It handles:
* Automatic `stateRoot` computation from the MSU Root node (SHA-256) if not present in the JSON.
* Both existence proofs (leaf-terminated) and non-existence proofs (empty-slot-terminated with sibling verification).
* Key-derived MSU Root slot offset (see [§ Slot Offset Derivation](#slot-offset-derivation)), enforced as a soundness invariant.
* Optional cross-validation of `stateRoot` against an RPC endpoint.
> Earlier versions of this script trusted `nextBeginOffset` for the MSU Root layer. Integrators using a downstream fork of this script should ensure their copy includes the key-derived slot check; without it, non-existence proofs are forgeable.
### Usage
```bash
# Basic verification (no RPC cross-check):
python3 spv_verify.py proof.json --address 0x<account-address> --no-rpc
# With stateRoot cross-check against RPC:
python3 spv_verify.py proof.json --address 0x<account-address> \
--block 0x<block-number> --rpc-url http://127.0.0.1:18100
# If the JSON already contains 'address' and 'stateRoot':
python3 spv_verify.py proof.json --no-rpc
```
The full script source is available at the [`examples` repository](https://github.com/PharosNetwork/examples/blob/main/spv-verification/spv_verify.py).
***
## 7. Comparison with Ethereum
For teams familiar with Ethereum's `eth_getProof` ([EIP-1186](https://eips.ethereum.org/EIPS/eip-1186)), the key differences are:
| Aspect | Ethereum | Pharos |
| ----------------------- | ------------------------------------ | --------------------------------------------------------------- |
| **Hash algorithm** | Keccak-256 | SHA-256 |
| **Trie structure** | Merkle Patricia Trie (MPT) | Hexary hash tree with 256-slot MSU Root |
| **Node encoding** | RLP-encoded hex strings | Fixed-size binary objects |
| **Proof format** | `accountProof: string[]` | `accountProof: object[]` (with `nextBeginOffset/nextEndOffset`) |
| **Non-existence proof** | Implicit (path terminates naturally) | Explicit `siblingLeftmostLeafProofs` |
**Why are non-existence proofs different?**
In Ethereum's MPT, nodes are RLP-encoded and self-describing — an empty branch is simply an empty string in the RLP list, and the verifier can decode and confirm it directly. In Pharos's hexary trie, Internal nodes are fixed-size binary structures where an empty slot is 32 zero-bytes. To prevent trivial forgery of all-zero Internal nodes, the non-existence proof includes sibling subtree proofs that allow the verifier to independently reconstruct and validate the Internal node's hash. This is a trade-off: proof verification is more complex, but the underlying storage engine benefits from significant optimizations. The verification semantics are complete and fully meet practical use case requirements.
For users who're interested in the implementation details of such proof and how it works, you can refer to [SPV Proof Theory Explanation](/api-and-sdk/eth-getproof/spv-proof-theory)
# SPV Proof Theory Explanation
## SPV Proof Theory Explanation
SPV (in the context of this repository) refers to: On a Merkle state tree of a certain data version, for a key provided by the user, the server constructs proof data, allowing the verifier to independently verify "whether the key exists, and if so, what the value is" or "that the key does not exist", given that the verifier only knows the root hash (or equivalent commitment). In this implementation, the state is organized as a **nibble Trie**, with node hashes cryptographically bound to keys/values. The Letus-side entry point is `MerkleIndex::GetSPV`, and the key-based downward traversal follows `TrieNode::NodeRead` (TreeOpType::kGetSPV).
### Merkle Tree Structure
#### Two Layers: Grid (MSU) + Subtrees
In upper layers such as MyGrid, the state is sharded by MSU (Multi-Shard Unit): it can be understood as first routing keys to one of 256 slots based on the key, with each slot corresponding to a Letus Merkle subtree. The global root hash is obtained by concatenating "the root hashes of each MSU subtree" and then hashing them once more; on the client side, the 256×32-byte subtree roots are concatenated into a "large internal node" as the first hop of the proof chain, see `GetMerkleProofGridReq::handleAllPartIOSuccess`.
```
RootHash = Hash( MSU[0] || MSU[1] || ... || MSU[255] ) (each MSU[i] is a 32-byte subtree root hash)
MSU[0] MSU[1] MSU[255]
| | |
+--- Letus +--- Letus +--- ... (nibble Trie)
subtree subtree
(nibble Trie) (nibble Trie)
```
Within a single MSU is Letus's 16-ary nibble Trie (each layer takes one nibble 0\~F of the key\_hash). Below is a minimal schematic diagram using ASCII art (showing only some slots and two layers):
```
[ Root_internal ]
/ | \\ ... (up to 16 child slots)
/ | \\
v v v
slot_3 slot_7 slot_A
| | |
[Inter] (Leaf K1) [Inter]
| \\
v v
(Leaf K2) (Leaf K3)
```
* **Internal nodes**: Up to 16 child slots, each slot corresponding to a 32-byte subtree hash (empty slots are often all zeros).
* **Leaf nodes**: Store key\_hash and value\_hash, corresponding one-to-one with the existence of the queried key.
#### State Tree Root Hash Calculation Method
```
Explanation:
1. The + in the formulas below indicates string concatenation
2. RootHash represents the root hash of the state DB
3. MSU[0] represents the root hash of MSU slot 0
4. Inter_0 represents the hash of the intermediate node corresponding to slot 0 on the Merkle tree
5. Leaf_0 represents the hash of the leaf node corresponding to slot 0 on the Merkle tree
RootHash = Hash( MSU[0] + MSU[1] + ... + MSU[255] )
MSU[0] = Hash( Inter_0 + Inter_1 + ... + Inter_e )
Inter_x = Hash( Leaf_0 + Leaf_1 + ... + Leaf_e )
Leaf_x = Hash( key + value )
```
Additionally, note that to more efficiently handle the case where there are many empty slots in intermediate nodes in the Trie, Letus chooses to skip empty slots when computing hashes. The relevant logic is similar to the following code:
```c++
std::string hash_val = "";
for (int i = 0; i < kInternalSlotCount; i++) {
if (node_impl->IsSlotCommittedEmpty(i)) {
continue;
}
hash_val = hash_update(hash_val, node_impl->GetSlotHash[i]);
}
```
### SPV Verification Method
Like other Merkle tree implementations, Letus's SPV is the reverse process of computing the root hash. Specifically, the process is as follows:
#### Trie Path
1. Perform `ComputeKeyHash` on the user key to obtain a fixed-length NibbleHash.
2. Starting from the MSU root (and the Grid layer above), sequentially take key\_hash\[d] as the slot index 0\~15 for depth d = 0,1,2…, enter the corresponding subtree on the internal node, until reaching a **leaf** or terminating at some layer where the **slot is empty**.
3. These obtained slots (slot\_idx) will be used later to verify the SPV return results layer by layer.
#### Proof Chain tree\_proofs
1. Each element in the chain is a `TreeProofNode`, which may correspond to an intermediate node or a leaf node.
2. For an **intermediate node TreeProofNode**: It contains the `proof_node` with hex-encoded node content, and `next_begin_offset` and `next_end_offset` that indicate "where the current subtree root hash falls within the parent node's byte string". **A sound verifier MUST independently derive these offsets from the key and treat the prover-supplied values as advisory cross-check inputs only.** The derivation differs by layer:
* **MSU Root layer** (the first proof node, 256 × 32-byte flat slot array, no header): `next_begin_offset = slot_idx * 32`, where `slot_idx` is derived from the queried key via the network's MSU routing function — `slot_idx = key[len(key) - 1]` for the Pharos mainnet/testnet — not from any prover-supplied data.
* **Internal node layer** (every subsequent non-leaf node): `next_begin_offset = 3 + 32 * slot_idx`, where `slot_idx` is the nibble of `ComputeKeyHash(key)` at the corresponding trie depth. The leading 3 bytes are node metadata.
* `next_end_offset = next_begin_offset + 32` in both cases.
If the prover-supplied `next_begin_offset` disagrees with the key-derived value at any layer — especially at the MSU Root — the proof must be rejected. See the Correctness Discussion below for why this is load-bearing for non-existence soundness.
3. For a **leaf node TreeProofNode**: It contains the `proof_node` with hex-encoded node content, representing the concatenation of the key's hash and the value's hash (specific encoding depends on the implementation).
#### Proof Chain Verification Logic
Verifier input: `root_hash` (committed root), `key`, returned `proofs[]` (and optional sibling sub-proofs, see below).
```
cur = Starting from the last node (deepest) in proofs, compute "the subtree root hash of that node" according to the node type
for i = len(proofs)-2 .. 0:
parent = proofs[i]
# Independently derive the expected slot offset from the queried key — do not
# trust the prover-supplied next_begin_offset for slicing.
if parent is the MSU Root layer (i == 0):
expected_offset = key[len(key) - 1] * 32 # 256-slot flat array
else:
slot_idx = nibble_at_depth(ComputeKeyHash(key), trie_depth_of(parent))
expected_offset = 3 + slot_idx * 32 # internal node layout
Assert parent.next_begin_offset == expected_offset # cross-check
H_slot = parent.proof_node[expected_offset : expected_offset + 32]
Assert H_slot == cur
cur = Hash(parent.proof_node) // Or the parent node hash rule agreed upon by the implementation
Assert cur == root_hash (or consistent with the root after concatenation with the MSU/Grid chain)
```
**Existence**: The last hop is a leaf, and the key\_hash in the leaf is consistent with `ComputeKeyHash(key)`, and the value can be verified.
**Non-existence** has two typical forms (consistent with the "instance" numbering below):
* **Case 1**: The last hop is a leaf, but the key\_hash in the leaf is inconsistent with the queried key (the path leads to "someone else's leaf") — typically without sibling sub-proofs.
* **Case 2**: At an internal node, the next nibble corresponding to the query is an empty slot, while other slots at the same layer have data — often accompanied by `sibling_leftmost_leaf_proofs` (sub-chains to the leftmost leaf of each sibling slot); the information of these sibling slots is also used to assist in non-existence proofs.
## SPV Instance Explanation
Consistent with the implementation: The `sha256(key)` in the pseudocode below and the hexadecimal strings in the comments (such as "12e2aef") are only for illustrative purposes to facilitate comparison with the diagrams; actual verification should be based on the NibbleHash obtained from `ComputeKeyHash` and the node encoding rules.
### Existence Proof
**Scenario**: key = K, (K, V) exists in the tree, the query path goes from the MSU root along the nibble of hash(K) all the way to a leaf, and that leaf is the storage for K.
**Instance**:
<figure><img src="https://3298017099-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNmFp0ycownpuaUNf2xeE%2Fuploads%2Fgit-blob-e98cca0b6c16499a86ab7e90f0ea6893ddeecb61%2Fspv-existence-proof.jpeg?alt=media" alt=""><figcaption><p>SPV Existence Proof</p></figcaption></figure>
As shown in the figure above, a total of three diagrams illustrate an actual example of SPV verification.
* The **leftmost diagram** shows the structure of the Trie, and the hash corresponding to the key we expect to verify, i.e., "12e2aef"
* The **middle diagram** shows the response given by SPV, and the correspondence between the response content and each layer of the Trie
* The **rightmost diagram** shows the SPV verification flow, verifying from the leaf node to the state root hash. We focus on explaining the SPV verification flow shown on the rightmost side:
```
# Step 1: Get slot_idx at each layer
key_hash = sha256(key) # key_hash = "12e2aef"
slot_idx[0] = 1
slot_idx[1] = 2
...
# Step 2: Verify leaf node
check: proof[-1][1] == key_hash # proof[-1] consists of three elements, proof[-1][1] represents key_hash
tmp_hash = sha256(proof[-1])
# Step 3: Verify the intermediate node one layer above the leaf node
check: proof[-2][slot_idx[-1]] == tmp_hash
# Additionally, the correspondence between next_begin_offset and slot_idx can be checked
tmp_hash = sha256(proof[-2])
# Step 4: Verify the intermediate node one layer above that
check: proof[-3][slot_idx[-2]] == tmp_hash
# Additionally, the correspondence between next_begin_offset and slot_idx can be checked
tmp_hash = sha256(proof[-3])
...
# Final step: Verify the root hash matches the expected state DB root hash
check: tmp_hash == root_hash
```
### Non-Existence Proof - Case 1
**Meaning**: The proof chain ends with a leaf node, but the key\_hash stored in that leaf is inconsistent with the key\_hash obtained by applying the same hash algorithm to the queried key — that is, following the query path leads to the leaf of another existing key (the path prefix overlaps with another, and the last hop lands on "someone else's leaf").
<figure><img src="https://3298017099-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNmFp0ycownpuaUNf2xeE%2Fuploads%2Fgit-blob-410ce942f69c704d429daadbfe1c101d75fcbc19%2Fspv-nonexistence-proof-case1.jpeg?alt=media" alt=""><figcaption><p>SPV Non-Existence Proof - Case 1</p></figcaption></figure>
As shown in the figure above, this is an example of a non-existence proof: the hash corresponding to the key we expect to verify is "12e2111".
Obviously, from the leftmost diagram, we can see that according to our expected key\_hash, a leaf node of the Merkle tree is still found. However, the key corresponding to this leaf node is not the same as the key we expect, which indicates that the key we expect for SPV does not exist. Next, let's look at how to verify this through SPV.
```
# Step 1: Get slot_idx at each layer
key_hash = sha256(key) # key_hash = "12e2111"
slot_idx[0] = 1
slot_idx[1] = 2
...
# Step 2: Verify leaf node
check: proof[-1][1] != key_hash # This step indicates that this verification is a non-existence proof!
tmp_hash = sha256(proof[-1])
# Step 3: Verify the intermediate node one layer above the leaf node
check: proof[-2][slot_idx[-1]] == tmp_hash
# Additionally, the correspondence between next_begin_offset and slot_idx can be checked
tmp_hash = sha256(proof[-2])
# Step 4: Verify the intermediate node one layer above that
check: proof[-3][slot_idx[-2]] == tmp_hash
# Additionally, the correspondence between next_begin_offset and slot_idx can be checked
tmp_hash = sha256(proof[-3])
...
# Final step: Verify the root hash matches the expected state DB root hash
check: tmp_hash == root_hash
```
**In summary**: "key\_hash verification fails" && "the entire proof can be verified using the target key's offset" yields a valid non-existence proof.
### Non-Existence Proof - Case 2
**Meaning**: At a certain internal node, the next nibble of the query path corresponds to an empty slot (the subtree is not created, or an all-zero empty slot proof is provided), and the path ends at an intermediate node rather than a leaf node.
<figure><img src="https://3298017099-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNmFp0ycownpuaUNf2xeE%2Fuploads%2Fgit-blob-6a87671625002c9b28789c79c37c3a3e6647e446%2Fspv-nonexistence-proof-case2.jpeg?alt=media" alt=""><figcaption><p>SPV Non-Existence Proof - Case 2</p></figcaption></figure>
As shown in the figure above, this is an example of a non-existence proof: the hash corresponding to the key we expect to verify is "12221".
In this case, the verification process is more complex. Returning only the main path of the target key (tree\_proofs) is not sufficient; we also need `sibling_leftmost_leaf_proofs` corresponding to each non-empty sibling slot: each sibling item contains `slot_index`, `leftmost_leaf_key` (the original key of the leftmost leaf in that slot's subtree), and `proof_path` (the sequence of nodes from a certain layer's internal node down to that leaf along the leftmost path). The reason is explained in the "Non-Existence Proof Case Discussion - Case 2" section below. During verification, it can be understood in a manner consistent with the implementation: the main chain first verifies to the "empty slot internal"; then for each sibling sub-proof, concatenate "main chain prefix + sibling path" to form a complete chain, and verify to the root using the existence proof method (using the sibling's leftmost leaf key to walk the nibble path).
```
# The main chain is denoted as proof (i.e., tree_proofs); siblings are sibling_leftmost_leaf_proofs.
# The last section is an internal node, not a leaf.
# Step 1: Get slot_idx at each layer for the queried key
key_hash = sha256(key) # key_hash = "12221"
slot_idx[0] = 1
slot_idx[1] = 2
...
# Step 2: Verify the last section internal node: the query path falls on an empty slot at the last layer
check: proof[-1][slot_idx[-1]] == 0
# Step 3: Compute hash upward from the last section internal node
tmp_hash = sha256(proof[-1])
# Step 4: Verify the intermediate node one layer above
check: proof[-2][slot_idx[-2]] == tmp_hash
# Additionally, the correspondence between next_begin_offset and slot_idx can be checked
tmp_hash = sha256(proof[-2])
# Step 5: One layer above that
check: proof[-3][slot_idx[-3]] == tmp_hash
# Additionally, the correspondence between next_begin_offset and slot_idx can be checked
tmp_hash = sha256(proof[-3])
...
# Final step: Verify the root hash matches the expected state DB root hash
check: tmp_hash == root_hash
# For each sibling sub-proof in siblings (where proof_path is non-empty):
# Remove the last section from the main chain, append that item's proof_path,
# then roll to the root using the same steps as "existence proof"
for sib in siblings:
if not sib.proof_path:
continue
combined = proof[0 : len(proof)-1] + sib.proof_path
key_hash = sha256(sib.leftmost_leaf_key)
slot_idx[0] = 1
slot_idx[1] = 2
...
check: combined[-1][1] == key_hash
tmp_hash = sha256(combined[-1])
check: combined[-2][slot_idx[-1]] == tmp_hash
tmp_hash = sha256(combined[-2])
check: combined[-3][slot_idx[-2]] == tmp_hash
tmp_hash = sha256(combined[-3])
...
check: tmp_hash == root_hash
```
**Summary**: Case 2 = Main chain (terminating at empty slot internal) + Several sibling chains (each being an "existence-style" sub-proof of the leftmost leaf of a certain slot); sibling chains share the same root\_hash with the main chain, ensuring branch completeness under the parent node's 16-slot semantics.
## Correctness Discussion
This section explains: Given that the root\_hash root\_hash is trustworthy (or has been anchored to a trusted state), why the verification steps above are semantically sufficient to support the conclusion of "existence / non-existence". The text first explains SkipEmpty and the overall security goals, then discusses existence, non-existence (leaf key mismatch), and non-existence (internal empty slot + sibling sub-proofs) in three sections.
### Prerequisites and Overall Conclusions (Including SkipEmpty)
**Prerequisite — Key-Derived Slot Offsets at Every Layer (including MSU Root).** All correctness arguments below presume that the verifier derives the slot offset at each layer of the proof chain from the queried key itself, **not** from prover-supplied fields. For internal nodes inside an MSU subtree the slot index is the corresponding nibble of `ComputeKeyHash(key)`; for the MSU Root layer the slot index is fixed by the network's MSU routing function applied to the key (the last byte of the key for the Pharos network). If a verifier accepts the prover-supplied `next_begin_offset` for the MSU Root layer, the Case 2 non-existence argument below collapse프로젝트로 돌아가기