Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
- In Lean, `followsIn_eq_error_pastGenesis` (`Execution/Proofs/Network/Blocks.lean`) states that a header after one with no next number fails with `pastGenesis`.
`HeaderRequest.next_eq_none_iff` states that a header has no next number exactly when the answer falls and the header is below `skip + 1`.

- In Lean, `accountProofOfJson_unknown_key` and `storageProofOfJson_unknown_key` (`Execution/Proofs/Rpc/Proof.lean`) state that the readers of an `eth_getProof` answer and of one of its slots reject an object with a key outside its schema.

Check warning on line 21 in CHANGELOG.md

View workflow job for this annotation

GitHub Actions / writing

Writing S1

This sentence has about 29 words. Consider a split if it improves clarity. 'In Lean, `accountProofOfJson_unknown_key` and `storageProofOfJson_unknown_key` ('
`onlyKeys_mkObj` and `onlyKeys_rejects` (`Serialization/Proofs/JsonRpc.lean`) state when an object holds only the given keys.

- In Python, `serialization.ssz` gains `verify_merkle_proof`, `compute_merkle_multiproof`, `verify_merkle_multiproof`, `value_of_json` and `json_of_value`, over the definitions of `Serialization/Ssz/Merkle/Verify.lean`, `Serialization/Ssz/Codec/Proof.lean` and `Serialization/Ssz/Codec/Json.lean`.
The tagged form of a type spells the byte alias as `{"byte": None}`, which the JSON mapping writes as hex.
The suite runs the 575 vectors of the ssz-specs release v0.2.0, in all six of its formats.
Expand Down Expand Up @@ -2031,6 +2034,12 @@
It failed with `wrongNumber`, code 204, with 0 in place of an expected number, where none follows.
In Lean, `HeadersError` (`Execution/Network/Blocks.lean`) gains `pastGenesis`.

- `execution.trie.verify_account_proof` rejects an answer or a slot with a key outside the `AccountProof` or `StorageProof` schema of execution-apis, which allow no other property.
It raises `TrieError` code 0 with `answer: unknown key` or `slot: unknown key`, followed by the key, where it ignored that key.
In Lean, `accountProofOfJson` and `storageProofOfJson` (`Execution/Rpc/Proof.lean`) reject such an object, where they accepted it.
In Lean, `onlyKeys` moves from `Execution/Rpc/Simulate.lean` to `Serialization/JsonRpc.lean`, so its name is `EthLib.Serialization.JsonRpc.onlyKeys`.
It and `hasOnly` both read `outsideField`, new in the same module, the first field whose name is none of the given names.

- `serialization.ssz.get_generalized_index` names the SSZ fault of a path that it cannot read, with the code of `Err`, where it raised code 0 with "path: no field".
A field name that a container does not declare, or a position given for a field, is `noSuchField`, code 45; a name on a basic value is `noParts`, code 40; a name on another shape is `notAPosition`, code 22.
These are the names that the ssz-specs release v0.2.0 gives these paths.
Expand Down
32 changes: 30 additions & 2 deletions EthLib/Execution/Proofs/Rpc/Proof.lean
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ private theorem storageProofOfJson_storageProofJson {s : StorageProof}
cases hb : s.key.asBytes <;>
simp [Base.Toolchain.Json.isNull_eq, storageKeyJson, hb, quantityJson, proofNodesJson,
listJson, dataJson])
-- The writer writes the three properties of the schema, and no other.
have honly : onlyKeys "slot" storageProofKeys (Lean.Json.mkObj [
("key", storageKeyJson s.key), ("value", quantityJson s.value.toNat),
("proof", proofNodesJson s.proof)]) = .ok () :=
onlyKeys_mkObj "slot" (by simp) (by simp [storageProofKeys])
have f1 : field "slot" fs "key" = .ok (storageKeyJson s.key) :=
field_eq_ok_iff.mpr (hl "key" _ (by simp))
have f2 : field "slot" fs "value" = .ok (quantityJson s.value.toNat) :=
Expand All @@ -169,7 +174,7 @@ private theorem storageProofOfJson_storageProofJson {s : StorageProof}
field_eq_ok_iff.mpr (hl "proof" _ (by simp))
unfold storageProofOfJson
rw [storageProofJson, hfs]
simp only [bind, Except.bind, f1, f2, f3, answerKey_storageKeyJson _ hkey,
simp only [bind, Except.bind, honly, f1, f2, f3, answerKey_storageKeyJson _ hkey,
quantity_toDigits _ (bits := 256) (by simpa using s.value.isLt), proofNodes_proofNodesJson]
simp [pure, Except.pure]

Expand Down Expand Up @@ -199,6 +204,13 @@ theorem accountProofOfJson_accountProofJson {p : AccountProof} (hnonce : p.nonce
("nonce", quantityJson p.nonce), ("storageHash", dataJson p.storageHash.toList),
("storageProof", listJson storageProofJson p.storageProof)]) (by simp)
(by simp [Base.Toolchain.Json.isNull_eq, quantityJson, proofNodesJson, listJson, dataJson])
-- The writer writes the seven properties of the schema, and no other.
have honly : onlyKeys "answer" accountProofKeys (Lean.Json.mkObj [
("address", dataJson p.address.toList), ("accountProof", proofNodesJson p.accountProof),
("balance", quantityJson p.balance.toNat), ("codeHash", dataJson p.codeHash.toList),
("nonce", quantityJson p.nonce), ("storageHash", dataJson p.storageHash.toList),
("storageProof", listJson storageProofJson p.storageProof)]) = .ok () :=
onlyKeys_mkObj "answer" (by simp) (by simp [accountProofKeys])
have f1 : field "answer" fs "address" = .ok (dataJson p.address.toList) :=
field_eq_ok_iff.mpr (hl "address" _ (by simp))
have f2 : field "answer" fs "accountProof" = .ok (proofNodesJson p.accountProof) :=
Expand All @@ -215,13 +227,29 @@ theorem accountProofOfJson_accountProofJson {p : AccountProof} (hnonce : p.nonce
field_eq_ok_iff.mpr (hl "storageProof" _ (by simp))
unfold accountProofOfJson
rw [accountProofJson, hfs]
simp only [bind, Except.bind, f1, f2, f3, f4, f5, f6, f7, proofNodes_proofNodesJson,
simp only [bind, Except.bind, honly, f1, f2, f3, f4, f5, f6, f7, proofNodes_proofNodesJson,
array_storageProofOfJson _ hkeys, quantity_toDigits _ hnonce,
quantity_toDigits _ (bits := 256) (by simpa using p.balance.isLt)]
unfold dataJson
simp only [fixed_hexString, address]
simp [pure, Except.pure]

/-- A slot of an answer with a key outside the `StorageProof` schema is rejected. -/
theorem storageProofOfJson_unknown_key {kvs : Std.TreeMap.Raw String Lean.Json compare}
{name : String} {value : Lean.Json} (hmem : (name, value) ∈ kvs.toList)
(hk : name ∉ storageProofKeys) (s : StorageProof) : storageProofOfJson (.obj kvs) ≠ .ok s := by
obtain ⟨e, he⟩ := onlyKeys_rejects "slot" hmem hk
intro hs
simp [storageProofOfJson, he, bind, Except.bind] at hs

/-- An answer with a key outside the `AccountProof` schema is rejected. -/
theorem accountProofOfJson_unknown_key {kvs : Std.TreeMap.Raw String Lean.Json compare}
{name : String} {value : Lean.Json} (hmem : (name, value) ∈ kvs.toList)
(hk : name ∉ accountProofKeys) (p : AccountProof) : accountProofOfJson (.obj kvs) ≠ .ok p := by
obtain ⟨e, he⟩ := onlyKeys_rejects "answer" hmem hk
intro hp
simp [accountProofOfJson, he, bind, Except.bind] at hp

/-- The word of the storage map that the state gives is the word that the proof reads. -/
private theorem getD_storage (state : State) (a : Address) (key : Bytes32) :
(state.storage.getD a ∅).getD key 0 = state.getStorage a key := by
Expand Down
13 changes: 1 addition & 12 deletions EthLib/Execution/Proofs/Rpc/Simulate.lean
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
module

public import EthLib.Execution.Rpc.Simulate
import EthLib.Serialization.Proofs.JsonRpc

/-!

Check warning on line 6 in EthLib/Execution/Proofs/Rpc/Simulate.lean

View workflow job for this annotation

GitHub Actions / writing

Writing D1

This module or section doc has 7 lines, more than 6. Keep a title, what the module provides and its source. Move each detail to a comment above its line in the body. '# Proofs: the request of `eth_simulateV1`'
# Proofs: the request of `eth_simulateV1`

The reader rejects an unknown key, or an account override that gives both `state` and `stateDiff`.
Expand Down Expand Up @@ -30,18 +31,6 @@

/-! ## The reader -/

private theorem onlyKeys_rejects {kvs : Std.TreeMap.Raw String Json compare} {name : String}
{value : Json} {keys : List String} (what : String) (hmem : (name, value) ∈ kvs.toList)
(hk : name ∉ keys) : ∃ e, onlyKeys what keys (.obj kvs) = .error e := by
unfold onlyKeys
cases h : kvs.toList.find? fun (name, _) => !keys.contains name with
| none =>
have := List.find?_eq_none.1 h _ hmem
simp_all
| some p =>
obtain ⟨n, v⟩ := p
exact ⟨_, by simp only [h]; rfl⟩

/-- Block overrides with a key outside their schema are rejected. -/
theorem blockOverrides_unknown_key {kvs : Std.TreeMap.Raw String Json compare} {name : String}
{value : Json} (hmem : (name, value) ∈ kvs.toList) (hk : name ∉ blockOverrideKeys)
Expand Down
11 changes: 11 additions & 0 deletions EthLib/Execution/Rpc/Proof.lean
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,17 @@
def proofNodes (what : String) (j : Json) : Read (List ByteArray) :=
array what (bytes what) j

/-- The properties of the `StorageProof` schema, which allows no other. -/
def storageProofKeys : List String := ["key", "value", "proof"]

/-- The properties of the `AccountProof` schema, which allows no other. -/
def accountProofKeys : List String :=
["address", "accountProof", "balance", "codeHash", "nonce", "storageHash", "storageProof"]

/-- One slot of an answer: its key, its word and the nodes of its proof. -/
def storageProofOfJson (j : Json) : Read StorageProof := do
-- The `StorageProof` schema: `key`, `value` and `proof`, and no other property.
onlyKeys "slot" storageProofKeys j
let fs ← fields "slot" j
return ⟨← answerKey "key" (← field "slot" fs "key"),
BitVec.ofNat 256 (← quantity "value" 256 (← field "slot" fs "value")),
Expand All @@ -67,6 +76,8 @@

Its fields are those of the `AccountProof` schema. -/
def accountProofOfJson (j : Json) : Read AccountProof := do
-- The `AccountProof` schema: its seven properties, and no other property.
onlyKeys "answer" accountProofKeys j
let fs ← fields "answer" j
let field := field "answer" fs
-- The schema: an address of 20 bytes, a nonce below `2^64`, and a balance below `2^256`.
Expand Down Expand Up @@ -110,7 +121,7 @@
The source requires a node to take at least 1024 keys, and lets it limit the number above that. -/
def maxProofKeys : Nat := 1024

/-- The proof of an address and some of its slots after a block, as `eth_getProof` gives it.

Check warning on line 124 in EthLib/Execution/Rpc/Proof.lean

View workflow job for this annotation

GitHub Actions / writing

Writing D1

This declaration doc has 5 lines, more than 4. Keep what it states or returns. Move each detail to a comment above its line in the body. 'The proof of an address and some of its slots after a block, as `eth_getProof` g'

A request with more than 1024 storage keys is an invalid parameter.

Expand Down
7 changes: 0 additions & 7 deletions EthLib/Execution/Rpc/Simulate.lean
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,6 @@ def blockOverrideKeys : List String :=
def accountOverrideKeys : List String :=
["nonce", "balance", "code", "movePrecompileToAddress", "state", "stateDiff"]

/-- An object of the request that holds only the given keys, or why it does not. -/
def onlyKeys (what : String) (keys : List String) (j : Json) : Read Unit := do
let .obj kvs := j | reject s!"{what}: not an object"
match kvs.toList.find? fun (name, _) => !keys.contains name with
| some (name, _) => reject s!"{what}: unknown key {name}"
| none => pure ()

/-- Block overrides, with only the keys of their schema. -/
def blockOverrides (j : Json) : Read BlockOverrides := do
onlyKeys "blockOverrides" blockOverrideKeys j
Expand Down
15 changes: 14 additions & 1 deletion EthLib/Serialization/JsonRpc.lean
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
public import EthLib.Base.Hex
public import EthLib.Base.HexDigits

/-!

Check warning on line 8 in EthLib/Serialization/JsonRpc.lean

View workflow job for this annotation

GitHub Actions / writing

Writing D1

This module or section doc has 7 lines, more than 6. Keep a title, what the module provides and its source. Move each detail to a comment above its line in the body. '# `Serialization.JsonRpc`'
# `Serialization.JsonRpc`

The JSON form of the base types that the Engine API and the execution JSON-RPC API share.
Expand Down Expand Up @@ -157,9 +157,22 @@
-- So the same count and every expected name present suffice.
fs.length == names.length && names.all fun name => fs.any (·.1 == name)

/-- The first of a list of fields whose name is none of the names, if one is. -/
def outsideField (fs : List (String × Json)) (names : List String) : Option (String × Json) :=
fs.find? fun (name, _) => !names.contains name

/-- Whether each of a list of fields has one of the names. -/
def hasOnly (fs : List (String × Json)) (names : List String) : Bool :=
fs.all fun (name, _) => names.contains name
(outsideField fs names).isNone

/-- An object that holds only the given keys, or why it does not.

A key counts whatever its value, `null` included. -/
def onlyKeys (what : String) (keys : List String) (j : Json) : Read Unit := do
let .obj kvs := j | reject s!"{what}: not an object"
match outsideField kvs.toList keys with
| some (name, _) => reject s!"{what}: unknown key {name}"
| none => pure ()

/-- The value of a field that an object holds. -/
def field (what : String) (fs : List (String × Json)) (name : String) : Read Json :=
Expand Down
31 changes: 30 additions & 1 deletion EthLib/Serialization/Proofs/JsonRpc.lean
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,35 @@ theorem fields_mkObj (what : String) {pairs : List (String × Lean.Json)}
fun l h => h.imp_of_mem (fun {a b} _ _ hne heq => hne (by rw [heq]))
exact (List.perm_ext_iff_of_nodup (nodup _ hd) (nodup _ distinct)).mpr hmem

/-- An object with a key outside the given keys is rejected. -/
theorem onlyKeys_rejects {kvs : Std.TreeMap.Raw String Lean.Json compare} {name : String}
{value : Lean.Json} {keys : List String} (what : String) (hmem : (name, value) ∈ kvs.toList)
(hk : name ∉ keys) : ∃ e, onlyKeys what keys (.obj kvs) = .error e := by
unfold onlyKeys
cases h : outsideField kvs.toList keys with
| none =>
have := List.find?_eq_none.1 h _ hmem
simp_all
| some p =>
obtain ⟨n, v⟩ := p
exact ⟨_, by simp only [h]; rfl⟩

/-- An object of pairs with distinct names, each among the given keys, holds only those keys. -/
theorem onlyKeys_mkObj (what : String) {keys : List String} {pairs : List (String × Lean.Json)}
(distinct : pairs.Pairwise fun a b => a.1 ≠ b.1) (named : ∀ p ∈ pairs, p.1 ∈ keys) :
onlyKeys what keys (Lean.Json.mkObj pairs) = .ok () := by
obtain ⟨kvs, hobj, -, hmem, -⟩ := toList_mkObj distinct
rw [hobj]
unfold onlyKeys
dsimp only
split
-- A pair that the search finds is a pair of the list, so its name is among the keys.
· rename_i name value hfind
have hkey := List.find?_some hfind
have hin := named _ ((hmem _).mp (List.mem_of_find?_eq_some hfind))
simp_all
· rfl

/-- An object built from pairs with distinct names has the pairs that are not `null` as fields.

They may come in another order. -/
Expand Down Expand Up @@ -1332,7 +1361,7 @@ theorem nullable_optionJson {α : Type} {f : Lean.Json → Read α} {g : α →
/-- Fields that are some pairs in another order hold only the names of those pairs. -/
theorem hasOnly_of_perm {fs pairs : List (String × Lean.Json)} {names : List String}
(h : fs.Perm pairs) (hn : ∀ p ∈ pairs, p.1 ∈ names) : hasOnly fs names = true := by
simp only [hasOnly, List.all_eq_true]
simp only [hasOnly, outsideField, Option.isNone_iff_eq_none, List.find?_eq_none]
intro p hp
simpa using hn p (h.mem_iff.mp hp)

Expand Down
2 changes: 2 additions & 0 deletions SOUNDNESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3463,7 +3463,7 @@

The node's side is `AccountProof.ofState`: the answer that a state gives, with the proofs of its own tries.
For an address with no account it reads no storage, and gives the answer that the text fixes.
Each slot gives back its key in the form of the request: 32 bytes for a key of 63 or 64 hex digits, and a number otherwise.

Check warning on line 3466 in SOUNDNESS.md

View workflow job for this annotation

GitHub Actions / writing

Writing S1

This sentence has about 27 words. Consider a split if it improves clarity. 'Each slot gives back its key in the form of the request: 32 bytes for a key of 6'
`ChainView.accountProof` (`Execution/Rpc/Proof.lean`) serves it as `eth_getProof` at the block that the parameter names.
It prepares the storage trie once, and takes the proof of each slot from it.
`getProof_of_prepareProof` (`Execution/Proofs/Trie/Proof.lean`) shows that this proof is the one that `getProof` gives.
Expand All @@ -3471,7 +3471,7 @@
The method requires a node to take at least 1024 keys, and lets it limit the number above that.
So the limit of 1024 is a choice of EthLib, the least that the method allows.
`verify_ofState` (`Execution/Proofs/State/AccountProofOfState.lean`) proves completeness: the answer passes the check against the state root.
It reports the account present exactly when the state has it, and, for a present account, each slot set exactly when its word is not zero.

Check warning on line 3474 in SOUNDNESS.md

View workflow job for this annotation

GitHub Actions / writing

Writing S1

This sentence has about 26 words. Consider a split if it improves clarity. 'It reports the account present exactly when the state has it, and, for a present'
The theorem does not assume distinct key hashes.
When the answer does not pass, the search `findAnswerCollision` returns two keys with one hash.
It reads the address, the addresses of the state, the slots asked for and the storage keys of the address.
Expand All @@ -3481,6 +3481,8 @@
For an account in the state, it proves that the words are those of `eth_getStorageAt`.
`accountProof_absent` proves that for an address with no account, the answer has zero hashes and each slot the word 0 with an empty proof.
`accountProofOfJson_accountProofJson` proves that the reader reads back what the writer writes, for a nonce below `2^64` and for keys written as numbers below `16^63`.
The [`AccountProof` and `StorageProof` schemas](https://github.com/ethereum/execution-apis/blob/1ca0818569467cff85b7f41372f22e728d5daa14/src/schemas/state.yaml#L1-L63) allow no other property.
So the readers of an answer and of a slot reject an object with another key, even of value `null` (`accountProofOfJson_unknown_key`, `storageProofOfJson_unknown_key`).

### The RLPx session

Expand Down
6 changes: 5 additions & 1 deletion bindings/python/tests/trie/test_account_proof.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,10 +326,14 @@ def test_field_pattern() -> None:
({"storageProof": [dict(_SLOT, key="0x" + "1" * 65)]}, "key: more than 64 hex digits"),
({"storageProof": [dict(_SLOT, key="0xA")]}, "key: not a hex digit"),
({"storageProof": [dict(_SLOT, key="00")]}, "key: no 0x marker"),
# The AccountProof and StorageProof schemas allow no other property, even of value null.
({"extra": "0x0"}, "answer: unknown key extra"),
({"extra": None}, "answer: unknown key extra"),
({"storageProof": [dict(_SLOT, extra="0x0")]}, "slot: unknown key extra"),
],
)
def test_field_out_of_its_pattern(change: dict[str, Any], message: str) -> None:
"""Lean reads each field of the answer in the pattern of its base type, before any check."""
"""Lean reads each field in the pattern of its base type, and no other key, before any check."""
with raises(TrieError, message) as error:
trie.verify_account_proof(STATE_ROOT, {**_WITH_STORAGE, **change})
assert error.value.code == 0
Expand Down
Loading