-
Notifications
You must be signed in to change notification settings - Fork 578
/
merkletree.ts
690 lines (592 loc) · 21.6 KB
/
merkletree.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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import { Assert } from '../assert'
import { JsonSerializable } from '../serde'
import {
DatabaseKey,
IDatabase,
IDatabaseStore,
IDatabaseTransaction,
JsonEncoding,
NumberEncoding,
SchemaValue,
} from '../storage'
import { LeafEncoding, NodeEncoding } from './encoding'
import { MerkleHasher } from './hasher'
import { CounterSchema, LeavesIndexSchema, LeavesSchema, NodesSchema } from './schema'
import { depthAtLeafCount, isEmpty, isRight } from './utils'
import { Witness, WitnessNode } from './witness'
export class MerkleTree<
E,
H extends DatabaseKey,
SE extends JsonSerializable,
SH extends JsonSerializable,
> {
readonly hasher: MerkleHasher<E, H, SE, SH>
readonly db: IDatabase
readonly name: string = ''
readonly depth: number = 32
readonly counter: IDatabaseStore<CounterSchema>
readonly leaves: IDatabaseStore<LeavesSchema<E, H>>
readonly leavesIndex: IDatabaseStore<LeavesIndexSchema<H>>
readonly nodes: IDatabaseStore<NodesSchema<H>>
constructor({
hasher,
db,
name = '',
depth = 32,
}: {
hasher: MerkleHasher<E, H, SE, SH>
db: IDatabase
name?: string
depth?: number
}) {
this.hasher = hasher
this.db = db
this.name = name
this.depth = depth
this.counter = db.addStore({
name: `${name}c`,
keyEncoding: new JsonEncoding<CounterSchema['key']>(),
valueEncoding: new JsonEncoding<CounterSchema['value']>(),
})
this.leaves = db.addStore({
name: `${name}l`,
keyEncoding: new JsonEncoding<LeavesSchema<E, H>['key']>(),
valueEncoding: new LeafEncoding<E, H, SE, SH>(hasher),
})
this.leavesIndex = db.addStore({
name: `${name}i`,
keyEncoding: new JsonEncoding<LeavesIndexSchema<H>['key']>(),
valueEncoding: new NumberEncoding(),
})
this.nodes = db.addStore({
name: `${name}n`,
keyEncoding: new JsonEncoding<NodesSchema<H>['key']>(),
valueEncoding: new NodeEncoding(hasher),
})
}
async upgrade(): Promise<void> {
if ((await this.counter.get('Leaves')) === undefined) {
await this.counter.put('Leaves', 0)
}
if ((await this.counter.get('Nodes')) === undefined) {
await this.counter.put('Nodes', 1)
}
}
/**
* Get the number of leaf nodes (elements) in the tree.
*/
async size(tx?: IDatabaseTransaction): Promise<number> {
return await this.db.withTransaction(tx, async (tx) => {
const value = await this.counter.get('Leaves', tx)
if (value === undefined) {
throw new Error(`No counter record found for tree ${this.name}`)
}
return value
})
}
/**
* Get the leaf element at the given index. Throws an error if the
* index is not in bounds.
*/
async get(position: LeafIndex, tx?: IDatabaseTransaction): Promise<E> {
return (await this.getLeaf(position, tx)).element
}
/**
* Get the leaf element at the given index. Throws an error if the
* index is not in bounds.
*/
async getLeaf(
index: LeafIndex,
tx?: IDatabaseTransaction,
): Promise<SchemaValue<LeavesSchema<E, H>>> {
const leaf = await this.getLeafOrNull(index, tx)
if (!leaf) {
throw new Error(`No leaf found in tree ${this.name} at index ${index}`)
}
return leaf
}
/**
* Get the leaf element at the given index. Returns null if the
* index is not in bounds.
*/
async getLeafOrNull(
index: LeafIndex,
tx?: IDatabaseTransaction,
): Promise<SchemaValue<LeavesSchema<E, H>> | null> {
return await this.db.withTransaction(tx, async (tx) => {
const leaf = await this.leaves.get(index, tx)
return leaf || null
})
}
/**
* Get the node element at the given index. Throws an error if the
* index is not in bounds.
*/
async getNode(
index: NodeIndex,
tx?: IDatabaseTransaction,
): Promise<SchemaValue<NodesSchema<H>>> {
const node = await this.getNodeOrNull(index, tx)
if (!node) {
throw new Error(`No node found in tree ${this.name} at index ${index}`)
}
return node
}
/**
* Get the node element at the given index. Returns null if the
* index is not in bounds.
*/
async getNodeOrNull(
index: NodeIndex,
tx?: IDatabaseTransaction,
): Promise<SchemaValue<NodesSchema<H>> | null> {
const node = await this.nodes.get(index, tx)
return node || null
}
/**
* Get the count of a given tree. Throws an error if the
* count is not in the store.
*/
async getCount(countType: 'Leaves' | 'Nodes', tx?: IDatabaseTransaction): Promise<LeafIndex> {
const count = await this.counter.get(countType, tx)
if (count === undefined) {
throw new Error(`No counts found in tree ${this.name} for type ${countType}`)
}
return count
}
/** Iterate over all notes in the tree. This happens asynchronously
* and behaviour is undefined if the tree changes while iterating.
*/
async *notes(tx?: IDatabaseTransaction): AsyncGenerator<E, void, unknown> {
const numLeaves = await this.size(tx)
for (let index = 0; index < numLeaves; index++) {
const leaf = await this.getLeafOrNull(index, tx)
if (leaf === null) {
return
}
yield leaf.element
}
}
/**
* Add the new leaf element into the tree, and update all hashes.
*/
async add(element: E, tx?: IDatabaseTransaction): Promise<void> {
await this.db.withTransaction(tx, async (tx) => {
const merkleHash = this.hasher.merkleHash(element)
const indexOfNewLeaf = await this.getCount('Leaves', tx)
let newParentIndex: NodeIndex
if (indexOfNewLeaf === 0) {
// Special case where this is the first leaf, with no parent
newParentIndex = 0
} else if (indexOfNewLeaf === 1) {
// Special case where this is the second leaf, and both leaves need a new parent
newParentIndex = 1
const leftLeafIndex = 0
const leftLeaf = await this.getLeaf(leftLeafIndex, tx)
const hashOfSibling = this.hasher.combineHash(0, leftLeaf.merkleHash, merkleHash)
await this.nodes.put(
newParentIndex,
{
side: Side.Left,
parentIndex: 0,
hashOfSibling,
index: newParentIndex,
},
tx,
)
await this.addLeaf(
leftLeafIndex,
{
element: leftLeaf.element,
merkleHash: leftLeaf.merkleHash,
parentIndex: newParentIndex,
index: leftLeafIndex,
},
tx,
)
await this.counter.put('Nodes', 2, tx)
} else if (isRight(indexOfNewLeaf)) {
// Simple case where we are adding a new node to a parent with an empty right child
const leftLeafIndex = indexOfNewLeaf - 1
const leaf = await this.getLeaf(leftLeafIndex, tx)
newParentIndex = leaf.parentIndex
} else {
// Walk up the path from the previous leaf until finding an empty or right-hand node
// Create a bunch of left-hand nodes for each step up that path
const previousLeafIndex = indexOfNewLeaf - 1
const previousLeaf = await this.getLeaf(previousLeafIndex, tx)
let previousParentIndex = previousLeaf.parentIndex
let nextNodeIndex = await this.getCount('Nodes', tx)
let myHash = this.hasher.combineHash(0, merkleHash, merkleHash)
let depth = 1
let shouldContinue = true
newParentIndex = nextNodeIndex
while (shouldContinue) {
const previousParent = await this.getNode(previousParentIndex, tx)
if (previousParent.side === Side.Left) {
// found a node we can attach a child too; hook it up to the new chain of left nodes
const newNode = {
side: Side.Right,
leftIndex: previousParentIndex,
hashOfSibling: previousParent.hashOfSibling,
index: nextNodeIndex,
}
await this.nodes.put(nextNodeIndex, newNode, tx)
nextNodeIndex += 1
await this.counter.put('Nodes', nextNodeIndex, tx)
if (!previousParent.parentIndex || isEmpty(previousParent.parentIndex)) {
const newParent = {
side: Side.Left,
parentIndex: 0,
hashOfSibling: this.hasher.combineHash(
depth,
previousParent.hashOfSibling,
myHash,
),
index: nextNodeIndex,
}
await this.nodes.put(nextNodeIndex, newParent, tx)
await this.nodes.put(
previousParentIndex,
{
side: Side.Left,
hashOfSibling: previousParent.hashOfSibling,
parentIndex: nextNodeIndex,
index: previousParentIndex,
},
tx,
)
nextNodeIndex += 1
await this.counter.put('Nodes', nextNodeIndex, tx)
}
shouldContinue = false
} else {
// previous parent is a right node, gotta go up a step
myHash = this.hasher.combineHash(depth, myHash, myHash)
if (previousParent.leftIndex === undefined) {
throw new Error(`Parent has no left sibling`)
}
const leftSibling = await this.getNode(previousParent.leftIndex, tx)
if (leftSibling.parentIndex === undefined) {
throw new Error(`Left sibling has no parent`)
}
const leftSiblingParentIndex = leftSibling.parentIndex
const newNode = {
side: Side.Left,
parentIndex: nextNodeIndex + 1, // where the next node will be (in the next iteration)
hashOfSibling: myHash,
index: nextNodeIndex,
}
await this.nodes.put(nextNodeIndex, newNode, tx)
nextNodeIndex += 1
await this.counter.put('Nodes', nextNodeIndex, tx)
previousParentIndex = leftSiblingParentIndex
depth += 1
}
}
}
await this.counter.put('Leaves', indexOfNewLeaf + 1, tx)
await this.addLeaf(
indexOfNewLeaf,
{
element,
merkleHash,
parentIndex: newParentIndex,
index: indexOfNewLeaf,
},
tx,
)
await this.rehashRightPath(tx)
})
}
async addLeaf(
index: LeafIndex,
value: { index: LeafIndex; element: E; merkleHash: H; parentIndex: NodeIndex },
tx?: IDatabaseTransaction,
): Promise<void> {
await this.leaves.put(
index,
{
index: index,
element: value.element,
merkleHash: value.merkleHash,
parentIndex: value.parentIndex,
},
tx,
)
await this.leavesIndex.put(this.hasher.merkleHash(value.element), index, tx)
}
/**
* Truncate the tree to the values it contained when it contained pastSize
* elements.
*
* After calling, it will contain at most pastSize elements, but truncating
* to a size that is higher than this.length is a no-op.
*
* This function doesn't do any garbage collection. The old leaves and nodes
* are still in the database, but they will be overwritten as the new tree
* grows.
*/
async truncate(pastSize: number, tx?: IDatabaseTransaction): Promise<void> {
return await this.db.withTransaction(tx, async (tx) => {
const oldSize = await this.getCount('Leaves', tx)
if (pastSize >= oldSize) {
return
}
await this.counter.put('Leaves', pastSize, tx)
if (pastSize === 0) {
await this.counter.put('Nodes', 1, tx)
return
}
if (pastSize === 1) {
await this.counter.put('Nodes', 1, tx)
const firstLeaf = await this.getLeaf(0, tx)
firstLeaf.parentIndex = 0
await this.addLeaf(firstLeaf.index, firstLeaf, tx)
return
}
const depth = depthAtLeafCount(pastSize) - 2
const leaf = await this.getLeaf(pastSize - 1, tx)
let parentIndex = leaf.parentIndex
let maxParentIndex = parentIndex
for (let i = 0; i < depth; i++) {
let parent = await this.getNode(parentIndex, tx)
if (parent.side === Side.Right) {
Assert.isNotUndefined(parent.leftIndex)
parent = await this.getNode(parent.leftIndex, tx)
}
Assert.isNotUndefined(parent.parentIndex)
parentIndex = parent.parentIndex
if (parent.parentIndex > maxParentIndex) {
maxParentIndex = parent.parentIndex
}
}
const parent = await this.getNode(parentIndex, tx)
if (parent.side === Side.Right) {
// Indicates error in this method's code
throw new Error('Expected new root node to be a left node')
}
parent.parentIndex = 0
await this.nodes.put(parent.index, parent, tx)
await this.counter.put('Nodes', maxParentIndex + 1, tx)
await this.rehashRightPath(tx)
})
}
/**
* Calculate what the root hash was at the time the tree contained
* `pastSize` elements. Throws an error if the tree is empty,
* the request size is greater than the size of the tree, or the requested
* size is 0
*/
async pastRoot(pastSize: number, tx?: IDatabaseTransaction): Promise<H> {
return this.db.withTransaction(tx, async (tx) => {
const leafCount = await this.getCount('Leaves', tx)
if (leafCount === 0 || pastSize > leafCount || pastSize === 0) {
throw new Error(`Unable to get past size ${pastSize} for tree with ${leafCount} nodes`)
}
const rootDepth = depthAtLeafCount(pastSize)
const minTreeDepth = Math.min(rootDepth, this.depth)
const leafIndex = pastSize - 1
const leaf = await this.getLeaf(leafIndex, tx)
let currentHash = leaf.merkleHash
let currentNodeIndex = leaf.parentIndex
if (isRight(leafIndex)) {
const sibling = await this.getLeaf(leafIndex - 1, tx)
const siblingHash = sibling.merkleHash
currentHash = this.hasher.combineHash(0, siblingHash, currentHash)
} else {
currentHash = this.hasher.combineHash(0, currentHash, currentHash)
}
for (let depth = 1; depth < minTreeDepth; depth++) {
const node = await this.getNode(currentNodeIndex, tx)
switch (node.side) {
case Side.Left:
Assert.isNotUndefined(node.parentIndex)
currentNodeIndex = node.parentIndex
currentHash = this.hasher.combineHash(depth, currentHash, currentHash)
break
case Side.Right: {
Assert.isNotUndefined(node.leftIndex)
const leftNode = await this.getNode(node.leftIndex, tx)
Assert.isNotUndefined(leftNode.parentIndex)
currentNodeIndex = leftNode.parentIndex
currentHash = this.hasher.combineHash(depth, node.hashOfSibling, currentHash)
break
}
default:
Assert.isUnreachable(node.side)
}
}
for (let depth = rootDepth; depth < this.depth; depth++) {
currentHash = this.hasher.combineHash(depth, currentHash, currentHash)
}
return currentHash
})
}
/**
* Get the root hash of the tree. Throws an error if the tree is empty.
*/
async rootHash(tx?: IDatabaseTransaction): Promise<H> {
const size = await this.size(tx)
return await this.pastRoot(size, tx)
}
/**
* Check if the tree contained the given element when it was the given size.
*/
private async contained(
value: E,
pastSize: number,
tx?: IDatabaseTransaction,
): Promise<boolean> {
return this.db.withTransaction(tx, async (tx) => {
const elementIndex = await this.leavesIndex.get(this.hasher.merkleHash(value), tx)
return elementIndex !== undefined && elementIndex < pastSize
})
}
/**
* Check if the tree currently contains the given element.
*/
async contains(value: E, tx?: IDatabaseTransaction): Promise<boolean> {
return await this.contained(value, await this.size(), tx)
}
/**
* Construct the proof that the leaf node at `position` exists.
*
* The length of the returned vector is the depth of the leaf node in the tree
*
* The leftmost value in the vector, the hash at index 0, is the hash of the
* leaf node's sibling. The rightmost value in the vector contains the hash of
* sibling of the child of the root node.
*
* The root hash is not included in the authentication path.
*
* returns null if there are no leaves or the position is not in the list.
*/
async witness(
index: LeafIndex,
tx?: IDatabaseTransaction,
): Promise<Witness<E, H, SE, SH> | null> {
return this.db.withTransaction(tx, async (tx) => {
const authenticationPath: WitnessNode<H>[] = []
const leafCount = await this.size(tx)
if (leafCount === 0 || index >= leafCount) {
return null
}
const leaf = await this.getLeaf(index, tx)
let currentHash = leaf.merkleHash
let currentPosition = leaf.parentIndex as NodeIndex | undefined
if (isRight(index)) {
const hashOfSibling = (await this.getLeaf(index - 1, tx)).merkleHash
authenticationPath.push({ side: Side.Right, hashOfSibling })
currentHash = this.hasher.combineHash(0, hashOfSibling, currentHash)
} else if (index < leafCount - 1) {
// Left leaf and have a right sibling
const hashOfSibling = (await this.getLeaf(index + 1, tx)).merkleHash
authenticationPath.push({ side: Side.Left, hashOfSibling })
currentHash = this.hasher.combineHash(0, currentHash, hashOfSibling)
} else {
// Left leaf and rightmost node
authenticationPath.push({ side: Side.Left, hashOfSibling: currentHash })
currentHash = this.hasher.combineHash(0, currentHash, currentHash)
}
for (let depth = 1; depth < this.depth; depth++) {
const node =
currentPosition !== undefined ? await this.getNodeOrNull(currentPosition, tx) : null
if (node === null) {
authenticationPath.push({ side: Side.Left, hashOfSibling: currentHash })
currentHash = this.hasher.combineHash(depth, currentHash, currentHash)
} else if (node.side === Side.Left) {
authenticationPath.push({ side: Side.Left, hashOfSibling: node.hashOfSibling })
currentHash = this.hasher.combineHash(depth, currentHash, node.hashOfSibling)
currentPosition = node.parentIndex
} else {
authenticationPath.push({ side: Side.Right, hashOfSibling: node.hashOfSibling })
currentHash = this.hasher.combineHash(depth, node.hashOfSibling, currentHash)
Assert.isNotUndefined(node.leftIndex)
const leftSibling = await this.getNode(node.leftIndex, tx)
currentPosition = leftSibling.parentIndex
}
}
return new Witness(leafCount, currentHash, authenticationPath, this.hasher)
})
}
/**
* Recalculate all the hashes between the most recently added leaf in the group
* and the root hash.
*
* `transaction` is passed in so that a rollback happens for the entire change
* if a conflict occurs.
*/
private async rehashRightPath(tx: IDatabaseTransaction) {
let depth = 0
const leafIndex = (await this.getCount('Leaves', tx)) - 1
const leaf = await this.getLeaf(leafIndex, tx)
let parentIndex = leaf.parentIndex as NodeIndex | undefined
const leafHash = leaf.merkleHash
let parentHash
if (isRight(leafIndex)) {
const leftSiblingIndex = leafIndex - 1
const leftSibling = await this.getLeaf(leftSiblingIndex, tx)
const leftSiblingHash = leftSibling.merkleHash
parentHash = this.hasher.combineHash(depth, leftSiblingHash, leafHash)
} else {
parentHash = this.hasher.combineHash(depth, leafHash, leafHash)
}
while (!isEmpty(parentIndex)) {
const node = await this.getNode(parentIndex, tx)
depth += 1
switch (node.side) {
case Side.Left: {
// Since we are walking the rightmost path, left nodes do not
// have right children. Therefore its sibling hash is set to its
// own hash and its parent hash is set to the combination of that hash
// with itself
await this.nodes.put(
parentIndex,
{
side: Side.Left,
hashOfSibling: parentHash,
parentIndex: node.parentIndex,
index: parentIndex,
},
tx,
)
parentIndex = node.parentIndex
parentHash = this.hasher.combineHash(depth, parentHash, parentHash)
break
}
case Side.Right: {
// since this is a new right node, we know that we have the correct
// hash because we set it correctly when we inserted it. But the left
// node needs to have its hashOfSibling set to our current hash.
if (node.leftIndex === undefined) {
throw new Error(`Expected node ${node.index} to have left node`)
}
const leftNode = await this.getNode(node.leftIndex, tx)
await this.nodes.put(
node.leftIndex,
{
side: Side.Left,
parentIndex: leftNode.parentIndex,
hashOfSibling: parentHash,
index: node.leftIndex,
},
tx,
)
parentIndex = leftNode.parentIndex
parentHash = this.hasher.combineHash(depth, node.hashOfSibling, parentHash)
break
}
}
}
}
}
export enum Side {
Left = 'Left',
Right = 'Right',
}
export type LeafIndex = number
export type NodeIndex = number