-
Notifications
You must be signed in to change notification settings - Fork 42
/
protocol_block.go
1394 lines (1235 loc) · 43.1 KB
/
protocol_block.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 miner
import (
"bytes"
"context"
"errors"
"fmt"
"math"
"sort"
"strconv"
"sync"
"time"
cstate "0chain.net/chaincore/chain/state"
"0chain.net/core/config"
"github.com/rcrowley/go-metrics"
"go.uber.org/zap"
"0chain.net/chaincore/block"
"0chain.net/chaincore/chain"
"0chain.net/chaincore/client"
"0chain.net/chaincore/node"
"0chain.net/chaincore/transaction"
"0chain.net/core/common"
"0chain.net/core/datastore"
"0chain.net/core/encryption"
"0chain.net/smartcontract/minersc"
"0chain.net/smartcontract/storagesc"
"github.com/0chain/common/core/logging"
"github.com/0chain/common/core/util"
)
// InsufficientTxns - to indicate an error when the transactions are not sufficient to make a block
const InsufficientTxns = "insufficient_txns"
// ErrLFBClientStateNil is returned when client state of latest finalized block is nil
var ErrLFBClientStateNil = errors.New("client state of latest finalized block is empty")
var (
ErrNotTimeTolerant = common.NewError("not_time_tolerant", "transaction is behind time tolerance")
FutureTransaction = common.NewError("future_transaction", "transaction has future nonce")
PastTransaction = common.NewError("past_transaction", "transaction has past nonce")
)
var (
bgTimer metrics.Timer // block generation timer
bpTimer metrics.Timer // block processing timer (includes block verification)
btvTimer metrics.Timer // block verification timer
bsHistogram metrics.Histogram
)
func init() {
bgTimer = metrics.GetOrRegisterTimer("bg_time", nil)
bpTimer = metrics.GetOrRegisterTimer("bv_time", nil)
btvTimer = metrics.GetOrRegisterTimer("btv_time", nil)
bsHistogram = metrics.GetOrRegisterHistogram("bs_histogram", nil, metrics.NewUniformSample(1024))
}
func (mc *Chain) processTxn(ctx context.Context, txn *transaction.Transaction, b *block.Block, bState util.MerklePatriciaTrieI, clients map[string]*client.Client) error {
clients[txn.ClientID] = nil
events, err := mc.UpdateState(ctx, b, bState, txn)
if err != nil {
logging.Logger.Error("processTxn", zap.String("txn", txn.Hash),
zap.String("txn_object", datastore.ToJSON(txn).String()),
zap.Error(err))
return err
}
b.Events = append(b.Events, events...)
b.Txns = append(b.Txns, txn)
b.AddTransaction(txn)
return nil
}
func (mc *Chain) createFeeTxn(b *block.Block) (*transaction.Transaction, error) {
feeTxn := transaction.Provider().(*transaction.Transaction)
feeTxn.ClientID = node.Self.ID
feeTxn.PublicKey = node.Self.PublicKey
feeTxn.ToClientID = minersc.ADDRESS
feeTxn.CreationDate = b.CreationDate
feeTxn.TransactionType = transaction.TxnTypeSmartContract
feeTxn.TransactionData = fmt.Sprintf(`{"name":"payFees","input":{"round":%v}}`, b.Round)
feeTxn.Fee = 0 //TODO: fee needs to be set to governance minimum fee
if err := feeTxn.ComputeProperties(); err != nil {
return nil, err
}
return feeTxn, nil
}
func (mc *Chain) getCurrentSelfNonce(round int64, minerId datastore.Key, bState util.MerklePatriciaTrieI) (int64, error) {
s, err := chain.GetStateById(bState, minerId)
if err != nil {
if cstate.ErrInvalidState(err) {
mc.SyncMissingNodes(round, bState.GetMissingNodeKeys())
}
if err != util.ErrValueNotPresent {
logging.Logger.Error("can't get nonce", zap.Error(err))
return 0, err
}
return 1, nil
}
node.Self.SetNonce(s.Nonce)
return node.Self.GetNextNonce(), nil
}
func (mc *Chain) storageScCommitSettingChangesTx(b *block.Block) (*transaction.Transaction, error) {
scTxn := transaction.Provider().(*transaction.Transaction)
scTxn.ClientID = node.Self.ID
scTxn.PublicKey = node.Self.PublicKey
scTxn.ToClientID = storagesc.ADDRESS
scTxn.CreationDate = b.CreationDate
scTxn.TransactionType = transaction.TxnTypeSmartContract
scTxn.TransactionData = fmt.Sprintf(`{"name":"commit_settings_changes","input":{"round":%v}}`, b.Round)
scTxn.Fee = 0
if err := scTxn.ComputeProperties(); err != nil {
return nil, err
}
return scTxn, nil
}
func (mc *Chain) createBlockRewardTxn(b *block.Block) (*transaction.Transaction, error) {
brTxn := transaction.Provider().(*transaction.Transaction)
brTxn.ClientID = node.Self.ID
brTxn.PublicKey = node.Self.PublicKey
brTxn.ToClientID = storagesc.ADDRESS
brTxn.CreationDate = b.CreationDate
brTxn.TransactionType = transaction.TxnTypeSmartContract
brTxn.TransactionData = fmt.Sprintf(`{"name":"blobber_block_rewards","input":{"round":%v}}`, b.Round)
brTxn.Fee = 0
if err := brTxn.ComputeProperties(); err != nil {
return nil, err
}
return brTxn, nil
}
func (mc *Chain) validateTransaction(b *block.Block,
bState util.MerklePatriciaTrieI, txn *transaction.Transaction, waitC chan struct{}) (int64, error) {
if !common.WithinTime(int64(b.CreationDate), int64(txn.CreationDate), transaction.TXN_TIME_TOLERANCE) {
return 0, ErrNotTimeTolerant
}
state, err := chain.GetStateById(bState, txn.ClientID)
if err != nil {
if err == util.ErrValueNotPresent {
if txn.Nonce > 1 {
return 0, FutureTransaction
}
if txn.Nonce < 1 {
return 0, PastTransaction
}
return 0, nil
}
if cstate.ErrInvalidState(err) {
mc.SyncMissingNodes(b.Round, bState.GetMissingNodeKeys(), waitC)
}
return 0, err
}
if txn.Nonce-state.Nonce > 1 {
return state.Nonce, FutureTransaction
}
if txn.Nonce-state.Nonce < 1 {
return state.Nonce, PastTransaction
}
return state.Nonce, nil
}
// UpdatePendingBlock - updates the block that is generated and pending
// rest of the process.
func (mc *Chain) UpdatePendingBlock(ctx context.Context, b *block.Block, txns []datastore.Entity) {
transactionMetadataProvider := datastore.GetEntityMetadata("txn")
// NOTE: Since we are not explicitly maintaining state in the db, we just
// need to adjust the collection score and don't need to write the
// entities themselves
//
// transactionMetadataProvider.GetStore().MultiWrite(ctx, transactionMetadataProvider, txns)
//
if err := transactionMetadataProvider.GetStore().MultiAddToCollection(ctx,
transactionMetadataProvider, txns); err != nil {
logging.Logger.Error("update pending block failed", zap.Error(err))
}
}
func (mc *Chain) verifySmartContracts(ctx context.Context, b *block.Block) error {
for _, txn := range b.Txns {
if txn.TransactionType == transaction.TxnTypeSmartContract {
err := txn.VerifyOutputHash(ctx)
if err != nil {
logging.Logger.Error("Smart contract output verification failed", zap.Error(err), zap.String("output", txn.TransactionOutput))
return common.NewError("txn_output_verification_failed", "Transaction output hash verification failed")
}
}
}
return nil
}
// VerifyBlockMagicBlockReference verifies LatestFinalizedMagicBlockHash and
// LatestFinalizedMagicBlockRound fields of the block.
func (mc *Chain) VerifyBlockMagicBlockReference(b *block.Block) (err error) {
var (
round = b.Round
lfmbr = mc.GetLatestFinalizedMagicBlockRound(round)
offsetRound = mbRoundOffset(round)
nextVCRound = mc.NextViewChange()
)
if lfmbr == nil {
return common.NewError("verify_block_mb_reference", "can't get lfmbr")
}
if nextVCRound > 0 && offsetRound >= nextVCRound && lfmbr.StartingRound < nextVCRound {
// TODO: offsetRound could >= nextVCRound on start when the nextVCRound was not updated correctly.
logging.Logger.Warn("verify_block_mb_reference - required MB missing or still not finalized")
return common.NewError("verify_block_mb_reference",
"required MB missing or still not finalized")
}
if b.LatestFinalizedMagicBlockHash != lfmbr.Hash {
return common.NewError("verify_block_mb_reference",
"unexpected latest_finalized_mb_hash")
}
if b.LatestFinalizedMagicBlockRound != lfmbr.Round {
return common.NewError("verify_block_mb_reference",
"unexpected latest_finalized_mb_round")
}
return
}
// VerifyBlockMagicBlock verifies MagicBlock of the block. If this miner is
// member of miners of the MagicBlock it can do the verification. Otherwise,
// this method does nothing.
func (mc *Chain) VerifyBlockMagicBlock(ctx context.Context, b *block.Block) (
err error) {
var (
mb = b.MagicBlock
selfNodeKey = node.Self.Underlying().GetKey()
nvc int64
)
if mb == nil || !mb.Miners.HasNode(selfNodeKey) {
return // ok
}
if !b.IsStateComputed() {
return common.NewErrorf("verify_block_mb",
"block state is not computed or synced %d", b.Round)
}
// the block state required for the NextViewChangeOfBlock to
// get fresh NVC value
if b.ClientState == nil {
if err = mc.InitBlockState(b); err != nil {
return common.NewErrorf("verify_block_mb",
"can't initialize block state %d: %v", b.Round, err)
}
}
if nvc, err = mc.NextViewChangeOfBlock(b); err != nil {
return common.NewErrorf("verify_block_mb",
"can't get NVC of the block %d: %v", b.Round, err)
}
logging.Logger.Debug("verify_block_mb", zap.Int64("round", b.Round),
zap.Int64("mb_sr", mb.StartingRound), zap.Int64("nvc", nvc))
if mb.StartingRound != b.Round {
return common.NewErrorf("verify_block_mb", "got block with invalid "+
"MB, MB starting round not equal to the block round: R: %d, SR: %d",
b.Round, mb.StartingRound)
}
// check out next view change (miner SC MB rejection)
if mb.StartingRound != nvc {
return common.NewErrorf("verify_block_mb",
"got block with MB rejected by miner SC: %d, %d",
mb.StartingRound, nvc)
}
// check out the MB if this miner is member of it
var (
id = strconv.FormatInt(mb.MagicBlockNumber, 10)
lmb *block.MagicBlock
)
// get stored MB
if lmb, err = LoadMagicBlock(ctx, id); err != nil {
return common.NewErrorf("verify_block_mb",
"can't load related MB from store: %v", err)
}
// compare given MB and the stored one (should be equal)
if !bytes.Equal(mb.Encode(), lmb.Encode()) {
return common.NewError("verify_block_mb",
"MB given doesn't match the stored one")
}
return
}
// VerifyBlock - given a set of transaction ids within a block, validate the block.
func (mc *Chain) VerifyBlock(ctx context.Context, b *block.Block) (
bvt *block.BlockVerificationTicket, err error) {
//ctx = common.GetRootContext()
var start = time.Now()
cur := time.Now()
if err = b.Validate(ctx); err != nil {
return
}
logging.Logger.Debug("Validating finished", zap.String("block", b.Hash), zap.Duration("spent", time.Since(cur)))
cur = time.Now()
if err = mc.VerifyBlockMagicBlockReference(b); err != nil {
return
}
logging.Logger.Debug("VerifyBlockMagicBlockReference finished", zap.String("block", b.Hash), zap.Duration("spent", time.Since(cur)))
var pb *block.Block
cur = time.Now()
if pb = mc.GetPreviousBlock(ctx, b); pb == nil {
return nil, block.ErrPreviousBlockUnavailable
}
logging.Logger.Debug("GetPreviousBlock finished", zap.String("block", b.Hash), zap.Duration("spent", time.Since(cur)))
cur = time.Now()
if err = mc.ValidateTransactions(ctx, b); err != nil {
return
}
logging.Logger.Debug("ValidateTransactions finished", zap.String("block", b.Hash), zap.Duration("spent", time.Since(cur)))
cost := 0
lfb := mc.GetLatestFinalizedBlock()
if lfb.ClientState == nil {
logging.Logger.Warn("ValidateBlockCost, could not estimate txn cost",
zap.Int64("round", b.Round),
zap.String("hash", b.Hash),
zap.Error(ErrLFBClientStateNil))
return nil, ErrLFBClientStateNil
}
var costs []int
for _, txn := range b.Txns {
if err := mc.syncAndRetry(ctx, b, "estimate cost", func(ctx context.Context, waitC chan struct{}) error {
c, err := mc.EstimateTransactionCost(ctx, lfb, txn, chain.WithSync(), chain.WithNotifyC(waitC))
if err != nil {
return err
}
cost += c
costs = append(costs, c)
return nil
}); err != nil {
return nil, err
}
}
if cost > mc.ChainConfig.MaxBlockCost() {
logging.Logger.Error("cost limit exceeded", zap.Int("calculated_cost", cost),
zap.Int("cost_limit", mc.ChainConfig.MaxBlockCost()), zap.String("block_hash", b.Hash),
zap.Int("txn_amount", len(b.Txns)), zap.Ints("txn_costs", costs))
return nil, block.ErrCostTooBig
}
logging.Logger.Debug("ValidateBlockCost",
zap.Int64("round", b.Round),
zap.String("hash", b.Hash),
zap.Int("calculated cost", cost))
cur = time.Now()
if err := mc.syncAndRetry(ctx, b, "verify block", func(ctx context.Context, waitC chan struct{}) error {
return mc.ComputeState(ctx, b, waitC)
}); err != nil {
return nil, err
}
logging.Logger.Debug("verify block - ComputeState finished",
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.Duration("spent", time.Since(cur)))
cur = time.Now()
if err = mc.verifySmartContracts(ctx, b); err != nil {
return
}
logging.Logger.Debug("verifySmartContracts finished", zap.String("block", b.Hash), zap.Duration("spent", time.Since(cur)))
cur = time.Now()
if err = mc.VerifyBlockMagicBlock(ctx, b); err != nil {
return
}
logging.Logger.Debug("VerifyBlockMagicBlock finished", zap.String("block", b.Hash), zap.Duration("spent", time.Since(cur)))
cur = time.Now()
if bvt, err = mc.SignBlock(ctx, b); err != nil {
return nil, err
}
bpTimer.UpdateSince(start)
logging.Logger.Debug("SignBlock finished", zap.String("block", b.Hash), zap.Duration("spent", time.Since(cur)))
logging.Logger.Info("verify block successful", zap.Int64("round", b.Round),
zap.Int("block_size", len(b.Txns)), zap.Duration("time", time.Since(start)),
zap.String("block", b.Hash), zap.String("prev_block", b.PrevHash),
zap.String("state_hash", util.ToHex(b.ClientStateHash)),
zap.Int8("state_status", b.GetStateStatus()))
return
}
func (mc *Chain) syncAndRetry(ctx context.Context, b *block.Block, desc string, f func(ctx context.Context, ch chan struct{}) error) error {
cctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
for {
retry, err := func() (retry bool, err error) {
wc := make(chan struct{}, 1)
err = f(cctx, wc)
if err == nil {
return false, nil
}
if !cstate.ErrInvalidState(err) {
logging.Logger.Warn("sync and retry - none invalid state error",
zap.String("desc", desc),
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.Error(err))
return false, err
}
select {
case <-cctx.Done():
return false, cctx.Err()
case _, ok := <-wc:
if !ok {
logging.Logger.Error("sync and retry - sync failed",
zap.String("desc", desc),
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.Error(err))
return false, err
}
logging.Logger.Debug("sync and retry - retry",
zap.String("desc", desc),
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.String("prev_block", b.PrevHash),
zap.String("state_hash", util.ToHex(b.ClientStateHash)))
return true, nil
}
}()
if err != nil {
return err
}
if !retry {
return nil
}
}
}
func (mc *Chain) ValidateTransactions(ctx context.Context, b *block.Block) error {
return mc.validateTxnsWithContext.Run(ctx, func() error {
if len(b.Txns) == 0 {
logging.Logger.Warn("validating block with empty transactions")
return nil
}
var roundMismatch bool
var cancel bool
numWorkers := len(b.Txns) / mc.ValidationBatchSize()
if numWorkers*mc.ValidationBatchSize() < len(b.Txns) {
numWorkers++
}
var aggregate bool
aggregateSignatureScheme := encryption.GetAggregateSignatureScheme(mc.ClientSignatureScheme(), len(b.Txns), mc.ValidationBatchSize())
if aggregateSignatureScheme != nil {
aggregate = true
}
var (
validChannel = make(chan bool, numWorkers)
buildInTxnsMap = make(map[string]struct{})
bicLock = &sync.Mutex{}
)
hasDuplicateBuildInTxns := func(txn *transaction.Transaction) bool {
bicLock.Lock()
defer bicLock.Unlock()
if mc.isBuildInTxn(txn) {
if _, ok := buildInTxnsMap[txn.FunctionName]; ok {
return true
}
buildInTxnsMap[txn.FunctionName] = struct{}{}
}
return false
}
validate := func(ctx context.Context, txns []*transaction.Transaction, start int) {
result := false
defer func() {
select {
case validChannel <- result:
case <-ctx.Done():
}
}()
validTxns := make([]*transaction.Transaction, 0, len(txns))
for _, txn := range txns {
if cancel {
return
}
if mc.GetCurrentRound() > b.Round {
cancel = true
roundMismatch = true
return
}
if txn.OutputHash == "" {
cancel = true
logging.Logger.Error("validate transactions - no output hash", zap.Int64("round", b.Round), zap.String("block", b.Hash), zap.String("txn", datastore.ToJSON(txn).String()))
return
}
err := txn.ValidateWrtTimeForBlock(ctx, b.CreationDate, !aggregate)
if err != nil {
cancel = true
logging.Logger.Error("validate transactions", zap.Int64("round", b.Round), zap.String("block", b.Hash), zap.String("txn", datastore.ToJSON(txn).String()), zap.Error(err))
return
}
if hasDuplicateBuildInTxns(txn) {
logging.Logger.Error("validate transactions - duplicated build-in transaction",
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.String("txn", txn.Hash),
zap.String("function_name", txn.FunctionName))
cancel = true
return
}
validTxns = append(validTxns, txn)
}
txnsNeedVerify := mc.FilterOutValidatedTxns(validTxns)
if aggregate {
for i, txn := range txnsNeedVerify {
sigScheme, err := txn.GetSignatureScheme(ctx)
if err != nil {
panic(err)
}
if err := aggregateSignatureScheme.Aggregate(sigScheme, start+i, txn.Signature, txn.Hash); err != nil {
logging.Logger.Error("validate transactions failed",
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.Error(err))
cancel = true
return
}
}
}
result = true
}
ts := time.Now()
for start := 0; start < len(b.Txns); start += mc.ValidationBatchSize() {
end := start + mc.ValidationBatchSize()
if end > len(b.Txns) {
end = len(b.Txns)
}
go validate(ctx, b.Txns[start:end], start)
}
for count := 0; count < numWorkers; count++ {
select {
case <-ctx.Done():
return ctx.Err()
case result := <-validChannel:
if roundMismatch {
logging.Logger.Info("validate transactions (round mismatch)", zap.Int64("round", b.Round), zap.String("block", b.Hash), zap.Int64("current_round", mc.GetCurrentRound()))
return ErrRoundMismatch
}
if !result {
return common.NewError("txn_validation_failed", "Transaction validation failed")
}
}
}
if aggregate {
if _, err := aggregateSignatureScheme.Verify(); err != nil {
return err
}
}
btvTimer.UpdateSince(ts)
if mc.discoverClients {
go func() {
cs, err := b.GetClients()
if err != nil {
logging.Logger.Warn("validate transactions, get clients of block failed",
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.Error(err))
return
}
if err := mc.SaveClients(cs); err != nil {
logging.Logger.Warn("validate transactions, save discovered clients failed",
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.Error(err))
}
}()
}
return nil
})
}
/*SignBlock - sign the block and provide the verification ticket */
func (mc *Chain) signBlock(ctx context.Context, b *block.Block) (*block.BlockVerificationTicket, error) {
var bvt = &block.BlockVerificationTicket{}
bvt.BlockID = b.Hash
bvt.Round = b.Round
var (
self = node.Self
err error
)
bvt.VerifierID = self.Underlying().GetKey()
bvt.Signature, err = self.Sign(b.Hash)
b.SetVerificationStatus(block.VerificationSuccessful)
if err != nil {
return nil, err
}
return bvt, nil
}
/*UpdateFinalizedBlock - update the latest finalized block */
func (mc *Chain) updateFinalizedBlock(ctx context.Context, b *block.Block) {
logging.Logger.Info("update finalized block", zap.Int64("round", b.Round), zap.String("block", b.Hash), zap.Int64("lf_round", mc.GetLatestFinalizedBlock().Round), zap.Int64("current_round", mc.GetCurrentRound()), zap.Float64("weight", b.Weight()))
if config.Development() {
for _, t := range b.Txns {
if !t.DebugTxn() {
continue
}
logging.Logger.Info("update finalized block (debug transaction)", zap.String("txn", t.Hash), zap.String("block", b.Hash))
}
}
if err := mc.FinalizeBlock(ctx, b); err != nil {
logging.Logger.Warn("finalize block failed",
zap.Int64("round", b.Round),
zap.String("block", b.Hash),
zap.Error(err))
}
go mc.SendFinalizedBlock(context.Background(), b)
fr := mc.GetRound(b.Round)
if fr != nil {
fr.Finalize(b)
}
mc.DeleteRoundsBelow(b.Round)
var txns []datastore.Entity
for _, txn := range b.Txns {
txns = append(txns, txn)
}
cleanPoolCtx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
defer cancel()
transaction.RemoveFromPool(cleanPoolCtx, txns)
}
/*FinalizeBlock - finalize the transactions in the block */
func (mc *Chain) FinalizeBlock(ctx context.Context, b *block.Block) error {
modifiedTxns := make([]datastore.Entity, len(b.Txns))
for idx, txn := range b.Txns {
modifiedTxns[idx] = txn
}
return mc.deleteTxns(modifiedTxns)
}
func getLatestBlockFromSharders(ctx context.Context) *block.Block {
mc := GetMinerChain()
mb := mc.GetCurrentMagicBlock()
mb.Sharders.OneTimeStatusMonitor(ctx, mb.StartingRound)
lfBlocks := mc.GetLatestFinalizedBlockFromSharder(ctx)
if len(lfBlocks) > 0 {
logging.Logger.Info("bc-1 latest finalized Block",
zap.Int64("lfb_round", lfBlocks[0].Round))
return lfBlocks[0].Block
}
logging.Logger.Info("bc-1 sharders returned no lfb.")
return nil
}
// NotarizedBlockFetched - handler to process fetched notarized block
func (mc *Chain) NotarizedBlockFetched(ctx context.Context, b *block.Block) {
// mc.SendNotarization(ctx, b)
}
// txnProcessorHandler process transaction and return bool and error to indicate
// whether processed successfully, or error if any
type txnProcessorHandler func(context.Context,
util.MerklePatriciaTrieI,
*transaction.Transaction,
*TxnIterInfo, chan struct{}) (bool, error)
func txnProcessorHandlerFunc(mc *Chain, b *block.Block) txnProcessorHandler {
return func(ctx context.Context,
bState util.MerklePatriciaTrieI,
txn *transaction.Transaction,
tii *TxnIterInfo,
waitC chan struct{}) (bool, error) {
if _, ok := tii.txnMap[txn.GetKey()]; ok {
return false, nil
}
var debugTxn = true
nonce, err := mc.validateTransaction(b, bState, txn, waitC)
switch err {
case PastTransaction:
tii.pastTxns = append(tii.pastTxns, txn)
if debugTxn {
logging.Logger.Debug("generate block (debug transaction) error, transaction hash old nonce",
zap.Any("txn", txn),
zap.Int32("iterate count", tii.count),
zap.Any("now", common.Now()),
zap.Int64("nonce", txn.Nonce))
}
return false, nil
case FutureTransaction:
list, ok := tii.futureTxns[txn.ClientID]
if !ok {
list = &clientNonceTxns{}
}
if list.nonce < nonce {
list.nonce = nonce
}
list.txns = append(list.txns, txn)
sort.SliceStable(list.txns, func(i, j int) bool {
if list.txns[i].Nonce == list.txns[j].Nonce {
//if the same nonce order by fee
return list.txns[i].Fee > list.txns[j].Fee
}
return list.txns[i].Nonce < list.txns[j].Nonce
})
tii.futureTxns[txn.ClientID] = list
if debugTxn {
logging.Logger.Debug("generate block - future transaction",
zap.String("txn", txn.Hash),
zap.Int64("round", b.Round),
zap.Int32("iterate count", tii.count))
}
return false, nil
case ErrNotTimeTolerant:
tii.invalidTxns = append(tii.invalidTxns, txn)
if debugTxn {
logging.Logger.Info("generate block (debug transaction) error - txn creation not within tolerance",
zap.String("txn", txn.Hash), zap.Int32("idx", tii.idx),
zap.Any("now", common.Now()))
}
return false, nil
default:
if err != nil && cstate.ErrInvalidState(err) {
return false, err // return err to break the txns pool iteration
}
}
if debugTxn {
logging.Logger.Info("generate block (debug transaction)",
zap.String("txn", txn.Hash), zap.Int32("idx", tii.idx),
zap.String("txn_object", datastore.ToJSON(txn).String()))
}
events, err := mc.UpdateState(ctx, b, bState, txn, waitC)
if err != nil {
if debugTxn {
logging.Logger.Error("generate block (debug transaction) update state",
zap.String("txn", txn.Hash), zap.Int32("idx", tii.idx),
zap.String("txn_object", datastore.ToJSON(txn).String()),
zap.Error(err))
}
tii.failedStateCount++
if cstate.ErrInvalidState(err) {
return false, err // return err to break the txns pool iteration
}
return false, nil
}
b.Events = append(b.Events, events...)
// Setting the score lower so the next time blocks are generated
// these transactions don't show up at the top.
tii.txnMap[txn.GetKey()] = struct{}{}
b.Txns = append(b.Txns, txn)
if debugTxn {
logging.Logger.Info("generate block (debug transaction) success in processing Txn hash: " + txn.Hash + " blockHash? = " + b.Hash)
}
tii.eTxns = append(tii.eTxns, txn)
b.AddTransaction(txn)
tii.byteSize += int64(len(txn.TransactionData)) + int64(len(txn.TransactionOutput))
if txn.PublicKey == "" {
tii.clients[txn.ClientID] = nil
}
tii.idx++
tii.checkForCurrent(txn)
return true, nil
}
}
type clientNonceTxns struct {
nonce int64
txns []*transaction.Transaction
}
type TxnIterInfo struct {
clients map[string]*client.Client
eTxns []datastore.Entity
invalidTxns []datastore.Entity
pastTxns []datastore.Entity
futureTxns map[datastore.Key]*clientNonceTxns
currentTxns []*transaction.Transaction
txnMap map[datastore.Key]struct{}
roundMismatch bool
roundTimeout bool
count int32
roundTimeoutCount int64
// reInclusionErr is set if the transaction was found in previous block
reInclusionErr error
// state compute failed count
failedStateCount int32
// transaction index in a block
idx int32
// included transaction data size
byteSize int64
// accumulated transaction cost
cost int
}
func (tii *TxnIterInfo) checkForCurrent(txn *transaction.Transaction) {
if tii.futureTxns == nil {
return
}
//check whether we can execute future transactions
nonceTxns, ok := tii.futureTxns[txn.ClientID]
if !ok {
return
}
futures := nonceTxns.txns
if len(futures) == 0 {
return
}
currentNonce := txn.Nonce
i := 0
for ; i < len(futures); i++ {
if futures[i].Nonce-currentNonce > 1 {
break
}
//we can have several transactions with the same nonce execute first and skip others
// included n=0 in the list 1, 1, 2. take first 1 and skip the second
if futures[i].Nonce-currentNonce < 1 {
tii.pastTxns = append(tii.pastTxns, futures[i])
continue
}
currentNonce = futures[i].Nonce
tii.currentTxns = append(tii.currentTxns, futures[i])
}
//will not sorted by fee here but at least will be sorted by nonce correctly, can improve it
sort.SliceStable(tii.currentTxns, func(i, j int) bool { return tii.currentTxns[i].Nonce < tii.currentTxns[j].Nonce })
if i > -1 {
tii.futureTxns[txn.ClientID].txns = futures[i:]
tii.futureTxns[txn.ClientID].nonce = currentNonce
futureNonces := make([]int64, len(futures[i:]))
for j, t := range futures[i:] {
futureNonces[j] = t.Nonce
}
logging.Logger.Debug("generate block - debug future transactions",
zap.Int64("current nonce", currentNonce),
zap.Int64s("future nonces", futureNonces))
}
}
func newTxnIterInfo(blockSize int32) *TxnIterInfo {
return &TxnIterInfo{
clients: make(map[string]*client.Client),
eTxns: make([]datastore.Entity, 0, blockSize),
futureTxns: make(map[datastore.Key]*clientNonceTxns),
txnMap: make(map[datastore.Key]struct{}, blockSize),
}
}
// txns iterate handler, the function will return bool and error to indicate
// whether the iteration should continue or not, or error if any to stop the iteration
func txnIterHandlerFunc(
mc *Chain,
b *block.Block,
lfb *block.Block,
bState util.MerklePatriciaTrieI,
txnProcessor txnProcessorHandler,
tii *TxnIterInfo,
waitC chan struct{}) func(context.Context, datastore.CollectionEntity) (bool, error) {
return func(ctx context.Context, qe datastore.CollectionEntity) (bool, error) {
tii.count++
if ctx.Err() != nil {
return false, ctx.Err()
}
if mc.GetCurrentRound() > b.Round {
tii.roundMismatch = true
return false, nil
}
if tii.roundTimeoutCount != mc.GetRoundTimeoutCount() {
tii.roundTimeout = true
return false, nil
}
txn, ok := qe.(*transaction.Transaction)
if !ok {
logging.Logger.Error("generate block (invalid entity)", zap.Any("entity", qe))
// continue iteration to process next transaction
return true, nil
}
if lfb.ClientState == nil {
logging.Logger.Warn("generate block, chain is not ready yet",
zap.Int64("round", b.Round),
zap.String("hash", b.Hash),
zap.Error(ErrLFBClientStateNil))
return false, nil
}
if txn.Value > config.MaxTokenSupply {
logging.Logger.Error("generate block, invalid transaction value",
zap.String("hash", txn.Hash),
zap.Uint64("value", uint64(txn.Value)))
tii.invalidTxns = append(tii.invalidTxns, txn)
return false, errors.New("invalid transaction value, exceeds max token supply")
}
cost, fee, err := mc.EstimateTransactionCostFee(ctx, lfb, txn, chain.WithSync(), chain.WithNotifyC(waitC))
if err != nil {
logging.Logger.Debug("generate block - bad transaction cost fee",
zap.Error(err),
zap.String("txn_hash", txn.Hash))
// return error to break iteration due to the invalid state error
if cstate.ErrInvalidState(err) {
return false, err
}
// skipping and continue
return true, nil
}
if mc.IsFeeEnabled() {
confMinFee := mc.ChainConfig.MinTxnFee()
if confMinFee > fee {
fee = confMinFee
}
if err := txn.ValidateFee(mc.ChainConfig.TxnExempt(), fee); err != nil {
logging.Logger.Error("generate block - invalid transaction fee",
zap.Any("txn", txn),
zap.Any("estimated fee", fee),
zap.Error(err))
tii.invalidTxns = append(tii.invalidTxns, txn)
return true, nil // skipping and continue
}
}
if tii.cost+cost >= mc.ChainConfig.MaxBlockCost() {
logging.Logger.Debug("generate block (too big cost, skipping)")
return true, nil
}
success, err := txnProcessor(ctx, bState, txn, tii, waitC)
if err != nil {
logging.Logger.Debug("generate block txn processor failed",
zap.Error(err),
zap.Int64("round", b.Round),
zap.Int32("iterate count", tii.count),
zap.Int("current block size", len(b.Txns)))
return false, err
}
if !success {
// skipping and continue to check the next transaction
logging.Logger.Debug("generate block txn processor failed",
zap.Int64("round", b.Round),
zap.Int32("iterate count", tii.count),
zap.Int("current block size", len(b.Txns)))