forked from neo-ngd/neo-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
blockchain.go
1548 lines (1401 loc) · 49 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
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
package core
import (
"errors"
"fmt"
"math/big"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/config"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/consensus"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/block"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/blockchainer"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/dao"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/filters"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/interop"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/mempool"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/mpt"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/native"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/native/noderoles"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/state"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/statedb"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/stateroot"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/storage"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/core/transaction"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/crypto/hash"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/crypto/keys"
"github.com/DigitalLabs-web3/neo-go-evm/pkg/vm"
evm "github.com/DigitalLabs-web3/neo-go-evm/pkg/vm"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
"go.uber.org/zap"
)
// Tuning parameters.
const (
headerBatchCount = 2000
version = "0.2.5"
defaultInitialGAS = 52000000 //wei
defaultGCPeriod = 10000
defaultMemPoolSize = 50000
defaultP2PNotaryRequestPayloadPoolSize = 1000
defaultMaxBlockSize = 262144
defaultMaxBlockGas = 90000000000
defaultMaxTraceableBlocks = 2102400 // 1 year of 15s blocks
defaultMaxTransactionsPerBlock = 512
// HeaderVerificationGasLimit is the maximum amount of GAS for block header verification.
HeaderVerificationGasLimit = 3_00000000 // 3 GAS
defaultStateSyncInterval = 40000
)
var (
// ErrAlreadyExists is returned when trying to add some already existing
// transaction into the pool (not specifying whether it exists in the
// chain or mempool).
ErrAlreadyExists = errors.New("already exists")
// ErrOOM is returned when adding transaction to the memory pool because
// it reached its full capacity.
ErrOOM = errors.New("no space left in the memory pool")
// ErrPolicy is returned on attempt to add transaction that doesn't
// comply with node's configured policy into the mempool.
ErrPolicy = errors.New("not allowed by policy")
// ErrInvalidBlockIndex is returned when trying to add block with index
// other than expected height of the blockchain.
ErrInvalidBlockIndex = errors.New("invalid block index")
// ErrHasConflicts is returned when trying to add some transaction which
// conflicts with other transaction in the chain or pool according to
// Conflicts attribute.
ErrHasConflicts = errors.New("has conflicts")
)
var (
persistInterval = 1 * time.Second
)
// Blockchain represents the blockchain. It maintans internal state representing
// the state of the ledger that can be accessed in various ways and changed by
// adding new blocks or headers.
type Blockchain struct {
config config.ProtocolConfiguration
// The only way chain state changes is by adding blocks, so we can't
// allow concurrent block additions. It differs from the next lock in
// that it's only for AddBlock method itself, the chain state is
// protected by the lock below, but holding it during all of AddBlock
// is too expensive (because the state only changes when persisting
// change cache).
addLock sync.Mutex
// This lock ensures blockchain immutability for operations that need
// that while performing their tasks. It's mostly used as a read lock
// with the only writer being the block addition logic.
lock sync.RWMutex
// Data access object for CRUD operations around storage. It's write-cached.
dao *dao.Simple
// persistent is the same DB as dao, but we never write to it, so all reads
// are directly from underlying persistent store.
persistent *dao.Simple
// Underlying persistent store.
store storage.Store
// Current index/height of the highest block.
// Read access should always be called by BlockHeight().
// Write access should only happen in storeBlock().
blockHeight uint32
// Current top Block wrapped in an atomic.Value for safe access.
topBlock atomic.Value
topBlockAer atomic.Value
// Current persisted block count.
persistedHeight uint32
// Number of headers stored in the chain file.
storedHeaderCount uint32
// Header hashes list with associated lock.
headerHashesLock sync.RWMutex
headerHashes []common.Hash
// Stop synchronization mechanisms.
stopCh chan struct{}
runToExitCh chan struct{}
memPool *mempool.Pool
// postBlock is a set of callback methods which should be run under the Blockchain lock after new block is persisted.
// Block's transactions are passed via mempool.
postBlock []func(func(*transaction.Transaction, *mempool.Pool, bool) bool, *mempool.Pool, *block.Block)
log *zap.Logger
lastBatch *storage.MemBatch
contracts native.Contracts
extensible atomic.Value
// knownValidatorsCount is the latest known validators count used
// for defaultBlockWitness.
knownValidatorsCount atomic.Value
// defaultBlockWitness stores transaction.Witness with m out of n multisig,
// where n = knownValidatorsCount.
defaultBlockWitness atomic.Value
stateRoot *stateroot.Module
// Notification subsystem.
events chan bcEvent
subCh chan interface{}
unsubCh chan interface{}
}
// bcEvent is an internal event generated by the Blockchain and then
// broadcasted to other parties. It joins the new block and associated
// invocation logs, all the other events visible from outside can be produced
// from this combination.
type bcEvent struct {
block *block.Block
appExecResults []*types.Receipt
}
// NewBlockchain returns a new blockchain object the will use the
// given Store as its underlying storage. For it to work correctly you need
// to spawn a goroutine for its Run method after this initialization.
func NewBlockchain(s storage.Store, cfg config.ProtocolConfiguration, log *zap.Logger) (*Blockchain, error) {
if log == nil {
return nil, errors.New("empty logger")
}
if cfg.InitialGASSupply <= 0 {
cfg.InitialGASSupply = defaultInitialGAS
log.Info("initial gas supply is not set or wrong, setting default value", zap.Uint64("InitialGASSupply", cfg.InitialGASSupply))
}
if cfg.MemPoolSize <= 0 {
cfg.MemPoolSize = defaultMemPoolSize
log.Info("mempool size is not set or wrong, setting default value", zap.Int("MemPoolSize", cfg.MemPoolSize))
}
if cfg.MaxBlockSize == 0 {
cfg.MaxBlockSize = defaultMaxBlockSize
log.Info("MaxBlockSize is not set or wrong, setting default value", zap.Uint32("MaxBlockSize", cfg.MaxBlockSize))
}
if cfg.MaxBlockGas <= 0 {
cfg.MaxBlockGas = defaultMaxBlockGas
log.Info("MaxBlockSystemFee is not set or wrong, setting default value", zap.Uint64("MaxBlockSystemFee", cfg.MaxBlockGas))
}
if cfg.MaxTraceableBlocks == 0 {
cfg.MaxTraceableBlocks = defaultMaxTraceableBlocks
log.Info("MaxTraceableBlocks is not set or wrong, using default value", zap.Uint32("MaxTraceableBlocks", cfg.MaxTraceableBlocks))
}
if cfg.MaxTransactionsPerBlock == 0 {
cfg.MaxTransactionsPerBlock = defaultMaxTransactionsPerBlock
log.Info("MaxTransactionsPerBlock is not set or wrong, using default value",
zap.Uint16("MaxTransactionsPerBlock", cfg.MaxTransactionsPerBlock))
}
if cfg.RemoveUntraceableBlocks && cfg.GarbageCollectionPeriod == 0 {
cfg.GarbageCollectionPeriod = defaultGCPeriod
log.Info("GarbageCollectionPeriod is not set or wrong, using default value", zap.Uint32("GarbageCollectionPeriod", cfg.GarbageCollectionPeriod))
}
bc := &Blockchain{
config: cfg,
dao: dao.NewSimple(s),
persistent: dao.NewSimple(s),
store: s,
stopCh: make(chan struct{}),
runToExitCh: make(chan struct{}),
memPool: mempool.New(cfg.MemPoolSize, 0, false),
log: log,
events: make(chan bcEvent),
subCh: make(chan interface{}),
unsubCh: make(chan interface{}),
contracts: *native.NewContracts(cfg),
}
bc.stateRoot = stateroot.NewModule(bc.GetConfig(), bc.VerifyWitness, bc.log, bc.dao.Store)
if err := bc.init(); err != nil {
return nil, err
}
return bc, nil
}
func (bc *Blockchain) init() error {
// If we could not find the version in the Store, we know that there is nothing stored.
ver, err := bc.dao.GetVersion()
if err != nil {
bc.log.Info("no storage version found! creating genesis block")
ver = dao.Version{
StoragePrefix: storage.STStorage,
KeepOnlyLatestState: bc.config.KeepOnlyLatestState,
Value: version,
}
bc.dao.PutVersion(ver)
bc.dao.Version = ver
bc.persistent.Version = ver
genesisBlock, err := createGenesisBlock(&bc.config)
if err != nil {
return err
}
bc.headerHashes = []common.Hash{genesisBlock.Hash()}
bc.dao.PutCurrentHeader(genesisBlock.Hash(), genesisBlock.Index)
if err := bc.stateRoot.Init(0); err != nil {
return fmt.Errorf("can't init MPT: %w", err)
}
return bc.storeBlock(genesisBlock, nil)
}
if ver.Value != version {
return fmt.Errorf("storage version mismatch (expected=%s, actual=%s)", version, ver.Value)
}
if ver.KeepOnlyLatestState != bc.config.KeepOnlyLatestState {
return fmt.Errorf("KeepOnlyLatestState setting mismatch (old=%v, new=%v)",
ver.KeepOnlyLatestState, bc.config.KeepOnlyLatestState)
}
bc.dao.Version = ver
bc.persistent.Version = ver
// At this point there was no version found in the storage which
// implies a creating fresh storage with the version specified
// and the genesis block as first block.
bc.log.Info("restoring blockchain", zap.String("version", version))
bc.headerHashes, err = bc.dao.GetHeaderHashes()
if err != nil {
return err
}
bc.storedHeaderCount = uint32(len(bc.headerHashes))
currHeaderHeight, currHeaderHash, err := bc.dao.GetCurrentHeaderHeight()
if err != nil {
return fmt.Errorf("failed to retrieve current header info: %w", err)
}
if bc.storedHeaderCount == 0 && currHeaderHeight == 0 {
bc.headerHashes = append(bc.headerHashes, currHeaderHash)
}
// There is a high chance that the Node is stopped before the next
// batch of 2000 headers was stored. Via the currentHeaders stored we can sync
// that with stored blocks.
if currHeaderHeight >= bc.storedHeaderCount {
hash := currHeaderHash
var targetHash common.Hash
if len(bc.headerHashes) > 0 {
targetHash = bc.headerHashes[len(bc.headerHashes)-1]
} else {
genesisBlock, err := createGenesisBlock(&bc.config)
if err != nil {
return err
}
targetHash = genesisBlock.Hash()
bc.headerHashes = append(bc.headerHashes, targetHash)
}
headers := make([]*block.Header, 0)
for hash != targetHash {
header, err := bc.GetHeader(hash)
if err != nil {
return fmt.Errorf("could not get header %s: %w", hash, err)
}
headers = append(headers, header)
hash = header.PrevHash
}
headerSliceReverse(headers)
for _, h := range headers {
bc.headerHashes = append(bc.headerHashes, h.Hash())
}
}
bHeight, err := bc.dao.GetCurrentBlockHeight()
if err != nil {
return fmt.Errorf("failed to retrieve current block height: %w", err)
}
bc.blockHeight = bHeight
bc.persistedHeight = bHeight
if err = bc.stateRoot.Init(bHeight); err != nil {
return fmt.Errorf("can't init MPT at height %d: %w", bHeight, err)
}
err = bc.initializeNativeCache(bc.blockHeight, bc.dao)
if err != nil {
return fmt.Errorf("can't init natives cache: %w", err)
}
return bc.updateExtensibleWhitelist(bHeight)
}
func (bc *Blockchain) initializeNativeCache(blockHeight uint32, d *dao.Simple) error {
err := bc.contracts.Designate.UpdateCache(d)
if err != nil {
return fmt.Errorf("can't init cache for Designation native contract: %w", err)
}
err = bc.contracts.Policy.UpdateCache(d)
if err != nil {
return fmt.Errorf("can't init cache for Policy native contract: %w", err)
}
return nil
}
// Run runs chain loop, it needs to be run as goroutine and executing it is
// critical for correct Blockchain operation.
func (bc *Blockchain) Run() {
persistTimer := time.NewTimer(persistInterval)
defer func() {
persistTimer.Stop()
if _, err := bc.persist(true); err != nil {
bc.log.Warn("failed to persist", zap.Error(err))
}
if err := bc.dao.Store.Close(); err != nil {
bc.log.Warn("failed to close db", zap.Error(err))
}
close(bc.runToExitCh)
}()
go bc.notificationDispatcher()
var nextSync bool
for {
select {
case <-bc.stopCh:
return
case <-persistTimer.C:
var oldPersisted uint32
var gcDur time.Duration
if bc.config.RemoveUntraceableBlocks {
oldPersisted = atomic.LoadUint32(&bc.persistedHeight)
}
dur, err := bc.persist(nextSync)
if err != nil {
bc.log.Warn("failed to persist blockchain", zap.Error(err))
}
if bc.config.RemoveUntraceableBlocks {
gcDur = bc.tryRunGC(oldPersisted)
}
nextSync = dur > persistInterval*2
interval := persistInterval - dur - gcDur
if interval <= 0 {
interval = time.Microsecond // Reset doesn't work with zero value
}
persistTimer.Reset(interval)
}
}
}
func (bc *Blockchain) tryRunGC(old uint32) time.Duration {
var dur time.Duration
new := atomic.LoadUint32(&bc.persistedHeight)
var tgtBlock = int64(new)
tgtBlock -= int64(bc.config.MaxTraceableBlocks)
// Always round to the GCP.
tgtBlock /= int64(bc.config.GarbageCollectionPeriod)
tgtBlock *= int64(bc.config.GarbageCollectionPeriod)
// Count periods.
old /= bc.config.GarbageCollectionPeriod
new /= bc.config.GarbageCollectionPeriod
if tgtBlock > int64(bc.config.GarbageCollectionPeriod) && new != old {
tgtBlock /= int64(bc.config.GarbageCollectionPeriod)
tgtBlock *= int64(bc.config.GarbageCollectionPeriod)
dur = bc.stateRoot.GC(uint32(tgtBlock), bc.store)
}
return dur
}
// notificationDispatcher manages subscription to events and broadcasts new events.
func (bc *Blockchain) notificationDispatcher() {
var (
// These are just sets of subscribers, though modelled as maps
// for ease of management (not a lot of subscriptions is really
// expected, but maps are convenient for adding/deleting elements).
blockFeed = make(map[chan<- *block.Block]bool)
txFeed = make(map[chan<- *transaction.Transaction]bool)
notificationFeed = make(map[chan<- *types.Log]bool)
executionFeed = make(map[chan<- *types.Receipt]bool)
)
for {
select {
case <-bc.stopCh:
return
case sub := <-bc.subCh:
switch ch := sub.(type) {
case chan<- *block.Block:
blockFeed[ch] = true
case chan<- *transaction.Transaction:
txFeed[ch] = true
case chan<- *types.Log:
notificationFeed[ch] = true
case chan<- *types.Receipt:
executionFeed[ch] = true
default:
panic(fmt.Sprintf("bad subscription: %T", sub))
}
case unsub := <-bc.unsubCh:
switch ch := unsub.(type) {
case chan<- *block.Block:
delete(blockFeed, ch)
case chan<- *transaction.Transaction:
delete(txFeed, ch)
case chan<- *types.Log:
delete(notificationFeed, ch)
case chan<- *types.Receipt:
delete(executionFeed, ch)
default:
panic(fmt.Sprintf("bad unsubscription: %T", unsub))
}
case event := <-bc.events:
// We don't want to waste time looping through transactions when there are no
// subscribers.
if len(txFeed) != 0 || len(notificationFeed) != 0 || len(executionFeed) != 0 {
for i, tx := range event.block.Transactions {
aer := event.appExecResults[i]
if aer.TxHash != (tx.Hash()) {
panic("inconsistent application execution results")
}
for ch := range executionFeed {
ch <- aer
}
if aer.Status == 1 {
for _, log := range aer.Logs {
for ch := range notificationFeed {
ch <- log
}
}
}
for ch := range txFeed {
ch <- tx
}
}
}
for ch := range blockFeed {
ch <- event.block
}
}
}
}
// Close stops Blockchain's internal loop, syncs changes to persistent storage
// and closes it. The Blockchain is no longer functional after the call to Close.
func (bc *Blockchain) Close() {
// If there is a block addition in progress, wait for it to finish and
// don't allow new ones.
bc.addLock.Lock()
close(bc.stopCh)
<-bc.runToExitCh
bc.addLock.Unlock()
}
// AddBlock accepts successive block for the Blockchain, verifies it and
// stores internally. Eventually it will be persisted to the backing storage.
func (bc *Blockchain) AddBlock(block *block.Block) error {
bc.addLock.Lock()
defer bc.addLock.Unlock()
var mp *mempool.Pool
expectedHeight := bc.BlockHeight() + 1
if expectedHeight != block.Index {
return fmt.Errorf("expected %d, got %d: %w", expectedHeight, block.Index, ErrInvalidBlockIndex)
}
if block.Index == bc.HeaderHeight()+1 {
err := bc.addHeaders(bc.config.VerifyBlocks, &block.Header)
if err != nil {
return err
}
}
if bc.config.VerifyBlocks {
merkle := block.ComputeMerkleRoot()
if block.MerkleRoot != merkle {
return errors.New("invalid block: MerkleRoot mismatch")
}
mp = mempool.New(len(block.Transactions), 0, false)
for _, tx := range block.Transactions {
var err error
// Transactions are verified before adding them
// into the pool, so there is no point in doing
// it again even if we're verifying in-block transactions.
if bc.memPool.ContainsKey(tx.Hash()) {
err = mp.Add(tx, bc)
if err == nil {
continue
}
} else {
err = bc.verifyAndPoolTx(tx, mp, bc)
}
if err != nil && bc.config.VerifyTransactions {
return fmt.Errorf("transaction %s failed to verify: %w", tx.Hash().String(), err)
}
}
}
return bc.storeBlock(block, mp)
}
// AddHeaders processes the given headers and add them to the
// HeaderHashList. It expects headers to be sorted by index.
func (bc *Blockchain) AddHeaders(headers ...*block.Header) error {
return bc.addHeaders(bc.config.VerifyBlocks, headers...)
}
// addHeaders is an internal implementation of AddHeaders (`verify` parameter
// tells it to verify or not verify given headers).
func (bc *Blockchain) addHeaders(verify bool, headers ...*block.Header) error {
var (
start = time.Now()
batch = bc.dao.GetPrivate()
err error
)
if len(headers) > 0 {
var i int
curHeight := bc.HeaderHeight()
for i = range headers {
if headers[i].Index > curHeight {
break
}
}
headers = headers[i:]
}
if len(headers) == 0 {
return nil
} else if verify {
// Verify that the chain of the headers is consistent.
var lastHeader *block.Header
if lastHeader, err = bc.GetHeader(headers[0].PrevHash); err != nil {
return fmt.Errorf("previous header was not found: %w", err)
}
for _, h := range headers {
if err = bc.verifyHeader(h, lastHeader); err != nil {
return err
}
lastHeader = h
}
}
bc.headerHashesLock.Lock()
defer bc.headerHashesLock.Unlock()
oldlen := len(bc.headerHashes)
var lastHeader *block.Header
for _, h := range headers {
if int(h.Index) != len(bc.headerHashes) {
continue
}
bc.headerHashes = append(bc.headerHashes, h.Hash())
lastHeader = h
bc.dao.StoreAsHeader(h)
}
if oldlen != len(bc.headerHashes) {
for int(lastHeader.Index)-headerBatchCount >= int(bc.storedHeaderCount) {
err = batch.StoreHeaderHashes(bc.headerHashes[bc.storedHeaderCount:bc.storedHeaderCount+headerBatchCount],
bc.storedHeaderCount)
if err != nil {
return err
}
bc.storedHeaderCount += headerBatchCount
}
batch.PutCurrentHeader(lastHeader.Hash(), lastHeader.Index)
updateHeaderHeightMetric(len(bc.headerHashes) - 1)
if _, err = batch.Persist(); err != nil {
return err
}
bc.log.Debug("done processing headers",
zap.Int("headerIndex", len(bc.headerHashes)-1),
zap.Uint32("blockHeight", bc.BlockHeight()),
zap.Duration("took", time.Since(start)))
}
return nil
}
// GetStateModule returns state root service instance.
func (bc *Blockchain) GetStateModule() blockchainer.StateRoot {
return bc.stateRoot
}
// storeBlock performs chain update using the block given, it executes all
// transactions with all appropriate side-effects and updates Blockchain state.
// This is the only way to change Blockchain state.
func (bc *Blockchain) storeBlock(block *block.Block, txpool *mempool.Pool) error {
var (
cache = bc.dao.GetPrivate()
aerCache = bc.dao.GetPrivate()
appExecResults = make([]*types.Receipt, 0, 2+len(block.Transactions))
aerchan = make(chan *types.Receipt, len(block.Transactions)/8) // Tested 8 and 4 with no practical difference, but feel free to test more and tune.
aerdone = make(chan error)
)
go func() {
var (
kvcache = aerCache
err error
txCnt int
blockaer *types.Receipt
)
kvcache.StoreAsCurrentBlock(block)
if bc.config.RemoveUntraceableBlocks {
var start, stop uint32
if block.Index > bc.config.MaxTraceableBlocks {
start = block.Index - bc.config.MaxTraceableBlocks // is at least 1
stop = start + 1
}
for index := start; index < stop; index++ {
err := kvcache.DeleteBlock(bc.headerHashes[index])
if err != nil {
bc.log.Warn("error while removing old block",
zap.Uint32("index", index),
zap.Error(err))
}
}
}
for aer := range aerchan {
if txCnt == len(block.Transactions) {
blockaer = aer
break
}
err = kvcache.StoreAsTransaction(block.Transactions[txCnt], aer)
txCnt++
if err != nil {
err = fmt.Errorf("failed to store exec result: %w", err)
break
}
}
if err != nil {
aerdone <- err
return
}
if err := kvcache.StoreAsBlock(block, blockaer); err != nil {
aerdone <- err
return
}
close(aerdone)
}()
var (
err error
execErr error
logIndex uint
cumulativeGas uint64
blockGasUsed uint64
)
err = bc.onPersist(cache, block)
if err != nil {
return fmt.Errorf("onPersist failed: %w", err)
}
sdb := statedb.NewStateDB(cache, bc)
for i, tx := range block.Transactions {
bc.log.Debug("executing tx", zap.String("hash", tx.Hash().String()))
gasPrice := tx.GasPrice()
blockGasUsed += tx.Gas()
netFee := transaction.CalculateNetworkFee(tx, bc.FeePerByte())
gas := tx.Gas() - netFee
ic, err := interop.NewContext(block, tx, sdb, bc, nil)
if err != nil {
panic(err)
}
vm := ic.VM
var (
left uint64
address common.Address
)
sdb.PrepareAccessList(tx.From(), tx.To(), evm.PrecompiledAddressesBerlin, tx.AccessList())
if tx.To() == nil {
_, address, left, execErr = vm.Create(ic, tx.Data(), gas, tx.Value())
} else {
_, left, execErr = vm.Call(ic, *tx.To(), tx.Data(), gas, tx.Value())
}
if execErr != nil {
bc.log.Debug("error when executing tx", zap.Uint32("block_index", block.Index),
zap.String("tx_hash", tx.Hash().String()),
zap.String("error", execErr.Error()))
}
gasUsed := tx.Gas() - left
logs := sdb.GetLogs()
sdb.SetNonce(tx.From(), sdb.GetNonce(tx.From())+1)
if block.Index > 0 {
sdb.AddBalance(ic.Coinbase(), big.NewInt(0).Mul(big.NewInt(int64(netFee)), gasPrice))
}
if gas > left {
commitAddress, err := bc.GetConsensusAddress()
if err != nil {
panic(err)
}
sdb.AddBalance(commitAddress, big.NewInt(0).Mul(big.NewInt(int64(gas-left)), gasPrice))
}
refund := sdb.GetRefund()
maxRefund := gasUsed / params.RefundQuotientEIP3529
if refund > maxRefund {
refund = maxRefund
}
sdb.SubBalance(tx.From(), big.NewInt(0).Mul(big.NewInt(int64(gasUsed-refund)), gasPrice))
sdb.Commit()
cumulativeGas += gasUsed
for _, log := range logs {
log.BlockHash = block.Hash()
log.TxHash = tx.Hash()
log.TxIndex = uint(i)
log.Index = logIndex
logIndex++
}
aer := &types.Receipt{
BlockHash: block.Hash(),
BlockNumber: big.NewInt(int64(block.Index)),
TxHash: tx.Hash(),
TransactionIndex: uint(i),
GasUsed: gasUsed,
ContractAddress: address,
CumulativeGasUsed: cumulativeGas,
Logs: logs,
}
aer.Bloom = types.BytesToBloom(types.LogsBloom(aer.Logs))
if execErr == nil {
aer.Status = 1
}
//aer.PostState = []byte{byte(aer.Status)}
aer.PostState = block.MerkleRoot.Bytes()
appExecResults = append(appExecResults, aer)
aerchan <- aer
}
err = bc.postPersist(cache, block)
if err != nil {
return fmt.Errorf("postPersist failed: %w", err)
}
aer := &types.Receipt{
BlockHash: block.Hash(),
BlockNumber: big.NewInt(int64(block.Index)),
TxHash: block.Hash(),
TransactionIndex: 0,
GasUsed: blockGasUsed,
ContractAddress: common.Address{},
CumulativeGasUsed: cumulativeGas,
Logs: []*types.Log{},
}
aerchan <- aer
close(aerchan)
b := mpt.MapToMPTBatch(cache.Store.GetStorageChanges())
mpt, sr, err := bc.stateRoot.AddMPTBatch(block.Index, b, cache.Store)
if err != nil {
// Release goroutines, don't care about errors, we already have one.
<-aerdone
// Here MPT can be left in a half-applied state.
// However if this error occurs, this is a bug somewhere in code
// because changes applied are the ones from HALTed transactions.
return fmt.Errorf("error while trying to apply MPT changes: %s", err.Error())
}
if bc.config.SaveStorageBatch {
bc.lastBatch = cache.GetBatch()
}
// Every persist cycle we also compact our in-memory MPT. It's flushed
// already in AddMPTBatch, so collapsing it is safe.
persistedHeight := atomic.LoadUint32(&bc.persistedHeight)
if persistedHeight == block.Index-1 {
// 10 is good and roughly estimated to fit remaining trie into 1M of memory.
mpt.Collapse(10)
}
aererr := <-aerdone
if aererr != nil {
bc.log.Debug("receipt save error", zap.Error(aererr))
return aererr
}
bc.lock.Lock()
_, err = aerCache.Persist()
if err != nil {
bc.lock.Unlock()
return err
}
_, err = cache.Persist()
if err != nil {
bc.lock.Unlock()
return err
}
mpt.Store = bc.dao.Store
bc.stateRoot.UpdateCurrentLocal(mpt, sr)
bc.topBlock.Store(block)
bc.topBlockAer.Store(aer)
atomic.StoreUint32(&bc.blockHeight, block.Index)
senders := bc.memPool.RemoveStale(func(tx *transaction.Transaction) bool { return bc.IsTxStillRelevant(tx, txpool, false) }, bc)
// refresh nonce for deleted items
for sender := range senders {
bc.memPool.RefreshNonce(sender, bc.GetNonce(sender))
}
for _, f := range bc.postBlock {
f(bc.IsTxStillRelevant, txpool, block)
}
if err := bc.updateExtensibleWhitelist(block.Index); err != nil {
bc.lock.Unlock()
return err
}
bc.lock.Unlock()
updateBlockHeightMetric(block.Index)
// Genesis block is stored when Blockchain is not yet running, so there
// is no one to read this event. And it doesn't make much sense as event
// anyway.
if block.Index != 0 {
bc.events <- bcEvent{block, appExecResults}
}
return nil
}
func (bc *Blockchain) onPersist(d *dao.Simple, b *block.Block) error {
return bc.contracts.OnPersist(d, b)
}
func (bc *Blockchain) postPersist(d *dao.Simple, b *block.Block) error {
err := bc.contracts.PostPersist(d, b)
if err != nil {
return err
}
nodes, index, err := bc.contracts.Designate.GetDesignatedByRole(d, noderoles.StateValidator, b.Index)
if err != nil {
return err
}
bc.stateRoot.UpdateStateValidators(index, nodes)
return nil
}
func (bc *Blockchain) updateExtensibleWhitelist(height uint32) error {
stateVals, _, err := bc.contracts.Designate.GetDesignatedByRole(bc.dao, noderoles.StateValidator, height+1)
if err != nil {
return err
}
validators, err := bc.contracts.Designate.GetValidators(bc.dao, height+1)
if err != nil {
return err
}
newList := []common.Address{}
bc.updateExtensibleList(&newList, validators)
bc.updateExtensibleList(&newList, stateVals)
sort.Slice(newList, func(i, j int) bool {
return newList[i].Hash().Big().Cmp(newList[j].Hash().Big()) < 0
})
bc.extensible.Store(newList)
return nil
}
func (bc *Blockchain) updateExtensibleList(s *[]common.Address, pubs keys.PublicKeys) {
for _, pub := range pubs {
*s = append(*s, pub.Address())
}
}
// IsExtensibleAllowed determines if script hash is allowed to send extensible payloads.
func (bc *Blockchain) IsExtensibleAllowed(u common.Address) bool {
us := bc.extensible.Load().([]common.Address)
for _, addr := range us {
if addr == u {
return true
}
}
return false
}
// GetUtilityTokenBalance returns utility token (GAS) balance for the acc.
func (bc *Blockchain) GetUtilityTokenBalance(acc common.Address) *big.Int {
bs := bc.contracts.GAS.GetBalance(bc.dao, acc)
if bs == nil {
return big.NewInt(0)
}
return bs
}
// LastBatch returns last persisted storage batch.
func (bc *Blockchain) LastBatch() *storage.MemBatch {
return bc.lastBatch
}
// persist flushes current in-memory Store contents to the persistent storage.
func (bc *Blockchain) persist(isSync bool) (time.Duration, error) {
var (
start = time.Now()
duration time.Duration
persisted int
err error
)
if isSync {
persisted, err = bc.dao.PersistSync()
} else {
persisted, err = bc.dao.Persist()
}
if err != nil {
return 0, err
}
if persisted > 0 {
bHeight, err := bc.persistent.GetCurrentBlockHeight()
if err != nil {
return 0, err
}
oldHeight := atomic.SwapUint32(&bc.persistedHeight, bHeight)
diff := bHeight - oldHeight
storedHeaderHeight, _, err := bc.persistent.GetCurrentHeaderHeight()
if err != nil {
return 0, err
}
duration = time.Since(start)
bc.log.Info("persisted to disk",
zap.Uint32("blocks", diff),
zap.Int("keys", persisted),
zap.Uint32("headerHeight", storedHeaderHeight),
zap.Uint32("blockHeight", bHeight),
zap.Duration("took", duration))
// update monitoring metrics.
updatePersistedHeightMetric(bHeight)
}
return duration, nil
}
// GetTransaction returns a TX and its height by the given hash. The height is MaxUint32 if tx is in the mempool.
func (bc *Blockchain) GetTransaction(hash common.Hash) (*transaction.Transaction, *types.Receipt, error) {
if tx, ok := bc.memPool.TryGetValue(hash); ok {
return tx, nil, nil // the height is not actually defined for memPool transaction.
}
return bc.dao.GetTransaction(hash)
}
// GetStorageItem returns an item from storage.
func (bc *Blockchain) GetStorageItem(hash common.Address, key []byte) state.StorageItem {
return bc.dao.GetStorageItem(hash, key)
}
// GetStorageItems returns all storage items for a given contract id.
func (bc *Blockchain) GetStorageItems(hash common.Address) ([]state.StorageItemWithKey, error) {
return bc.dao.GetStorageItems(hash)
}
// GetBlock returns a Block by the given hash.
func (bc *Blockchain) GetBlock(hash common.Hash, full bool) (*block.Block, *types.Receipt, error) {
topBlock := bc.topBlock.Load()
if topBlock != nil {
tb := topBlock.(*block.Block)
if tb.Hash() == hash {
return tb, bc.topBlockAer.Load().(*types.Receipt), nil
}
}
block, receipt, err := bc.dao.GetBlock(hash)
if err != nil {
return nil, nil, err
}
if block.MerkleRoot != (common.Hash{}) && len(block.Transactions) == 0 {
return nil, nil, errors.New("only header is found")
}
if full {
for _, tx := range block.Transactions {
stx, _, err := bc.dao.GetTransaction(tx.Hash())