forked from btcsuite/btcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.go
2135 lines (1919 loc) · 73.6 KB
/
generate.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) 2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
// The vast majority of the rules tested in this package were ported from the
// the original Java-based 'official' block acceptance tests at
// https://github.com/TheBlueMatt/test-scripts as well as some additional tests
// available in the Core python port of the same.
package fullblocktests
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"runtime"
"time"
"github.com/John-Tonny/vclsuite_vcld/blockchain"
"github.com/John-Tonny/vclsuite_vcld/btcec"
"github.com/John-Tonny/vclsuite_vcld/chaincfg"
"github.com/John-Tonny/vclsuite_vcld/chaincfg/chainhash"
"github.com/John-Tonny/vclsuite_vcld/txscript"
"github.com/John-Tonny/vclsuite_vcld/wire"
vclutil "github.com/John-Tonny/vclsuite_vclutil"
)
const (
// Intentionally defined here rather than using constants from codebase
// to ensure consensus changes are detected.
maxBlockSigOps = 20000
maxBlockSize = 1000000
minCoinbaseScriptLen = 2
maxCoinbaseScriptLen = 100
medianTimeBlocks = 11
maxScriptElementSize = 520
// numLargeReorgBlocks is the number of blocks to use in the large block
// reorg test (when enabled). This is the equivalent of 1 week's worth
// of blocks.
numLargeReorgBlocks = 1088
)
var (
// opTrueScript is simply a public key script that contains the OP_TRUE
// opcode. It is defined here to reduce garbage creation.
opTrueScript = []byte{txscript.OP_TRUE}
// lowFee is a single satoshi and exists to make the test code more
// readable.
lowFee = vclutil.Amount(1)
)
// TestInstance is an interface that describes a specific test instance returned
// by the tests generated in this package. It should be type asserted to one
// of the concrete test instance types in order to test accordingly.
type TestInstance interface {
FullBlockTestInstance()
}
// AcceptedBlock defines a test instance that expects a block to be accepted to
// the blockchain either by extending the main chain, on a side chain, or as an
// orphan.
type AcceptedBlock struct {
Name string
Block *wire.MsgBlock
Height int32
IsMainChain bool
IsOrphan bool
}
// Ensure AcceptedBlock implements the TestInstance interface.
var _ TestInstance = AcceptedBlock{}
// FullBlockTestInstance only exists to allow AcceptedBlock to be treated as a
// TestInstance.
//
// This implements the TestInstance interface.
func (b AcceptedBlock) FullBlockTestInstance() {}
// RejectedBlock defines a test instance that expects a block to be rejected by
// the blockchain consensus rules.
type RejectedBlock struct {
Name string
Block *wire.MsgBlock
Height int32
RejectCode blockchain.ErrorCode
}
// Ensure RejectedBlock implements the TestInstance interface.
var _ TestInstance = RejectedBlock{}
// FullBlockTestInstance only exists to allow RejectedBlock to be treated as a
// TestInstance.
//
// This implements the TestInstance interface.
func (b RejectedBlock) FullBlockTestInstance() {}
// OrphanOrRejectedBlock defines a test instance that expects a block to either
// be accepted as an orphan or rejected. This is useful since some
// implementations might optimize the immediate rejection of orphan blocks when
// their parent was previously rejected, while others might accept it as an
// orphan that eventually gets flushed (since the parent can never be accepted
// to ultimately link it).
type OrphanOrRejectedBlock struct {
Name string
Block *wire.MsgBlock
Height int32
}
// Ensure ExpectedTip implements the TestInstance interface.
var _ TestInstance = OrphanOrRejectedBlock{}
// FullBlockTestInstance only exists to allow OrphanOrRejectedBlock to be
// treated as a TestInstance.
//
// This implements the TestInstance interface.
func (b OrphanOrRejectedBlock) FullBlockTestInstance() {}
// ExpectedTip defines a test instance that expects a block to be the current
// tip of the main chain.
type ExpectedTip struct {
Name string
Block *wire.MsgBlock
Height int32
}
// Ensure ExpectedTip implements the TestInstance interface.
var _ TestInstance = ExpectedTip{}
// FullBlockTestInstance only exists to allow ExpectedTip to be treated as a
// TestInstance.
//
// This implements the TestInstance interface.
func (b ExpectedTip) FullBlockTestInstance() {}
// RejectedNonCanonicalBlock defines a test instance that expects a serialized
// block that is not canonical and therefore should be rejected.
type RejectedNonCanonicalBlock struct {
Name string
RawBlock []byte
Height int32
}
// FullBlockTestInstance only exists to allow RejectedNonCanonicalBlock to be treated as
// a TestInstance.
//
// This implements the TestInstance interface.
func (b RejectedNonCanonicalBlock) FullBlockTestInstance() {}
// spendableOut represents a transaction output that is spendable along with
// additional metadata such as the block its in and how much it pays.
type spendableOut struct {
prevOut wire.OutPoint
amount vclutil.Amount
}
// makeSpendableOutForTx returns a spendable output for the given transaction
// and transaction output index within the transaction.
func makeSpendableOutForTx(tx *wire.MsgTx, txOutIndex uint32) spendableOut {
return spendableOut{
prevOut: wire.OutPoint{
Hash: tx.TxHash(),
Index: txOutIndex,
},
amount: vclutil.Amount(tx.TxOut[txOutIndex].Value),
}
}
// makeSpendableOut returns a spendable output for the given block, transaction
// index within the block, and transaction output index within the transaction.
func makeSpendableOut(block *wire.MsgBlock, txIndex, txOutIndex uint32) spendableOut {
return makeSpendableOutForTx(block.Transactions[txIndex], txOutIndex)
}
// testGenerator houses state used to easy the process of generating test blocks
// that build from one another along with housing other useful things such as
// available spendable outputs used throughout the tests.
type testGenerator struct {
params *chaincfg.Params
tip *wire.MsgBlock
tipName string
tipHeight int32
blocks map[chainhash.Hash]*wire.MsgBlock
blocksByName map[string]*wire.MsgBlock
blockHeights map[string]int32
// Used for tracking spendable coinbase outputs.
spendableOuts []spendableOut
prevCollectedHash chainhash.Hash
// Common key for any tests which require signed transactions.
privKey *btcec.PrivateKey
}
// makeTestGenerator returns a test generator instance initialized with the
// genesis block as the tip.
func makeTestGenerator(params *chaincfg.Params) (testGenerator, error) {
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), []byte{0x01})
genesis := params.GenesisBlock
genesisHash := genesis.BlockHash()
return testGenerator{
params: params,
blocks: map[chainhash.Hash]*wire.MsgBlock{genesisHash: genesis},
blocksByName: map[string]*wire.MsgBlock{"genesis": genesis},
blockHeights: map[string]int32{"genesis": 0},
tip: genesis,
tipName: "genesis",
tipHeight: 0,
privKey: privKey,
}, nil
}
// payToScriptHashScript returns a standard pay-to-script-hash for the provided
// redeem script.
func payToScriptHashScript(redeemScript []byte) []byte {
redeemScriptHash := vclutil.Hash160(redeemScript)
script, err := txscript.NewScriptBuilder().
AddOp(txscript.OP_HASH160).AddData(redeemScriptHash).
AddOp(txscript.OP_EQUAL).Script()
if err != nil {
panic(err)
}
return script
}
// pushDataScript returns a script with the provided items individually pushed
// to the stack.
func pushDataScript(items ...[]byte) []byte {
builder := txscript.NewScriptBuilder()
for _, item := range items {
builder.AddData(item)
}
script, err := builder.Script()
if err != nil {
panic(err)
}
return script
}
// standardCoinbaseScript returns a standard script suitable for use as the
// signature script of the coinbase transaction of a new block. In particular,
// it starts with the block height that is required by version 2 blocks.
func standardCoinbaseScript(blockHeight int32, extraNonce uint64) ([]byte, error) {
return txscript.NewScriptBuilder().AddInt64(int64(blockHeight)).
AddInt64(int64(extraNonce)).Script()
}
// opReturnScript returns a provably-pruneable OP_RETURN script with the
// provided data.
func opReturnScript(data []byte) []byte {
builder := txscript.NewScriptBuilder()
script, err := builder.AddOp(txscript.OP_RETURN).AddData(data).Script()
if err != nil {
panic(err)
}
return script
}
// uniqueOpReturnScript returns a standard provably-pruneable OP_RETURN script
// with a random uint64 encoded as the data.
func uniqueOpReturnScript() []byte {
rand, err := wire.RandomUint64()
if err != nil {
panic(err)
}
data := make([]byte, 8)
binary.LittleEndian.PutUint64(data[0:8], rand)
return opReturnScript(data)
}
// createCoinbaseTx returns a coinbase transaction paying an appropriate
// subsidy based on the passed block height. The coinbase signature script
// conforms to the requirements of version 2 blocks.
func (g *testGenerator) createCoinbaseTx(blockHeight int32) *wire.MsgTx {
extraNonce := uint64(0)
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
if err != nil {
panic(err)
}
tx := wire.NewMsgTx(1)
tx.AddTxIn(&wire.TxIn{
// Coinbase transactions have no inputs, so previous outpoint is
// zero hash and max index.
PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},
wire.MaxPrevOutIndex),
Sequence: wire.MaxTxInSequenceNum,
SignatureScript: coinbaseScript,
})
tx.AddTxOut(&wire.TxOut{
Value: blockchain.CalcBlockSubsidy(blockHeight, g.params),
PkScript: opTrueScript,
})
return tx
}
// calcMerkleRoot creates a merkle tree from the slice of transactions and
// returns the root of the tree.
func calcMerkleRoot(txns []*wire.MsgTx) chainhash.Hash {
if len(txns) == 0 {
return chainhash.Hash{}
}
utilTxns := make([]*vclutil.Tx, 0, len(txns))
for _, tx := range txns {
utilTxns = append(utilTxns, vclutil.NewTx(tx))
}
merkles := blockchain.BuildMerkleTreeStore(utilTxns, false)
return *merkles[len(merkles)-1]
}
// solveBlock attempts to find a nonce which makes the passed block header hash
// to a value less than the target difficulty. When a successful solution is
// found true is returned and the nonce field of the passed header is updated
// with the solution. False is returned if no solution exists.
//
// NOTE: This function will never solve blocks with a nonce of 0. This is done
// so the 'nextBlock' function can properly detect when a nonce was modified by
// a munge function.
func solveBlock(header *wire.BlockHeader) bool {
// sbResult is used by the solver goroutines to send results.
type sbResult struct {
found bool
nonce uint32
}
// solver accepts a block header and a nonce range to test. It is
// intended to be run as a goroutine.
targetDifficulty := blockchain.CompactToBig(header.Bits)
quit := make(chan bool)
results := make(chan sbResult)
solver := func(hdr wire.BlockHeader, startNonce, stopNonce uint32) {
// We need to modify the nonce field of the header, so make sure
// we work with a copy of the original header.
for i := startNonce; i >= startNonce && i <= stopNonce; i++ {
select {
case <-quit:
return
default:
hdr.Nonce = i
hash := hdr.BlockHash()
if blockchain.HashToBig(&hash).Cmp(
targetDifficulty) <= 0 {
results <- sbResult{true, i}
return
}
}
}
results <- sbResult{false, 0}
}
startNonce := uint32(1)
stopNonce := uint32(math.MaxUint32)
numCores := uint32(runtime.NumCPU())
noncesPerCore := (stopNonce - startNonce) / numCores
for i := uint32(0); i < numCores; i++ {
rangeStart := startNonce + (noncesPerCore * i)
rangeStop := startNonce + (noncesPerCore * (i + 1)) - 1
if i == numCores-1 {
rangeStop = stopNonce
}
go solver(*header, rangeStart, rangeStop)
}
for i := uint32(0); i < numCores; i++ {
result := <-results
if result.found {
close(quit)
header.Nonce = result.nonce
return true
}
}
return false
}
// additionalCoinbase returns a function that itself takes a block and
// modifies it by adding the provided amount to coinbase subsidy.
func additionalCoinbase(amount vclutil.Amount) func(*wire.MsgBlock) {
return func(b *wire.MsgBlock) {
// Increase the first proof-of-work coinbase subsidy by the
// provided amount.
b.Transactions[0].TxOut[0].Value += int64(amount)
}
}
// additionalSpendFee returns a function that itself takes a block and modifies
// it by adding the provided fee to the spending transaction.
//
// NOTE: The coinbase value is NOT updated to reflect the additional fee. Use
// 'additionalCoinbase' for that purpose.
func additionalSpendFee(fee vclutil.Amount) func(*wire.MsgBlock) {
return func(b *wire.MsgBlock) {
// Increase the fee of the spending transaction by reducing the
// amount paid.
if int64(fee) > b.Transactions[1].TxOut[0].Value {
panic(fmt.Sprintf("additionalSpendFee: fee of %d "+
"exceeds available spend transaction value",
fee))
}
b.Transactions[1].TxOut[0].Value -= int64(fee)
}
}
// replaceSpendScript returns a function that itself takes a block and modifies
// it by replacing the public key script of the spending transaction.
func replaceSpendScript(pkScript []byte) func(*wire.MsgBlock) {
return func(b *wire.MsgBlock) {
b.Transactions[1].TxOut[0].PkScript = pkScript
}
}
// replaceCoinbaseSigScript returns a function that itself takes a block and
// modifies it by replacing the signature key script of the coinbase.
func replaceCoinbaseSigScript(script []byte) func(*wire.MsgBlock) {
return func(b *wire.MsgBlock) {
b.Transactions[0].TxIn[0].SignatureScript = script
}
}
// additionalTx returns a function that itself takes a block and modifies it by
// adding the the provided transaction.
func additionalTx(tx *wire.MsgTx) func(*wire.MsgBlock) {
return func(b *wire.MsgBlock) {
b.AddTransaction(tx)
}
}
// createSpendTx creates a transaction that spends from the provided spendable
// output and includes an additional unique OP_RETURN output to ensure the
// transaction ends up with a unique hash. The script is a simple OP_TRUE
// script which avoids the need to track addresses and signature scripts in the
// tests.
func createSpendTx(spend *spendableOut, fee vclutil.Amount) *wire.MsgTx {
spendTx := wire.NewMsgTx(1)
spendTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: spend.prevOut,
Sequence: wire.MaxTxInSequenceNum,
SignatureScript: nil,
})
spendTx.AddTxOut(wire.NewTxOut(int64(spend.amount-fee),
opTrueScript))
spendTx.AddTxOut(wire.NewTxOut(0, uniqueOpReturnScript()))
return spendTx
}
// createSpendTxForTx creates a transaction that spends from the first output of
// the provided transaction and includes an additional unique OP_RETURN output
// to ensure the transaction ends up with a unique hash. The public key script
// is a simple OP_TRUE script which avoids the need to track addresses and
// signature scripts in the tests. The signature script is nil.
func createSpendTxForTx(tx *wire.MsgTx, fee vclutil.Amount) *wire.MsgTx {
spend := makeSpendableOutForTx(tx, 0)
return createSpendTx(&spend, fee)
}
// nextBlock builds a new block that extends the current tip associated with the
// generator and updates the generator's tip to the newly generated block.
//
// The block will include the following:
// - A coinbase that pays the required subsidy to an OP_TRUE script
// - When a spendable output is provided:
// - A transaction that spends from the provided output the following outputs:
// - One that pays the inputs amount minus 1 atom to an OP_TRUE script
// - One that contains an OP_RETURN output with a random uint64 in order to
// ensure the transaction has a unique hash
//
// Additionally, if one or more munge functions are specified, they will be
// invoked with the block prior to solving it. This provides callers with the
// opportunity to modify the block which is especially useful for testing.
//
// In order to simply the logic in the munge functions, the following rules are
// applied after all munge functions have been invoked:
// - The merkle root will be recalculated unless it was manually changed
// - The block will be solved unless the nonce was changed
func (g *testGenerator) nextBlock(blockName string, spend *spendableOut, mungers ...func(*wire.MsgBlock)) *wire.MsgBlock {
// Create coinbase transaction for the block using any additional
// subsidy if specified.
nextHeight := g.tipHeight + 1
coinbaseTx := g.createCoinbaseTx(nextHeight)
txns := []*wire.MsgTx{coinbaseTx}
if spend != nil {
// Create the transaction with a fee of 1 atom for the
// miner and increase the coinbase subsidy accordingly.
fee := vclutil.Amount(1)
coinbaseTx.TxOut[0].Value += int64(fee)
// Create a transaction that spends from the provided spendable
// output and includes an additional unique OP_RETURN output to
// ensure the transaction ends up with a unique hash, then add
// add it to the list of transactions to include in the block.
// The script is a simple OP_TRUE script in order to avoid the
// need to track addresses and signature scripts in the tests.
txns = append(txns, createSpendTx(spend, fee))
}
// Use a timestamp that is one second after the previous block unless
// this is the first block in which case the current time is used.
var ts time.Time
if nextHeight == 1 {
ts = time.Unix(time.Now().Unix(), 0)
} else {
ts = g.tip.Header.Timestamp.Add(time.Second)
}
block := wire.MsgBlock{
Header: wire.BlockHeader{
Version: 1,
PrevBlock: g.tip.BlockHash(),
MerkleRoot: calcMerkleRoot(txns),
Bits: g.params.PowLimitBits,
Timestamp: ts,
Nonce: 0, // To be solved.
},
Transactions: txns,
}
// Perform any block munging just before solving. Only recalculate the
// merkle root if it wasn't manually changed by a munge function.
curMerkleRoot := block.Header.MerkleRoot
curNonce := block.Header.Nonce
for _, f := range mungers {
f(&block)
}
if block.Header.MerkleRoot == curMerkleRoot {
block.Header.MerkleRoot = calcMerkleRoot(block.Transactions)
}
// Only solve the block if the nonce wasn't manually changed by a munge
// function.
if block.Header.Nonce == curNonce && !solveBlock(&block.Header) {
panic(fmt.Sprintf("Unable to solve block at height %d",
nextHeight))
}
// Update generator state and return the block.
blockHash := block.BlockHash()
g.blocks[blockHash] = &block
g.blocksByName[blockName] = &block
g.blockHeights[blockName] = nextHeight
g.tip = &block
g.tipName = blockName
g.tipHeight = nextHeight
return &block
}
// updateBlockState manually updates the generator state to remove all internal
// map references to a block via its old hash and insert new ones for the new
// block hash. This is useful if the test code has to manually change a block
// after 'nextBlock' has returned.
func (g *testGenerator) updateBlockState(oldBlockName string, oldBlockHash chainhash.Hash, newBlockName string, newBlock *wire.MsgBlock) {
// Look up the height from the existing entries.
blockHeight := g.blockHeights[oldBlockName]
// Remove existing entries.
delete(g.blocks, oldBlockHash)
delete(g.blocksByName, oldBlockName)
delete(g.blockHeights, oldBlockName)
// Add new entries.
newBlockHash := newBlock.BlockHash()
g.blocks[newBlockHash] = newBlock
g.blocksByName[newBlockName] = newBlock
g.blockHeights[newBlockName] = blockHeight
}
// setTip changes the tip of the instance to the block with the provided name.
// This is useful since the tip is used for things such as generating subsequent
// blocks.
func (g *testGenerator) setTip(blockName string) {
g.tip = g.blocksByName[blockName]
g.tipName = blockName
g.tipHeight = g.blockHeights[blockName]
}
// oldestCoinbaseOuts removes the oldest coinbase output that was previously
// saved to the generator and returns the set as a slice.
func (g *testGenerator) oldestCoinbaseOut() spendableOut {
op := g.spendableOuts[0]
g.spendableOuts = g.spendableOuts[1:]
return op
}
// saveTipCoinbaseOut adds the coinbase tx output in the current tip block to
// the list of spendable outputs.
func (g *testGenerator) saveTipCoinbaseOut() {
g.spendableOuts = append(g.spendableOuts, makeSpendableOut(g.tip, 0, 0))
g.prevCollectedHash = g.tip.BlockHash()
}
// saveSpendableCoinbaseOuts adds all coinbase outputs from the last block that
// had its coinbase tx output colleted to the current tip. This is useful to
// batch the collection of coinbase outputs once the tests reach a stable point
// so they don't have to manually add them for the right tests which will
// ultimately end up being the best chain.
func (g *testGenerator) saveSpendableCoinbaseOuts() {
// Ensure tip is reset to the current one when done.
curTipName := g.tipName
defer g.setTip(curTipName)
// Loop through the ancestors of the current tip until the
// reaching the block that has already had the coinbase outputs
// collected.
var collectBlocks []*wire.MsgBlock
for b := g.tip; b != nil; b = g.blocks[b.Header.PrevBlock] {
if b.BlockHash() == g.prevCollectedHash {
break
}
collectBlocks = append(collectBlocks, b)
}
for i := range collectBlocks {
g.tip = collectBlocks[len(collectBlocks)-1-i]
g.saveTipCoinbaseOut()
}
}
// nonCanonicalVarInt return a variable-length encoded integer that is encoded
// with 9 bytes even though it could be encoded with a minimal canonical
// encoding.
func nonCanonicalVarInt(val uint32) []byte {
var rv [9]byte
rv[0] = 0xff
binary.LittleEndian.PutUint64(rv[1:], uint64(val))
return rv[:]
}
// encodeNonCanonicalBlock serializes the block in a non-canonical way by
// encoding the number of transactions using a variable-length encoded integer
// with 9 bytes even though it should be encoded with a minimal canonical
// encoding.
func encodeNonCanonicalBlock(b *wire.MsgBlock) []byte {
var buf bytes.Buffer
b.Header.BtcEncode(&buf, 0, wire.BaseEncoding)
buf.Write(nonCanonicalVarInt(uint32(len(b.Transactions))))
for _, tx := range b.Transactions {
tx.BtcEncode(&buf, 0, wire.BaseEncoding)
}
return buf.Bytes()
}
// cloneBlock returns a deep copy of the provided block.
func cloneBlock(b *wire.MsgBlock) wire.MsgBlock {
var blockCopy wire.MsgBlock
blockCopy.Header = b.Header
for _, tx := range b.Transactions {
blockCopy.AddTransaction(tx.Copy())
}
return blockCopy
}
// repeatOpcode returns a byte slice with the provided opcode repeated the
// specified number of times.
func repeatOpcode(opcode uint8, numRepeats int) []byte {
return bytes.Repeat([]byte{opcode}, numRepeats)
}
// assertScriptSigOpsCount panics if the provided script does not have the
// specified number of signature operations.
func assertScriptSigOpsCount(script []byte, expected int) {
numSigOps := txscript.GetSigOpCount(script)
if numSigOps != expected {
_, file, line, _ := runtime.Caller(1)
panic(fmt.Sprintf("assertion failed at %s:%d: generated number "+
"of sigops for script is %d instead of expected %d",
file, line, numSigOps, expected))
}
}
// countBlockSigOps returns the number of legacy signature operations in the
// scripts in the passed block.
func countBlockSigOps(block *wire.MsgBlock) int {
totalSigOps := 0
for _, tx := range block.Transactions {
for _, txIn := range tx.TxIn {
numSigOps := txscript.GetSigOpCount(txIn.SignatureScript)
totalSigOps += numSigOps
}
for _, txOut := range tx.TxOut {
numSigOps := txscript.GetSigOpCount(txOut.PkScript)
totalSigOps += numSigOps
}
}
return totalSigOps
}
// assertTipBlockSigOpsCount panics if the current tip block associated with the
// generator does not have the specified number of signature operations.
func (g *testGenerator) assertTipBlockSigOpsCount(expected int) {
numSigOps := countBlockSigOps(g.tip)
if numSigOps != expected {
panic(fmt.Sprintf("generated number of sigops for block %q "+
"(height %d) is %d instead of expected %d", g.tipName,
g.tipHeight, numSigOps, expected))
}
}
// assertTipBlockSize panics if the if the current tip block associated with the
// generator does not have the specified size when serialized.
func (g *testGenerator) assertTipBlockSize(expected int) {
serializeSize := g.tip.SerializeSize()
if serializeSize != expected {
panic(fmt.Sprintf("block size of block %q (height %d) is %d "+
"instead of expected %d", g.tipName, g.tipHeight,
serializeSize, expected))
}
}
// assertTipNonCanonicalBlockSize panics if the if the current tip block
// associated with the generator does not have the specified non-canonical size
// when serialized.
func (g *testGenerator) assertTipNonCanonicalBlockSize(expected int) {
serializeSize := len(encodeNonCanonicalBlock(g.tip))
if serializeSize != expected {
panic(fmt.Sprintf("block size of block %q (height %d) is %d "+
"instead of expected %d", g.tipName, g.tipHeight,
serializeSize, expected))
}
}
// assertTipBlockNumTxns panics if the number of transactions in the current tip
// block associated with the generator does not match the specified value.
func (g *testGenerator) assertTipBlockNumTxns(expected int) {
numTxns := len(g.tip.Transactions)
if numTxns != expected {
panic(fmt.Sprintf("number of txns in block %q (height %d) is "+
"%d instead of expected %d", g.tipName, g.tipHeight,
numTxns, expected))
}
}
// assertTipBlockHash panics if the current tip block associated with the
// generator does not match the specified hash.
func (g *testGenerator) assertTipBlockHash(expected chainhash.Hash) {
hash := g.tip.BlockHash()
if hash != expected {
panic(fmt.Sprintf("block hash of block %q (height %d) is %v "+
"instead of expected %v", g.tipName, g.tipHeight, hash,
expected))
}
}
// assertTipBlockMerkleRoot panics if the merkle root in header of the current
// tip block associated with the generator does not match the specified hash.
func (g *testGenerator) assertTipBlockMerkleRoot(expected chainhash.Hash) {
hash := g.tip.Header.MerkleRoot
if hash != expected {
panic(fmt.Sprintf("merkle root of block %q (height %d) is %v "+
"instead of expected %v", g.tipName, g.tipHeight, hash,
expected))
}
}
// assertTipBlockTxOutOpReturn panics if the current tip block associated with
// the generator does not have an OP_RETURN script for the transaction output at
// the provided tx index and output index.
func (g *testGenerator) assertTipBlockTxOutOpReturn(txIndex, txOutIndex uint32) {
if txIndex >= uint32(len(g.tip.Transactions)) {
panic(fmt.Sprintf("Transaction index %d in block %q "+
"(height %d) does not exist", txIndex, g.tipName,
g.tipHeight))
}
tx := g.tip.Transactions[txIndex]
if txOutIndex >= uint32(len(tx.TxOut)) {
panic(fmt.Sprintf("transaction index %d output %d in block %q "+
"(height %d) does not exist", txIndex, txOutIndex,
g.tipName, g.tipHeight))
}
txOut := tx.TxOut[txOutIndex]
if txOut.PkScript[0] != txscript.OP_RETURN {
panic(fmt.Sprintf("transaction index %d output %d in block %q "+
"(height %d) is not an OP_RETURN", txIndex, txOutIndex,
g.tipName, g.tipHeight))
}
}
// Generate returns a slice of tests that can be used to exercise the consensus
// validation rules. The tests are intended to be flexible enough to allow both
// unit-style tests directly against the blockchain code as well as integration
// style tests over the peer-to-peer network. To achieve that goal, each test
// contains additional information about the expected result, however that
// information can be ignored when doing comparison tests between two
// independent versions over the peer-to-peer network.
func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
// In order to simplify the generation code which really should never
// fail unless the test code itself is broken, panics are used
// internally. This deferred func ensures any panics don't escape the
// generator by replacing the named error return with the underlying
// panic error.
defer func() {
if r := recover(); r != nil {
tests = nil
switch rt := r.(type) {
case string:
err = errors.New(rt)
case error:
err = rt
default:
err = errors.New("Unknown panic")
}
}
}()
// Create a test generator instance initialized with the genesis block
// as the tip.
g, err := makeTestGenerator(regressionNetParams)
if err != nil {
return nil, err
}
// Define some convenience helper functions to return an individual test
// instance that has the described characteristics.
//
// acceptBlock creates a test instance that expects the provided block
// to be accepted by the consensus rules.
//
// rejectBlock creates a test instance that expects the provided block
// to be rejected by the consensus rules.
//
// rejectNonCanonicalBlock creates a test instance that encodes the
// provided block using a non-canonical encoded as described by the
// encodeNonCanonicalBlock function and expected it to be rejected.
//
// orphanOrRejectBlock creates a test instance that expected the
// provided block to either by accepted as an orphan or rejected by the
// consensus rules.
//
// expectTipBlock creates a test instance that expects the provided
// block to be the current tip of the block chain.
acceptBlock := func(blockName string, block *wire.MsgBlock, isMainChain, isOrphan bool) TestInstance {
blockHeight := g.blockHeights[blockName]
return AcceptedBlock{blockName, block, blockHeight, isMainChain,
isOrphan}
}
rejectBlock := func(blockName string, block *wire.MsgBlock, code blockchain.ErrorCode) TestInstance {
blockHeight := g.blockHeights[blockName]
return RejectedBlock{blockName, block, blockHeight, code}
}
rejectNonCanonicalBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
blockHeight := g.blockHeights[blockName]
encoded := encodeNonCanonicalBlock(block)
return RejectedNonCanonicalBlock{blockName, encoded, blockHeight}
}
orphanOrRejectBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
blockHeight := g.blockHeights[blockName]
return OrphanOrRejectedBlock{blockName, block, blockHeight}
}
expectTipBlock := func(blockName string, block *wire.MsgBlock) TestInstance {
blockHeight := g.blockHeights[blockName]
return ExpectedTip{blockName, block, blockHeight}
}
// Define some convenience helper functions to populate the tests slice
// with test instances that have the described characteristics.
//
// accepted creates and appends a single acceptBlock test instance for
// the current tip which expects the block to be accepted to the main
// chain.
//
// acceptedToSideChainWithExpectedTip creates an appends a two-instance
// test. The first instance is an acceptBlock test instance for the
// current tip which expects the block to be accepted to a side chain.
// The second instance is an expectBlockTip test instance for provided
// values.
//
// rejected creates and appends a single rejectBlock test instance for
// the current tip.
//
// rejectedNonCanonical creates and appends a single
// rejectNonCanonicalBlock test instance for the current tip.
//
// orphanedOrRejected creates and appends a single orphanOrRejectBlock
// test instance for the current tip.
accepted := func() {
tests = append(tests, []TestInstance{
acceptBlock(g.tipName, g.tip, true, false),
})
}
acceptedToSideChainWithExpectedTip := func(tipName string) {
tests = append(tests, []TestInstance{
acceptBlock(g.tipName, g.tip, false, false),
expectTipBlock(tipName, g.blocksByName[tipName]),
})
}
rejected := func(code blockchain.ErrorCode) {
tests = append(tests, []TestInstance{
rejectBlock(g.tipName, g.tip, code),
})
}
rejectedNonCanonical := func() {
tests = append(tests, []TestInstance{
rejectNonCanonicalBlock(g.tipName, g.tip),
})
}
orphanedOrRejected := func() {
tests = append(tests, []TestInstance{
orphanOrRejectBlock(g.tipName, g.tip),
})
}
// ---------------------------------------------------------------------
// Generate enough blocks to have mature coinbase outputs to work with.
//
// genesis -> bm0 -> bm1 -> ... -> bm99
// ---------------------------------------------------------------------
coinbaseMaturity := g.params.CoinbaseMaturity
var testInstances []TestInstance
for i := uint16(0); i < coinbaseMaturity; i++ {
blockName := fmt.Sprintf("bm%d", i)
g.nextBlock(blockName, nil)
g.saveTipCoinbaseOut()
testInstances = append(testInstances, acceptBlock(g.tipName,
g.tip, true, false))
}
tests = append(tests, testInstances)
// Collect spendable outputs. This simplifies the code below.
var outs []*spendableOut
for i := uint16(0); i < coinbaseMaturity; i++ {
op := g.oldestCoinbaseOut()
outs = append(outs, &op)
}
// ---------------------------------------------------------------------
// Basic forking and reorg tests.
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// The comments below identify the structure of the chain being built.
//
// The values in parenthesis repesent which outputs are being spent.
//
// For example, b1(0) indicates the first collected spendable output
// which, due to the code above to create the correct number of blocks,
// is the first output that can be spent at the current block height due
// to the coinbase maturity requirement.
// ---------------------------------------------------------------------
// Start by building a couple of blocks at current tip (value in parens
// is which output is spent):
//
// ... -> b1(0) -> b2(1)
g.nextBlock("b1", outs[0])
accepted()
g.nextBlock("b2", outs[1])
accepted()
// Create a fork from b1. There should not be a reorg since b2 was seen
// first.
//
// ... -> b1(0) -> b2(1)
// \-> b3(1)
g.setTip("b1")
g.nextBlock("b3", outs[1])
b3Tx1Out := makeSpendableOut(g.tip, 1, 0)
acceptedToSideChainWithExpectedTip("b2")
// Extend b3 fork to make the alternative chain longer and force reorg.
//
// ... -> b1(0) -> b2(1)
// \-> b3(1) -> b4(2)
g.nextBlock("b4", outs[2])
accepted()
// Extend b2 fork twice to make first chain longer and force reorg.
//
// ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
// \-> b3(1) -> b4(2)
g.setTip("b2")
g.nextBlock("b5", outs[2])
acceptedToSideChainWithExpectedTip("b4")
g.nextBlock("b6", outs[3])
accepted()
// ---------------------------------------------------------------------
// Double spend tests.
// ---------------------------------------------------------------------
// Create a fork that double spends.
//
// ... -> b1(0) -> b2(1) -> b5(2) -> b6(3)
// \-> b7(2) -> b8(4)
// \-> b3(1) -> b4(2)
g.setTip("b5")
g.nextBlock("b7", outs[2])
acceptedToSideChainWithExpectedTip("b6")
g.nextBlock("b8", outs[4])
rejected(blockchain.ErrMissingTxOut)