-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
2029 lines (1896 loc) · 69.5 KB
/
index.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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {toBigIntBE, toBufferBE} from 'bigint-buffer';
import {hashAsBigInt, hashAsBuffer, HashType} from 'bigint-hash';
import {RlpDecode, RlpEncode, RlpItem, RlpList} from 'rlp-stream';
const originalNode = require('./trieNode');
const matchingNibbleLength = require('./util').matchingNibbleLength;
interface OriginalTreeNode {
value: Buffer;
type: string;
raw: Buffer[]|Buffer[][];
key: Buffer;
serialize(): Buffer;
}
/**
* An interface for a [[Witness]], which is a combination of a value and a proof
* (witnessed at a certain root)
*/
export interface Witness<V> {
/** The value mapped to the key, or null, if nothing */
value: V|null;
/**
* A proof, which consists of the list of nodes traversed to reach the node
* containing the value.
*/
proof: Array<MerklePatriciaTreeNode<V>>;
}
/**
* An interface for a RlpWitness, which is a serialized witness in RLP format.
*/
export interface RlpWitness {
/** The value mapped to the key, or null, if nothing is mapped */
value: Buffer|null;
/**
* A proof, which consists a RLP serialized list of nodes traversed to reach
* the node containing the value.
*/
proof: Buffer[];
}
/**
* A concise interface for multiple [[Witnesses]], each a combination of a value
* and proof in case of bulk reads
*/
export interface MultiWitness {
proofIndex: Buffer[];
indexedWitnesses: IndexedWitness[];
}
/**
* A concise interface for a witness, where the proof is a list of indexes
* index refers to the node at the corresponding index in a list of RLP encoded
* nodes
*/
export interface IndexedWitness {
value: Buffer|null;
proof: number[];
}
/** A search result, returned as a result for searching for a key. */
export interface SearchResult<V = Buffer> {
/** The node, if found, or null, if no node was found. */
node: MerklePatriciaTreeNode<V>|null;
/** Contains any remaining nibbles. */
remainder: number[];
/** Contains a stack of nodes encountered while traversing the tree. */
stack: Array<MerklePatriciaTreeNode<V>>;
}
/** Describes a key value pair used in a batched put operation. */
export interface BatchPut<K = Buffer, V = Buffer> {
/** The key to insert. */
key: K;
/** The value to insert */
val: V;
}
/** Returned when next() is called on a tree node */
export interface NextNode<V> {
/** Any remaining nibbles after traversing the node. */
remainingNibbles: number[];
/** The next node, or null, if no node was present. */
next: MerklePatriciaTreeNode<V>|null;
}
/** Represents an abstract node in a modified Ethereum merkle patricia tree. */
export abstract class MerklePatriciaTreeNode<V> {
/**
* The nibbles (of the key) used when traversing this node. Not present for
* branch/null nodes.
*/
abstract nibbles: number[];
/**
* The value stored in the node. Null represents value not present.
*/
abstract value: V|null;
/**
* Memoizing RLP encoding of the serialized node
*/
rlpNodeEncoding: Buffer|null = null;
/**
* Only used for batchCOW to mark nodes to be copied
*/
markForCopy = false;
/**
* Serializes and computes the RLP encoding of the node
* Also stores it for future references.
*/
getRlpNodeEncoding(options: MerklePatriciaTreeOptions<{}, V>): Buffer {
if (options.memoizeSerialization === undefined ||
options.memoizeSerialization === false) {
return RlpEncode(this.serialize(options));
}
if (this.rlpNodeEncoding === null) {
this.rlpNodeEncoding = RlpEncode(this.serialize(options));
}
return this.rlpNodeEncoding;
}
/**
* Clears the memoized RLP node encoding
*/
clearRlpNodeEncoding() {
this.rlpNodeEncoding = null;
}
/**
* Serializes and computes the RLP encoding of the node and returns
* the length of the rlp encoding of the node.
* getNodeRlpSize also stores the computed rlp encoding for future references.
*/
getNodeRlpSize(options: MerklePatriciaTreeOptions<{}, V>): number {
if (this.rlpNodeEncoding) {
return this.rlpNodeEncoding.length;
}
if (options.memoizeSerialization === undefined ||
options.memoizeSerialization === false) {
return RlpEncode(this.serialize(options)).length;
}
if (this.rlpNodeEncoding === null) {
this.rlpNodeEncoding = RlpEncode(this.serialize(options));
}
return this.rlpNodeEncoding.length;
}
/**
* Serialize the node into a buffer or an array of buffers which may be RLP
* serialized.
*/
abstract serialize(options: MerklePatriciaTreeOptions<{}, V>): RlpItem;
/** When calling toString(), sets the length of the hashes printed. */
static HUMAN_READABLE_HASH_LENGTH = 6;
/**
* When calling toString(), sets the length of the values printed. Values
* longer will be appended with ...
*/
static HUMAN_READABLE_VAL_LENGTH = 6;
private memoizedHash: bigint|null = null;
clearMemoizedHash() {
this.memoizedHash = null;
}
/**
* Return the hash for the node.
* @param rlpEncodedBuffer An optional RLP encoded buffer of the node to use
* for hashing
* @returns A Buffer containing the hash for the node.
*/
hash(
options: MerklePatriciaTreeOptions<{}, V>,
rlpEncodedBuffer: Buffer|null = null): bigint {
if (this.memoizedHash === null) {
if (rlpEncodedBuffer === null) {
rlpEncodedBuffer = this.getRlpNodeEncoding(options);
}
this.memoizedHash = hashAsBigInt(HashType.KECCAK256, rlpEncodedBuffer);
}
return this.memoizedHash!;
}
/**
* Returns nibbles remaining if this node were to be traversed.
* Only consumes the nibbles if this node is a match.
* @param nibbles Nibbles to process for traversal.
* @returns Nibbles remaining after the traversal.
*/
protected consumeNibbles(nibbles: number[]): number[] {
let sliceIndex = 0;
for (let i = 0; i < nibbles.length; i++) {
if (i > this.nibbles.length - 1 || this.nibbles[i] !== nibbles[i]) {
return nibbles; // Don't consume anything if there wasn't a match
}
sliceIndex = i + 1;
}
return (sliceIndex !== this.nibbles.length) ? nibbles :
nibbles.slice(sliceIndex);
}
/**
* Get the next node as a result of evaluating the nibbles given.
* @param nibbles The nibbles to evaluate
* @returns A [NextNode] with the remaining nibbles and the next node, if any.
*/
abstract next(nibbles: number[]): NextNode<V>;
/**
* Convert a buffer into a nibble representation.
* @param buffer The buffer to convert.
* @return An array of nibbles.
*/
static bufferToNibbles(buffer: Buffer): number[] {
// Convert to nibbles
const nibbles = [];
for (const byte of buffer) {
nibbles.push((byte & 0xF0) >> 4); // Top nibble
nibbles.push(byte & 0x0F); // Bottom nibble
}
return nibbles;
}
/**
* Return the intersecting prefix, which contains the nibbles shared by
* both n0 and n1 at the beginning of each nibble set.
*
* @param n0 The first set of nibbles
* @param n1 The second set of nibbles
*
* @returns A set of nibbles representing the intersecting prefix of both
* input sets.
*/
static intersectingPrefix(n0: number[], n1: number[]): number[] {
const prefix: number[] = [];
for (let i = 0; i < n0.length; i++) {
if (n0[i] === n1[i]) {
prefix.push(n0[i]);
} else {
return prefix;
}
}
return prefix;
}
/**
* Converts to node to a human readable hash representation. This is set to
* the last n characters in the hash, as defined by
* HUMAN_READABLE_HASH_LENGTH.
*
* @returns A human readable hash string.
*/
toReadableHash(options: MerklePatriciaTreeOptions<{}, V>): string {
const hash = this.hash(options).toString(16);
return hash.substring(
hash.length - MerklePatriciaTreeNode.HUMAN_READABLE_HASH_LENGTH);
}
/**
* Converts a value to a human readable value. This is set to the first n
* characters of the hex representation of a value, as defined by
* HUMAN_READABLE_VAL_LENGTH.
* @param val The value to convert.
* @returns A human readable value string
*/
static toReadableValue<V>(val: V): string {
let hex = (val as {} as Buffer).toString('hex');
if (hex.length > MerklePatriciaTreeNode.HUMAN_READABLE_VAL_LENGTH) {
hex = `${
hex.substring(
0, MerklePatriciaTreeNode.HUMAN_READABLE_VAL_LENGTH)}...`;
}
return hex;
}
/**
* Converts a set of nibbles to its representation as a hex string.
* @param nibbles The nibbles to convert.
* @returns The input nibbles as a hex string.
*/
static nibblesAsHex(nibbles: number[]): string {
return nibbles.map(n => n.toString(16)).join('');
}
/**
* Converts a set of nibbles and an attached prefix to its buffer
* representation.
* @param nibbles The nibbles to convert.
* @param prefix The prefix for the nibbles to convert.
*
* @returns The representation of the nibbles with the given prefix as a
* buffer.
*/
static toBuffer(nibbles: number[], prefix: number): Buffer {
// NOTE: "optional terminator is not supported"
const out = Buffer.allocUnsafe((nibbles.length / 2) + 1);
const odd = nibbles.length % 2 !== 0;
for (let i = 0; i < out.length; i++) {
// Append a prefix on the first byte
if (i === 0) {
// If there's an even number, we 0 pad
out[i] = odd ? ((prefix << 4) | nibbles[0]) : (prefix << 4);
} else {
// If we're odd, we the first nibble ended up in the prefix, so
// we need to skip 1.
const nibbleIndex = odd ? ((i - 1) * 2) + 1 : (i - 1) * 2;
out[i] = nibbles[nibbleIndex] << 4 | nibbles[nibbleIndex + 1];
}
}
return out;
}
/**
* Converts a buffer to the nibbles and prefix representation.
* @param Buffer representation of nibbles and prefix
* @returns nibbles The nibbles to convert.
* @returns prefix The prefix for the nibbles to convert.
*/
static fromBuffer(out: Buffer): {nibbles: number[], prefix: number} {
// Convert buffer into nibbles
const nibbles = this.bufferToNibbles(out);
// Get prefix and nibbles based on the first nibble
const first = nibbles[0];
if (first % 2) {
nibbles.splice(0, 1);
} else {
nibbles.splice(0, 2);
}
return {nibbles, prefix: first};
}
}
/**
* Represents a null node, which is -only- used at the root of the tree to
* represent a tree with no elements.
*/
export class NullNode<V> extends MerklePatriciaTreeNode<V> {
/** A null node always has no nibbles. */
readonly nibbles = [];
/** The value of a null node cannot be set. */
set value(val: V) {
throw new Error('Attempted to set the value of a NullNode');
}
/** The hash of a null node is always the empty hash. */
hash() {
return BigInt(
'0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421');
}
/** The serialized version of a null node is always the empty buffer. */
serialize() {
return Buffer.from([]);
}
/** Traversing a null node always yields nothing. */
next(nibbles: number[]) {
return {remainingNibbles: nibbles, next: null};
}
/** Returns the string representation of this null node. */
toString() {
return '[NullNode]';
}
}
/**
* Represents a branch node in the tree. A branch node contains 16 branches,
* one for each hex character, and may also act as a "leaf" node by containing a
* value.
*/
export class BranchNode<V> extends MerklePatriciaTreeNode<V> {
/** A branch node has no nibbles to be set. */
readonly nibbles: number[] = [];
/** The value this branch holds, initially unset. */
value: V|null = null;
/** An array of branches this tree node holds. */
branches: Array<MerklePatriciaTreeNode<V>> =
new Array<MerklePatriciaTreeNode<V>>(16);
/**
* Checks if the last nibble will result in the given branch.
* This is only the case if the given branch is a LeafNode/BranchNode AND
* (1) if a LeafNode, it has no nibbles
* (2) if a BranchNode, it has a value
* (3) There is only one nibble remaining
*
* @param nibbles The input set of nibbles
* @param branch The branch to check
*
* @returns True, if the last nibble will not result in the given branch.
*/
private static lastNibbleNoMatch<N>(
nibbles: number[], branch: MerklePatriciaTreeNode<N>): boolean {
return nibbles.length === 1 &&
((branch instanceof LeafNode && branch.nibbles.length > 0) ||
(branch instanceof BranchNode && branch.value === null) ||
branch instanceof ExtensionNode || branch instanceof NullNode);
}
/**
* @inheritdoc
*/
next(nibbles: number[]) {
if (nibbles.length === 0) {
return {next: null, remainingNibbles: nibbles};
}
const branch = this.branches[nibbles[0]];
if (branch === undefined || BranchNode.lastNibbleNoMatch(nibbles, branch)) {
// Nothing in this branch, or last nibble and branch doesn't match
return {next: null, remainingNibbles: nibbles};
} else {
// Return the branch
return {next: branch, remainingNibbles: nibbles.slice(1)};
}
}
/**
* Returns the string representation of this node.
*
* @returns The string representation of this node.
*/
toString(options?: MerklePatriciaTreeOptions<{}, V>) {
let outString =
`(${options === undefined ? '?' : this.toReadableHash(options)})`;
for (const [idx, branch] of this.branches.entries()) {
if (branch !== undefined) {
outString += ` ${idx.toString(16)}: ${
options === undefined ? '?' : branch.toReadableHash(options)}`;
}
}
if (this.value !== null) {
outString +=
` val: ${MerklePatriciaTreeNode.toReadableValue(this.value)}`;
}
return `[branch ${outString}]`;
}
/**
* @inheritdoc
*/
serialize(options: MerklePatriciaTreeOptions<{}, V>) {
const hashedBranches: RlpItem = [];
for (const [idx, branch] of this.branches.entries()) {
if (branch === undefined) {
hashedBranches[idx] = Buffer.from([]);
} else if (branch instanceof HashNode) {
hashedBranches[idx] = toBufferBE(branch.nodeHash, 32);
} else if (
branch instanceof BranchNode || (branch.nibbles.length / 2) > 30) {
// Will be >32 when RLP serialized, so just hash
hashedBranches[idx] =
toBufferBE((branch as MerklePatriciaTreeNode<V>).hash(options), 32);
} else {
const serialized = branch.serialize(options);
const rlpEncoded = branch.getRlpNodeEncoding(options);
hashedBranches[idx] = (rlpEncoded.length >= 32) ?
toBufferBE(
branch.hash(options, rlpEncoded),
32) : // Non-embedded node
serialized; // Embedded node in branch
}
}
hashedBranches.push(
this.value === null ? Buffer.from([]) :
options.valueConverter!(this.value));
return hashedBranches;
}
}
/**
* Represents an extension node, which "consumes" a set of nibbles and points to
* another node.
*/
export class ExtensionNode<V> extends MerklePatriciaTreeNode<V> {
/** Extension nodes never contain a value. */
readonly value: null = null;
/** The prefix when the number of nibbles in the extension node is odd. */
static PREFIX_EXTENSION_ODD = 1;
/** The prefix when the number of nibbles in the extension node is even. */
static PREFIX_EXTENSION_EVEN = 0;
/**
* Return the prefix for this extension node.
* @returns The prefix for the node.
*/
get prefix() {
return this.nibbles.length % 2 === 0 ? ExtensionNode.PREFIX_EXTENSION_EVEN :
ExtensionNode.PREFIX_EXTENSION_ODD;
}
/**
* @inheritdoc
*/
next(nibbles: number[]) {
const intersection =
MerklePatriciaTreeNode.intersectingPrefix(nibbles, this.nibbles);
if (intersection.length === this.nibbles.length) {
return {
next: this.nextNode,
remainingNibbles: nibbles.slice(intersection.length)
};
} else {
return {next: null, remainingNibbles: nibbles};
}
}
/**
* Construct a new extension node.
* @param nibbles The nibbles that will be consumed when this node is
* traversed.
* @param nextNode The node that this node points to.
*/
constructor(
public nibbles: number[], public nextNode: MerklePatriciaTreeNode<V>) {
super();
if (nibbles.length === 0) {
throw new Error('Extension branch cannot have 0 nibbles');
}
}
/** @inheritdoc */
serialize(options: MerklePatriciaTreeOptions<{}, V>) {
let serialized: RlpItem;
if (this.nextNode instanceof HashNode) {
serialized = toBufferBE(this.nextNode.nodeHash, 32);
} else {
serialized = this.nextNode!.serialize(options);
}
const rlpEncodeNextNode = this.nextNode!.getRlpNodeEncoding(options);
return [
MerklePatriciaTreeNode.toBuffer(this.nibbles, this.prefix),
rlpEncodeNextNode.length >= 32 ?
toBufferBE(this.nextNode!.hash(options), 32) :
serialized
];
}
/**
* Returns the string representation of this node.
*
* @returns The string representation of this node.
*/
toString(options?: MerklePatriciaTreeOptions<{}, V>) {
const outString =
`(${options === undefined ? '?' : this.toReadableHash(options)}) -(${
MerklePatriciaTreeNode.nibblesAsHex(this.nibbles)})-> ${
options === undefined ? '?' :
this.nextNode.toReadableHash(options)}`;
return `[extension ${outString}]`;
}
}
/**
* Represents a leaf node, which are terminal nodes in the tree which holds
* values.
*/
export class LeafNode<V> extends MerklePatriciaTreeNode<V> {
/** The prefix of the leaf node if the number of nibbles is odd */
private static PREFIX_LEAF_ODD = 3;
/** The prefix of the leaf node if the number of nibbles is even. */
private static PREFIX_LEAF_EVEN = 2;
/**
* Constructs a new leaf node with the given nibbles and value.
* @param nibbles The nibbles consumed by the leaf node.
* @param value The value held in the leaf node.
*/
constructor(public nibbles: number[], public value: V) {
super();
}
/** Returns the prefix for this leaf node. */
get prefix() {
return this.nibbles.length % 2 === 0 ? LeafNode.PREFIX_LEAF_EVEN :
LeafNode.PREFIX_LEAF_ODD;
}
/** @inheritdoc */
next(nibbles: number[]) {
return {remainingNibbles: this.consumeNibbles(nibbles), next: null};
}
/** @inheritdoc */
serialize(options: MerklePatriciaTreeOptions<{}, V>) {
return [
MerklePatriciaTreeNode.toBuffer(this.nibbles, this.prefix),
options.valueConverter!(this.value)
];
}
/**
* Returns the string representation of this node.
*
* @returns The string representation of this node.
*/
toString(options: MerklePatriciaTreeOptions<{}, V>) {
const outString =
`(${options === undefined ? '?' : this.toReadableHash(options)}) -(${
MerklePatriciaTreeNode.nibblesAsHex(this.nibbles)})-> val: ${
MerklePatriciaTreeNode.toReadableValue(this.value)}`;
return `[leaf ${outString}]`;
}
}
/**
* Represents a hash node, which is -only- used for pruning the
* CachedMerklePatriciaTreeNode to maxCacheDepth.
*/
export class HashNode<V> extends MerklePatriciaTreeNode<V> {
/** A hash node always has no nibbles. */
readonly nibbles = [];
/** nodeHash stores the hash of the current node. */
nodeHash: bigint;
/** The serialized version of a hash node. */
serialization: RlpItem|null = null;
/** The value of a hash node cannot be set. */
set value(val: V) {
throw new Error('Attempted to set the value of a NullNode');
}
constructor(hash: bigint, serialization?: RlpItem) {
super();
this.nodeHash = hash;
if (serialization) {
this.serialization = serialization;
}
}
/** The hash of a hash node returned. */
hash() {
return this.nodeHash;
}
serialize(): RlpItem {
if (!this.serialization) {
throw new Error('Cannot serialize HashNode');
}
return this.serialization;
}
/** Traversing a hash node always yields nothing. */
next(nibbles: number[]) {
return {remainingNibbles: nibbles, next: null};
}
/** Returns the string representation of this null node. */
toString() {
return `[HashNode ${this.nodeHash}]`;
}
}
/** The interface for a merkle tree. */
export interface MerkleTree<K, V> {
/** The root hash of the tree. */
root: Buffer;
/**
* The root hash of the tree, as a bigint. Reading this property is more
* efficient than obtaining a buffer.
*/
rootHash: bigint;
/**
* Insert a new mapping into the tree. If the key is already mapped in the
* tree, it is updated with the new value.
*
* @param key The key to insert.
* @param val A Buffer representing the value.
*
*/
put: (key: K, val: V) => void;
/**
* Given a key, retrieve a [[Witness]] for the mapping.
*
* @param key The key to retrieve the [[Witness]] for.
*
* @returns A [[Witness]], with a proof of the value read (or a null
* value, with a proof of the value's nonexistence).
*/
get: (key: K) => Witness<V>;
/**
* Given a key, delete any mapping that exists for that key.
*
* @param key The key to unmap.
*
*/
del: (key: K) => void;
/**
* Execute a batch of put and delete operations. The execution is batched,
* so calling this function with multiple updates provides more opportunities
* for optimization and can be faster than call put() and del() multiple
* times.
*
* @param putOps An array of put operations on the tree, of type
* [[BatchPut]].
* @param delOps An optional array of keys to delete from the tree.
*
* @returns The root that results from this set of operations.
*/
batch: (putOps: Array<BatchPut<K, V>>, delOps?: K[]) => Buffer;
/**
* Search for the given key, returning a [[SearchResult]] which contains the
* path traversed to search for the key.
*
* @param key The key to search for.
* @returns A [[SearchResult]] containing the path to the key, and the
* value if it was present.
*/
search: (key: K) => SearchResult<V>;
}
/** Configuration for a merkle tree. */
export interface MerklePatriciaTreeOptions<K, V> {
/** A function which converts keys to the native type of the tree. */
keyConverter?: (key: K) => Buffer;
/** A function which converts values to the native type of the tree */
valueConverter?: (val: V) => Buffer;
/**
* Whether a put with an empty value can delete a node. Note that turning
* this on will require serialization at insert time.
*/
putCanDelete: boolean;
/**
* Whether or not to memoize serializations or not. If true, serializations
* will be memoized, which will increase the speed of proof generation at
* the cost of increased memory overhead.
*/
memoizeSerialization?: boolean;
}
/** A Merkle Patricia Tree, as defined in the Ethereum Yellow Paper. */
export class MerklePatriciaTree<K = Buffer, V = Buffer> implements
MerkleTree<K, V> {
/** The root node of the tree. */
rootNode: MerklePatriciaTreeNode<V>;
/**
* A Buffer representing the root hash of the tree. Always 256-bits (32
* bytes).
*/
get root(): Buffer {
return toBufferBE(
this.rootNode.hash(
this.options as {} as MerklePatriciaTreeOptions<{}, V>),
32);
}
/**
* The root hash of the tree, as a bigint. Reading this property is more
* efficient than obtaining a buffer.
*/
get rootHash(): bigint {
return this.rootNode.hash(
this.options as {} as MerklePatriciaTreeOptions<{}, V>);
}
/** Construct a new Merkle Patricia Tree. */
constructor(public options: MerklePatriciaTreeOptions<K, V> = {
putCanDelete: true
}) {
if (options.valueConverter === undefined) {
options.valueConverter = (v) => v as {} as Buffer;
}
if (options.keyConverter === undefined) {
options.keyConverter = (k) => k as {} as Buffer;
}
this.rootNode = new NullNode<V>();
}
/**
* Insert a new mapping into the tree. If the key is already mapped in the
* tree, it is updated with the new value.
*
* @param key The key to insert.
* @param val A Buffer representing the value.
*
*/
put(key: K, val: V) {
const convKey = this.options.keyConverter!(key);
if (convKey.length === 0) {
throw new Error('Empty key is not supported');
}
if (this.options.putCanDelete &&
this.options.valueConverter!(val).length === 0) {
this.del(key);
return;
}
if (this.rootNode instanceof NullNode) {
// Null node, so insert this value as a leaf.
this.rootNode =
new LeafNode(MerklePatriciaTreeNode.bufferToNibbles(convKey), val);
} else {
// search
const result = this.search(key);
if (result.remainder.length === 0 && result.node !== null) {
// Matches, update the value.
result.node!.value = val;
} else {
// Doesn't match, perform tree insertion using stack
this.insert(result.stack, result.remainder, val);
}
// Clear all memoized hashes in the path, they will be reset.
for (const node of result.stack) {
node.clearMemoizedHash();
node.clearRlpNodeEncoding();
}
}
}
/**
* Copies only the node; leaving its successors the same
* @param node : Node for copy
*/
getNodeCopy(node: MerklePatriciaTreeNode<V>): MerklePatriciaTreeNode<V> {
if (node instanceof BranchNode) {
const copyNode = new BranchNode<V>();
for (const nib of node.nibbles) {
copyNode.nibbles.push(nib);
}
for (let i = 0; i < node.branches.length; i++) {
copyNode.branches[i] = node.branches[i];
}
if (node.value) {
copyNode.value = node.value.slice(0);
}
return copyNode;
} else if (node instanceof ExtensionNode) {
const copyNode = new ExtensionNode<V>(node.nibbles, node.nextNode);
return copyNode;
} else if (node instanceof LeafNode) {
const copyNode = new LeafNode<V>(node.nibbles, node.value);
return copyNode;
} else if (node instanceof HashNode) {
const nodeSerialization =
(node.serialization) ? node.serialization : undefined;
const copyNode = new HashNode<V>(node.nodeHash, nodeSerialization);
return copyNode;
}
return new NullNode<V>();
}
/**
* CopyTreePaths
* Copies paths that are marked for copy
*/
copyTreePaths(
node1: MerklePatriciaTreeNode<V>,
node2: MerklePatriciaTreeNode<V>): MerklePatriciaTreeNode<V> {
if (node1.markForCopy) {
node2 = this.getNodeCopy(node1);
if (node1 instanceof BranchNode && node2 instanceof BranchNode) {
for (let branchIdx = 0; branchIdx < node1.branches.length;
branchIdx += 1) {
if (node1.branches[branchIdx]) {
node2.branches[branchIdx] = this.copyTreePaths(
node1.branches[branchIdx], node2.branches[branchIdx]);
}
}
} else if (
node1 instanceof ExtensionNode && node2 instanceof ExtensionNode) {
node2.nextNode = this.copyTreePaths(node1.nextNode, node2.nextNode);
} else if (
node1 instanceof HashNode && node2 instanceof HashNode ||
node1 instanceof LeafNode && node2 instanceof LeafNode ||
node1 instanceof NullNode && node2 instanceof NullNode) {
return node2;
} else {
throw new Error('Unexpected node type while copying nodes');
}
}
return node2;
}
/**
* multiSearch searches the tree for all keys and marks nodes for copy
* @param putOps : List of key, value pairs
* @param delOps : List of keys
* @param flag : True if we want to mark the nodes for copy
*/
multiSearch(putOps: Array<BatchPut<K, V>>, delOps: K[], flag: boolean) {
for (const put of putOps) {
this.search(put.key, flag);
}
for (const key of delOps) {
this.search(key, flag);
}
}
/**
* Insert a node with the given value after a search.
* @param stack The stack as a result of the search
* @param remainder The remainder as a result of the search
* @param value The value to insert.
*/
insert(
stack: Array<MerklePatriciaTreeNode<V>>, remainder: number[], value: V) {
const last = stack[stack.length - 1];
if (remainder.length === 0) {
last.value = value;
} else {
if (last instanceof BranchNode) {
// Insert into branch
if (last.branches[remainder[0]] !== undefined) {
// Branch occupied. Create new branch
const branch = new BranchNode();
const prevNode = last.branches[remainder[0]];
if (remainder.length === 1) {
branch.value = value;
} else {
branch.branches[remainder[1]] =
new LeafNode(remainder.slice(2), value);
}
if (prevNode instanceof LeafNode) {
if (prevNode.nibbles.length === 0) {
branch.value = value;
} else {
branch.branches[prevNode.nibbles[0]] =
new LeafNode(prevNode.nibbles.slice(1), prevNode.value);
}
} else if (prevNode instanceof ExtensionNode) {
branch.branches[prevNode.nibbles[0]] = prevNode;
prevNode.nibbles = prevNode.nibbles.slice(1);
} else if (prevNode instanceof BranchNode) {
throw new Error('Unexpected branch node in occupied branch');
}
last.branches[remainder[0]] = branch;
} else {
last.branches[remainder[0]] = new LeafNode(remainder.slice(1), value);
}
} else if (last instanceof ExtensionNode) {
// We will be shrinking this extension node and inserting a branch
const intersection =
MerklePatriciaTreeNode.intersectingPrefix(remainder, last.nibbles);
const prevNibbles = last.nibbles;
let prevNext = last.nextNode;
const branch = new BranchNode<V>();
// The intersection is now the extension
last.nibbles = intersection;
last.nextNode = branch;
// And update the branch according to what type was previously in the
// extension
if (prevNext instanceof LeafNode) {
// If leaf node, update the key for the leaf node
prevNext.nibbles =
prevNibbles.slice(intersection.length).concat(prevNext.nibbles);
} else if (prevNext instanceof BranchNode) {
if (prevNibbles.length > intersection.length + 1) {
// Otherwise, if branch node and the remainder is > 1, create an
// extension
const extension = new ExtensionNode(
prevNibbles.slice(intersection.length + 1), prevNext);
prevNext = extension;
}
}
// And insert both the new value and prevNext into the branch
branch.branches[prevNibbles[intersection.length]] = prevNext;
if (intersection.length === remainder.length) {
// Goes in as value
branch.value = value;
} else if (intersection.length >= remainder.length) {
// Unexpected, intersection is longer than remainder
throw new Error('Unexpected remainder longer than intersection');
} else {
// Insert new value
branch.branches[remainder[intersection.length]] =
new LeafNode<V>(remainder.slice(intersection.length + 1), value);
}
// If the intersection is 0, then eliminate the extension.
if (intersection.length === 0) {
// Remove the extension
if (stack.length === 1) {
this.rootNode = branch;
} else {
const prevNode = stack[stack.length - 2];
if (prevNode instanceof BranchNode) {
for (const [idx, prevBranch] of prevNode.branches.entries()) {
if (prevBranch === last) {
prevNode.branches[idx] = branch;