-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathblockchain.go
931 lines (786 loc) · 27.3 KB
/
blockchain.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
package blockchain
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"github.com/Masterminds/semver/v3"
"github.com/NethermindEth/juno/core"
"github.com/NethermindEth/juno/core/felt"
"github.com/NethermindEth/juno/db"
"github.com/NethermindEth/juno/encoder"
"github.com/NethermindEth/juno/utils"
"github.com/ethereum/go-ethereum/common"
)
//go:generate mockgen -destination=../mocks/mock_blockchain.go -package=mocks github.com/NethermindEth/juno/blockchain Reader
type Reader interface {
Height() (height uint64, err error)
Head() (head *core.Block, err error)
L1Head() (*core.L1Head, error)
BlockByNumber(number uint64) (block *core.Block, err error)
BlockByHash(hash *felt.Felt) (block *core.Block, err error)
HeadsHeader() (header *core.Header, err error)
BlockHeaderByNumber(number uint64) (header *core.Header, err error)
BlockHeaderByHash(hash *felt.Felt) (header *core.Header, err error)
TransactionByHash(hash *felt.Felt) (transaction core.Transaction, err error)
TransactionByBlockNumberAndIndex(blockNumber, index uint64) (transaction core.Transaction, err error)
Receipt(hash *felt.Felt) (receipt *core.TransactionReceipt, blockHash *felt.Felt, blockNumber uint64, err error)
StateUpdateByNumber(number uint64) (update *core.StateUpdate, err error)
StateUpdateByHash(hash *felt.Felt) (update *core.StateUpdate, err error)
L1HandlerTxnHash(msgHash *common.Hash) (l1HandlerTxnHash *felt.Felt, err error)
HeadState() (core.StateReader, StateCloser, error)
StateAtBlockHash(blockHash *felt.Felt) (core.StateReader, StateCloser, error)
StateAtBlockNumber(blockNumber uint64) (core.StateReader, StateCloser, error)
BlockCommitmentsByNumber(blockNumber uint64) (*core.BlockCommitments, error)
EventFilter(from *felt.Felt, keys [][]felt.Felt) (EventFilterer, error)
Network() *utils.Network
}
var (
ErrParentDoesNotMatchHead = errors.New("block's parent hash does not match head block hash")
ErrPendingBlockNotFound = errors.New("pending block not found")
SupportedStarknetVersion = semver.MustParse("0.13.3")
)
func CheckBlockVersion(protocolVersion string) error {
blockVer, err := core.ParseBlockVersion(protocolVersion)
if err != nil {
return err
}
// We ignore changes in patch part of the version
blockVerMM, supportedVerMM := copyWithoutPatch(blockVer), copyWithoutPatch(SupportedStarknetVersion)
if blockVerMM.GreaterThan(supportedVerMM) {
return errors.New("unsupported block version")
}
return nil
}
func copyWithoutPatch(v *semver.Version) *semver.Version {
if v == nil {
return nil
}
return semver.New(v.Major(), v.Minor(), 0, v.Prerelease(), v.Metadata())
}
var _ Reader = (*Blockchain)(nil)
// Blockchain is responsible for keeping track of all things related to the Starknet blockchain
type Blockchain struct {
network *utils.Network
database db.DB
listener EventListener
pendingBlockFn func() *core.Block
}
func New(database db.DB, network *utils.Network, pendingBlockFn func() *core.Block) *Blockchain {
RegisterCoreTypesToEncoder()
return &Blockchain{
database: database,
network: network,
listener: &SelectiveListener{},
pendingBlockFn: pendingBlockFn,
}
}
func (b *Blockchain) WithListener(listener EventListener) *Blockchain {
b.listener = listener
return b
}
func (b *Blockchain) Network() *utils.Network {
return b.network
}
// StateCommitment returns the latest block state commitment.
// If blockchain is empty zero felt is returned.
func (b *Blockchain) StateCommitment() (*felt.Felt, error) {
b.listener.OnRead("StateCommitment")
var commitment *felt.Felt
return commitment, b.database.View(func(txn db.Transaction) error {
var err error
commitment, err = core.NewState(txn).Root()
return err
})
}
// Height returns the latest block height. If blockchain is empty nil is returned.
func (b *Blockchain) Height() (uint64, error) {
b.listener.OnRead("Height")
var height uint64
return height, b.database.View(func(txn db.Transaction) error {
var err error
height, err = chainHeight(txn)
return err
})
}
func chainHeight(txn db.Transaction) (uint64, error) {
var height uint64
return height, txn.Get(db.ChainHeight.Key(), func(val []byte) error {
height = binary.BigEndian.Uint64(val)
return nil
})
}
func (b *Blockchain) Head() (*core.Block, error) {
b.listener.OnRead("Head")
var h *core.Block
return h, b.database.View(func(txn db.Transaction) error {
var err error
h, err = head(txn)
return err
})
}
func (b *Blockchain) HeadsHeader() (*core.Header, error) {
b.listener.OnRead("HeadsHeader")
var header *core.Header
return header, b.database.View(func(txn db.Transaction) error {
var err error
header, err = headsHeader(txn)
return err
})
}
func head(txn db.Transaction) (*core.Block, error) {
height, err := chainHeight(txn)
if err != nil {
return nil, err
}
return blockByNumber(txn, height)
}
func headsHeader(txn db.Transaction) (*core.Header, error) {
height, err := chainHeight(txn)
if err != nil {
return nil, err
}
return blockHeaderByNumber(txn, height)
}
func (b *Blockchain) BlockByNumber(number uint64) (*core.Block, error) {
b.listener.OnRead("BlockByNumber")
var block *core.Block
return block, b.database.View(func(txn db.Transaction) error {
var err error
block, err = blockByNumber(txn, number)
return err
})
}
func (b *Blockchain) BlockHeaderByNumber(number uint64) (*core.Header, error) {
b.listener.OnRead("BlockHeaderByNumber")
var header *core.Header
return header, b.database.View(func(txn db.Transaction) error {
var err error
header, err = blockHeaderByNumber(txn, number)
return err
})
}
func (b *Blockchain) BlockByHash(hash *felt.Felt) (*core.Block, error) {
b.listener.OnRead("BlockByHash")
var block *core.Block
return block, b.database.View(func(txn db.Transaction) error {
var err error
block, err = blockByHash(txn, hash)
return err
})
}
func (b *Blockchain) BlockHeaderByHash(hash *felt.Felt) (*core.Header, error) {
b.listener.OnRead("BlockHeaderByHash")
var header *core.Header
return header, b.database.View(func(txn db.Transaction) error {
var err error
header, err = blockHeaderByHash(txn, hash)
return err
})
}
func (b *Blockchain) StateUpdateByNumber(number uint64) (*core.StateUpdate, error) {
b.listener.OnRead("StateUpdateByNumber")
var update *core.StateUpdate
return update, b.database.View(func(txn db.Transaction) error {
var err error
update, err = stateUpdateByNumber(txn, number)
return err
})
}
func (b *Blockchain) StateUpdateByHash(hash *felt.Felt) (*core.StateUpdate, error) {
b.listener.OnRead("StateUpdateByHash")
var update *core.StateUpdate
return update, b.database.View(func(txn db.Transaction) error {
var err error
update, err = stateUpdateByHash(txn, hash)
return err
})
}
func (b *Blockchain) L1HandlerTxnHash(msgHash *common.Hash) (*felt.Felt, error) {
b.listener.OnRead("L1HandlerTxnHash")
var l1HandlerTxnHash *felt.Felt
return l1HandlerTxnHash, b.database.View(func(txn db.Transaction) error {
var err error
l1HandlerTxnHash, err = l1HandlerTxnHashByMsgHash(txn, msgHash)
return err
})
}
// TransactionByBlockNumberAndIndex gets the transaction for a given block number and index.
func (b *Blockchain) TransactionByBlockNumberAndIndex(blockNumber, index uint64) (core.Transaction, error) {
b.listener.OnRead("TransactionByBlockNumberAndIndex")
var transaction core.Transaction
return transaction, b.database.View(func(txn db.Transaction) error {
var err error
transaction, err = transactionByBlockNumberAndIndex(txn, &txAndReceiptDBKey{blockNumber, index})
return err
})
}
// TransactionByHash gets the transaction for a given hash.
func (b *Blockchain) TransactionByHash(hash *felt.Felt) (core.Transaction, error) {
b.listener.OnRead("TransactionByHash")
var transaction core.Transaction
return transaction, b.database.View(func(txn db.Transaction) error {
var err error
transaction, err = transactionByHash(txn, hash)
return err
})
}
// Receipt gets the transaction receipt for a given transaction hash.
func (b *Blockchain) Receipt(hash *felt.Felt) (*core.TransactionReceipt, *felt.Felt, uint64, error) {
b.listener.OnRead("Receipt")
var (
receipt *core.TransactionReceipt
blockHash *felt.Felt
blockNumber uint64
)
return receipt, blockHash, blockNumber, b.database.View(func(txn db.Transaction) error {
var err error
receipt, blockHash, blockNumber, err = receiptByHash(txn, hash)
return err
})
}
func (b *Blockchain) L1Head() (*core.L1Head, error) {
b.listener.OnRead("L1Head")
var update *core.L1Head
return update, b.database.View(func(txn db.Transaction) error {
var err error
update, err = l1Head(txn)
return err
})
}
func l1Head(txn db.Transaction) (*core.L1Head, error) {
var update *core.L1Head
if err := txn.Get(db.L1Height.Key(), func(updateBytes []byte) error {
return encoder.Unmarshal(updateBytes, &update)
}); err != nil {
return nil, err
}
return update, nil
}
func (b *Blockchain) SetL1Head(update *core.L1Head) error {
updateBytes, err := encoder.Marshal(update)
if err != nil {
return err
}
return b.database.Update(func(txn db.Transaction) error {
return txn.Set(db.L1Height.Key(), updateBytes)
})
}
// Store takes a block and state update and performs sanity checks before putting in the database.
func (b *Blockchain) Store(block *core.Block, blockCommitments *core.BlockCommitments,
stateUpdate *core.StateUpdate, newClasses map[felt.Felt]core.Class,
) error {
return b.database.Update(func(txn db.Transaction) error {
if err := verifyBlock(txn, block); err != nil {
return err
}
if err := core.NewState(txn).Update(block.Number, stateUpdate, newClasses); err != nil {
return err
}
if err := storeBlockHeader(txn, block.Header); err != nil {
return err
}
for i, tx := range block.Transactions {
if err := storeTransactionAndReceipt(txn, block.Number, uint64(i), tx,
block.Receipts[i]); err != nil {
return err
}
}
if err := storeStateUpdate(txn, block.Number, stateUpdate); err != nil {
return err
}
if err := storeBlockCommitments(txn, block.Number, blockCommitments); err != nil {
return err
}
if err := storeL1HandlerMsgHashes(txn, block.Transactions); err != nil {
return err
}
// Head of the blockchain is maintained as follows:
// [db.chainHeight]() -> (BlockNumber)
heightBin := core.MarshalBlockNumber(block.Number)
return txn.Set(db.ChainHeight.Key(), heightBin)
})
}
// VerifyBlock assumes the block has already been sanity-checked.
func (b *Blockchain) VerifyBlock(block *core.Block) error {
return b.database.View(func(txn db.Transaction) error {
return verifyBlock(txn, block)
})
}
func verifyBlock(txn db.Transaction, block *core.Block) error {
if err := CheckBlockVersion(block.ProtocolVersion); err != nil {
return err
}
expectedBlockNumber := uint64(0)
expectedParentHash := &felt.Zero
h, err := headsHeader(txn)
if err == nil {
expectedBlockNumber = h.Number + 1
expectedParentHash = h.Hash
} else if !errors.Is(err, db.ErrKeyNotFound) {
return err
}
if expectedBlockNumber != block.Number {
return fmt.Errorf("expected block #%d, got block #%d", expectedBlockNumber, block.Number)
}
if !block.ParentHash.Equal(expectedParentHash) {
return ErrParentDoesNotMatchHead
}
return nil
}
func storeBlockCommitments(txn db.Transaction, blockNumber uint64, commitments *core.BlockCommitments) error {
numBytes := core.MarshalBlockNumber(blockNumber)
commitmentBytes, err := encoder.Marshal(commitments)
if err != nil {
return err
}
return txn.Set(db.BlockCommitments.Key(numBytes), commitmentBytes)
}
func (b *Blockchain) BlockCommitmentsByNumber(blockNumber uint64) (*core.BlockCommitments, error) {
b.listener.OnRead("BlockCommitmentsByNumber")
var commitments *core.BlockCommitments
return commitments, b.database.View(func(txn db.Transaction) error {
var err error
commitments, err = blockCommitmentsByNumber(txn, blockNumber)
return err
})
}
func blockCommitmentsByNumber(txn db.Transaction, blockNumber uint64) (*core.BlockCommitments, error) {
numBytes := core.MarshalBlockNumber(blockNumber)
var commitments *core.BlockCommitments
if err := txn.Get(db.BlockCommitments.Key(numBytes), func(val []byte) error {
commitments = new(core.BlockCommitments)
return encoder.Unmarshal(val, commitments)
}); err != nil {
return nil, err
}
return commitments, nil
}
// storeBlockHeader stores the given block in the database.
// The db storage for blocks is maintained by two buckets as follows:
//
// [db.BlockHeaderNumbersByHash](BlockHash) -> (BlockNumber)
// [db.BlockHeadersByNumber](BlockNumber) -> (BlockHeader)
//
// "[]" is the db prefix to represent a bucket
// "()" are additional keys appended to the prefix or multiple values marshalled together
// "->" represents a key value pair.
func storeBlockHeader(txn db.Transaction, header *core.Header) error {
numBytes := core.MarshalBlockNumber(header.Number)
if err := txn.Set(db.BlockHeaderNumbersByHash.Key(header.Hash.Marshal()), numBytes); err != nil {
return err
}
headerBytes, err := encoder.Marshal(header)
if err != nil {
return err
}
return txn.Set(db.BlockHeadersByNumber.Key(numBytes), headerBytes)
}
// blockHeaderByNumber retrieves a block header from database by its number
func blockHeaderByNumber(txn db.Transaction, number uint64) (*core.Header, error) {
numBytes := core.MarshalBlockNumber(number)
var header *core.Header
if err := txn.Get(db.BlockHeadersByNumber.Key(numBytes), func(val []byte) error {
header = new(core.Header)
return encoder.Unmarshal(val, header)
}); err != nil {
return nil, err
}
return header, nil
}
func blockHeaderByHash(txn db.Transaction, hash *felt.Felt) (*core.Header, error) {
var header *core.Header
return header, txn.Get(db.BlockHeaderNumbersByHash.Key(hash.Marshal()), func(val []byte) error {
var err error
header, err = blockHeaderByNumber(txn, binary.BigEndian.Uint64(val))
return err
})
}
// blockByNumber retrieves a block from database by its number
func blockByNumber(txn db.Transaction, number uint64) (*core.Block, error) {
header, err := blockHeaderByNumber(txn, number)
if err != nil {
return nil, err
}
block := new(core.Block)
block.Header = header
block.Transactions, err = transactionsByBlockNumber(txn, number)
if err != nil {
return nil, err
}
block.Receipts, err = receiptsByBlockNumber(txn, number)
if err != nil {
return nil, err
}
return block, nil
}
func transactionsByBlockNumber(txn db.Transaction, number uint64) ([]core.Transaction, error) {
iterator, err := txn.NewIterator()
if err != nil {
return nil, err
}
var txs []core.Transaction
numBytes := core.MarshalBlockNumber(number)
prefix := db.TransactionsByBlockNumberAndIndex.Key(numBytes)
for iterator.Seek(prefix); iterator.Valid(); iterator.Next() {
if !bytes.HasPrefix(iterator.Key(), prefix) {
break
}
val, vErr := iterator.Value()
if vErr != nil {
return nil, utils.RunAndWrapOnError(iterator.Close, vErr)
}
var tx core.Transaction
if err = encoder.Unmarshal(val, &tx); err != nil {
return nil, utils.RunAndWrapOnError(iterator.Close, err)
}
txs = append(txs, tx)
}
if err = iterator.Close(); err != nil {
return nil, err
}
return txs, nil
}
func receiptsByBlockNumber(txn db.Transaction, number uint64) ([]*core.TransactionReceipt, error) {
iterator, err := txn.NewIterator()
if err != nil {
return nil, err
}
var receipts []*core.TransactionReceipt
numBytes := core.MarshalBlockNumber(number)
prefix := db.ReceiptsByBlockNumberAndIndex.Key(numBytes)
for iterator.Seek(prefix); iterator.Valid(); iterator.Next() {
if !bytes.HasPrefix(iterator.Key(), prefix) {
break
}
val, vErr := iterator.Value()
if vErr != nil {
return nil, utils.RunAndWrapOnError(iterator.Close, vErr)
}
receipt := new(core.TransactionReceipt)
if err = encoder.Unmarshal(val, receipt); err != nil {
return nil, utils.RunAndWrapOnError(iterator.Close, err)
}
receipts = append(receipts, receipt)
}
if err = iterator.Close(); err != nil {
return nil, err
}
return receipts, nil
}
// blockByHash retrieves a block from database by its hash
func blockByHash(txn db.Transaction, hash *felt.Felt) (*core.Block, error) {
var block *core.Block
return block, txn.Get(db.BlockHeaderNumbersByHash.Key(hash.Marshal()), func(val []byte) error {
var err error
block, err = blockByNumber(txn, binary.BigEndian.Uint64(val))
return err
})
}
func storeL1HandlerMsgHashes(dbTxn db.Transaction, blockTxns []core.Transaction) error {
for _, txn := range blockTxns {
if l1Handler, ok := (txn).(*core.L1HandlerTransaction); ok {
err := dbTxn.Set(db.L1HandlerTxnHashByMsgHash.Key(l1Handler.MessageHash()), txn.Hash().Marshal())
if err != nil {
return err
}
}
}
return nil
}
func storeStateUpdate(txn db.Transaction, blockNumber uint64, update *core.StateUpdate) error {
numBytes := core.MarshalBlockNumber(blockNumber)
updateBytes, err := encoder.Marshal(update)
if err != nil {
return err
}
return txn.Set(db.StateUpdatesByBlockNumber.Key(numBytes), updateBytes)
}
func stateUpdateByNumber(txn db.Transaction, blockNumber uint64) (*core.StateUpdate, error) {
numBytes := core.MarshalBlockNumber(blockNumber)
var update *core.StateUpdate
if err := txn.Get(db.StateUpdatesByBlockNumber.Key(numBytes), func(val []byte) error {
update = new(core.StateUpdate)
return encoder.Unmarshal(val, update)
}); err != nil {
return nil, err
}
return update, nil
}
func stateUpdateByHash(txn db.Transaction, hash *felt.Felt) (*core.StateUpdate, error) {
var update *core.StateUpdate
return update, txn.Get(db.BlockHeaderNumbersByHash.Key(hash.Marshal()), func(val []byte) error {
var err error
update, err = stateUpdateByNumber(txn, binary.BigEndian.Uint64(val))
return err
})
}
func l1HandlerTxnHashByMsgHash(txn db.Transaction, l1HandlerMsgHash *common.Hash) (*felt.Felt, error) {
l1HandlerTxnHash := new(felt.Felt)
return l1HandlerTxnHash, txn.Get(db.L1HandlerTxnHashByMsgHash.Key(l1HandlerMsgHash.Bytes()), func(val []byte) error {
l1HandlerTxnHash.Unmarshal(val)
return nil
})
}
// SanityCheckNewHeight checks integrity of a block and resulting state update
func (b *Blockchain) SanityCheckNewHeight(block *core.Block, stateUpdate *core.StateUpdate,
newClasses map[felt.Felt]core.Class,
) (*core.BlockCommitments, error) {
if !block.Hash.Equal(stateUpdate.BlockHash) {
return nil, errors.New("block hashes do not match")
}
if !block.GlobalStateRoot.Equal(stateUpdate.NewRoot) {
return nil, errors.New("block's GlobalStateRoot does not match state update's NewRoot")
}
if err := core.VerifyClassHashes(newClasses); err != nil {
return nil, err
}
return core.VerifyBlockHash(block, b.network, stateUpdate.StateDiff)
}
type txAndReceiptDBKey struct {
Number uint64
Index uint64
}
func (t *txAndReceiptDBKey) MarshalBinary() []byte {
return binary.BigEndian.AppendUint64(binary.BigEndian.AppendUint64([]byte{}, t.Number), t.Index)
}
func (t *txAndReceiptDBKey) UnmarshalBinary(data []byte) error {
r := bytes.NewReader(data)
if err := binary.Read(r, binary.BigEndian, &t.Number); err != nil {
return err
}
return binary.Read(r, binary.BigEndian, &t.Index)
}
// storeTransactionAndReceipt stores the given transaction receipt in the database.
// The db storage for transaction and receipts is maintained by three buckets as follows:
//
// [db.TransactionBlockNumbersAndIndicesByHash](TransactionHash) -> (BlockNumber, Index)
// [db.TransactionsByBlockNumberAndIndex](BlockNumber, Index) -> Transaction
// [db.ReceiptsByBlockNumberAndIndex](BlockNumber, Index) -> Receipt
//
// Note: we are using the same transaction hash bucket which keeps track of block number and
// index for both transactions and receipts since transaction and its receipt share the same hash.
// "[]" is the db prefix to represent a bucket
// "()" are additional keys appended to the prefix or multiple values marshalled together
// "->" represents a key value pair.
func storeTransactionAndReceipt(txn db.Transaction, number, i uint64, t core.Transaction, r *core.TransactionReceipt) error {
bnIndexBytes := (&txAndReceiptDBKey{number, i}).MarshalBinary()
if err := txn.Set(db.TransactionBlockNumbersAndIndicesByHash.Key((r.TransactionHash).Marshal()),
bnIndexBytes); err != nil {
return err
}
txnBytes, err := encoder.Marshal(t)
if err != nil {
return err
}
if err = txn.Set(db.TransactionsByBlockNumberAndIndex.Key(bnIndexBytes), txnBytes); err != nil {
return err
}
rBytes, err := encoder.Marshal(r)
if err != nil {
return err
}
return txn.Set(db.ReceiptsByBlockNumberAndIndex.Key(bnIndexBytes), rBytes)
}
// transactionBlockNumberAndIndexByHash gets the block number and index for a given transaction hash
func transactionBlockNumberAndIndexByHash(txn db.Transaction, hash *felt.Felt) (*txAndReceiptDBKey, error) {
var bnIndex *txAndReceiptDBKey
if err := txn.Get(db.TransactionBlockNumbersAndIndicesByHash.Key(hash.Marshal()), func(val []byte) error {
bnIndex = new(txAndReceiptDBKey)
return bnIndex.UnmarshalBinary(val)
}); err != nil {
return nil, err
}
return bnIndex, nil
}
// transactionByBlockNumberAndIndex gets the transaction for a given block number and index.
func transactionByBlockNumberAndIndex(txn db.Transaction, bnIndex *txAndReceiptDBKey) (core.Transaction, error) {
var transaction core.Transaction
err := txn.Get(db.TransactionsByBlockNumberAndIndex.Key(bnIndex.MarshalBinary()), func(val []byte) error {
return encoder.Unmarshal(val, &transaction)
})
return transaction, err
}
// transactionByHash gets the transaction for a given hash.
func transactionByHash(txn db.Transaction, hash *felt.Felt) (core.Transaction, error) {
bnIndex, err := transactionBlockNumberAndIndexByHash(txn, hash)
if err != nil {
return nil, err
}
return transactionByBlockNumberAndIndex(txn, bnIndex)
}
// receiptByHash gets the transaction receipt for a given hash.
func receiptByHash(txn db.Transaction, hash *felt.Felt) (*core.TransactionReceipt, *felt.Felt, uint64, error) {
bnIndex, err := transactionBlockNumberAndIndexByHash(txn, hash)
if err != nil {
return nil, nil, 0, err
}
receipt, err := receiptByBlockNumberAndIndex(txn, bnIndex)
if err != nil {
return nil, nil, 0, err
}
header, err := blockHeaderByNumber(txn, bnIndex.Number)
if err != nil {
return nil, nil, 0, err
}
return receipt, header.Hash, header.Number, nil
}
// receiptByBlockNumberAndIndex gets the transaction receipt for a given block number and index.
func receiptByBlockNumberAndIndex(txn db.Transaction, bnIndex *txAndReceiptDBKey) (*core.TransactionReceipt, error) {
var r *core.TransactionReceipt
err := txn.Get(db.ReceiptsByBlockNumberAndIndex.Key(bnIndex.MarshalBinary()), func(val []byte) error {
return encoder.Unmarshal(val, &r)
})
return r, err
}
type StateCloser = func() error
// HeadState returns a StateReader that provides a stable view to the latest state
func (b *Blockchain) HeadState() (core.StateReader, StateCloser, error) {
b.listener.OnRead("HeadState")
txn, err := b.database.NewTransaction(false)
if err != nil {
return nil, nil, err
}
_, err = chainHeight(txn)
if err != nil {
return nil, nil, utils.RunAndWrapOnError(txn.Discard, err)
}
return core.NewState(txn), txn.Discard, nil
}
// StateAtBlockNumber returns a StateReader that provides a stable view to the state at the given block number
func (b *Blockchain) StateAtBlockNumber(blockNumber uint64) (core.StateReader, StateCloser, error) {
b.listener.OnRead("StateAtBlockNumber")
txn, err := b.database.NewTransaction(false)
if err != nil {
return nil, nil, err
}
_, err = blockHeaderByNumber(txn, blockNumber)
if err != nil {
return nil, nil, utils.RunAndWrapOnError(txn.Discard, err)
}
return core.NewStateSnapshot(core.NewState(txn), blockNumber), txn.Discard, nil
}
// StateAtBlockHash returns a StateReader that provides a stable view to the state at the given block hash
func (b *Blockchain) StateAtBlockHash(blockHash *felt.Felt) (core.StateReader, StateCloser, error) {
b.listener.OnRead("StateAtBlockHash")
if blockHash.IsZero() {
txn := db.NewMemTransaction()
emptyState := core.NewState(txn)
return emptyState, txn.Discard, nil
}
txn, err := b.database.NewTransaction(false)
if err != nil {
return nil, nil, err
}
header, err := blockHeaderByHash(txn, blockHash)
if err != nil {
return nil, nil, utils.RunAndWrapOnError(txn.Discard, err)
}
return core.NewStateSnapshot(core.NewState(txn), header.Number), txn.Discard, nil
}
// EventFilter returns an EventFilter object that is tied to a snapshot of the blockchain
func (b *Blockchain) EventFilter(from *felt.Felt, keys [][]felt.Felt) (EventFilterer, error) {
b.listener.OnRead("EventFilter")
txn, err := b.database.NewTransaction(false)
if err != nil {
return nil, err
}
latest, err := chainHeight(txn)
if err != nil {
return nil, err
}
return newEventFilter(txn, from, keys, 0, latest, b.pendingBlockFn), nil
}
// RevertHead reverts the head block
func (b *Blockchain) RevertHead() error {
return b.database.Update(b.revertHead)
}
func (b *Blockchain) GetReverseStateDiff() (*core.StateDiff, error) {
var reverseStateDiff *core.StateDiff
return reverseStateDiff, b.database.View(func(txn db.Transaction) error {
blockNumber, err := chainHeight(txn)
if err != nil {
return err
}
stateUpdate, err := stateUpdateByNumber(txn, blockNumber)
if err != nil {
return err
}
state := core.NewState(txn)
reverseStateDiff, err = state.GetReverseStateDiff(blockNumber, stateUpdate.StateDiff)
return err
})
}
func (b *Blockchain) revertHead(txn db.Transaction) error {
blockNumber, err := chainHeight(txn)
if err != nil {
return err
}
numBytes := core.MarshalBlockNumber(blockNumber)
stateUpdate, err := stateUpdateByNumber(txn, blockNumber)
if err != nil {
return err
}
state := core.NewState(txn)
// revert state
if err = state.Revert(blockNumber, stateUpdate); err != nil {
return err
}
header, err := blockHeaderByNumber(txn, blockNumber)
if err != nil {
return err
}
genesisBlock := blockNumber == 0
// remove block header
for _, key := range [][]byte{
db.BlockHeadersByNumber.Key(numBytes),
db.BlockHeaderNumbersByHash.Key(header.Hash.Marshal()),
db.BlockCommitments.Key(numBytes),
} {
if err = txn.Delete(key); err != nil {
return err
}
}
if err = removeTxsAndReceipts(txn, blockNumber, header.TransactionCount); err != nil {
return err
}
// remove state update
if err = txn.Delete(db.StateUpdatesByBlockNumber.Key(numBytes)); err != nil {
return err
}
// Revert chain height.
if genesisBlock {
return txn.Delete(db.ChainHeight.Key())
}
heightBin := core.MarshalBlockNumber(blockNumber - 1)
return txn.Set(db.ChainHeight.Key(), heightBin)
}
func removeTxsAndReceipts(txn db.Transaction, blockNumber, numTxs uint64) error {
blockIDAndIndex := txAndReceiptDBKey{
Number: blockNumber,
}
// remove txs and receipts
for i := uint64(0); i < numTxs; i++ {
blockIDAndIndex.Index = i
reorgedTxn, err := transactionByBlockNumberAndIndex(txn, &blockIDAndIndex)
if err != nil {
return err
}
keySuffix := blockIDAndIndex.MarshalBinary()
if err = txn.Delete(db.TransactionsByBlockNumberAndIndex.Key(keySuffix)); err != nil {
return err
}
if err = txn.Delete(db.ReceiptsByBlockNumberAndIndex.Key(keySuffix)); err != nil {
return err
}
if err = txn.Delete(db.TransactionBlockNumbersAndIndicesByHash.Key(reorgedTxn.Hash().Marshal())); err != nil {
return err
}
if l1handler, ok := reorgedTxn.(*core.L1HandlerTransaction); ok {
if err = txn.Delete(db.L1HandlerTxnHashByMsgHash.Key(l1handler.MessageHash())); err != nil {
return err
}
}
}
return nil
}