-
Notifications
You must be signed in to change notification settings - Fork 746
/
range.ts
525 lines (462 loc) · 16 KB
/
range.ts
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import { equalsBytes } from '@ethereumjs/util'
import { createTrieFromProof } from '../index.js'
import { BranchNode, ExtensionNode, LeafNode } from '../node/index.js'
import { Trie } from '../trie.js'
import { nibblesCompare, nibblesTypeToPackedBytes } from '../util/nibbles.js'
import type { HashKeysFunction, Nibbles, TrieNode } from '../types.js'
// reference: https://github.com/ethereum/go-ethereum/blob/20356e57b119b4e70ce47665a71964434e15200d/trie/proof.go
/**
* unset will remove all nodes to the left or right of the target key(decided by `removeLeft`).
* @param trie - trie object.
* @param parent - parent node, it can be `null`.
* @param child - child node.
* @param key - target nibbles.
* @param pos - key position.
* @param removeLeft - remove all nodes to the left or right of the target key.
* @param stack - a stack of modified nodes.
* @returns The end position of key.
*/
async function unset(
trie: Trie,
parent: TrieNode,
child: TrieNode | null,
key: Nibbles,
pos: number,
removeLeft: boolean,
stack: TrieNode[],
): Promise<number> {
if (child instanceof BranchNode) {
/**
* This node is a branch node,
* remove all branches on the left or right
*/
if (removeLeft) {
for (let i = 0; i < key[pos]; i++) {
child.setBranch(i, null)
}
} else {
for (let i = key[pos] + 1; i < 16; i++) {
child.setBranch(i, null)
}
}
// record this node on the stack
stack.push(child)
// continue to the next node
const next = child.getBranch(key[pos])
const _child = next && (await trie.lookupNode(next))
return unset(trie, child, _child, key, pos + 1, removeLeft, stack)
} else if (child instanceof ExtensionNode || child instanceof LeafNode) {
/**
* This node is an extension node or lead node,
* if node._nibbles is less or greater than the target key,
* remove self from parent
*/
if (
key.length - pos < child.keyLength() ||
nibblesCompare(child._nibbles, key.slice(pos, pos + child.keyLength())) !== 0
) {
if (removeLeft) {
if (nibblesCompare(child._nibbles, key.slice(pos)) < 0) {
;(parent as BranchNode).setBranch(key[pos - 1], null)
}
} else {
if (nibblesCompare(child._nibbles, key.slice(pos)) > 0) {
;(parent as BranchNode).setBranch(key[pos - 1], null)
}
}
return pos - 1
}
if (child instanceof LeafNode) {
// This node is a leaf node, directly remove it from parent
;(parent as BranchNode).setBranch(key[pos - 1], null)
return pos - 1
} else {
const _child = await trie.lookupNode(child.value())
if (_child instanceof LeafNode) {
// The child of this node is leaf node, remove it from parent too
;(parent as BranchNode).setBranch(key[pos - 1], null)
return pos - 1
}
// record this node on the stack
stack.push(child)
// continue to the next node
return unset(trie, child, _child, key, pos + child.keyLength(), removeLeft, stack)
}
} else if (child === null) {
return pos - 1
} else {
throw new Error('invalid node')
}
}
/**
* unsetInternal will remove all nodes between `left` and `right` (including `left` and `right`)
* @param trie - trie object.
* @param left - left nibbles.
* @param right - right nibbles.
* @returns Is it an empty trie.
*/
async function unsetInternal(trie: Trie, left: Nibbles, right: Nibbles): Promise<boolean> {
// Key position
let pos = 0
// Parent node
let parent: TrieNode | null = null
// Current node
let node: TrieNode | null = await trie.lookupNode(trie.root())
let shortForkLeft!: number
let shortForkRight!: number
// A stack of modified nodes.
const stack: TrieNode[] = []
// 1. Find the fork point of `left` and `right`
// eslint-disable-next-line no-constant-condition
while (true) {
if (node instanceof ExtensionNode || node instanceof LeafNode) {
// record this node on the stack
stack.push(node)
if (left.length - pos < node.keyLength()) {
shortForkLeft = nibblesCompare(left.slice(pos), node._nibbles)
} else {
shortForkLeft = nibblesCompare(left.slice(pos, pos + node.keyLength()), node._nibbles)
}
if (right.length - pos < node.keyLength()) {
shortForkRight = nibblesCompare(right.slice(pos), node._nibbles)
} else {
shortForkRight = nibblesCompare(right.slice(pos, pos + node.keyLength()), node._nibbles)
}
// If one of `left` and `right` is not equal to node._nibbles, it means we found the fork point
if (shortForkLeft !== 0 || shortForkRight !== 0) {
break
}
if (node instanceof LeafNode) {
// it shouldn't happen
throw new Error('invalid node')
}
// continue to the next node
parent = node
pos += node.keyLength()
node = await trie.lookupNode(node.value())
} else if (node instanceof BranchNode) {
// record this node on the stack
stack.push(node)
const leftNode = node.getBranch(left[pos])
const rightNode = node.getBranch(right[pos])
// One of `left` and `right` is `null`, stop searching
if (leftNode === null || rightNode === null) {
break
}
// Stop searching if `left` and `right` are not equal
if (!(leftNode instanceof Uint8Array)) {
if (rightNode instanceof Uint8Array) {
break
}
if (leftNode.length !== rightNode.length) {
break
}
let abort = false
for (let i = 0; i < leftNode.length; i++) {
if (!equalsBytes(leftNode[i], rightNode[i])) {
abort = true
break
}
}
if (abort) {
break
}
} else {
if (!(rightNode instanceof Uint8Array)) {
break
}
if (!equalsBytes(leftNode, rightNode)) {
break
}
}
// continue to the next node
parent = node
node = await trie.lookupNode(leftNode)
pos += 1
} else {
throw new Error('invalid node')
}
}
// 2. Starting from the fork point, delete all nodes between `left` and `right`
const saveStack = (key: Nibbles, stack: TrieNode[]) => {
return trie.saveStack(key, stack, [])
}
if (node instanceof ExtensionNode || node instanceof LeafNode) {
/**
* There can have these five scenarios:
* - both proofs are less than the trie path => no valid range
* - both proofs are greater than the trie path => no valid range
* - left proof is less and right proof is greater => valid range, unset the entire trie
* - left proof points to the trie node, but right proof is greater => valid range, unset left node
* - right proof points to the trie node, but left proof is less => valid range, unset right node
*/
const removeSelfFromParentAndSaveStack = async (key: Nibbles) => {
if (parent === null) {
return true
}
stack.pop()
;(parent as BranchNode).setBranch(key[pos - 1], null)
await saveStack(key.slice(0, pos - 1), stack)
return false
}
if (shortForkLeft === -1 && shortForkRight === -1) {
throw new Error('invalid range')
}
if (shortForkLeft === 1 && shortForkRight === 1) {
throw new Error('invalid range')
}
if (shortForkLeft !== 0 && shortForkRight !== 0) {
// Unset the entire trie
return removeSelfFromParentAndSaveStack(left)
}
// Unset left node
if (shortForkRight !== 0) {
if (node instanceof LeafNode) {
return removeSelfFromParentAndSaveStack(left)
}
const child = await trie.lookupNode(node._value)
if (child instanceof LeafNode) {
return removeSelfFromParentAndSaveStack(left)
}
const endPos = await unset(trie, node, child, left.slice(pos), node.keyLength(), false, stack)
await saveStack(left.slice(0, pos + endPos), stack)
return false
}
// Unset right node
if (shortForkLeft !== 0) {
if (node instanceof LeafNode) {
return removeSelfFromParentAndSaveStack(right)
}
const child = await trie.lookupNode(node._value)
if (child instanceof LeafNode) {
return removeSelfFromParentAndSaveStack(right)
}
const endPos = await unset(trie, node, child, right.slice(pos), node.keyLength(), true, stack)
await saveStack(right.slice(0, pos + endPos), stack)
return false
}
return false
} else if (node instanceof BranchNode) {
// Unset all internal nodes in the forkPoint
for (let i = left[pos] + 1; i < right[pos]; i++) {
node.setBranch(i, null)
}
{
/**
* `stack` records the path from root to fork point.
* Since we need to unset both left and right nodes once,
* we need to make a copy here.
*/
const _stack = [...stack]
const next = node.getBranch(left[pos])
const child = next && (await trie.lookupNode(next))
const endPos = await unset(trie, node, child, left.slice(pos), 1, false, _stack)
await saveStack(left.slice(0, pos + endPos), _stack)
}
{
const _stack = [...stack]
const next = node.getBranch(right[pos])
const child = next && (await trie.lookupNode(next))
const endPos = await unset(trie, node, child, right.slice(pos), 1, true, _stack)
await saveStack(right.slice(0, pos + endPos), _stack)
}
return false
} else {
throw new Error('invalid node')
}
}
/**
* Verifies a proof and return the verified trie.
* @param rootHash - root hash.
* @param key - target key.
* @param proof - proof node list.
* @throws If proof is found to be invalid.
* @returns The value from the key, or null if valid proof of non-existence.
*/
async function verifyMerkleProof(
rootHash: Uint8Array,
key: Uint8Array,
proof: Uint8Array[],
useKeyHashingFunction: HashKeysFunction,
): Promise<{ value: Uint8Array | null; trie: Trie }> {
const proofTrie = await createTrieFromProof(proof, {
root: rootHash,
useKeyHashingFunction,
})
try {
const value = await proofTrie.get(key, true)
return {
trie: proofTrie,
value,
}
} catch (err: any) {
if (err.message === 'Missing node in DB') {
throw new Error('Invalid proof provided')
} else {
throw err
}
}
}
/**
* hasRightElement returns the indicator whether there exists more elements
* on the right side of the given path
* @param trie - trie object.
* @param key - given path.
*/
async function hasRightElement(trie: Trie, key: Nibbles): Promise<boolean> {
let pos = 0
let node: TrieNode | null = await trie.lookupNode(trie.root())
while (node !== null) {
if (node instanceof BranchNode) {
for (let i = key[pos] + 1; i < 16; i++) {
if (node.getBranch(i) !== null) {
return true
}
}
const next = node.getBranch(key[pos])
node = next && (await trie.lookupNode(next))
pos += 1
} else if (node instanceof ExtensionNode) {
if (
key.length - pos < node.keyLength() ||
nibblesCompare(node._nibbles, key.slice(pos, pos + node.keyLength())) !== 0
) {
return nibblesCompare(node._nibbles, key.slice(pos)) > 0
}
pos += node.keyLength()
node = await trie.lookupNode(node._value)
} else if (node instanceof LeafNode) {
return false
} else {
throw new Error('invalid node')
}
}
return false
}
/**
* verifyRangeProof checks whether the given leaf nodes and edge proof
* can prove the given trie leaves range is matched with the specific root.
*
* There are four situations:
*
* - All elements proof. In this case the proof can be null, but the range should
* be all the leaves in the trie.
*
* - One element proof. In this case no matter the edge proof is a non-existent
* proof or not, we can always verify the correctness of the proof.
*
* - Zero element proof. In this case a single non-existent proof is enough to prove.
* Besides, if there are still some other leaves available on the right side, then
* an error will be returned.
*
* - Two edge elements proof. In this case two existent or non-existent proof(first and last) should be provided.
*
* NOTE: Currently only supports verification when the length of firstKey and lastKey are the same.
*
* @param rootHash - root hash of state trie this proof is being verified against.
* @param firstKey - first key of range being proven.
* @param lastKey - last key of range being proven.
* @param keys - key list of leaf data being proven.
* @param values - value list of leaf data being proven, one-to-one correspondence with keys.
* @param proof - proof node list, if all-elements-proof where no proof is needed, proof should be null, and both `firstKey` and `lastKey` must be null as well
* @returns a flag to indicate whether there exists more trie node in the trie
*/
export async function verifyRangeProof(
rootHash: Uint8Array,
firstKey: Nibbles | null,
lastKey: Nibbles | null,
keys: Nibbles[],
values: Uint8Array[],
proof: Uint8Array[] | null,
useKeyHashingFunction: HashKeysFunction,
): Promise<boolean> {
if (keys.length !== values.length) {
throw new Error('invalid keys length or values length')
}
// Make sure the keys are in order
for (let i = 0; i < keys.length - 1; i++) {
if (nibblesCompare(keys[i], keys[i + 1]) >= 0) {
throw new Error('invalid keys order')
}
}
// Make sure all values are present
for (const value of values) {
if (value.length === 0) {
throw new Error('invalid values')
}
}
// All elements proof
if (proof === null && firstKey === null && lastKey === null) {
const trie = new Trie({ useKeyHashingFunction })
for (let i = 0; i < keys.length; i++) {
await trie.put(nibblesTypeToPackedBytes(keys[i]), values[i])
}
if (!equalsBytes(rootHash, trie.root())) {
throw new Error('invalid all elements proof: root mismatch')
}
return false
}
if (proof !== null && firstKey !== null && lastKey === null) {
// Zero element proof
if (keys.length === 0) {
const { trie, value } = await verifyMerkleProof(
rootHash,
nibblesTypeToPackedBytes(firstKey),
proof,
useKeyHashingFunction,
)
if (value !== null || (await hasRightElement(trie, firstKey))) {
throw new Error('invalid zero element proof: value mismatch')
}
return false
}
}
if (proof === null || firstKey === null || lastKey === null) {
throw new Error(
'invalid all elements proof: proof, firstKey, lastKey must be null at the same time',
)
}
// One element proof
if (keys.length === 1 && nibblesCompare(firstKey, lastKey) === 0) {
const { trie, value } = await verifyMerkleProof(
rootHash,
nibblesTypeToPackedBytes(firstKey),
proof,
useKeyHashingFunction,
)
if (nibblesCompare(firstKey, keys[0]) !== 0) {
throw new Error('invalid one element proof: firstKey should be equal to keys[0]')
}
if (value === null || !equalsBytes(value, values[0])) {
throw new Error('invalid one element proof: value mismatch')
}
return hasRightElement(trie, firstKey)
}
// Two edge elements proof
if (nibblesCompare(firstKey, lastKey) >= 0) {
throw new Error('invalid two edge elements proof: firstKey should be less than lastKey')
}
if (firstKey.length !== lastKey.length) {
throw new Error(
'invalid two edge elements proof: the length of firstKey should be equal to the length of lastKey',
)
}
const trie = await createTrieFromProof(proof, {
useKeyHashingFunction,
root: rootHash,
})
// Remove all nodes between two edge proofs
const empty = await unsetInternal(trie, firstKey, lastKey)
if (empty) {
trie.root(trie.EMPTY_TRIE_ROOT)
}
// Put all elements to the trie
for (let i = 0; i < keys.length; i++) {
await trie.put(nibblesTypeToPackedBytes(keys[i]), values[i])
}
// Compare rootHash
if (!equalsBytes(trie.root(), rootHash)) {
throw new Error('invalid two edge elements proof: root mismatch')
}
return hasRightElement(trie, keys[keys.length - 1])
}