forked from ledgerwatch/erigon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin_patricia_hashed.go
1818 lines (1712 loc) · 53.9 KB
/
bin_patricia_hashed.go
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
/*
Copyright 2022 The Erigon contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package commitment
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"math/bits"
"github.com/holiman/uint256"
"github.com/ledgerwatch/log/v3"
"golang.org/x/crypto/sha3"
"github.com/tenderly/erigon/erigon-lib/common"
"github.com/tenderly/erigon/erigon-lib/common/length"
"github.com/tenderly/erigon/erigon-lib/rlp"
)
const (
maxKeySize = 512
halfKeySize = maxKeySize / 2
maxChild = 2
)
type bitstring []uint8
// converts slice of nibbles (lowest 4 bits of each byte) to bitstring
func hexToBin(hex []byte) bitstring {
bin := make([]byte, 4*len(hex))
for i := range bin {
if hex[i/4]&(1<<(3-i%4)) != 0 {
bin[i] = 1
}
}
return bin
}
// encodes bitstring to its compact representation
func binToCompact(bin []byte) []byte {
compact := make([]byte, 2+common.BitLenToByteLen(len(bin)))
binary.BigEndian.PutUint16(compact, uint16(len(bin)))
for i := 0; i < len(bin); i++ {
if bin[i] != 0 {
compact[2+i/8] |= byte(1) << (i % 8)
}
}
return compact
}
// decodes compact bitstring representation into actual bitstring
func compactToBin(compact []byte) []byte {
bin := make([]byte, binary.BigEndian.Uint16(compact))
for i := 0; i < len(bin); i++ {
if compact[2+i/8]&(byte(1)<<(i%8)) == 0 {
bin[i] = 0
} else {
bin[i] = 1
}
}
return bin
}
// BinHashed implements commitment based on patricia merkle tree with radix 16,
// with keys pre-hashed by keccak256
type BinPatriciaHashed struct {
root BinaryCell // Root cell of the tree
// Rows of the grid correspond to the level of depth in the patricia tree
// Columns of the grid correspond to pointers to the nodes further from the root
grid [maxKeySize][maxChild]BinaryCell // First halfKeySize rows of this grid are for account trie, and next halfKeySize rows are for storage trie
// How many rows (starting from row 0) are currently active and have corresponding selected columns
// Last active row does not have selected column
activeRows int
// Length of the key that reflects current positioning of the grid. It maybe larger than number of active rows,
// if a account leaf cell represents multiple nibbles in the key
currentKeyLen int
currentKey [maxKeySize]byte // For each row indicates which column is currently selected
depths [maxKeySize]int // For each row, the depth of cells in that row
rootChecked bool // Set to false if it is not known whether the root is empty, set to true if it is checked
rootTouched bool
rootPresent bool
branchBefore [maxKeySize]bool // For each row, whether there was a branch node in the database loaded in unfold
touchMap [maxKeySize]uint16 // For each row, bitmap of cells that were either present before modification, or modified or deleted
afterMap [maxKeySize]uint16 // For each row, bitmap of cells that were present after modification
keccak keccakState
keccak2 keccakState
accountKeyLen int
trace bool
hashAuxBuffer [maxKeySize]byte // buffer to compute cell hash or write hash-related things
auxBuffer *bytes.Buffer // auxiliary buffer used during branch updates encoding
// Function used to load branch node and fill up the cells
// For each cell, it sets the cell type, clears the modified flag, fills the hash,
// and for the extension, account, and leaf type, the `l` and `k`
branchFn func(prefix []byte) ([]byte, error)
// Function used to fetch account with given plain key
accountFn func(plainKey []byte, cell *BinaryCell) error
// Function used to fetch account with given plain key
storageFn func(plainKey []byte, cell *BinaryCell) error
}
func NewBinPatriciaHashed(accountKeyLen int,
branchFn func(prefix []byte) ([]byte, error),
accountFn func(plainKey []byte, cell *Cell) error,
storageFn func(plainKey []byte, cell *Cell) error,
) *BinPatriciaHashed {
return &BinPatriciaHashed{
keccak: sha3.NewLegacyKeccak256().(keccakState),
keccak2: sha3.NewLegacyKeccak256().(keccakState),
accountKeyLen: accountKeyLen,
branchFn: branchFn,
accountFn: wrapAccountStorageFn(accountFn),
storageFn: wrapAccountStorageFn(storageFn),
auxBuffer: bytes.NewBuffer(make([]byte, 8192)),
}
}
type BinaryCell struct {
h [length.Hash]byte // cell hash
hl int // Length of the hash (or embedded)
apk [length.Addr]byte // account plain key
apl int // length of account plain key
spk [length.Addr + length.Hash]byte // storage plain key
spl int // length of the storage plain key
downHashedKey [maxKeySize]byte
downHashedLen int
extension [halfKeySize]byte
extLen int
Nonce uint64
Balance uint256.Int
CodeHash [length.Hash]byte // hash of the bytecode
Storage [length.Hash]byte
StorageLen int
Delete bool
}
func (cell *BinaryCell) unwrapToHexCell() (cl *Cell) {
cl = new(Cell)
cl.Balance = *cell.Balance.Clone()
cl.Nonce = cell.Nonce
cl.StorageLen = cell.StorageLen
cl.apl = cell.apl
cl.spl = cell.spl
cl.hl = cell.hl
copy(cl.apk[:], cell.apk[:])
copy(cl.spk[:], cell.spk[:])
copy(cl.h[:], cell.h[:])
if cell.extLen > 0 {
compactedExt := binToCompact(cell.extension[:cell.extLen])
copy(cl.extension[:], compactedExt)
cl.extLen = len(compactedExt)
}
if cell.downHashedLen > 0 {
compactedDHK := binToCompact(cell.downHashedKey[:cell.downHashedLen])
copy(cl.downHashedKey[:], compactedDHK)
cl.downHashedLen = len(compactedDHK)
}
copy(cl.CodeHash[:], cell.CodeHash[:])
copy(cl.Storage[:], cell.Storage[:])
cl.Delete = cell.Delete
return cl
}
var ( // TODO REEAVL
EmptyBinRootHash, _ = hex.DecodeString("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
EmptyBinCodeHash, _ = hex.DecodeString("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
)
func (cell *BinaryCell) fillEmpty() {
cell.apl = 0
cell.spl = 0
cell.downHashedLen = 0
cell.extLen = 0
cell.hl = 0
cell.Nonce = 0
cell.Balance.Clear()
copy(cell.CodeHash[:], EmptyCodeHash)
cell.StorageLen = 0
cell.Delete = false
}
func (cell *BinaryCell) fillFromUpperCell(upBinaryCell *BinaryCell, depth, depthIncrement int) {
if upBinaryCell.downHashedLen >= depthIncrement {
cell.downHashedLen = upBinaryCell.downHashedLen - depthIncrement
} else {
cell.downHashedLen = 0
}
if upBinaryCell.downHashedLen > depthIncrement {
copy(cell.downHashedKey[:], upBinaryCell.downHashedKey[depthIncrement:upBinaryCell.downHashedLen])
}
if upBinaryCell.extLen >= depthIncrement {
cell.extLen = upBinaryCell.extLen - depthIncrement
} else {
cell.extLen = 0
}
if upBinaryCell.extLen > depthIncrement {
copy(cell.extension[:], upBinaryCell.extension[depthIncrement:upBinaryCell.extLen])
}
if depth <= halfKeySize {
cell.apl = upBinaryCell.apl
if upBinaryCell.apl > 0 {
copy(cell.apk[:], upBinaryCell.apk[:cell.apl])
cell.Balance.Set(&upBinaryCell.Balance)
cell.Nonce = upBinaryCell.Nonce
copy(cell.CodeHash[:], upBinaryCell.CodeHash[:])
cell.extLen = upBinaryCell.extLen
if upBinaryCell.extLen > 0 {
copy(cell.extension[:], upBinaryCell.extension[:upBinaryCell.extLen])
}
}
} else {
cell.apl = 0
}
cell.spl = upBinaryCell.spl
if upBinaryCell.spl > 0 {
copy(cell.spk[:], upBinaryCell.spk[:upBinaryCell.spl])
cell.StorageLen = upBinaryCell.StorageLen
if upBinaryCell.StorageLen > 0 {
copy(cell.Storage[:], upBinaryCell.Storage[:upBinaryCell.StorageLen])
}
}
cell.hl = upBinaryCell.hl
if upBinaryCell.hl > 0 {
copy(cell.h[:], upBinaryCell.h[:upBinaryCell.hl])
}
}
func (cell *BinaryCell) fillFromLowerBinaryCell(lowBinaryCell *BinaryCell, lowDepth int, preExtension []byte, nibble int) {
if lowBinaryCell.apl > 0 || lowDepth < halfKeySize {
cell.apl = lowBinaryCell.apl
}
if lowBinaryCell.apl > 0 {
copy(cell.apk[:], lowBinaryCell.apk[:cell.apl])
cell.Balance.Set(&lowBinaryCell.Balance)
cell.Nonce = lowBinaryCell.Nonce
copy(cell.CodeHash[:], lowBinaryCell.CodeHash[:])
}
cell.spl = lowBinaryCell.spl
if lowBinaryCell.spl > 0 {
copy(cell.spk[:], lowBinaryCell.spk[:cell.spl])
cell.StorageLen = lowBinaryCell.StorageLen
if lowBinaryCell.StorageLen > 0 {
copy(cell.Storage[:], lowBinaryCell.Storage[:lowBinaryCell.StorageLen])
}
}
if lowBinaryCell.hl > 0 {
if (lowBinaryCell.apl == 0 && lowDepth < halfKeySize) || (lowBinaryCell.spl == 0 && lowDepth > halfKeySize) {
// Extension is related to either accounts branch node, or storage branch node, we prepend it by preExtension | nibble
if len(preExtension) > 0 {
copy(cell.extension[:], preExtension)
}
cell.extension[len(preExtension)] = byte(nibble)
if lowBinaryCell.extLen > 0 {
copy(cell.extension[1+len(preExtension):], lowBinaryCell.extension[:lowBinaryCell.extLen])
}
cell.extLen = lowBinaryCell.extLen + 1 + len(preExtension)
} else {
// Extension is related to a storage branch node, so we copy it upwards as is
cell.extLen = lowBinaryCell.extLen
if lowBinaryCell.extLen > 0 {
copy(cell.extension[:], lowBinaryCell.extension[:lowBinaryCell.extLen])
}
}
}
cell.hl = lowBinaryCell.hl
if lowBinaryCell.hl > 0 {
copy(cell.h[:], lowBinaryCell.h[:lowBinaryCell.hl])
}
}
func (cell *BinaryCell) deriveHashedKeys(depth int, keccak keccakState, accountKeyLen int) error {
extraLen := 0
if cell.apl > 0 {
if depth > halfKeySize {
return fmt.Errorf("deriveHashedKeys accountPlainKey present at depth > halfKeySize")
}
extraLen = halfKeySize - depth
}
if cell.spl > 0 {
if depth >= halfKeySize {
extraLen = maxKeySize - depth
} else {
extraLen += halfKeySize
}
}
if extraLen > 0 {
if cell.downHashedLen > 0 {
copy(cell.downHashedKey[extraLen:], cell.downHashedKey[:cell.downHashedLen])
}
cell.downHashedLen += extraLen
var hashedKeyOffset, downOffset int
if cell.apl > 0 {
if err := binHashKey(keccak, cell.apk[:cell.apl], cell.downHashedKey[:], depth); err != nil {
return err
}
downOffset = halfKeySize - depth
}
if cell.spl > 0 {
if depth >= halfKeySize {
hashedKeyOffset = depth - halfKeySize
}
if err := binHashKey(keccak, cell.spk[accountKeyLen:cell.spl], cell.downHashedKey[downOffset:], hashedKeyOffset); err != nil {
return err
}
}
}
return nil
}
func (cell *BinaryCell) fillFromFields(data []byte, pos int, fieldBits PartFlags) (int, error) {
if fieldBits&HashedKeyPart != 0 {
l, n := binary.Uvarint(data[pos:])
if n == 0 {
return 0, fmt.Errorf("fillFromFields buffer too small for hashedKey len")
} else if n < 0 {
return 0, fmt.Errorf("fillFromFields value overflow for hashedKey len")
}
pos += n
if len(data) < pos+int(l) {
return 0, fmt.Errorf("fillFromFields buffer too small for hashedKey exp %d got %d", pos+int(l), len(data))
}
cell.downHashedLen = int(l)
cell.extLen = int(l)
if l > 0 {
copy(cell.downHashedKey[:], data[pos:pos+int(l)])
copy(cell.extension[:], data[pos:pos+int(l)])
pos += int(l)
}
} else {
cell.downHashedLen = 0
cell.extLen = 0
}
if fieldBits&AccountPlainPart != 0 {
l, n := binary.Uvarint(data[pos:])
if n == 0 {
return 0, fmt.Errorf("fillFromFields buffer too small for accountPlainKey len")
} else if n < 0 {
return 0, fmt.Errorf("fillFromFields value overflow for accountPlainKey len")
}
pos += n
if len(data) < pos+int(l) {
return 0, fmt.Errorf("fillFromFields buffer too small for accountPlainKey")
}
cell.apl = int(l)
if l > 0 {
copy(cell.apk[:], data[pos:pos+int(l)])
pos += int(l)
}
} else {
cell.apl = 0
}
if fieldBits&StoragePlainPart != 0 {
l, n := binary.Uvarint(data[pos:])
if n == 0 {
return 0, fmt.Errorf("fillFromFields buffer too small for storagePlainKey len")
} else if n < 0 {
return 0, fmt.Errorf("fillFromFields value overflow for storagePlainKey len")
}
pos += n
if len(data) < pos+int(l) {
return 0, fmt.Errorf("fillFromFields buffer too small for storagePlainKey")
}
cell.spl = int(l)
if l > 0 {
copy(cell.spk[:], data[pos:pos+int(l)])
pos += int(l)
}
} else {
cell.spl = 0
}
if fieldBits&HashPart != 0 {
l, n := binary.Uvarint(data[pos:])
if n == 0 {
return 0, fmt.Errorf("fillFromFields buffer too small for hash len")
} else if n < 0 {
return 0, fmt.Errorf("fillFromFields value overflow for hash len")
}
pos += n
if len(data) < pos+int(l) {
return 0, fmt.Errorf("fillFromFields buffer too small for hash")
}
cell.hl = int(l)
if l > 0 {
copy(cell.h[:], data[pos:pos+int(l)])
pos += int(l)
}
} else {
cell.hl = 0
}
return pos, nil
}
func (cell *BinaryCell) setStorage(value []byte) {
cell.StorageLen = len(value)
if len(value) > 0 {
copy(cell.Storage[:], value)
}
}
func (cell *BinaryCell) setAccountFields(codeHash []byte, balance *uint256.Int, nonce uint64) {
copy(cell.CodeHash[:], codeHash)
cell.Balance.SetBytes(balance.Bytes())
cell.Nonce = nonce
}
func (cell *BinaryCell) accountForHashing(buffer []byte, storageRootHash [length.Hash]byte) int {
balanceBytes := 0
if !cell.Balance.LtUint64(128) {
balanceBytes = cell.Balance.ByteLen()
}
var nonceBytes int
if cell.Nonce < 128 && cell.Nonce != 0 {
nonceBytes = 0
} else {
nonceBytes = common.BitLenToByteLen(bits.Len64(cell.Nonce))
}
var structLength = uint(balanceBytes + nonceBytes + 2)
structLength += 66 // Two 32-byte arrays + 2 prefixes
var pos int
if structLength < 56 {
buffer[0] = byte(192 + structLength)
pos = 1
} else {
lengthBytes := common.BitLenToByteLen(bits.Len(structLength))
buffer[0] = byte(247 + lengthBytes)
for i := lengthBytes; i > 0; i-- {
buffer[i] = byte(structLength)
structLength >>= 8
}
pos = lengthBytes + 1
}
// Encoding nonce
if cell.Nonce < 128 && cell.Nonce != 0 {
buffer[pos] = byte(cell.Nonce)
} else {
buffer[pos] = byte(128 + nonceBytes)
var nonce = cell.Nonce
for i := nonceBytes; i > 0; i-- {
buffer[pos+i] = byte(nonce)
nonce >>= 8
}
}
pos += 1 + nonceBytes
// Encoding balance
if cell.Balance.LtUint64(128) && !cell.Balance.IsZero() {
buffer[pos] = byte(cell.Balance.Uint64())
pos++
} else {
buffer[pos] = byte(128 + balanceBytes)
pos++
cell.Balance.WriteToSlice(buffer[pos : pos+balanceBytes])
pos += balanceBytes
}
// Encoding Root and CodeHash
buffer[pos] = 128 + 32
pos++
copy(buffer[pos:], storageRootHash[:])
pos += 32
buffer[pos] = 128 + 32
pos++
copy(buffer[pos:], cell.CodeHash[:])
pos += 32
return pos
}
func (bph *BinPatriciaHashed) completeLeafHash(buf, keyPrefix []byte, kp, kl, compactLen int, key []byte, compact0 byte, ni int, val rlp.RlpSerializable, singleton bool) ([]byte, error) {
totalLen := kp + kl + val.DoubleRLPLen()
var lenPrefix [4]byte
pt := rlp.GenerateStructLen(lenPrefix[:], totalLen)
embedded := !singleton && totalLen+pt < length.Hash
var writer io.Writer
if embedded {
//bph.byteArrayWriter.Setup(buf)
bph.auxBuffer.Reset()
writer = bph.auxBuffer
} else {
bph.keccak.Reset()
writer = bph.keccak
}
if _, err := writer.Write(lenPrefix[:pt]); err != nil {
return nil, err
}
if _, err := writer.Write(keyPrefix[:kp]); err != nil {
return nil, err
}
var b [1]byte
b[0] = compact0
if _, err := writer.Write(b[:]); err != nil {
return nil, err
}
for i := 1; i < compactLen; i++ {
b[0] = key[ni]*16 + key[ni+1]
if _, err := writer.Write(b[:]); err != nil {
return nil, err
}
ni += 2
}
var prefixBuf [8]byte
if err := val.ToDoubleRLP(writer, prefixBuf[:]); err != nil {
return nil, err
}
if embedded {
buf = bph.auxBuffer.Bytes()
} else {
var hashBuf [33]byte
hashBuf[0] = 0x80 + length.Hash
if _, err := bph.keccak.Read(hashBuf[1:]); err != nil {
return nil, err
}
buf = append(buf, hashBuf[:]...)
}
return buf, nil
}
func (bph *BinPatriciaHashed) leafHashWithKeyVal(buf, key []byte, val rlp.RlpSerializableBytes, singleton bool) ([]byte, error) {
// Compute the total length of binary representation
var kp, kl int
// Write key
var compactLen int
var ni int
var compact0 byte
compactLen = (len(key)-1)/2 + 1
if len(key)&1 == 0 {
compact0 = 0x30 + key[0] // Odd: (3<<4) + first nibble
ni = 1
} else {
compact0 = 0x20
}
var keyPrefix [1]byte
if compactLen > 1 {
keyPrefix[0] = 0x80 + byte(compactLen)
kp = 1
kl = compactLen
} else {
kl = 1
}
return bph.completeLeafHash(buf, keyPrefix[:], kp, kl, compactLen, key, compact0, ni, val, singleton)
}
func (bph *BinPatriciaHashed) accountLeafHashWithKey(buf, key []byte, val rlp.RlpSerializable) ([]byte, error) {
// Compute the total length of binary representation
var kp, kl int
// Write key
var compactLen int
var ni int
var compact0 byte
if hasTerm(key) {
compactLen = (len(key)-1)/2 + 1
if len(key)&1 == 0 {
compact0 = 48 + key[0] // Odd (1<<4) + first nibble
ni = 1
} else {
compact0 = 32
}
} else {
compactLen = len(key)/2 + 1
if len(key)&1 == 1 {
compact0 = 16 + key[0] // Odd (1<<4) + first nibble
ni = 1
}
}
var keyPrefix [1]byte
if compactLen > 1 {
keyPrefix[0] = byte(128 + compactLen)
kp = 1
kl = compactLen
} else {
kl = 1
}
return bph.completeLeafHash(buf, keyPrefix[:], kp, kl, compactLen, key, compact0, ni, val, true)
}
func (bph *BinPatriciaHashed) extensionHash(key []byte, hash []byte) ([length.Hash]byte, error) {
var hashBuf [length.Hash]byte
// Compute the total length of binary representation
var kp, kl int
// Write key
var compactLen int
var ni int
var compact0 byte
if hasTerm(key) {
compactLen = (len(key)-1)/2 + 1
if len(key)&1 == 0 {
compact0 = 0x30 + key[0] // Odd: (3<<4) + first nibble
ni = 1
} else {
compact0 = 0x20
}
} else {
compactLen = len(key)/2 + 1
if len(key)&1 == 1 {
compact0 = 0x10 + key[0] // Odd: (1<<4) + first nibble
ni = 1
}
}
var keyPrefix [1]byte
if compactLen > 1 {
keyPrefix[0] = 0x80 + byte(compactLen)
kp = 1
kl = compactLen
} else {
kl = 1
}
totalLen := kp + kl + 33
var lenPrefix [4]byte
pt := rlp.GenerateStructLen(lenPrefix[:], totalLen)
bph.keccak.Reset()
if _, err := bph.keccak.Write(lenPrefix[:pt]); err != nil {
return hashBuf, err
}
if _, err := bph.keccak.Write(keyPrefix[:kp]); err != nil {
return hashBuf, err
}
var b [1]byte
b[0] = compact0
if _, err := bph.keccak.Write(b[:]); err != nil {
return hashBuf, err
}
for i := 1; i < compactLen; i++ {
b[0] = key[ni]*16 + key[ni+1]
if _, err := bph.keccak.Write(b[:]); err != nil {
return hashBuf, err
}
ni += 2
}
b[0] = 0x80 + length.Hash
if _, err := bph.keccak.Write(b[:]); err != nil {
return hashBuf, err
}
if _, err := bph.keccak.Write(hash); err != nil {
return hashBuf, err
}
// Replace previous hash with the new one
if _, err := bph.keccak.Read(hashBuf[:]); err != nil {
return hashBuf, err
}
return hashBuf, nil
}
func (bph *BinPatriciaHashed) computeBinaryCellHashLen(cell *BinaryCell, depth int) int {
if cell.spl > 0 && depth >= halfKeySize {
keyLen := 128 - depth + 1 // Length of hex key with terminator character
var kp, kl int
compactLen := (keyLen-1)/2 + 1
if compactLen > 1 {
kp = 1
kl = compactLen
} else {
kl = 1
}
val := rlp.RlpSerializableBytes(cell.Storage[:cell.StorageLen])
totalLen := kp + kl + val.DoubleRLPLen()
var lenPrefix [4]byte
pt := rlp.GenerateStructLen(lenPrefix[:], totalLen)
if totalLen+pt < length.Hash {
return totalLen + pt
}
}
return length.Hash + 1
}
func (bph *BinPatriciaHashed) computeBinaryCellHash(cell *BinaryCell, depth int, buf []byte) ([]byte, error) {
var err error
var storageRootHash [length.Hash]byte
storageRootHashIsSet := false
if cell.spl > 0 {
var hashedKeyOffset int
if depth >= halfKeySize {
hashedKeyOffset = depth - halfKeySize
}
singleton := depth <= halfKeySize
if err := binHashKey(bph.keccak, cell.spk[bph.accountKeyLen:cell.spl], cell.downHashedKey[:], hashedKeyOffset); err != nil {
return nil, err
}
cell.downHashedKey[halfKeySize-hashedKeyOffset] = 16 // Add terminator
if singleton {
if bph.trace {
fmt.Printf("leafHashWithKeyVal(singleton) for [%x]=>[%x]\n", cell.downHashedKey[:halfKeySize-hashedKeyOffset+1], cell.Storage[:cell.StorageLen])
}
aux := make([]byte, 0, 33)
if aux, err = bph.leafHashWithKeyVal(aux, cell.downHashedKey[:halfKeySize-hashedKeyOffset+1], cell.Storage[:cell.StorageLen], true); err != nil {
return nil, err
}
storageRootHash = *(*[length.Hash]byte)(aux[1:])
storageRootHashIsSet = true
} else {
if bph.trace {
fmt.Printf("leafHashWithKeyVal for [%x]=>[%x]\n", cell.downHashedKey[:halfKeySize-hashedKeyOffset+1], cell.Storage[:cell.StorageLen])
}
return bph.leafHashWithKeyVal(buf, cell.downHashedKey[:halfKeySize-hashedKeyOffset+1], cell.Storage[:cell.StorageLen], false)
}
}
if cell.apl > 0 {
if err := binHashKey(bph.keccak, cell.apk[:cell.apl], cell.downHashedKey[:], depth); err != nil {
return nil, err
}
cell.downHashedKey[halfKeySize-depth] = 16 // Add terminator
if !storageRootHashIsSet {
if cell.extLen > 0 {
// Extension
if cell.hl > 0 {
if bph.trace {
fmt.Printf("extensionHash for [%x]=>[%x]\n", cell.extension[:cell.extLen], cell.h[:cell.hl])
}
if storageRootHash, err = bph.extensionHash(cell.extension[:cell.extLen], cell.h[:cell.hl]); err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("computeBinaryCellHash extension without hash")
}
} else if cell.hl > 0 {
storageRootHash = cell.h
} else {
storageRootHash = *(*[length.Hash]byte)(EmptyRootHash)
}
}
var valBuf [128]byte
valLen := cell.accountForHashing(valBuf[:], storageRootHash)
if bph.trace {
fmt.Printf("accountLeafHashWithKey for [%x]=>[%x]\n", bph.hashAuxBuffer[:halfKeySize+1-depth], valBuf[:valLen])
}
return bph.accountLeafHashWithKey(buf, cell.downHashedKey[:halfKeySize+1-depth], rlp.RlpEncodedBytes(valBuf[:valLen]))
}
buf = append(buf, 0x80+32)
if cell.extLen > 0 {
// Extension
if cell.hl > 0 {
if bph.trace {
fmt.Printf("extensionHash for [%x]=>[%x]\n", cell.extension[:cell.extLen], cell.h[:cell.hl])
}
var hash [length.Hash]byte
if hash, err = bph.extensionHash(cell.extension[:cell.extLen], cell.h[:cell.hl]); err != nil {
return nil, err
}
buf = append(buf, hash[:]...)
} else {
return nil, fmt.Errorf("computeBinaryCellHash extension without hash")
}
} else if cell.hl > 0 {
buf = append(buf, cell.h[:cell.hl]...)
} else {
buf = append(buf, EmptyRootHash...)
}
return buf, nil
}
func (bph *BinPatriciaHashed) needUnfolding(hashedKey []byte) int {
var cell *BinaryCell
var depth int
if bph.activeRows == 0 {
if bph.trace {
fmt.Printf("needUnfolding root, rootChecked = %t\n", bph.rootChecked)
}
if bph.rootChecked && bph.root.downHashedLen == 0 && bph.root.hl == 0 {
// Previously checked, empty root, no unfolding needed
return 0
}
cell = &bph.root
if cell.downHashedLen == 0 && cell.hl == 0 && !bph.rootChecked {
// Need to attempt to unfold the root
return 1
}
} else {
col := int(hashedKey[bph.currentKeyLen])
cell = &bph.grid[bph.activeRows-1][col]
depth = bph.depths[bph.activeRows-1]
if bph.trace {
fmt.Printf("needUnfolding cell (%d, %x), currentKey=[%x], depth=%d, cell.h=[%x]\n", bph.activeRows-1, col, bph.currentKey[:bph.currentKeyLen], depth, cell.h[:cell.hl])
}
}
if len(hashedKey) <= depth {
return 0
}
if cell.downHashedLen == 0 {
if cell.hl == 0 {
// cell is empty, no need to unfold further
return 0
}
// unfold branch node
return 1
}
cpl := commonPrefixLen(hashedKey[depth:], cell.downHashedKey[:cell.downHashedLen-1])
if bph.trace {
fmt.Printf("cpl=%d, cell.downHashedKey=[%x], depth=%d, hashedKey[depth:]=[%x]\n", cpl, cell.downHashedKey[:cell.downHashedLen], depth, hashedKey[depth:])
}
unfolding := cpl + 1
if depth < halfKeySize && depth+unfolding > halfKeySize {
// This is to make sure that unfolding always breaks at the level where storage subtrees start
unfolding = halfKeySize - depth
if bph.trace {
fmt.Printf("adjusted unfolding=%d\n", unfolding)
}
}
return unfolding
}
// unfoldBranchNode returns true if unfolding has been done
func (bph *BinPatriciaHashed) unfoldBranchNode(row int, deleted bool, depth int) (bool, error) {
branchData, err := bph.branchFn(binToCompact(bph.currentKey[:bph.currentKeyLen]))
if err != nil {
return false, err
}
if !bph.rootChecked && bph.currentKeyLen == 0 && len(branchData) == 0 {
// Special case - empty or deleted root
bph.rootChecked = true
return false, nil
}
if len(branchData) == 0 {
log.Warn("got empty branch data during unfold", "row", row, "depth", depth, "deleted", deleted)
}
bph.branchBefore[row] = true
bitmap := binary.BigEndian.Uint16(branchData[0:])
pos := 2
if deleted {
// All cells come as deleted (touched but not present after)
bph.afterMap[row] = 0
bph.touchMap[row] = bitmap
} else {
bph.afterMap[row] = bitmap
bph.touchMap[row] = 0
}
//fmt.Printf("unfoldBranchNode [%x], afterMap = [%016b], touchMap = [%016b]\n", branchData, bph.afterMap[row], bph.touchMap[row])
// Loop iterating over the set bits of modMask
for bitset, j := bitmap, 0; bitset != 0; j++ {
bit := bitset & -bitset
nibble := bits.TrailingZeros16(bit)
cell := &bph.grid[row][nibble]
fieldBits := branchData[pos]
pos++
var err error
if pos, err = cell.fillFromFields(branchData, pos, PartFlags(fieldBits)); err != nil {
return false, fmt.Errorf("prefix [%x], branchData[%x]: %w", bph.currentKey[:bph.currentKeyLen], branchData, err)
}
if bph.trace {
fmt.Printf("cell (%d, %x) depth=%d, hash=[%x], a=[%x], s=[%x], ex=[%x]\n", row, nibble, depth, cell.h[:cell.hl], cell.apk[:cell.apl], cell.spk[:cell.spl], cell.extension[:cell.extLen])
}
if cell.apl > 0 {
bph.accountFn(cell.apk[:cell.apl], cell)
if bph.trace {
fmt.Printf("accountFn[%x] return balance=%d, nonce=%d code=%x\n", cell.apk[:cell.apl], &cell.Balance, cell.Nonce, cell.CodeHash[:])
}
}
if cell.spl > 0 {
bph.storageFn(cell.spk[:cell.spl], cell)
}
if err = cell.deriveHashedKeys(depth, bph.keccak, bph.accountKeyLen); err != nil {
return false, err
}
bitset ^= bit
}
return true, nil
}
func (bph *BinPatriciaHashed) unfold(hashedKey []byte, unfolding int) error {
if bph.trace {
fmt.Printf("unfold %d: activeRows: %d\n", unfolding, bph.activeRows)
}
var upCell *BinaryCell
var touched, present bool
var col byte
var upDepth, depth int
if bph.activeRows == 0 {
if bph.rootChecked && bph.root.hl == 0 && bph.root.downHashedLen == 0 {
// No unfolding for empty root
return nil
}
upCell = &bph.root
touched = bph.rootTouched
present = bph.rootPresent
if bph.trace {
fmt.Printf("unfold root, touched %t, present %t, column %d\n", touched, present, col)
}
} else {
upDepth = bph.depths[bph.activeRows-1]
col = hashedKey[upDepth-1]
upCell = &bph.grid[bph.activeRows-1][col]
touched = bph.touchMap[bph.activeRows-1]&(uint16(1)<<col) != 0
present = bph.afterMap[bph.activeRows-1]&(uint16(1)<<col) != 0
if bph.trace {
fmt.Printf("upCell (%d, %x), touched %t, present %t\n", bph.activeRows-1, col, touched, present)
}
bph.currentKey[bph.currentKeyLen] = col
bph.currentKeyLen++
}
row := bph.activeRows
for i := 0; i < maxChild; i++ {
bph.grid[row][i].fillEmpty()
}
bph.touchMap[row] = 0
bph.afterMap[row] = 0
bph.branchBefore[row] = false
if upCell.downHashedLen == 0 {
depth = upDepth + 1
if unfolded, err := bph.unfoldBranchNode(row, touched && !present /* deleted */, depth); err != nil {
return err
} else if !unfolded {
// Return here to prevent activeRow from being incremented
return nil
}
} else if upCell.downHashedLen >= unfolding {
depth = upDepth + unfolding
nibble := upCell.downHashedKey[unfolding-1]
if touched {
bph.touchMap[row] = uint16(1) << nibble
}
if present {
bph.afterMap[row] = uint16(1) << nibble
}
cell := &bph.grid[row][nibble]
cell.fillFromUpperCell(upCell, depth, unfolding)
if bph.trace {
fmt.Printf("cell (%d, %x) depth=%d\n", row, nibble, depth)
}
if row >= halfKeySize {
cell.apl = 0
}
if unfolding > 1 {
copy(bph.currentKey[bph.currentKeyLen:], upCell.downHashedKey[:unfolding-1])
}
bph.currentKeyLen += unfolding - 1
} else {
// upCell.downHashedLen < unfolding
depth = upDepth + upCell.downHashedLen
nibble := upCell.downHashedKey[upCell.downHashedLen-1]
if touched {
bph.touchMap[row] = uint16(1) << nibble
}
if present {
bph.afterMap[row] = uint16(1) << nibble
}
cell := &bph.grid[row][nibble]
cell.fillFromUpperCell(upCell, depth, upCell.downHashedLen)
if bph.trace {
fmt.Printf("cell (%d, %x) depth=%d\n", row, nibble, depth)
}
if row >= halfKeySize {
cell.apl = 0
}
if upCell.downHashedLen > 1 {
copy(bph.currentKey[bph.currentKeyLen:], upCell.downHashedKey[:upCell.downHashedLen-1])
}
bph.currentKeyLen += upCell.downHashedLen - 1
}
bph.depths[bph.activeRows] = depth
bph.activeRows++
return nil
}
func (bph *BinPatriciaHashed) needFolding(hashedKey []byte) bool {
return !bytes.HasPrefix(hashedKey, bph.currentKey[:bph.currentKeyLen])
}
// The purpose of fold is to reduce hph.currentKey[:hph.currentKeyLen]. It should be invoked
// until that current key becomes a prefix of hashedKey that we will proccess next
// (in other words until the needFolding function returns 0)
func (bph *BinPatriciaHashed) fold() (branchData BranchData, updateKey []byte, err error) {
updateKeyLen := bph.currentKeyLen
if bph.activeRows == 0 {
return nil, nil, fmt.Errorf("cannot fold - no active rows")
}
if bph.trace {
fmt.Printf("fold: activeRows: %d, currentKey: [%x], touchMap: %016b, afterMap: %016b\n", bph.activeRows, bph.currentKey[:bph.currentKeyLen], bph.touchMap[bph.activeRows-1], bph.afterMap[bph.activeRows-1])
}
// Move information to the row above
row := bph.activeRows - 1
var upBinaryCell *BinaryCell
var col int
var upDepth int
if bph.activeRows == 1 {
if bph.trace {
fmt.Printf("upcell is root\n")