forked from decred/dcrd
/
validate.go
2721 lines (2420 loc) · 95.2 KB
/
validate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package blockchain
import (
"bytes"
"fmt"
"math"
"math/big"
"time"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/database"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
)
const (
// MaxSigOpsPerBlock is the maximum number of signature operations
// allowed for a block. This really should be based upon the max
// allowed block size for a network and any votes that might change it,
// however, since it was not updated to be based upon it before
// release, it will require a hard fork and associated vote agenda to
// change it. The original max block size for the protocol was 1MiB,
// so that is what this is based on.
MaxSigOpsPerBlock = 1000000 / 200
// MaxTimeOffsetSeconds is the maximum number of seconds a block time
// is allowed to be ahead of the current time. This is currently 2
// hours.
MaxTimeOffsetSeconds = 2 * 60 * 60
// MinCoinbaseScriptLen is the minimum length a coinbase script can be.
MinCoinbaseScriptLen = 2
// MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
MaxCoinbaseScriptLen = 100
// medianTimeBlocks is the number of previous blocks which should be
// used to calculate the median time used to validate block timestamps.
medianTimeBlocks = 11
// earlyVoteBitsValue is the only value of VoteBits allowed in a block
// header before stake validation height.
earlyVoteBitsValue = 0x0001
// maxRevocationsPerBlock is the maximum number of revocations that are
// allowed per block.
maxRevocationsPerBlock = 255
)
var (
// zeroHash is the zero value for a chainhash.Hash and is defined as a
// package level variable to avoid the need to create a new instance
// every time a check is needed.
zeroHash = &chainhash.Hash{}
// earlyFinalState is the only value of the final state allowed in a
// block header before stake validation height.
earlyFinalState = [6]byte{0x00}
)
// voteBitsApproveParent returns whether or not the passed vote bits indicate
// the regular transaction tree of the parent block should be considered valid.
func voteBitsApproveParent(voteBits uint16) bool {
return dcrutil.IsFlagSet16(voteBits, dcrutil.BlockValid)
}
// approvesParent returns whether or not the vote bits in the passed header
// indicate the regular transaction tree of the parent block should be
// considered valid.
func headerApprovesParent(header *wire.BlockHeader) bool {
return voteBitsApproveParent(header.VoteBits)
}
// isNullOutpoint determines whether or not a previous transaction output point
// is set.
func isNullOutpoint(outpoint *wire.OutPoint) bool {
if outpoint.Index == math.MaxUint32 &&
outpoint.Hash.IsEqual(zeroHash) &&
outpoint.Tree == wire.TxTreeRegular {
return true
}
return false
}
// isNullFraudProof determines whether or not a previous transaction fraud
// proof is set.
func isNullFraudProof(txIn *wire.TxIn) bool {
switch {
case txIn.BlockHeight != wire.NullBlockHeight:
return false
case txIn.BlockIndex != wire.NullBlockIndex:
return false
}
return true
}
// IsCoinBaseTx determines whether or not a transaction is a coinbase. A
// coinbase is a special transaction created by miners that has no inputs.
// This is represented in the block chain by a transaction with a single input
// that has a previous output transaction index set to the maximum value along
// with a zero hash.
//
// This function only differs from IsCoinBase in that it works with a raw wire
// transaction as opposed to a higher level util transaction.
func IsCoinBaseTx(msgTx *wire.MsgTx) bool {
// A coin base must only have one transaction input.
if len(msgTx.TxIn) != 1 {
return false
}
// The previous output of a coin base must have a max value index and a
// zero hash.
prevOut := &msgTx.TxIn[0].PreviousOutPoint
if prevOut.Index != math.MaxUint32 || !prevOut.Hash.IsEqual(zeroHash) {
return false
}
return true
}
// IsCoinBase determines whether or not a transaction is a coinbase. A
// coinbase is a special transaction created by miners that has no inputs.
// This is represented in the block chain by a transaction with a single input
// that has a previous output transaction index set to the maximum value along
// with a zero hash.
//
// This function only differs from IsCoinBaseTx in that it works with a higher
// level util transaction as opposed to a raw wire transaction.
func IsCoinBase(tx *dcrutil.Tx) bool {
return IsCoinBaseTx(tx.MsgTx())
}
// SequenceLockActive determines if all of the inputs to a given transaction
// have achieved a relative age that surpasses the requirements specified by
// their respective sequence locks as calculated by CalcSequenceLock. A single
// sequence lock is sufficient because the calculated lock selects the minimum
// required time and block height from all of the non-disabled inputs after
// which the transaction can be included.
func SequenceLockActive(lock *SequenceLock, blockHeight int64, medianTime time.Time) bool {
// The transaction is not yet mature if it has not yet reached the
// required minimum time and block height according to its sequence
// locks.
if blockHeight <= lock.MinHeight || medianTime.Unix() <= lock.MinTime {
return false
}
return true
}
// CheckTransactionSanity performs some preliminary checks on a transaction to
// ensure it is sane. These checks are context free.
func CheckTransactionSanity(tx *wire.MsgTx, params *chaincfg.Params) error {
// A transaction must have at least one input.
if len(tx.TxIn) == 0 {
return ruleError(ErrNoTxInputs, "transaction has no inputs")
}
// A transaction must have at least one output.
if len(tx.TxOut) == 0 {
return ruleError(ErrNoTxOutputs, "transaction has no outputs")
}
// A transaction must not exceed the maximum allowed size when
// serialized.
serializedTxSize := tx.SerializeSize()
if serializedTxSize > params.MaxTxSize {
str := fmt.Sprintf("serialized transaction is too big - got "+
"%d, max %d", serializedTxSize, params.MaxTxSize)
return ruleError(ErrTxTooBig, str)
}
// Ensure the transaction amounts are in range. Each transaction
// output must not be negative or more than the max allowed per
// transaction. Also, the total of all outputs must abide by the same
// restrictions. All amounts in a transaction are in a unit value
// known as an atom. One Decred is a quantity of atoms as defined by
// the AtomsPerCoin constant.
var totalAtom int64
for _, txOut := range tx.TxOut {
atom := txOut.Value
if atom < 0 {
str := fmt.Sprintf("transaction output has negative "+
"value of %v", atom)
return ruleError(ErrBadTxOutValue, str)
}
if atom > dcrutil.MaxAmount {
str := fmt.Sprintf("transaction output value of %v is "+
"higher than max allowed value of %v", atom,
dcrutil.MaxAmount)
return ruleError(ErrBadTxOutValue, str)
}
// Two's complement int64 overflow guarantees that any overflow
// is detected and reported. This is impossible for Decred,
// but perhaps possible if an alt increases the total money
// supply.
totalAtom += atom
if totalAtom < 0 {
str := fmt.Sprintf("total value of all transaction "+
"outputs exceeds max allowed value of %v",
dcrutil.MaxAmount)
return ruleError(ErrBadTxOutValue, str)
}
if totalAtom > dcrutil.MaxAmount {
str := fmt.Sprintf("total value of all transaction "+
"outputs is %v which is higher than max "+
"allowed value of %v", totalAtom,
dcrutil.MaxAmount)
return ruleError(ErrBadTxOutValue, str)
}
}
// Coinbase script length must be between min and max length.
if IsCoinBaseTx(tx) {
// The referenced outpoint should be null.
if !isNullOutpoint(&tx.TxIn[0].PreviousOutPoint) {
str := fmt.Sprintf("coinbase transaction did not use " +
"a null outpoint")
return ruleError(ErrBadCoinbaseOutpoint, str)
}
// The fraud proof should also be null.
if !isNullFraudProof(tx.TxIn[0]) {
str := fmt.Sprintf("coinbase transaction fraud proof " +
"was non-null")
return ruleError(ErrBadCoinbaseFraudProof, str)
}
slen := len(tx.TxIn[0].SignatureScript)
if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen {
str := fmt.Sprintf("coinbase transaction script "+
"length of %d is out of range (min: %d, max: "+
"%d)", slen, MinCoinbaseScriptLen,
MaxCoinbaseScriptLen)
return ruleError(ErrBadCoinbaseScriptLen, str)
}
} else if stake.IsSSGen(tx) {
// Check script length of stake base signature.
slen := len(tx.TxIn[0].SignatureScript)
if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen {
str := fmt.Sprintf("stakebase transaction script "+
"length of %d is out of range (min: %d, max: "+
"%d)", slen, MinCoinbaseScriptLen,
MaxCoinbaseScriptLen)
return ruleError(ErrBadStakebaseScriptLen, str)
}
// The script must be set to the one specified by the network.
// Check script length of stake base signature.
if !bytes.Equal(tx.TxIn[0].SignatureScript,
params.StakeBaseSigScript) {
str := fmt.Sprintf("stakebase transaction signature "+
"script was set to disallowed value (got %x, "+
"want %x)", tx.TxIn[0].SignatureScript,
params.StakeBaseSigScript)
return ruleError(ErrBadStakebaseScrVal, str)
}
// The ticket reference hash in an SSGen tx must not be null.
ticketHash := &tx.TxIn[1].PreviousOutPoint
if isNullOutpoint(ticketHash) {
return ruleError(ErrBadTxInput, "ssgen tx ticket input"+
" refers to previous output that is null")
}
} else {
// Previous transaction outputs referenced by the inputs to
// this transaction must not be null except in the case of
// stake bases for SSGen tx.
for _, txIn := range tx.TxIn {
prevOut := &txIn.PreviousOutPoint
if isNullOutpoint(prevOut) {
return ruleError(ErrBadTxInput, "transaction "+
"input refers to previous output that "+
"is null")
}
}
}
// Check for duplicate transaction inputs.
existingTxOut := make(map[wire.OutPoint]struct{})
for _, txIn := range tx.TxIn {
if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists {
return ruleError(ErrDuplicateTxInputs, "transaction "+
"contains duplicate inputs")
}
existingTxOut[txIn.PreviousOutPoint] = struct{}{}
}
return nil
}
// checkProofOfStake ensures that all ticket purchases in the block pay at least
// the amount required by the block header stake bits which indicate the target
// stake difficulty (aka ticket price) as claimed.
func checkProofOfStake(block *dcrutil.Block, posLimit int64) error {
msgBlock := block.MsgBlock()
for _, staketx := range block.STransactions() {
msgTx := staketx.MsgTx()
if stake.IsSStx(msgTx) {
commitValue := msgTx.TxOut[0].Value
// Check for underflow block sbits.
if commitValue < msgBlock.Header.SBits {
errStr := fmt.Sprintf("Stake tx %v has a "+
"commitment value less than the "+
"minimum stake difficulty specified in"+
" the block (%v)", staketx.Hash(),
msgBlock.Header.SBits)
return ruleError(ErrNotEnoughStake, errStr)
}
// Check if it's above the PoS limit.
if commitValue < posLimit {
errStr := fmt.Sprintf("Stake tx %v has a "+
"commitment value less than the "+
"minimum stake difficulty for the "+
"network (%v)", staketx.Hash(),
posLimit)
return ruleError(ErrStakeBelowMinimum, errStr)
}
}
}
return nil
}
// CheckProofOfStake ensures that all ticket purchases in the block pay at least
// the amount required by the block header stake bits which indicate the target
// stake difficulty (aka ticket price) as claimed.
func CheckProofOfStake(block *dcrutil.Block, posLimit int64) error {
return checkProofOfStake(block, posLimit)
}
// checkProofOfWork ensures the block header bits which indicate the target
// difficulty is in min/max range and that the block hash is less than the
// target difficulty as claimed.
//
// The flags modify the behavior of this function as follows:
// - BFNoPoWCheck: The check to ensure the block hash is less than the target
// difficulty is not performed.
func checkProofOfWork(header *wire.BlockHeader, powLimit *big.Int, flags BehaviorFlags) error {
// The target difficulty must be larger than zero.
target := CompactToBig(header.Bits)
if target.Sign() <= 0 {
str := fmt.Sprintf("block target difficulty of %064x is too "+
"low", target)
return ruleError(ErrUnexpectedDifficulty, str)
}
// The target difficulty must be less than the maximum allowed.
if target.Cmp(powLimit) > 0 {
str := fmt.Sprintf("block target difficulty of %064x is "+
"higher than max of %064x", target, powLimit)
return ruleError(ErrUnexpectedDifficulty, str)
}
// The block hash must be less than the claimed target unless the flag
// to avoid proof of work checks is set.
if flags&BFNoPoWCheck != BFNoPoWCheck {
// The block hash must be less than the claimed target.
hash := header.BlockHash()
hashNum := HashToBig(&hash)
if hashNum.Cmp(target) > 0 {
str := fmt.Sprintf("block hash of %064x is higher than"+
" expected max of %064x", hashNum, target)
return ruleError(ErrHighHash, str)
}
}
return nil
}
// CheckProofOfWork ensures the block header bits which indicate the target
// difficulty is in min/max range and that the block hash is less than the
// target difficulty as claimed.
func CheckProofOfWork(header *wire.BlockHeader, powLimit *big.Int) error {
return checkProofOfWork(header, powLimit, BFNone)
}
// checkBlockHeaderSanity performs some preliminary checks on a block header to
// ensure it is sane before continuing with processing. These checks are
// context free.
//
// The flags do not modify the behavior of this function directly, however they
// are needed to pass along to checkProofOfWork.
func checkBlockHeaderSanity(header *wire.BlockHeader, timeSource MedianTimeSource, flags BehaviorFlags, chainParams *chaincfg.Params) error {
// The stake validation height should always be at least stake enabled
// height, so assert it because the code below relies on that assumption.
stakeValidationHeight := uint32(chainParams.StakeValidationHeight)
stakeEnabledHeight := uint32(chainParams.StakeEnabledHeight)
if stakeEnabledHeight > stakeValidationHeight {
return AssertError(fmt.Sprintf("checkBlockHeaderSanity called "+
"with stake enabled height %d after stake validation "+
"height %d", stakeEnabledHeight, stakeValidationHeight))
}
// Ensure the proof of work bits in the block header is in min/max
// range and the block hash is less than the target value described by
// the bits.
err := checkProofOfWork(header, chainParams.PowLimit, flags)
if err != nil {
return err
}
// A block timestamp must not have a greater precision than one second.
// This check is necessary because Go time.Time values support
// nanosecond precision whereas the consensus rules only apply to
// seconds and it's much nicer to deal with standard Go time values
// instead of converting to seconds everywhere.
if !header.Timestamp.Equal(time.Unix(header.Timestamp.Unix(), 0)) {
str := fmt.Sprintf("block timestamp of %v has a higher "+
"precision than one second", header.Timestamp)
return ruleError(ErrInvalidTime, str)
}
// Ensure the block time is not too far in the future.
maxTimestamp := timeSource.AdjustedTime().Add(time.Second *
MaxTimeOffsetSeconds)
if header.Timestamp.After(maxTimestamp) {
str := fmt.Sprintf("block timestamp of %v is too far in the "+
"future", header.Timestamp)
return ruleError(ErrTimeTooNew, str)
}
// A block must not contain any votes or revocations, its vote bits
// must be 0x0001, and its final state must be all zeroes before
// stake validation begins.
if header.Height < stakeValidationHeight {
if header.Voters > 0 {
errStr := fmt.Sprintf("block at height %d commits to "+
"%d votes before stake validation height %d",
header.Height, header.Voters,
stakeValidationHeight)
return ruleError(ErrInvalidEarlyStakeTx, errStr)
}
if header.Revocations > 0 {
errStr := fmt.Sprintf("block at height %d commits to "+
"%d revocations before stake validation height %d",
header.Height, header.Revocations,
stakeValidationHeight)
return ruleError(ErrInvalidEarlyStakeTx, errStr)
}
if header.VoteBits != earlyVoteBitsValue {
errStr := fmt.Sprintf("block at height %d commits to "+
"invalid vote bits before stake validation "+
"height %d (expected %x, got %x)",
header.Height, stakeValidationHeight,
earlyVoteBitsValue, header.VoteBits)
return ruleError(ErrInvalidEarlyVoteBits, errStr)
}
if header.FinalState != earlyFinalState {
errStr := fmt.Sprintf("block at height %d commits to "+
"invalid final state before stake validation "+
"height %d (expected %x, got %x)",
header.Height, stakeValidationHeight,
earlyFinalState, header.FinalState)
return ruleError(ErrInvalidEarlyFinalState, errStr)
}
}
// A block must not contain more votes than the minimum required to
// reach majority once stake validation height has been reached.
if header.Height >= stakeValidationHeight {
majority := (chainParams.TicketsPerBlock / 2) + 1
if header.Voters < majority {
errStr := fmt.Sprintf("block does not commit to enough "+
"votes (min: %d, got %d)", majority,
header.Voters)
return ruleError(ErrNotEnoughVotes, errStr)
}
}
// The block header must not claim to contain more votes than the
// maximum allowed.
if header.Voters > chainParams.TicketsPerBlock {
errStr := fmt.Sprintf("block commits to too many votes (max: "+
"%d, got %d)", chainParams.TicketsPerBlock, header.Voters)
return ruleError(ErrTooManyVotes, errStr)
}
// The block must not contain more ticket purchases than the maximum
// allowed.
if header.FreshStake > chainParams.MaxFreshStakePerBlock {
errStr := fmt.Sprintf("block commits to too many ticket "+
"purchases (max: %d, got %d)",
chainParams.MaxFreshStakePerBlock, header.FreshStake)
return ruleError(ErrTooManySStxs, errStr)
}
return nil
}
// checkBlockSanity performs some preliminary checks on a block to ensure it is
// sane before continuing with block processing. These checks are context
// free.
//
// The flags do not modify the behavior of this function directly, however they
// are needed to pass along to checkBlockHeaderSanity.
func checkBlockSanity(block *dcrutil.Block, timeSource MedianTimeSource, flags BehaviorFlags, chainParams *chaincfg.Params) error {
msgBlock := block.MsgBlock()
header := &msgBlock.Header
err := checkBlockHeaderSanity(header, timeSource, flags, chainParams)
if err != nil {
return err
}
// All ticket purchases must meet the difficulty specified by the block
// header.
err = checkProofOfStake(block, chainParams.MinimumStakeDiff)
if err != nil {
return err
}
// A block must have at least one regular transaction.
numTx := len(msgBlock.Transactions)
if numTx == 0 {
return ruleError(ErrNoTransactions, "block does not contain "+
"any transactions")
}
// A block must not exceed the maximum allowed block payload when
// serialized.
//
// This is a quick and context-free sanity check of the maximum block
// size according to the wire protocol. Even though the wire protocol
// already prevents blocks bigger than this limit, there are other
// methods of receiving a block that might not have been checked
// already. A separate block size is enforced later that takes into
// account the network-specific block size and the results of block
// size votes. Typically that block size is more restrictive than this
// one.
serializedSize := msgBlock.SerializeSize()
if serializedSize > wire.MaxBlockPayload {
str := fmt.Sprintf("serialized block is too big - got %d, "+
"max %d", serializedSize, wire.MaxBlockPayload)
return ruleError(ErrBlockTooBig, str)
}
if header.Size != uint32(serializedSize) {
str := fmt.Sprintf("serialized block is not size indicated in "+
"header - got %d, expected %d", header.Size,
serializedSize)
return ruleError(ErrWrongBlockSize, str)
}
// The first transaction in a block's regular tree must be a coinbase.
transactions := block.Transactions()
if !IsCoinBaseTx(transactions[0].MsgTx()) {
return ruleError(ErrFirstTxNotCoinbase, "first transaction in "+
"block is not a coinbase")
}
// A block must not have more than one coinbase.
for i, tx := range transactions[1:] {
if IsCoinBaseTx(tx.MsgTx()) {
str := fmt.Sprintf("block contains second coinbase at "+
"index %d", i+1)
return ruleError(ErrMultipleCoinbases, str)
}
}
// Do some preliminary checks on each regular transaction to ensure they
// are sane before continuing.
for i, tx := range transactions {
// A block must not have stake transactions in the regular
// transaction tree.
msgTx := tx.MsgTx()
txType := stake.DetermineTxType(msgTx)
if txType != stake.TxTypeRegular {
errStr := fmt.Sprintf("block contains a stake "+
"transaction in the regular transaction tree at "+
"index %d", i)
return ruleError(ErrStakeTxInRegularTree, errStr)
}
err := CheckTransactionSanity(msgTx, chainParams)
if err != nil {
return err
}
}
// Do some preliminary checks on each stake transaction to ensure they
// are sane while tallying each type before continuing.
stakeValidationHeight := uint32(chainParams.StakeValidationHeight)
var totalTickets, totalVotes, totalRevocations int64
var totalYesVotes int64
for txIdx, stx := range msgBlock.STransactions {
err := CheckTransactionSanity(stx, chainParams)
if err != nil {
return err
}
// A block must not have regular transactions in the stake
// transaction tree.
txType := stake.DetermineTxType(stx)
if txType == stake.TxTypeRegular {
errStr := fmt.Sprintf("block contains regular "+
"transaction in stake transaction tree at "+
"index %d", txIdx)
return ruleError(ErrRegTxInStakeTree, errStr)
}
switch txType {
case stake.TxTypeSStx:
totalTickets++
case stake.TxTypeSSGen:
totalVotes++
// All votes in a block must commit to the parent of the
// block once stake validation height has been reached.
if header.Height >= stakeValidationHeight {
votedHash, votedHeight := stake.SSGenBlockVotedOn(stx)
if (votedHash != header.PrevBlock) || (votedHeight !=
header.Height-1) {
errStr := fmt.Sprintf("vote %s at index %d is "+
"for parent block %s (height %d) versus "+
"expected parent block %s (height %d)",
stx.TxHash(), txIdx, votedHash,
votedHeight, header.PrevBlock,
header.Height-1)
return ruleError(ErrVotesOnWrongBlock, errStr)
}
// Tally how many votes approve the previous block for use
// when validating the header commitment.
if voteBitsApproveParent(stake.SSGenVoteBits(stx)) {
totalYesVotes++
}
}
case stake.TxTypeSSRtx:
totalRevocations++
}
}
// A block must not contain more than the maximum allowed number of
// revocations.
if totalRevocations > maxRevocationsPerBlock {
errStr := fmt.Sprintf("block contains %d revocations which "+
"exceeds the maximum allowed amount of %d",
totalRevocations, maxRevocationsPerBlock)
return ruleError(ErrTooManyRevocations, errStr)
}
// A block must only contain stake transactions of the the allowed
// types.
//
// NOTE: This is not possible to hit at the time this comment was
// written because all transactions which are not specifically one of
// the recognized stake transaction forms are considered regular
// transactions and those are rejected above. However, if a new stake
// transaction type is added, that implicit condition would no longer
// hold and therefore an explicit check is performed here.
numStakeTx := int64(len(msgBlock.STransactions))
calcStakeTx := totalTickets + totalVotes + totalRevocations
if numStakeTx != calcStakeTx {
errStr := fmt.Sprintf("block contains an unexpected number "+
"of stake transactions (contains %d, expected %d)",
numStakeTx, calcStakeTx)
return ruleError(ErrNonstandardStakeTx, errStr)
}
// A block header must commit to the actual number of tickets purchases that
// are in the block.
if int64(header.FreshStake) != totalTickets {
errStr := fmt.Sprintf("block header commitment to %d ticket "+
"purchases does not match %d contained in the block",
header.FreshStake, totalTickets)
return ruleError(ErrFreshStakeMismatch, errStr)
}
// A block header must commit to the the actual number of votes that are
// in the block.
if int64(header.Voters) != totalVotes {
errStr := fmt.Sprintf("block header commitment to %d votes "+
"does not match %d contained in the block",
header.Voters, totalVotes)
return ruleError(ErrVotesMismatch, errStr)
}
// A block header must commit to the actual number of revocations that
// are in the block.
if int64(header.Revocations) != totalRevocations {
errStr := fmt.Sprintf("block header commitment to %d revocations "+
"does not match %d contained in the block",
header.Revocations, totalRevocations)
return ruleError(ErrRevocationsMismatch, errStr)
}
// A block header must commit to the same previous block acceptance
// semantics expressed by the votes once stake validation height has
// been reached.
if header.Height >= stakeValidationHeight {
totalNoVotes := totalVotes - totalYesVotes
headerApproves := headerApprovesParent(header)
votesApprove := totalYesVotes > totalNoVotes
if headerApproves != votesApprove {
errStr := fmt.Sprintf("block header commitment to previous "+
"block approval does not match votes (header claims: %v, "+
"votes: %v)", headerApproves, votesApprove)
return ruleError(ErrIncongruentVotebit, errStr)
}
}
// A block must not contain anything other than ticket purchases prior to
// stake validation height.
//
// NOTE: This case is impossible to hit at this point at the time this
// comment was written since the votes and revocations have already been
// proven to be zero before stake validation height and the only other
// type at the current time is ticket purchases, however, if another
// stake type is ever added, consensus would break without this check.
// It's better to be safe and it's a cheap check.
if header.Height < stakeValidationHeight {
if int64(len(msgBlock.STransactions)) != totalTickets {
errStr := fmt.Sprintf("block contains stake "+
"transactions other than ticket purchases before "+
"stake validation height %d (total: %d, expected %d)",
uint32(chainParams.StakeValidationHeight),
len(msgBlock.STransactions), header.FreshStake)
return ruleError(ErrInvalidEarlyStakeTx, errStr)
}
}
// Build merkle tree and ensure the calculated merkle root matches the
// entry in the block header. This also has the effect of caching all
// of the transaction hashes in the block to speed up future hash
// checks. Bitcoind builds the tree here and checks the merkle root
// after the following checks, but there is no reason not to check the
// merkle root matches here.
merkles := BuildMerkleTreeStore(block.Transactions())
calculatedMerkleRoot := merkles[len(merkles)-1]
if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) {
str := fmt.Sprintf("block merkle root is invalid - block "+
"header indicates %v, but calculated value is %v",
header.MerkleRoot, calculatedMerkleRoot)
return ruleError(ErrBadMerkleRoot, str)
}
// Build the stake tx tree merkle root too and check it.
merkleStake := BuildMerkleTreeStore(block.STransactions())
calculatedStakeMerkleRoot := merkleStake[len(merkleStake)-1]
if !header.StakeRoot.IsEqual(calculatedStakeMerkleRoot) {
str := fmt.Sprintf("block stake merkle root is invalid - block"+
" header indicates %v, but calculated value is %v",
header.StakeRoot, calculatedStakeMerkleRoot)
return ruleError(ErrBadMerkleRoot, str)
}
// Check for duplicate transactions. This check will be fairly quick
// since the transaction hashes are already cached due to building the
// merkle trees above.
existingTxHashes := make(map[chainhash.Hash]struct{})
stakeTransactions := block.STransactions()
allTransactions := append(transactions, stakeTransactions...)
for _, tx := range allTransactions {
hash := tx.Hash()
if _, exists := existingTxHashes[*hash]; exists {
str := fmt.Sprintf("block contains duplicate "+
"transaction %v", hash)
return ruleError(ErrDuplicateTx, str)
}
existingTxHashes[*hash] = struct{}{}
}
// The number of signature operations must be less than the maximum
// allowed per block.
totalSigOps := 0
for _, tx := range allTransactions {
// We could potentially overflow the accumulator so check for
// overflow.
lastSigOps := totalSigOps
msgTx := tx.MsgTx()
isCoinBase := IsCoinBaseTx(msgTx)
isSSGen := stake.IsSSGen(msgTx)
totalSigOps += CountSigOps(tx, isCoinBase, isSSGen)
if totalSigOps < lastSigOps || totalSigOps > MaxSigOpsPerBlock {
str := fmt.Sprintf("block contains too many signature "+
"operations - got %v, max %v", totalSigOps,
MaxSigOpsPerBlock)
return ruleError(ErrTooManySigOps, str)
}
}
return nil
}
// CheckBlockSanity performs some preliminary checks on a block to ensure it is
// sane before continuing with block processing. These checks are context
// free.
func CheckBlockSanity(block *dcrutil.Block, timeSource MedianTimeSource, chainParams *chaincfg.Params) error {
return checkBlockSanity(block, timeSource, BFNone, chainParams)
}
// CheckWorklessBlockSanity performs some preliminary checks on a block to
// ensure it is sane before continuing with block processing. These checks are
// context free.
func CheckWorklessBlockSanity(block *dcrutil.Block, timeSource MedianTimeSource, chainParams *chaincfg.Params) error {
return checkBlockSanity(block, timeSource, BFNoPoWCheck, chainParams)
}
// checkBlockHeaderContext peforms several validation checks on the block
// header which depend on its position within the block chain.
//
// The flags modify the behavior of this function as follows:
// - BFFastAdd: All checks except those involving comparing the header against
// the checkpoints are not performed.
//
// This function MUST be called with the chain state lock held (for writes).
func (b *BlockChain) checkBlockHeaderContext(header *wire.BlockHeader, prevNode *blockNode, flags BehaviorFlags) error {
// The genesis block is valid by definition.
if prevNode == nil {
return nil
}
fastAdd := flags&BFFastAdd == BFFastAdd
if !fastAdd {
// Ensure the difficulty specified in the block header matches
// the calculated difficulty based on the previous block and
// difficulty retarget rules.
expDiff, err := b.calcNextRequiredDifficulty(prevNode,
header.Timestamp)
if err != nil {
return err
}
blockDifficulty := header.Bits
if blockDifficulty != expDiff {
str := fmt.Sprintf("block difficulty of %d is not the"+
" expected value of %d", blockDifficulty,
expDiff)
return ruleError(ErrUnexpectedDifficulty, str)
}
// Ensure the stake difficulty specified in the block header
// matches the calculated difficulty based on the previous block
// and difficulty retarget rules.
expSDiff, err := b.calcNextRequiredStakeDifficulty(prevNode)
if err != nil {
return err
}
if header.SBits != expSDiff {
errStr := fmt.Sprintf("block stake difficulty of %d "+
"is not the expected value of %d", header.SBits,
expSDiff)
return ruleError(ErrUnexpectedDifficulty, errStr)
}
// Ensure the timestamp for the block header is after the
// median time of the last several blocks (medianTimeBlocks).
medianTime, err := b.index.CalcPastMedianTime(prevNode)
if err != nil {
log.Errorf("CalcPastMedianTime: %v", err)
return err
}
if !header.Timestamp.After(medianTime) {
str := "block timestamp of %v is not after expected %v"
str = fmt.Sprintf(str, header.Timestamp, medianTime)
return ruleError(ErrTimeTooOld, str)
}
}
// The height of this block is one more than the referenced previous
// block.
blockHeight := prevNode.height + 1
// Ensure the header commits to the correct height based on the height it
// actually connects in the blockchain.
if int64(header.Height) != blockHeight {
errStr := fmt.Sprintf("block header commitment to height %d "+
"does not match chain height %d", header.Height,
blockHeight)
return ruleError(ErrBadBlockHeight, errStr)
}
// Ensure chain matches up to predetermined checkpoints.
blockHash := header.BlockHash()
if !b.verifyCheckpoint(blockHeight, &blockHash) {
str := fmt.Sprintf("block at height %d does not match "+
"checkpoint hash", blockHeight)
return ruleError(ErrBadCheckpoint, str)
}
// Find the previous checkpoint and prevent blocks which fork the main
// chain before it. This prevents storage of new, otherwise valid,
// blocks which build off of old blocks that are likely at a much
// easier difficulty and therefore could be used to waste cache and
// disk space.
checkpointBlock, err := b.findPreviousCheckpoint()
if err != nil {
return err
}
if checkpointBlock != nil && blockHeight < checkpointBlock.Height() {
str := fmt.Sprintf("block at height %d forks the main chain "+
"before the previous checkpoint at height %d",
blockHeight, checkpointBlock.Height())
return ruleError(ErrForkTooOld, str)
}
if !fastAdd {
// Reject version 5 blocks for networks other than the main
// network once a majority of the network has upgraded.
if b.chainParams.Net != wire.MainNet && header.Version < 6 &&
b.isMajorityVersion(6, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 4 blocks once a majority of the network has
// upgraded.
if header.Version < 5 && b.isMajorityVersion(5, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 3 blocks once a majority of the network has
// upgraded.
if header.Version < 4 && b.isMajorityVersion(4, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 2 blocks once a majority of the network has
// upgraded.
if header.Version < 3 && b.isMajorityVersion(3, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Reject version 1 blocks once a majority of the network has
// upgraded.
if header.Version < 2 && b.isMajorityVersion(2, prevNode,
b.chainParams.BlockRejectNumRequired) {
str := "new blocks with version %d are no longer valid"
str = fmt.Sprintf(str, header.Version)
return ruleError(ErrBlockVersionTooOld, str)
}
// Enforce the stake version in the header once a majority of
// the network has upgraded to version 3 blocks.
if header.Version >= 3 && b.isMajorityVersion(3, prevNode,
b.chainParams.BlockEnforceNumRequired) {
expectedStakeVer := b.calcStakeVersion(prevNode)
if header.StakeVersion != expectedStakeVer {
str := fmt.Sprintf("block stake version of %d "+
"is not the expected version of %d",
header.StakeVersion, expectedStakeVer)
return ruleError(ErrBadStakeVersion, str)
}
}
// Ensure the header commits to the correct pool size based on
// its position within the chain.
parentStakeNode, err := b.fetchStakeNode(prevNode)
if err != nil {
return err
}
calcPoolSize := uint32(parentStakeNode.PoolSize())
if header.PoolSize != calcPoolSize {
errStr := fmt.Sprintf("block header commitment to "+
"pool size %d does not match expected size %d",
header.PoolSize, calcPoolSize)
return ruleError(ErrPoolSize, errStr)
}
// Ensure the header commits to the correct final state of the
// ticket lottery.
calcFinalState := parentStakeNode.FinalState()
if header.FinalState != calcFinalState {
errStr := fmt.Sprintf("block header commitment to "+
"final state of the ticket lottery %x does not "+
"match expected value %x", header.FinalState,