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