github.com/palcoin-project/palcd@v1.0.0/blockchain/validate.go (about)

     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  
     5  package blockchain
     6  
     7  import (
     8  	"encoding/binary"
     9  	"fmt"
    10  	"math"
    11  	"math/big"
    12  	"time"
    13  
    14  	"github.com/palcoin-project/palcd/chaincfg"
    15  	"github.com/palcoin-project/palcd/chaincfg/chainhash"
    16  	"github.com/palcoin-project/palcd/txscript"
    17  	"github.com/palcoin-project/palcd/wire"
    18  	"github.com/palcoin-project/palcutil"
    19  )
    20  
    21  const (
    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 = 10 * palcutil.SatoshiPerBitcoin // Base subsidy PALC
    44  )
    45  
    46  var (
    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.
    65  func 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.
    77  func 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.
    89  func 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.
   113  func IsCoinBase(tx *palcutil.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.
   120  func 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.
   135  func IsFinalizedTransaction(tx *palcutil.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.
   172  func 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.
   194  func 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.
   205  func CheckTransactionSanity(tx *palcutil.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 > palcutil.MaxSatoshi {
   241  			str := fmt.Sprintf("transaction output value of %v is "+
   242  				"higher than max allowed value of %v", satoshi,
   243  				palcutil.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  				palcutil.MaxSatoshi)
   255  			return ruleError(ErrBadTxOutValue, str)
   256  		}
   257  		if totalSatoshi > palcutil.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  				palcutil.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.
   307  func 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.
   342  func CheckProofOfWork(block *palcutil.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.
   350  func CountSigOps(tx *palcutil.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.
   375  func CountP2SHSigOps(tx *palcutil.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.
   430  func 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.
   467  func checkBlockSanity(block *palcutil.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.
   574  func CheckBlockSanity(block *palcutil.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.
   581  func ExtractCoinbaseHeight(coinbaseTx *palcutil.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.
   621  func checkSerializedHeight(coinbaseTx *palcutil.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).
   644  func (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).
   726  func (b *BlockChain) checkBlockContext(block *palcutil.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).
   832  func (b *BlockChain) checkBIP0030(node *blockNode, block *palcutil.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.
   874  func CheckTransactionInputs(tx *palcutil.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  	var totalSatoshiIn int64
   881  	for txInIndex, txIn := range tx.MsgTx().TxIn {
   882  		// Ensure the referenced input transaction is available.
   883  		utxo := utxoView.LookupEntry(txIn.PreviousOutPoint)
   884  		if utxo == nil || utxo.IsSpent() {
   885  			str := fmt.Sprintf("output %v referenced from "+
   886  				"transaction %s:%d either does not exist or "+
   887  				"has already been spent", txIn.PreviousOutPoint,
   888  				tx.Hash(), txInIndex)
   889  			return 0, ruleError(ErrMissingTxOut, str)
   890  		}
   891  
   892  		// Ensure the transaction is not spending coins which have not
   893  		// yet reached the required coinbase maturity.
   894  		if utxo.IsCoinBase() {
   895  			originHeight := utxo.BlockHeight()
   896  			blocksSincePrev := txHeight - originHeight
   897  			coinbaseMaturity := int32(chainParams.CoinbaseMaturity)
   898  			if blocksSincePrev < coinbaseMaturity {
   899  				str := fmt.Sprintf("tried to spend coinbase "+
   900  					"transaction output %v from height %v "+
   901  					"at height %v before required maturity "+
   902  					"of %v blocks", txIn.PreviousOutPoint,
   903  					originHeight, txHeight,
   904  					coinbaseMaturity)
   905  				return 0, ruleError(ErrImmatureSpend, str)
   906  			}
   907  		}
   908  
   909  		// Ensure the transaction amounts are in range.  Each of the
   910  		// output values of the input transactions must not be negative
   911  		// or more than the max allowed per transaction.  All amounts in
   912  		// a transaction are in a unit value known as a satoshi.  One
   913  		// bitcoin is a quantity of satoshi as defined by the
   914  		// SatoshiPerBitcoin constant.
   915  		originTxSatoshi := utxo.Amount()
   916  		if originTxSatoshi < 0 {
   917  			str := fmt.Sprintf("transaction output has negative "+
   918  				"value of %v", palcutil.Amount(originTxSatoshi))
   919  			return 0, ruleError(ErrBadTxOutValue, str)
   920  		}
   921  		if originTxSatoshi > palcutil.MaxSatoshi {
   922  			str := fmt.Sprintf("transaction output value of %v is "+
   923  				"higher than max allowed value of %v",
   924  				palcutil.Amount(originTxSatoshi),
   925  				palcutil.MaxSatoshi)
   926  			return 0, ruleError(ErrBadTxOutValue, str)
   927  		}
   928  
   929  		// The total of all outputs must not be more than the max
   930  		// allowed per transaction.  Also, we could potentially overflow
   931  		// the accumulator so check for overflow.
   932  		lastSatoshiIn := totalSatoshiIn
   933  		totalSatoshiIn += originTxSatoshi
   934  		if totalSatoshiIn < lastSatoshiIn ||
   935  			totalSatoshiIn > palcutil.MaxSatoshi {
   936  			str := fmt.Sprintf("total value of all transaction "+
   937  				"inputs is %v which is higher than max "+
   938  				"allowed value of %v", totalSatoshiIn,
   939  				palcutil.MaxSatoshi)
   940  			return 0, ruleError(ErrBadTxOutValue, str)
   941  		}
   942  	}
   943  
   944  	// Calculate the total output amount for this transaction.  It is safe
   945  	// to ignore overflow and out of range errors here because those error
   946  	// conditions would have already been caught by checkTransactionSanity.
   947  	var totalSatoshiOut int64
   948  	for _, txOut := range tx.MsgTx().TxOut {
   949  		totalSatoshiOut += txOut.Value
   950  	}
   951  
   952  	// Ensure the transaction does not spend more than its inputs.
   953  	if totalSatoshiIn < totalSatoshiOut {
   954  		str := fmt.Sprintf("total value of all transaction inputs for "+
   955  			"transaction %v is %v which is less than the amount "+
   956  			"spent of %v", tx.Hash(), totalSatoshiIn, totalSatoshiOut)
   957  		return 0, ruleError(ErrSpendTooHigh, str)
   958  	}
   959  
   960  	// NOTE: bitcoind checks if the transaction fees are < 0 here, but that
   961  	// is an impossible condition because of the check above that ensures
   962  	// the inputs are >= the outputs.
   963  	txFeeInSatoshi := totalSatoshiIn - totalSatoshiOut
   964  	return txFeeInSatoshi, nil
   965  }
   966  
   967  // checkConnectBlock performs several checks to confirm connecting the passed
   968  // block to the chain represented by the passed view does not violate any rules.
   969  // In addition, the passed view is updated to spend all of the referenced
   970  // outputs and add all of the new utxos created by block.  Thus, the view will
   971  // represent the state of the chain as if the block were actually connected and
   972  // consequently the best hash for the view is also updated to passed block.
   973  //
   974  // An example of some of the checks performed are ensuring connecting the block
   975  // would not cause any duplicate transaction hashes for old transactions that
   976  // aren't already fully spent, double spends, exceeding the maximum allowed
   977  // signature operations per block, invalid values in relation to the expected
   978  // block subsidy, or fail transaction script validation.
   979  //
   980  // The CheckConnectBlockTemplate function makes use of this function to perform
   981  // the bulk of its work.  The only difference is this function accepts a node
   982  // which may or may not require reorganization to connect it to the main chain
   983  // whereas CheckConnectBlockTemplate creates a new node which specifically
   984  // connects to the end of the current main chain and then calls this function
   985  // with that node.
   986  //
   987  // This function MUST be called with the chain state lock held (for writes).
   988  func (b *BlockChain) checkConnectBlock(node *blockNode, block *palcutil.Block, view *UtxoViewpoint, stxos *[]SpentTxOut) error {
   989  	// If the side chain blocks end up in the database, a call to
   990  	// CheckBlockSanity should be done here in case a previous version
   991  	// allowed a block that is no longer valid.  However, since the
   992  	// implementation only currently uses memory for the side chain blocks,
   993  	// it isn't currently necessary.
   994  
   995  	// The coinbase for the Genesis block is not spendable, so just return
   996  	// an error now.
   997  	if node.hash.IsEqual(b.chainParams.GenesisHash) {
   998  		str := "the coinbase for the genesis block is not spendable"
   999  		return ruleError(ErrMissingTxOut, str)
  1000  	}
  1001  
  1002  	// Ensure the view is for the node being checked.
  1003  	parentHash := &block.MsgBlock().Header.PrevBlock
  1004  	if !view.BestHash().IsEqual(parentHash) {
  1005  		return AssertError(fmt.Sprintf("inconsistent view when "+
  1006  			"checking block connection: best hash is %v instead "+
  1007  			"of expected %v", view.BestHash(), parentHash))
  1008  	}
  1009  
  1010  	// BIP0030 added a rule to prevent blocks which contain duplicate
  1011  	// transactions that 'overwrite' older transactions which are not fully
  1012  	// spent.  See the documentation for checkBIP0030 for more details.
  1013  	//
  1014  	// There are two blocks in the chain which violate this rule, so the
  1015  	// check must be skipped for those blocks.  The isBIP0030Node function
  1016  	// is used to determine if this block is one of the two blocks that must
  1017  	// be skipped.
  1018  	//
  1019  	// In addition, as of BIP0034, duplicate coinbases are no longer
  1020  	// possible due to its requirement for including the block height in the
  1021  	// coinbase and thus it is no longer possible to create transactions
  1022  	// that 'overwrite' older ones.  Therefore, only enforce the rule if
  1023  	// BIP0034 is not yet active.  This is a useful optimization because the
  1024  	// BIP0030 check is expensive since it involves a ton of cache misses in
  1025  	// the utxoset.
  1026  	if !isBIP0030Node(node) && (node.height < b.chainParams.BIP0034Height) {
  1027  		err := b.checkBIP0030(node, block, view)
  1028  		if err != nil {
  1029  			return err
  1030  		}
  1031  	}
  1032  
  1033  	// Load all of the utxos referenced by the inputs for all transactions
  1034  	// in the block don't already exist in the utxo view from the database.
  1035  	//
  1036  	// These utxo entries are needed for verification of things such as
  1037  	// transaction inputs, counting pay-to-script-hashes, and scripts.
  1038  	err := view.fetchInputUtxos(b.db, block)
  1039  	if err != nil {
  1040  		return err
  1041  	}
  1042  
  1043  	// BIP0016 describes a pay-to-script-hash type that is considered a
  1044  	// "standard" type.  The rules for this BIP only apply to transactions
  1045  	// after the timestamp defined by txscript.Bip16Activation.  See
  1046  	// https://en.bitcoin.it/wiki/BIP_0016 for more details.
  1047  	enforceBIP0016 := node.timestamp >= txscript.Bip16Activation.Unix()
  1048  
  1049  	// Query for the Version Bits state for the segwit soft-fork
  1050  	// deployment. If segwit is active, we'll switch over to enforcing all
  1051  	// the new rules.
  1052  	segwitState, err := b.deploymentState(node.parent, chaincfg.DeploymentSegwit)
  1053  	if err != nil {
  1054  		return err
  1055  	}
  1056  	enforceSegWit := segwitState == ThresholdActive
  1057  
  1058  	// The number of signature operations must be less than the maximum
  1059  	// allowed per block.  Note that the preliminary sanity checks on a
  1060  	// block also include a check similar to this one, but this check
  1061  	// expands the count to include a precise count of pay-to-script-hash
  1062  	// signature operations in each of the input transaction public key
  1063  	// scripts.
  1064  	transactions := block.Transactions()
  1065  	totalSigOpCost := 0
  1066  	for i, tx := range transactions {
  1067  		// Since the first (and only the first) transaction has
  1068  		// already been verified to be a coinbase transaction,
  1069  		// use i == 0 as an optimization for the flag to
  1070  		// countP2SHSigOps for whether or not the transaction is
  1071  		// a coinbase transaction rather than having to do a
  1072  		// full coinbase check again.
  1073  		sigOpCost, err := GetSigOpCost(tx, i == 0, view, enforceBIP0016,
  1074  			enforceSegWit)
  1075  		if err != nil {
  1076  			return err
  1077  		}
  1078  
  1079  		// Check for overflow or going over the limits.  We have to do
  1080  		// this on every loop iteration to avoid overflow.
  1081  		lastSigOpCost := totalSigOpCost
  1082  		totalSigOpCost += sigOpCost
  1083  		if totalSigOpCost < lastSigOpCost || totalSigOpCost > MaxBlockSigOpsCost {
  1084  			str := fmt.Sprintf("block contains too many "+
  1085  				"signature operations - got %v, max %v",
  1086  				totalSigOpCost, MaxBlockSigOpsCost)
  1087  			return ruleError(ErrTooManySigOps, str)
  1088  		}
  1089  	}
  1090  
  1091  	// Perform several checks on the inputs for each transaction.  Also
  1092  	// accumulate the total fees.  This could technically be combined with
  1093  	// the loop above instead of running another loop over the transactions,
  1094  	// but by separating it we can avoid running the more expensive (though
  1095  	// still relatively cheap as compared to running the scripts) checks
  1096  	// against all the inputs when the signature operations are out of
  1097  	// bounds.
  1098  	var totalFees int64
  1099  	for _, tx := range transactions {
  1100  		txFee, err := CheckTransactionInputs(tx, node.height, view,
  1101  			b.chainParams)
  1102  		if err != nil {
  1103  			return err
  1104  		}
  1105  
  1106  		// Sum the total fees and ensure we don't overflow the
  1107  		// accumulator.
  1108  		lastTotalFees := totalFees
  1109  		totalFees += txFee
  1110  		if totalFees < lastTotalFees {
  1111  			return ruleError(ErrBadFees, "total fees for block "+
  1112  				"overflows accumulator")
  1113  		}
  1114  
  1115  		// Add all of the outputs for this transaction which are not
  1116  		// provably unspendable as available utxos.  Also, the passed
  1117  		// spent txos slice is updated to contain an entry for each
  1118  		// spent txout in the order each transaction spends them.
  1119  		err = view.connectTransaction(tx, node.height, stxos)
  1120  		if err != nil {
  1121  			return err
  1122  		}
  1123  	}
  1124  
  1125  	// The total output values of the coinbase transaction must not exceed
  1126  	// the expected subsidy value plus total transaction fees gained from
  1127  	// mining the block.  It is safe to ignore overflow and out of range
  1128  	// errors here because those error conditions would have already been
  1129  	// caught by checkTransactionSanity.
  1130  	var totalSatoshiOut int64
  1131  	for _, txOut := range transactions[0].MsgTx().TxOut {
  1132  		totalSatoshiOut += txOut.Value
  1133  	}
  1134  	expectedSatoshiOut := CalcBlockSubsidy(node.height, b.chainParams) +
  1135  		totalFees
  1136  	if totalSatoshiOut > expectedSatoshiOut {
  1137  		str := fmt.Sprintf("coinbase transaction for block pays %v "+
  1138  			"which is more than expected value of %v",
  1139  			totalSatoshiOut, expectedSatoshiOut)
  1140  		return ruleError(ErrBadCoinbaseValue, str)
  1141  	}
  1142  
  1143  	// Don't run scripts if this node is before the latest known good
  1144  	// checkpoint since the validity is verified via the checkpoints (all
  1145  	// transactions are included in the merkle root hash and any changes
  1146  	// will therefore be detected by the next checkpoint).  This is a huge
  1147  	// optimization because running the scripts is the most time consuming
  1148  	// portion of block handling.
  1149  	checkpoint := b.LatestCheckpoint()
  1150  	runScripts := true
  1151  	if checkpoint != nil && node.height <= checkpoint.Height {
  1152  		runScripts = false
  1153  	}
  1154  
  1155  	// Blocks created after the BIP0016 activation time need to have the
  1156  	// pay-to-script-hash checks enabled.
  1157  	var scriptFlags txscript.ScriptFlags
  1158  	if enforceBIP0016 {
  1159  		scriptFlags |= txscript.ScriptBip16
  1160  	}
  1161  
  1162  	// Enforce DER signatures for block versions 3+ once the historical
  1163  	// activation threshold has been reached.  This is part of BIP0066.
  1164  	blockHeader := &block.MsgBlock().Header
  1165  	if blockHeader.Version >= 3 && node.height >= b.chainParams.BIP0066Height {
  1166  		scriptFlags |= txscript.ScriptVerifyDERSignatures
  1167  	}
  1168  
  1169  	// Enforce CHECKLOCKTIMEVERIFY for block versions 4+ once the historical
  1170  	// activation threshold has been reached.  This is part of BIP0065.
  1171  	if blockHeader.Version >= 4 && node.height >= b.chainParams.BIP0065Height {
  1172  		scriptFlags |= txscript.ScriptVerifyCheckLockTimeVerify
  1173  	}
  1174  
  1175  	// Enforce CHECKSEQUENCEVERIFY during all block validation checks once
  1176  	// the soft-fork deployment is fully active.
  1177  	csvState, err := b.deploymentState(node.parent, chaincfg.DeploymentCSV)
  1178  	if err != nil {
  1179  		return err
  1180  	}
  1181  	if csvState == ThresholdActive {
  1182  		// If the CSV soft-fork is now active, then modify the
  1183  		// scriptFlags to ensure that the CSV op code is properly
  1184  		// validated during the script checks bleow.
  1185  		scriptFlags |= txscript.ScriptVerifyCheckSequenceVerify
  1186  
  1187  		// We obtain the MTP of the *previous* block in order to
  1188  		// determine if transactions in the current block are final.
  1189  		medianTime := node.parent.CalcPastMedianTime()
  1190  
  1191  		// Additionally, if the CSV soft-fork package is now active,
  1192  		// then we also enforce the relative sequence number based
  1193  		// lock-times within the inputs of all transactions in this
  1194  		// candidate block.
  1195  		for _, tx := range block.Transactions() {
  1196  			// A transaction can only be included within a block
  1197  			// once the sequence locks of *all* its inputs are
  1198  			// active.
  1199  			sequenceLock, err := b.calcSequenceLock(node, tx, view,
  1200  				false)
  1201  			if err != nil {
  1202  				return err
  1203  			}
  1204  			if !SequenceLockActive(sequenceLock, node.height,
  1205  				medianTime) {
  1206  				str := fmt.Sprintf("block contains " +
  1207  					"transaction whose input sequence " +
  1208  					"locks are not met")
  1209  				return ruleError(ErrUnfinalizedTx, str)
  1210  			}
  1211  		}
  1212  	}
  1213  
  1214  	// Enforce the segwit soft-fork package once the soft-fork has shifted
  1215  	// into the "active" version bits state.
  1216  	if enforceSegWit {
  1217  		scriptFlags |= txscript.ScriptVerifyWitness
  1218  		scriptFlags |= txscript.ScriptStrictMultiSig
  1219  	}
  1220  
  1221  	// Now that the inexpensive checks are done and have passed, verify the
  1222  	// transactions are actually allowed to spend the coins by running the
  1223  	// expensive ECDSA signature check scripts.  Doing this last helps
  1224  	// prevent CPU exhaustion attacks.
  1225  	if runScripts {
  1226  		err := checkBlockScripts(block, view, scriptFlags, b.sigCache,
  1227  			b.hashCache)
  1228  		if err != nil {
  1229  			return err
  1230  		}
  1231  	}
  1232  
  1233  	// Update the best hash for view to include this block since all of its
  1234  	// transactions have been connected.
  1235  	view.SetBestHash(&node.hash)
  1236  
  1237  	return nil
  1238  }
  1239  
  1240  // CheckConnectBlockTemplate fully validates that connecting the passed block to
  1241  // the main chain does not violate any consensus rules, aside from the proof of
  1242  // work requirement. The block must connect to the current tip of the main chain.
  1243  //
  1244  // This function is safe for concurrent access.
  1245  func (b *BlockChain) CheckConnectBlockTemplate(block *palcutil.Block) error {
  1246  	b.chainLock.Lock()
  1247  	defer b.chainLock.Unlock()
  1248  
  1249  	// Skip the proof of work check as this is just a block template.
  1250  	flags := BFNoPoWCheck
  1251  
  1252  	// This only checks whether the block can be connected to the tip of the
  1253  	// current chain.
  1254  	tip := b.bestChain.Tip()
  1255  	header := block.MsgBlock().Header
  1256  	if tip.hash != header.PrevBlock {
  1257  		str := fmt.Sprintf("previous block must be the current chain tip %v, "+
  1258  			"instead got %v", tip.hash, header.PrevBlock)
  1259  		return ruleError(ErrPrevBlockNotBest, str)
  1260  	}
  1261  
  1262  	err := checkBlockSanity(block, b.chainParams.PowLimit, b.timeSource, flags)
  1263  	if err != nil {
  1264  		return err
  1265  	}
  1266  
  1267  	err = b.checkBlockContext(block, tip, flags)
  1268  	if err != nil {
  1269  		return err
  1270  	}
  1271  
  1272  	// Leave the spent txouts entry nil in the state since the information
  1273  	// is not needed and thus extra work can be avoided.
  1274  	view := NewUtxoViewpoint()
  1275  	view.SetBestHash(&tip.hash)
  1276  	newNode := newBlockNode(&header, tip)
  1277  	return b.checkConnectBlock(newNode, block, view, nil)
  1278  }