validate.go raw

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