1// Copyright (c) 2013-2017 The btcsuite developers
2// Use of this source code is governed by an ISC
3// license that can be found in the LICENSE file.
4
5package blockchain
6
7import (
8	"encoding/binary"
9	"fmt"
10	"math"
11	"math/big"
12	"time"
13
14	"github.com/btcsuite/btcd/chaincfg"
15	"github.com/btcsuite/btcd/chaincfg/chainhash"
16	"github.com/btcsuite/btcd/txscript"
17	"github.com/btcsuite/btcd/wire"
18	"github.com/btcsuite/btcutil"
19)
20
21const (
22	// MaxTimeOffsetSeconds is the maximum number of seconds a block time
23	// is allowed to be ahead of the current time.  This is currently 2
24	// hours.
25	MaxTimeOffsetSeconds = 2 * 60 * 60
26
27	// MinCoinbaseScriptLen is the minimum length a coinbase script can be.
28	MinCoinbaseScriptLen = 2
29
30	// MaxCoinbaseScriptLen is the maximum length a coinbase script can be.
31	MaxCoinbaseScriptLen = 100
32
33	// medianTimeBlocks is the number of previous blocks which should be
34	// used to calculate the median time used to validate block timestamps.
35	medianTimeBlocks = 11
36
37	// serializedHeightVersion is the block version which changed block
38	// coinbases to start with the serialized block height.
39	serializedHeightVersion = 2
40
41	// baseSubsidy is the starting subsidy amount for mined blocks.  This
42	// value is halved every SubsidyHalvingInterval blocks.
43	baseSubsidy = 50 * btcutil.SatoshiPerBitcoin
44)
45
46var (
47	// zeroHash is the zero value for a chainhash.Hash and is defined as
48	// a package level variable to avoid the need to create a new instance
49	// every time a check is needed.
50	zeroHash chainhash.Hash
51
52	// block91842Hash is one of the two nodes which violate the rules
53	// set forth in BIP0030.  It is defined as a package level variable to
54	// avoid the need to create a new instance every time a check is needed.
55	block91842Hash = newHashFromStr("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")
56
57	// block91880Hash is one of the two nodes which violate the rules
58	// set forth in BIP0030.  It is defined as a package level variable to
59	// avoid the need to create a new instance every time a check is needed.
60	block91880Hash = newHashFromStr("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")
61)
62
63// isNullOutpoint determines whether or not a previous transaction output point
64// is set.
65func isNullOutpoint(outpoint *wire.OutPoint) bool {
66	if outpoint.Index == math.MaxUint32 && outpoint.Hash == zeroHash {
67		return true
68	}
69	return false
70}
71
72// ShouldHaveSerializedBlockHeight determines if a block should have a
73// serialized block height embedded within the scriptSig of its
74// coinbase transaction. Judgement is based on the block version in the block
75// header. Blocks with version 2 and above satisfy this criteria. See BIP0034
76// for further information.
77func ShouldHaveSerializedBlockHeight(header *wire.BlockHeader) bool {
78	return header.Version >= serializedHeightVersion
79}
80
81// IsCoinBaseTx determines whether or not a transaction is a coinbase.  A coinbase
82// is a special transaction created by miners that has no inputs.  This is
83// represented in the block chain by a transaction with a single input that has
84// a previous output transaction index set to the maximum value along with a
85// zero hash.
86//
87// This function only differs from IsCoinBase in that it works with a raw wire
88// transaction as opposed to a higher level util transaction.
89func IsCoinBaseTx(msgTx *wire.MsgTx) bool {
90	// A coin base must only have one transaction input.
91	if len(msgTx.TxIn) != 1 {
92		return false
93	}
94
95	// The previous output of a coin base must have a max value index and
96	// a zero hash.
97	prevOut := &msgTx.TxIn[0].PreviousOutPoint
98	if prevOut.Index != math.MaxUint32 || prevOut.Hash != zeroHash {
99		return false
100	}
101
102	return true
103}
104
105// IsCoinBase determines whether or not a transaction is a coinbase.  A coinbase
106// is a special transaction created by miners that has no inputs.  This is
107// represented in the block chain by a transaction with a single input that has
108// a previous output transaction index set to the maximum value along with a
109// zero hash.
110//
111// This function only differs from IsCoinBaseTx in that it works with a higher
112// level util transaction as opposed to a raw wire transaction.
113func IsCoinBase(tx *btcutil.Tx) bool {
114	return IsCoinBaseTx(tx.MsgTx())
115}
116
117// SequenceLockActive determines if a transaction's sequence locks have been
118// met, meaning that all the inputs of a given transaction have reached a
119// height or time sufficient for their relative lock-time maturity.
120func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32,
121	medianTimePast time.Time) bool {
122
123	// If either the seconds, or height relative-lock time has not yet
124	// reached, then the transaction is not yet mature according to its
125	// sequence locks.
126	if sequenceLock.Seconds >= medianTimePast.Unix() ||
127		sequenceLock.BlockHeight >= blockHeight {
128		return false
129	}
130
131	return true
132}
133
134// IsFinalizedTransaction determines whether or not a transaction is finalized.
135func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int32, blockTime time.Time) bool {
136	msgTx := tx.MsgTx()
137
138	// Lock time of zero means the transaction is finalized.
139	lockTime := msgTx.LockTime
140	if lockTime == 0 {
141		return true
142	}
143
144	// The lock time field of a transaction is either a block height at
145	// which the transaction is finalized or a timestamp depending on if the
146	// value is before the txscript.LockTimeThreshold.  When it is under the
147	// threshold it is a block height.
148	blockTimeOrHeight := int64(0)
149	if lockTime < txscript.LockTimeThreshold {
150		blockTimeOrHeight = int64(blockHeight)
151	} else {
152		blockTimeOrHeight = blockTime.Unix()
153	}
154	if int64(lockTime) < blockTimeOrHeight {
155		return true
156	}
157
158	// At this point, the transaction's lock time hasn't occurred yet, but
159	// the transaction might still be finalized if the sequence number
160	// for all transaction inputs is maxed out.
161	for _, txIn := range msgTx.TxIn {
162		if txIn.Sequence != math.MaxUint32 {
163			return false
164		}
165	}
166	return true
167}
168
169// isBIP0030Node returns whether or not the passed node represents one of the
170// two blocks that violate the BIP0030 rule which prevents transactions from
171// overwriting old ones.
172func isBIP0030Node(node *blockNode) bool {
173	if node.height == 91842 && node.hash.IsEqual(block91842Hash) {
174		return true
175	}
176
177	if node.height == 91880 && node.hash.IsEqual(block91880Hash) {
178		return true
179	}
180
181	return false
182}
183
184// CalcBlockSubsidy returns the subsidy amount a block at the provided height
185// should have. This is mainly used for determining how much the coinbase for
186// newly generated blocks awards as well as validating the coinbase for blocks
187// has the expected value.
188//
189// The subsidy is halved every SubsidyReductionInterval blocks.  Mathematically
190// this is: baseSubsidy / 2^(height/SubsidyReductionInterval)
191//
192// At the target block generation rate for the main network, this is
193// approximately every 4 years.
194func CalcBlockSubsidy(height int32, chainParams *chaincfg.Params) int64 {
195	if chainParams.SubsidyReductionInterval == 0 {
196		return baseSubsidy
197	}
198
199	// Equivalent to: baseSubsidy / 2^(height/subsidyHalvingInterval)
200	return baseSubsidy >> uint(height/chainParams.SubsidyReductionInterval)
201}
202
203// CheckTransactionSanity performs some preliminary checks on a transaction to
204// ensure it is sane.  These checks are context free.
205func CheckTransactionSanity(tx *btcutil.Tx) error {
206	// A transaction must have at least one input.
207	msgTx := tx.MsgTx()
208	if len(msgTx.TxIn) == 0 {
209		return ruleError(ErrNoTxInputs, "transaction has no inputs")
210	}
211
212	// A transaction must have at least one output.
213	if len(msgTx.TxOut) == 0 {
214		return ruleError(ErrNoTxOutputs, "transaction has no outputs")
215	}
216
217	// A transaction must not exceed the maximum allowed block payload when
218	// serialized.
219	serializedTxSize := tx.MsgTx().SerializeSizeStripped()
220	if serializedTxSize > MaxBlockBaseSize {
221		str := fmt.Sprintf("serialized transaction is too big - got "+
222			"%d, max %d", serializedTxSize, MaxBlockBaseSize)
223		return ruleError(ErrTxTooBig, str)
224	}
225
226	// Ensure the transaction amounts are in range.  Each transaction
227	// output must not be negative or more than the max allowed per
228	// transaction.  Also, the total of all outputs must abide by the same
229	// restrictions.  All amounts in a transaction are in a unit value known
230	// as a satoshi.  One bitcoin is a quantity of satoshi as defined by the
231	// SatoshiPerBitcoin constant.
232	var totalSatoshi int64
233	for _, txOut := range msgTx.TxOut {
234		satoshi := txOut.Value
235		if satoshi < 0 {
236			str := fmt.Sprintf("transaction output has negative "+
237				"value of %v", satoshi)
238			return ruleError(ErrBadTxOutValue, str)
239		}
240		if satoshi > btcutil.MaxSatoshi {
241			str := fmt.Sprintf("transaction output value of %v is "+
242				"higher than max allowed value of %v", satoshi,
243				btcutil.MaxSatoshi)
244			return ruleError(ErrBadTxOutValue, str)
245		}
246
247		// Two's complement int64 overflow guarantees that any overflow
248		// is detected and reported.  This is impossible for Bitcoin, but
249		// perhaps possible if an alt increases the total money supply.
250		totalSatoshi += satoshi
251		if totalSatoshi < 0 {
252			str := fmt.Sprintf("total value of all transaction "+
253				"outputs exceeds max allowed value of %v",
254				btcutil.MaxSatoshi)
255			return ruleError(ErrBadTxOutValue, str)
256		}
257		if totalSatoshi > btcutil.MaxSatoshi {
258			str := fmt.Sprintf("total value of all transaction "+
259				"outputs is %v which is higher than max "+
260				"allowed value of %v", totalSatoshi,
261				btcutil.MaxSatoshi)
262			return ruleError(ErrBadTxOutValue, str)
263		}
264	}
265
266	// Check for duplicate transaction inputs.
267	existingTxOut := make(map[wire.OutPoint]struct{})
268	for _, txIn := range msgTx.TxIn {
269		if _, exists := existingTxOut[txIn.PreviousOutPoint]; exists {
270			return ruleError(ErrDuplicateTxInputs, "transaction "+
271				"contains duplicate inputs")
272		}
273		existingTxOut[txIn.PreviousOutPoint] = struct{}{}
274	}
275
276	// Coinbase script length must be between min and max length.
277	if IsCoinBase(tx) {
278		slen := len(msgTx.TxIn[0].SignatureScript)
279		if slen < MinCoinbaseScriptLen || slen > MaxCoinbaseScriptLen {
280			str := fmt.Sprintf("coinbase transaction script length "+
281				"of %d is out of range (min: %d, max: %d)",
282				slen, MinCoinbaseScriptLen, MaxCoinbaseScriptLen)
283			return ruleError(ErrBadCoinbaseScriptLen, str)
284		}
285	} else {
286		// Previous transaction outputs referenced by the inputs to this
287		// transaction must not be null.
288		for _, txIn := range msgTx.TxIn {
289			if isNullOutpoint(&txIn.PreviousOutPoint) {
290				return ruleError(ErrBadTxInput, "transaction "+
291					"input refers to previous output that "+
292					"is null")
293			}
294		}
295	}
296
297	return nil
298}
299
300// checkProofOfWork ensures the block header bits which indicate the target
301// difficulty is in min/max range and that the block hash is less than the
302// target difficulty as claimed.
303//
304// The flags modify the behavior of this function as follows:
305//  - BFNoPoWCheck: The check to ensure the block hash is less than the target
306//    difficulty is not performed.
307func checkProofOfWork(header *wire.BlockHeader, powLimit *big.Int, flags BehaviorFlags) error {
308	// The target difficulty must be larger than zero.
309	target := CompactToBig(header.Bits)
310	if target.Sign() <= 0 {
311		str := fmt.Sprintf("block target difficulty of %064x is too low",
312			target)
313		return ruleError(ErrUnexpectedDifficulty, str)
314	}
315
316	// The target difficulty must be less than the maximum allowed.
317	if target.Cmp(powLimit) > 0 {
318		str := fmt.Sprintf("block target difficulty of %064x is "+
319			"higher than max of %064x", target, powLimit)
320		return ruleError(ErrUnexpectedDifficulty, str)
321	}
322
323	// The block hash must be less than the claimed target unless the flag
324	// to avoid proof of work checks is set.
325	if flags&BFNoPoWCheck != BFNoPoWCheck {
326		// The block hash must be less than the claimed target.
327		hash := header.BlockHash()
328		hashNum := HashToBig(&hash)
329		if hashNum.Cmp(target) > 0 {
330			str := fmt.Sprintf("block hash of %064x is higher than "+
331				"expected max of %064x", hashNum, target)
332			return ruleError(ErrHighHash, str)
333		}
334	}
335
336	return nil
337}
338
339// CheckProofOfWork ensures the block header bits which indicate the target
340// difficulty is in min/max range and that the block hash is less than the
341// target difficulty as claimed.
342func CheckProofOfWork(block *btcutil.Block, powLimit *big.Int) error {
343	return checkProofOfWork(&block.MsgBlock().Header, powLimit, BFNone)
344}
345
346// CountSigOps returns the number of signature operations for all transaction
347// input and output scripts in the provided transaction.  This uses the
348// quicker, but imprecise, signature operation counting mechanism from
349// txscript.
350func CountSigOps(tx *btcutil.Tx) int {
351	msgTx := tx.MsgTx()
352
353	// Accumulate the number of signature operations in all transaction
354	// inputs.
355	totalSigOps := 0
356	for _, txIn := range msgTx.TxIn {
357		numSigOps := txscript.GetSigOpCount(txIn.SignatureScript)
358		totalSigOps += numSigOps
359	}
360
361	// Accumulate the number of signature operations in all transaction
362	// outputs.
363	for _, txOut := range msgTx.TxOut {
364		numSigOps := txscript.GetSigOpCount(txOut.PkScript)
365		totalSigOps += numSigOps
366	}
367
368	return totalSigOps
369}
370
371// CountP2SHSigOps returns the number of signature operations for all input
372// transactions which are of the pay-to-script-hash type.  This uses the
373// precise, signature operation counting mechanism from the script engine which
374// requires access to the input transaction scripts.
375func CountP2SHSigOps(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint) (int, error) {
376	// Coinbase transactions have no interesting inputs.
377	if isCoinBaseTx {
378		return 0, nil
379	}
380
381	// Accumulate the number of signature operations in all transaction
382	// inputs.
383	msgTx := tx.MsgTx()
384	totalSigOps := 0
385	for txInIndex, txIn := range msgTx.TxIn {
386		// Ensure the referenced input transaction is available.
387		utxo := utxoView.LookupEntry(txIn.PreviousOutPoint)
388		if utxo == nil || utxo.IsSpent() {
389			str := fmt.Sprintf("output %v referenced from "+
390				"transaction %s:%d either does not exist or "+
391				"has already been spent", txIn.PreviousOutPoint,
392				tx.Hash(), txInIndex)
393			return 0, ruleError(ErrMissingTxOut, str)
394		}
395
396		// We're only interested in pay-to-script-hash types, so skip
397		// this input if it's not one.
398		pkScript := utxo.PkScript()
399		if !txscript.IsPayToScriptHash(pkScript) {
400			continue
401		}
402
403		// Count the precise number of signature operations in the
404		// referenced public key script.
405		sigScript := txIn.SignatureScript
406		numSigOps := txscript.GetPreciseSigOpCount(sigScript, pkScript,
407			true)
408
409		// We could potentially overflow the accumulator so check for
410		// overflow.
411		lastSigOps := totalSigOps
412		totalSigOps += numSigOps
413		if totalSigOps < lastSigOps {
414			str := fmt.Sprintf("the public key script from output "+
415				"%v contains too many signature operations - "+
416				"overflow", txIn.PreviousOutPoint)
417			return 0, ruleError(ErrTooManySigOps, str)
418		}
419	}
420
421	return totalSigOps, nil
422}
423
424// checkBlockHeaderSanity performs some preliminary checks on a block header to
425// ensure it is sane before continuing with processing.  These checks are
426// context free.
427//
428// The flags do not modify the behavior of this function directly, however they
429// are needed to pass along to checkProofOfWork.
430func checkBlockHeaderSanity(header *wire.BlockHeader, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error {
431	// Ensure the proof of work bits in the block header is in min/max range
432	// and the block hash is less than the target value described by the
433	// bits.
434	err := checkProofOfWork(header, powLimit, flags)
435	if err != nil {
436		return err
437	}
438
439	// A block timestamp must not have a greater precision than one second.
440	// This check is necessary because Go time.Time values support
441	// nanosecond precision whereas the consensus rules only apply to
442	// seconds and it's much nicer to deal with standard Go time values
443	// instead of converting to seconds everywhere.
444	if !header.Timestamp.Equal(time.Unix(header.Timestamp.Unix(), 0)) {
445		str := fmt.Sprintf("block timestamp of %v has a higher "+
446			"precision than one second", header.Timestamp)
447		return ruleError(ErrInvalidTime, str)
448	}
449
450	// Ensure the block time is not too far in the future.
451	maxTimestamp := timeSource.AdjustedTime().Add(time.Second *
452		MaxTimeOffsetSeconds)
453	if header.Timestamp.After(maxTimestamp) {
454		str := fmt.Sprintf("block timestamp of %v is too far in the "+
455			"future", header.Timestamp)
456		return ruleError(ErrTimeTooNew, str)
457	}
458
459	return nil
460}
461
462// checkBlockSanity performs some preliminary checks on a block to ensure it is
463// sane before continuing with block processing.  These checks are context free.
464//
465// The flags do not modify the behavior of this function directly, however they
466// are needed to pass along to checkBlockHeaderSanity.
467func checkBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource, flags BehaviorFlags) error {
468	msgBlock := block.MsgBlock()
469	header := &msgBlock.Header
470	err := checkBlockHeaderSanity(header, powLimit, timeSource, flags)
471	if err != nil {
472		return err
473	}
474
475	// A block must have at least one transaction.
476	numTx := len(msgBlock.Transactions)
477	if numTx == 0 {
478		return ruleError(ErrNoTransactions, "block does not contain "+
479			"any transactions")
480	}
481
482	// A block must not have more transactions than the max block payload or
483	// else it is certainly over the weight limit.
484	if numTx > MaxBlockBaseSize {
485		str := fmt.Sprintf("block contains too many transactions - "+
486			"got %d, max %d", numTx, MaxBlockBaseSize)
487		return ruleError(ErrBlockTooBig, str)
488	}
489
490	// A block must not exceed the maximum allowed block payload when
491	// serialized.
492	serializedSize := msgBlock.SerializeSizeStripped()
493	if serializedSize > MaxBlockBaseSize {
494		str := fmt.Sprintf("serialized block is too big - got %d, "+
495			"max %d", serializedSize, MaxBlockBaseSize)
496		return ruleError(ErrBlockTooBig, str)
497	}
498
499	// The first transaction in a block must be a coinbase.
500	transactions := block.Transactions()
501	if !IsCoinBase(transactions[0]) {
502		return ruleError(ErrFirstTxNotCoinbase, "first transaction in "+
503			"block is not a coinbase")
504	}
505
506	// A block must not have more than one coinbase.
507	for i, tx := range transactions[1:] {
508		if IsCoinBase(tx) {
509			str := fmt.Sprintf("block contains second coinbase at "+
510				"index %d", i+1)
511			return ruleError(ErrMultipleCoinbases, str)
512		}
513	}
514
515	// Do some preliminary checks on each transaction to ensure they are
516	// sane before continuing.
517	for _, tx := range transactions {
518		err := CheckTransactionSanity(tx)
519		if err != nil {
520			return err
521		}
522	}
523
524	// Build merkle tree and ensure the calculated merkle root matches the
525	// entry in the block header.  This also has the effect of caching all
526	// of the transaction hashes in the block to speed up future hash
527	// checks.  Bitcoind builds the tree here and checks the merkle root
528	// after the following checks, but there is no reason not to check the
529	// merkle root matches here.
530	merkles := BuildMerkleTreeStore(block.Transactions(), false)
531	calculatedMerkleRoot := merkles[len(merkles)-1]
532	if !header.MerkleRoot.IsEqual(calculatedMerkleRoot) {
533		str := fmt.Sprintf("block merkle root is invalid - block "+
534			"header indicates %v, but calculated value is %v",
535			header.MerkleRoot, calculatedMerkleRoot)
536		return ruleError(ErrBadMerkleRoot, str)
537	}
538
539	// Check for duplicate transactions.  This check will be fairly quick
540	// since the transaction hashes are already cached due to building the
541	// merkle tree above.
542	existingTxHashes := make(map[chainhash.Hash]struct{})
543	for _, tx := range transactions {
544		hash := tx.Hash()
545		if _, exists := existingTxHashes[*hash]; exists {
546			str := fmt.Sprintf("block contains duplicate "+
547				"transaction %v", hash)
548			return ruleError(ErrDuplicateTx, str)
549		}
550		existingTxHashes[*hash] = struct{}{}
551	}
552
553	// The number of signature operations must be less than the maximum
554	// allowed per block.
555	totalSigOps := 0
556	for _, tx := range transactions {
557		// We could potentially overflow the accumulator so check for
558		// overflow.
559		lastSigOps := totalSigOps
560		totalSigOps += (CountSigOps(tx) * WitnessScaleFactor)
561		if totalSigOps < lastSigOps || totalSigOps > MaxBlockSigOpsCost {
562			str := fmt.Sprintf("block contains too many signature "+
563				"operations - got %v, max %v", totalSigOps,
564				MaxBlockSigOpsCost)
565			return ruleError(ErrTooManySigOps, str)
566		}
567	}
568
569	return nil
570}
571
572// CheckBlockSanity performs some preliminary checks on a block to ensure it is
573// sane before continuing with block processing.  These checks are context free.
574func CheckBlockSanity(block *btcutil.Block, powLimit *big.Int, timeSource MedianTimeSource) error {
575	return checkBlockSanity(block, powLimit, timeSource, BFNone)
576}
577
578// ExtractCoinbaseHeight attempts to extract the height of the block from the
579// scriptSig of a coinbase transaction.  Coinbase heights are only present in
580// blocks of version 2 or later.  This was added as part of BIP0034.
581func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int32, error) {
582	sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript
583	if len(sigScript) < 1 {
584		str := "the coinbase signature script for blocks of " +
585			"version %d or greater must start with the " +
586			"length of the serialized block height"
587		str = fmt.Sprintf(str, serializedHeightVersion)
588		return 0, ruleError(ErrMissingCoinbaseHeight, str)
589	}
590
591	// Detect the case when the block height is a small integer encoded with
592	// as single byte.
593	opcode := int(sigScript[0])
594	if opcode == txscript.OP_0 {
595		return 0, nil
596	}
597	if opcode >= txscript.OP_1 && opcode <= txscript.OP_16 {
598		return int32(opcode - (txscript.OP_1 - 1)), nil
599	}
600
601	// Otherwise, the opcode is the length of the following bytes which
602	// encode in the block height.
603	serializedLen := int(sigScript[0])
604	if len(sigScript[1:]) < serializedLen {
605		str := "the coinbase signature script for blocks of " +
606			"version %d or greater must start with the " +
607			"serialized block height"
608		str = fmt.Sprintf(str, serializedLen)
609		return 0, ruleError(ErrMissingCoinbaseHeight, str)
610	}
611
612	serializedHeightBytes := make([]byte, 8)
613	copy(serializedHeightBytes, sigScript[1:serializedLen+1])
614	serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes)
615
616	return int32(serializedHeight), nil
617}
618
619// checkSerializedHeight checks if the signature script in the passed
620// transaction starts with the serialized block height of wantHeight.
621func checkSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int32) error {
622	serializedHeight, err := ExtractCoinbaseHeight(coinbaseTx)
623	if err != nil {
624		return err
625	}
626
627	if serializedHeight != wantHeight {
628		str := fmt.Sprintf("the coinbase signature script serialized "+
629			"block height is %d when %d was expected",
630			serializedHeight, wantHeight)
631		return ruleError(ErrBadCoinbaseHeight, str)
632	}
633	return nil
634}
635
636// checkBlockHeaderContext performs several validation checks on the block header
637// which depend on its position within the block chain.
638//
639// The flags modify the behavior of this function as follows:
640//  - BFFastAdd: All checks except those involving comparing the header against
641//    the checkpoints are not performed.
642//
643// This function MUST be called with the chain state lock held (for writes).
644func (b *BlockChain) checkBlockHeaderContext(header *wire.BlockHeader, prevNode *blockNode, flags BehaviorFlags) error {
645	fastAdd := flags&BFFastAdd == BFFastAdd
646	if !fastAdd {
647		// Ensure the difficulty specified in the block header matches
648		// the calculated difficulty based on the previous block and
649		// difficulty retarget rules.
650		expectedDifficulty, err := b.calcNextRequiredDifficulty(prevNode,
651			header.Timestamp)
652		if err != nil {
653			return err
654		}
655		blockDifficulty := header.Bits
656		if blockDifficulty != expectedDifficulty {
657			str := "block difficulty of %d is not the expected value of %d"
658			str = fmt.Sprintf(str, blockDifficulty, expectedDifficulty)
659			return ruleError(ErrUnexpectedDifficulty, str)
660		}
661
662		// Ensure the timestamp for the block header is after the
663		// median time of the last several blocks (medianTimeBlocks).
664		medianTime := prevNode.CalcPastMedianTime()
665		if !header.Timestamp.After(medianTime) {
666			str := "block timestamp of %v is not after expected %v"
667			str = fmt.Sprintf(str, header.Timestamp, medianTime)
668			return ruleError(ErrTimeTooOld, str)
669		}
670	}
671
672	// The height of this block is one more than the referenced previous
673	// block.
674	blockHeight := prevNode.height + 1
675
676	// Ensure chain matches up to predetermined checkpoints.
677	blockHash := header.BlockHash()
678	if !b.verifyCheckpoint(blockHeight, &blockHash) {
679		str := fmt.Sprintf("block at height %d does not match "+
680			"checkpoint hash", blockHeight)
681		return ruleError(ErrBadCheckpoint, str)
682	}
683
684	// Find the previous checkpoint and prevent blocks which fork the main
685	// chain before it.  This prevents storage of new, otherwise valid,
686	// blocks which build off of old blocks that are likely at a much easier
687	// difficulty and therefore could be used to waste cache and disk space.
688	checkpointNode, err := b.findPreviousCheckpoint()
689	if err != nil {
690		return err
691	}
692	if checkpointNode != nil && blockHeight < checkpointNode.height {
693		str := fmt.Sprintf("block at height %d forks the main chain "+
694			"before the previous checkpoint at height %d",
695			blockHeight, checkpointNode.height)
696		return ruleError(ErrForkTooOld, str)
697	}
698
699	// Reject outdated block versions once a majority of the network
700	// has upgraded.  These were originally voted on by BIP0034,
701	// BIP0065, and BIP0066.
702	params := b.chainParams
703	if header.Version < 2 && blockHeight >= params.BIP0034Height ||
704		header.Version < 3 && blockHeight >= params.BIP0066Height ||
705		header.Version < 4 && blockHeight >= params.BIP0065Height {
706
707		str := "new blocks with version %d are no longer valid"
708		str = fmt.Sprintf(str, header.Version)
709		return ruleError(ErrBlockVersionTooOld, str)
710	}
711
712	return nil
713}
714
715// checkBlockContext peforms several validation checks on the block which depend
716// on its position within the block chain.
717//
718// The flags modify the behavior of this function as follows:
719//  - BFFastAdd: The transaction are not checked to see if they are finalized
720//    and the somewhat expensive BIP0034 validation is not performed.
721//
722// The flags are also passed to checkBlockHeaderContext.  See its documentation
723// for how the flags modify its behavior.
724//
725// This function MUST be called with the chain state lock held (for writes).
726func (b *BlockChain) checkBlockContext(block *btcutil.Block, prevNode *blockNode, flags BehaviorFlags) error {
727	// Perform all block header related validation checks.
728	header := &block.MsgBlock().Header
729	err := b.checkBlockHeaderContext(header, prevNode, flags)
730	if err != nil {
731		return err
732	}
733
734	fastAdd := flags&BFFastAdd == BFFastAdd
735	if !fastAdd {
736		// Obtain the latest state of the deployed CSV soft-fork in
737		// order to properly guard the new validation behavior based on
738		// the current BIP 9 version bits state.
739		csvState, err := b.deploymentState(prevNode, chaincfg.DeploymentCSV)
740		if err != nil {
741			return err
742		}
743
744		// Once the CSV soft-fork is fully active, we'll switch to
745		// using the current median time past of the past block's
746		// timestamps for all lock-time based checks.
747		blockTime := header.Timestamp
748		if csvState == ThresholdActive {
749			blockTime = prevNode.CalcPastMedianTime()
750		}
751
752		// The height of this block is one more than the referenced
753		// previous block.
754		blockHeight := prevNode.height + 1
755
756		// Ensure all transactions in the block are finalized.
757		for _, tx := range block.Transactions() {
758			if !IsFinalizedTransaction(tx, blockHeight,
759				blockTime) {
760
761				str := fmt.Sprintf("block contains unfinalized "+
762					"transaction %v", tx.Hash())
763				return ruleError(ErrUnfinalizedTx, str)
764			}
765		}
766
767		// Ensure coinbase starts with serialized block heights for
768		// blocks whose version is the serializedHeightVersion or newer
769		// once a majority of the network has upgraded.  This is part of
770		// BIP0034.
771		if ShouldHaveSerializedBlockHeight(header) &&
772			blockHeight >= b.chainParams.BIP0034Height {
773
774			coinbaseTx := block.Transactions()[0]
775			err := checkSerializedHeight(coinbaseTx, blockHeight)
776			if err != nil {
777				return err
778			}
779		}
780
781		// Query for the Version Bits state for the segwit soft-fork
782		// deployment. If segwit is active, we'll switch over to
783		// enforcing all the new rules.
784		segwitState, err := b.deploymentState(prevNode,
785			chaincfg.DeploymentSegwit)
786		if err != nil {
787			return err
788		}
789
790		// If segwit is active, then we'll need to fully validate the
791		// new witness commitment for adherence to the rules.
792		if segwitState == ThresholdActive {
793			// Validate the witness commitment (if any) within the
794			// block.  This involves asserting that if the coinbase
795			// contains the special commitment output, then this
796			// merkle root matches a computed merkle root of all
797			// the wtxid's of the transactions within the block. In
798			// addition, various other checks against the
799			// coinbase's witness stack.
800			if err := ValidateWitnessCommitment(block); err != nil {
801				return err
802			}
803
804			// Once the witness commitment, witness nonce, and sig
805			// op cost have been validated, we can finally assert
806			// that the block's weight doesn't exceed the current
807			// consensus parameter.
808			blockWeight := GetBlockWeight(block)
809			if blockWeight > MaxBlockWeight {
810				str := fmt.Sprintf("block's weight metric is "+
811					"too high - got %v, max %v",
812					blockWeight, MaxBlockWeight)
813				return ruleError(ErrBlockWeightTooHigh, str)
814			}
815		}
816	}
817
818	return nil
819}
820
821// checkBIP0030 ensures blocks do not contain duplicate transactions which
822// 'overwrite' older transactions that are not fully spent.  This prevents an
823// attack where a coinbase and all of its dependent transactions could be
824// duplicated to effectively revert the overwritten transactions to a single
825// confirmation thereby making them vulnerable to a double spend.
826//
827// For more details, see
828// https://github.com/bitcoin/bips/blob/master/bip-0030.mediawiki and
829// http://r6.ca/blog/20120206T005236Z.html.
830//
831// This function MUST be called with the chain state lock held (for reads).
832func (b *BlockChain) checkBIP0030(node *blockNode, block *btcutil.Block, view *UtxoViewpoint) error {
833	// Fetch utxos for all of the transaction ouputs in this block.
834	// Typically, there will not be any utxos for any of the outputs.
835	fetchSet := make(map[wire.OutPoint]struct{})
836	for _, tx := range block.Transactions() {
837		prevOut := wire.OutPoint{Hash: *tx.Hash()}
838		for txOutIdx := range tx.MsgTx().TxOut {
839			prevOut.Index = uint32(txOutIdx)
840			fetchSet[prevOut] = struct{}{}
841		}
842	}
843	err := view.fetchUtxos(b.db, fetchSet)
844	if err != nil {
845		return err
846	}
847
848	// Duplicate transactions are only allowed if the previous transaction
849	// is fully spent.
850	for outpoint := range fetchSet {
851		utxo := view.LookupEntry(outpoint)
852		if utxo != nil && !utxo.IsSpent() {
853			str := fmt.Sprintf("tried to overwrite transaction %v "+
854				"at block height %d that is not fully spent",
855				outpoint.Hash, utxo.BlockHeight())
856			return ruleError(ErrOverwriteTx, str)
857		}
858	}
859
860	return nil
861}
862
863// CheckTransactionInputs performs a series of checks on the inputs to a
864// transaction to ensure they are valid.  An example of some of the checks
865// include verifying all inputs exist, ensuring the coinbase seasoning
866// requirements are met, detecting double spends, validating all values and fees
867// are in the legal range and the total output amount doesn't exceed the input
868// amount, and verifying the signatures to prove the spender was the owner of
869// the bitcoins and therefore allowed to spend them.  As it checks the inputs,
870// it also calculates the total fees for the transaction and returns that value.
871//
872// NOTE: The transaction MUST have already been sanity checked with the
873// CheckTransactionSanity function prior to calling this function.
874func CheckTransactionInputs(tx *btcutil.Tx, txHeight int32, utxoView *UtxoViewpoint, chainParams *chaincfg.Params) (int64, error) {
875	// Coinbase transactions have no inputs.
876	if IsCoinBase(tx) {
877		return 0, nil
878	}
879
880	txHash := tx.Hash()
881	var totalSatoshiIn int64
882	for txInIndex, txIn := range tx.MsgTx().TxIn {
883		// Ensure the referenced input transaction is available.
884		utxo := utxoView.LookupEntry(txIn.PreviousOutPoint)
885		if utxo == nil || utxo.IsSpent() {
886			str := fmt.Sprintf("output %v referenced from "+
887				"transaction %s:%d either does not exist or "+
888				"has already been spent", txIn.PreviousOutPoint,
889				tx.Hash(), txInIndex)
890			return 0, ruleError(ErrMissingTxOut, str)
891		}
892
893		// Ensure the transaction is not spending coins which have not
894		// yet reached the required coinbase maturity.
895		if utxo.IsCoinBase() {
896			originHeight := utxo.BlockHeight()
897			blocksSincePrev := txHeight - originHeight
898			coinbaseMaturity := int32(chainParams.CoinbaseMaturity)
899			if blocksSincePrev < coinbaseMaturity {
900				str := fmt.Sprintf("tried to spend coinbase "+
901					"transaction output %v from height %v "+
902					"at height %v before required maturity "+
903					"of %v blocks", txIn.PreviousOutPoint,
904					originHeight, txHeight,
905					coinbaseMaturity)
906				return 0, ruleError(ErrImmatureSpend, str)
907			}
908		}
909
910		// Ensure the transaction amounts are in range.  Each of the
911		// output values of the input transactions must not be negative
912		// or more than the max allowed per transaction.  All amounts in
913		// a transaction are in a unit value known as a satoshi.  One
914		// bitcoin is a quantity of satoshi as defined by the
915		// SatoshiPerBitcoin constant.
916		originTxSatoshi := utxo.Amount()
917		if originTxSatoshi < 0 {
918			str := fmt.Sprintf("transaction output has negative "+
919				"value of %v", btcutil.Amount(originTxSatoshi))
920			return 0, ruleError(ErrBadTxOutValue, str)
921		}
922		if originTxSatoshi > btcutil.MaxSatoshi {
923			str := fmt.Sprintf("transaction output value of %v is "+
924				"higher than max allowed value of %v",
925				btcutil.Amount(originTxSatoshi),
926				btcutil.MaxSatoshi)
927			return 0, ruleError(ErrBadTxOutValue, str)
928		}
929
930		// The total of all outputs must not be more than the max
931		// allowed per transaction.  Also, we could potentially overflow
932		// the accumulator so check for overflow.
933		lastSatoshiIn := totalSatoshiIn
934		totalSatoshiIn += originTxSatoshi
935		if totalSatoshiIn < lastSatoshiIn ||
936			totalSatoshiIn > btcutil.MaxSatoshi {
937			str := fmt.Sprintf("total value of all transaction "+
938				"inputs is %v which is higher than max "+
939				"allowed value of %v", totalSatoshiIn,
940				btcutil.MaxSatoshi)
941			return 0, ruleError(ErrBadTxOutValue, str)
942		}
943	}
944
945	// Calculate the total output amount for this transaction.  It is safe
946	// to ignore overflow and out of range errors here because those error
947	// conditions would have already been caught by checkTransactionSanity.
948	var totalSatoshiOut int64
949	for _, txOut := range tx.MsgTx().TxOut {
950		totalSatoshiOut += txOut.Value
951	}
952
953	// Ensure the transaction does not spend more than its inputs.
954	if totalSatoshiIn < totalSatoshiOut {
955		str := fmt.Sprintf("total value of all transaction inputs for "+
956			"transaction %v is %v which is less than the amount "+
957			"spent of %v", txHash, totalSatoshiIn, totalSatoshiOut)
958		return 0, ruleError(ErrSpendTooHigh, str)
959	}
960
961	// NOTE: bitcoind checks if the transaction fees are < 0 here, but that
962	// is an impossible condition because of the check above that ensures
963	// the inputs are >= the outputs.
964	txFeeInSatoshi := totalSatoshiIn - totalSatoshiOut
965	return txFeeInSatoshi, nil
966}
967
968// checkConnectBlock performs several checks to confirm connecting the passed
969// block to the chain represented by the passed view does not violate any rules.
970// In addition, the passed view is updated to spend all of the referenced
971// outputs and add all of the new utxos created by block.  Thus, the view will
972// represent the state of the chain as if the block were actually connected and
973// consequently the best hash for the view is also updated to passed block.
974//
975// An example of some of the checks performed are ensuring connecting the block
976// would not cause any duplicate transaction hashes for old transactions that
977// aren't already fully spent, double spends, exceeding the maximum allowed
978// signature operations per block, invalid values in relation to the expected
979// block subsidy, or fail transaction script validation.
980//
981// The CheckConnectBlockTemplate function makes use of this function to perform
982// the bulk of its work.  The only difference is this function accepts a node
983// which may or may not require reorganization to connect it to the main chain
984// whereas CheckConnectBlockTemplate creates a new node which specifically
985// connects to the end of the current main chain and then calls this function
986// with that node.
987//
988// This function MUST be called with the chain state lock held (for writes).
989func (b *BlockChain) checkConnectBlock(node *blockNode, block *btcutil.Block, view *UtxoViewpoint, stxos *[]SpentTxOut) error {
990	// If the side chain blocks end up in the database, a call to
991	// CheckBlockSanity should be done here in case a previous version
992	// allowed a block that is no longer valid.  However, since the
993	// implementation only currently uses memory for the side chain blocks,
994	// it isn't currently necessary.
995
996	// The coinbase for the Genesis block is not spendable, so just return
997	// an error now.
998	if node.hash.IsEqual(b.chainParams.GenesisHash) {
999		str := "the coinbase for the genesis block is not spendable"
1000		return ruleError(ErrMissingTxOut, str)
1001	}
1002
1003	// Ensure the view is for the node being checked.
1004	parentHash := &block.MsgBlock().Header.PrevBlock
1005	if !view.BestHash().IsEqual(parentHash) {
1006		return AssertError(fmt.Sprintf("inconsistent view when "+
1007			"checking block connection: best hash is %v instead "+
1008			"of expected %v", view.BestHash(), parentHash))
1009	}
1010
1011	// BIP0030 added a rule to prevent blocks which contain duplicate
1012	// transactions that 'overwrite' older transactions which are not fully
1013	// spent.  See the documentation for checkBIP0030 for more details.
1014	//
1015	// There are two blocks in the chain which violate this rule, so the
1016	// check must be skipped for those blocks.  The isBIP0030Node function
1017	// is used to determine if this block is one of the two blocks that must
1018	// be skipped.
1019	//
1020	// In addition, as of BIP0034, duplicate coinbases are no longer
1021	// possible due to its requirement for including the block height in the
1022	// coinbase and thus it is no longer possible to create transactions
1023	// that 'overwrite' older ones.  Therefore, only enforce the rule if
1024	// BIP0034 is not yet active.  This is a useful optimization because the
1025	// BIP0030 check is expensive since it involves a ton of cache misses in
1026	// the utxoset.
1027	if !isBIP0030Node(node) && (node.height < b.chainParams.BIP0034Height) {
1028		err := b.checkBIP0030(node, block, view)
1029		if err != nil {
1030			return err
1031		}
1032	}
1033
1034	// Load all of the utxos referenced by the inputs for all transactions
1035	// in the block don't already exist in the utxo view from the database.
1036	//
1037	// These utxo entries are needed for verification of things such as
1038	// transaction inputs, counting pay-to-script-hashes, and scripts.
1039	err := view.fetchInputUtxos(b.db, block)
1040	if err != nil {
1041		return err
1042	}
1043
1044	// BIP0016 describes a pay-to-script-hash type that is considered a
1045	// "standard" type.  The rules for this BIP only apply to transactions
1046	// after the timestamp defined by txscript.Bip16Activation.  See
1047	// https://en.bitcoin.it/wiki/BIP_0016 for more details.
1048	enforceBIP0016 := node.timestamp >= txscript.Bip16Activation.Unix()
1049
1050	// Query for the Version Bits state for the segwit soft-fork
1051	// deployment. If segwit is active, we'll switch over to enforcing all
1052	// the new rules.
1053	segwitState, err := b.deploymentState(node.parent, chaincfg.DeploymentSegwit)
1054	if err != nil {
1055		return err
1056	}
1057	enforceSegWit := segwitState == ThresholdActive
1058
1059	// The number of signature operations must be less than the maximum
1060	// allowed per block.  Note that the preliminary sanity checks on a
1061	// block also include a check similar to this one, but this check
1062	// expands the count to include a precise count of pay-to-script-hash
1063	// signature operations in each of the input transaction public key
1064	// scripts.
1065	transactions := block.Transactions()
1066	totalSigOpCost := 0
1067	for i, tx := range transactions {
1068		// Since the first (and only the first) transaction has
1069		// already been verified to be a coinbase transaction,
1070		// use i == 0 as an optimization for the flag to
1071		// countP2SHSigOps for whether or not the transaction is
1072		// a coinbase transaction rather than having to do a
1073		// full coinbase check again.
1074		sigOpCost, err := GetSigOpCost(tx, i == 0, view, enforceBIP0016,
1075			enforceSegWit)
1076		if err != nil {
1077			return err
1078		}
1079
1080		// Check for overflow or going over the limits.  We have to do
1081		// this on every loop iteration to avoid overflow.
1082		lastSigOpCost := totalSigOpCost
1083		totalSigOpCost += sigOpCost
1084		if totalSigOpCost < lastSigOpCost || totalSigOpCost > MaxBlockSigOpsCost {
1085			str := fmt.Sprintf("block contains too many "+
1086				"signature operations - got %v, max %v",
1087				totalSigOpCost, MaxBlockSigOpsCost)
1088			return ruleError(ErrTooManySigOps, str)
1089		}
1090	}
1091
1092	// Perform several checks on the inputs for each transaction.  Also
1093	// accumulate the total fees.  This could technically be combined with
1094	// the loop above instead of running another loop over the transactions,
1095	// but by separating it we can avoid running the more expensive (though
1096	// still relatively cheap as compared to running the scripts) checks
1097	// against all the inputs when the signature operations are out of
1098	// bounds.
1099	var totalFees int64
1100	for _, tx := range transactions {
1101		txFee, err := CheckTransactionInputs(tx, node.height, view,
1102			b.chainParams)
1103		if err != nil {
1104			return err
1105		}
1106
1107		// Sum the total fees and ensure we don't overflow the
1108		// accumulator.
1109		lastTotalFees := totalFees
1110		totalFees += txFee
1111		if totalFees < lastTotalFees {
1112			return ruleError(ErrBadFees, "total fees for block "+
1113				"overflows accumulator")
1114		}
1115
1116		// Add all of the outputs for this transaction which are not
1117		// provably unspendable as available utxos.  Also, the passed
1118		// spent txos slice is updated to contain an entry for each
1119		// spent txout in the order each transaction spends them.
1120		err = view.connectTransaction(tx, node.height, stxos)
1121		if err != nil {
1122			return err
1123		}
1124	}
1125
1126	// The total output values of the coinbase transaction must not exceed
1127	// the expected subsidy value plus total transaction fees gained from
1128	// mining the block.  It is safe to ignore overflow and out of range
1129	// errors here because those error conditions would have already been
1130	// caught by checkTransactionSanity.
1131	var totalSatoshiOut int64
1132	for _, txOut := range transactions[0].MsgTx().TxOut {
1133		totalSatoshiOut += txOut.Value
1134	}
1135	expectedSatoshiOut := CalcBlockSubsidy(node.height, b.chainParams) +
1136		totalFees
1137	if totalSatoshiOut > expectedSatoshiOut {
1138		str := fmt.Sprintf("coinbase transaction for block pays %v "+
1139			"which is more than expected value of %v",
1140			totalSatoshiOut, expectedSatoshiOut)
1141		return ruleError(ErrBadCoinbaseValue, str)
1142	}
1143
1144	// Don't run scripts if this node is before the latest known good
1145	// checkpoint since the validity is verified via the checkpoints (all
1146	// transactions are included in the merkle root hash and any changes
1147	// will therefore be detected by the next checkpoint).  This is a huge
1148	// optimization because running the scripts is the most time consuming
1149	// portion of block handling.
1150	checkpoint := b.LatestCheckpoint()
1151	runScripts := true
1152	if checkpoint != nil && node.height <= checkpoint.Height {
1153		runScripts = false
1154	}
1155
1156	// Blocks created after the BIP0016 activation time need to have the
1157	// pay-to-script-hash checks enabled.
1158	var scriptFlags txscript.ScriptFlags
1159	if enforceBIP0016 {
1160		scriptFlags |= txscript.ScriptBip16
1161	}
1162
1163	// Enforce DER signatures for block versions 3+ once the historical
1164	// activation threshold has been reached.  This is part of BIP0066.
1165	blockHeader := &block.MsgBlock().Header
1166	if blockHeader.Version >= 3 && node.height >= b.chainParams.BIP0066Height {
1167		scriptFlags |= txscript.ScriptVerifyDERSignatures
1168	}
1169
1170	// Enforce CHECKLOCKTIMEVERIFY for block versions 4+ once the historical
1171	// activation threshold has been reached.  This is part of BIP0065.
1172	if blockHeader.Version >= 4 && node.height >= b.chainParams.BIP0065Height {
1173		scriptFlags |= txscript.ScriptVerifyCheckLockTimeVerify
1174	}
1175
1176	// Enforce CHECKSEQUENCEVERIFY during all block validation checks once
1177	// the soft-fork deployment is fully active.
1178	csvState, err := b.deploymentState(node.parent, chaincfg.DeploymentCSV)
1179	if err != nil {
1180		return err
1181	}
1182	if csvState == ThresholdActive {
1183		// If the CSV soft-fork is now active, then modify the
1184		// scriptFlags to ensure that the CSV op code is properly
1185		// validated during the script checks bleow.
1186		scriptFlags |= txscript.ScriptVerifyCheckSequenceVerify
1187
1188		// We obtain the MTP of the *previous* block in order to
1189		// determine if transactions in the current block are final.
1190		medianTime := node.parent.CalcPastMedianTime()
1191
1192		// Additionally, if the CSV soft-fork package is now active,
1193		// then we also enforce the relative sequence number based
1194		// lock-times within the inputs of all transactions in this
1195		// candidate block.
1196		for _, tx := range block.Transactions() {
1197			// A transaction can only be included within a block
1198			// once the sequence locks of *all* its inputs are
1199			// active.
1200			sequenceLock, err := b.calcSequenceLock(node, tx, view,
1201				false)
1202			if err != nil {
1203				return err
1204			}
1205			if !SequenceLockActive(sequenceLock, node.height,
1206				medianTime) {
1207				str := fmt.Sprintf("block contains " +
1208					"transaction whose input sequence " +
1209					"locks are not met")
1210				return ruleError(ErrUnfinalizedTx, str)
1211			}
1212		}
1213	}
1214
1215	// Enforce the segwit soft-fork package once the soft-fork has shifted
1216	// into the "active" version bits state.
1217	if enforceSegWit {
1218		scriptFlags |= txscript.ScriptVerifyWitness
1219		scriptFlags |= txscript.ScriptStrictMultiSig
1220	}
1221
1222	// Now that the inexpensive checks are done and have passed, verify the
1223	// transactions are actually allowed to spend the coins by running the
1224	// expensive ECDSA signature check scripts.  Doing this last helps
1225	// prevent CPU exhaustion attacks.
1226	if runScripts {
1227		err := checkBlockScripts(block, view, scriptFlags, b.sigCache,
1228			b.hashCache)
1229		if err != nil {
1230			return err
1231		}
1232	}
1233
1234	// Update the best hash for view to include this block since all of its
1235	// transactions have been connected.
1236	view.SetBestHash(&node.hash)
1237
1238	return nil
1239}
1240
1241// CheckConnectBlockTemplate fully validates that connecting the passed block to
1242// the main chain does not violate any consensus rules, aside from the proof of
1243// work requirement. The block must connect to the current tip of the main chain.
1244//
1245// This function is safe for concurrent access.
1246func (b *BlockChain) CheckConnectBlockTemplate(block *btcutil.Block) error {
1247	b.chainLock.Lock()
1248	defer b.chainLock.Unlock()
1249
1250	// Skip the proof of work check as this is just a block template.
1251	flags := BFNoPoWCheck
1252
1253	// This only checks whether the block can be connected to the tip of the
1254	// current chain.
1255	tip := b.bestChain.Tip()
1256	header := block.MsgBlock().Header
1257	if tip.hash != header.PrevBlock {
1258		str := fmt.Sprintf("previous block must be the current chain tip %v, "+
1259			"instead got %v", tip.hash, header.PrevBlock)
1260		return ruleError(ErrPrevBlockNotBest, str)
1261	}
1262
1263	err := checkBlockSanity(block, b.chainParams.PowLimit, b.timeSource, flags)
1264	if err != nil {
1265		return err
1266	}
1267
1268	err = b.checkBlockContext(block, tip, flags)
1269	if err != nil {
1270		return err
1271	}
1272
1273	// Leave the spent txouts entry nil in the state since the information
1274	// is not needed and thus extra work can be avoided.
1275	view := NewUtxoViewpoint()
1276	view.SetBestHash(&tip.hash)
1277	newNode := newBlockNode(&header, tip)
1278	return b.checkConnectBlock(newNode, block, view, nil)
1279}
1280