github.com/palcoin-project/palcd@v1.0.0/mining/mining.go (about) 1 // Copyright (c) 2014-2016 The btcsuite developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package mining 6 7 import ( 8 "bytes" 9 "container/heap" 10 "fmt" 11 "time" 12 13 "github.com/palcoin-project/palcd/blockchain" 14 "github.com/palcoin-project/palcd/chaincfg" 15 "github.com/palcoin-project/palcd/chaincfg/chainhash" 16 "github.com/palcoin-project/palcd/txscript" 17 "github.com/palcoin-project/palcd/wire" 18 "github.com/palcoin-project/palcutil" 19 ) 20 21 const ( 22 // MinHighPriority is the minimum priority value that allows a 23 // transaction to be considered high priority. 24 MinHighPriority = palcutil.SatoshiPerBitcoin * 144.0 / 250 25 26 // blockHeaderOverhead is the max number of bytes it takes to serialize 27 // a block header and max possible transaction count. 28 blockHeaderOverhead = wire.MaxBlockHeaderPayload + wire.MaxVarIntPayload 29 30 // CoinbaseFlags is added to the coinbase script of a generated block 31 // and is used to monitor BIP16 support as well as blocks that are 32 // generated via palcd. 33 CoinbaseFlags = "/P2SH/palcd/" 34 ) 35 36 // TxDesc is a descriptor about a transaction in a transaction source along with 37 // additional metadata. 38 type TxDesc struct { 39 // Tx is the transaction associated with the entry. 40 Tx *palcutil.Tx 41 42 // Added is the time when the entry was added to the source pool. 43 Added time.Time 44 45 // Height is the block height when the entry was added to the the source 46 // pool. 47 Height int32 48 49 // Fee is the total fee the transaction associated with the entry pays. 50 Fee int64 51 52 // FeePerKB is the fee the transaction pays in Satoshi per 1000 bytes. 53 FeePerKB int64 54 } 55 56 // TxSource represents a source of transactions to consider for inclusion in 57 // new blocks. 58 // 59 // The interface contract requires that all of these methods are safe for 60 // concurrent access with respect to the source. 61 type TxSource interface { 62 // LastUpdated returns the last time a transaction was added to or 63 // removed from the source pool. 64 LastUpdated() time.Time 65 66 // MiningDescs returns a slice of mining descriptors for all the 67 // transactions in the source pool. 68 MiningDescs() []*TxDesc 69 70 // HaveTransaction returns whether or not the passed transaction hash 71 // exists in the source pool. 72 HaveTransaction(hash *chainhash.Hash) bool 73 } 74 75 // txPrioItem houses a transaction along with extra information that allows the 76 // transaction to be prioritized and track dependencies on other transactions 77 // which have not been mined into a block yet. 78 type txPrioItem struct { 79 tx *palcutil.Tx 80 fee int64 81 priority float64 82 feePerKB int64 83 84 // dependsOn holds a map of transaction hashes which this one depends 85 // on. It will only be set when the transaction references other 86 // transactions in the source pool and hence must come after them in 87 // a block. 88 dependsOn map[chainhash.Hash]struct{} 89 } 90 91 // txPriorityQueueLessFunc describes a function that can be used as a compare 92 // function for a transaction priority queue (txPriorityQueue). 93 type txPriorityQueueLessFunc func(*txPriorityQueue, int, int) bool 94 95 // txPriorityQueue implements a priority queue of txPrioItem elements that 96 // supports an arbitrary compare function as defined by txPriorityQueueLessFunc. 97 type txPriorityQueue struct { 98 lessFunc txPriorityQueueLessFunc 99 items []*txPrioItem 100 } 101 102 // Len returns the number of items in the priority queue. It is part of the 103 // heap.Interface implementation. 104 func (pq *txPriorityQueue) Len() int { 105 return len(pq.items) 106 } 107 108 // Less returns whether the item in the priority queue with index i should sort 109 // before the item with index j by deferring to the assigned less function. It 110 // is part of the heap.Interface implementation. 111 func (pq *txPriorityQueue) Less(i, j int) bool { 112 return pq.lessFunc(pq, i, j) 113 } 114 115 // Swap swaps the items at the passed indices in the priority queue. It is 116 // part of the heap.Interface implementation. 117 func (pq *txPriorityQueue) Swap(i, j int) { 118 pq.items[i], pq.items[j] = pq.items[j], pq.items[i] 119 } 120 121 // Push pushes the passed item onto the priority queue. It is part of the 122 // heap.Interface implementation. 123 func (pq *txPriorityQueue) Push(x interface{}) { 124 pq.items = append(pq.items, x.(*txPrioItem)) 125 } 126 127 // Pop removes the highest priority item (according to Less) from the priority 128 // queue and returns it. It is part of the heap.Interface implementation. 129 func (pq *txPriorityQueue) Pop() interface{} { 130 n := len(pq.items) 131 item := pq.items[n-1] 132 pq.items[n-1] = nil 133 pq.items = pq.items[0 : n-1] 134 return item 135 } 136 137 // SetLessFunc sets the compare function for the priority queue to the provided 138 // function. It also invokes heap.Init on the priority queue using the new 139 // function so it can immediately be used with heap.Push/Pop. 140 func (pq *txPriorityQueue) SetLessFunc(lessFunc txPriorityQueueLessFunc) { 141 pq.lessFunc = lessFunc 142 heap.Init(pq) 143 } 144 145 // txPQByPriority sorts a txPriorityQueue by transaction priority and then fees 146 // per kilobyte. 147 func txPQByPriority(pq *txPriorityQueue, i, j int) bool { 148 // Using > here so that pop gives the highest priority item as opposed 149 // to the lowest. Sort by priority first, then fee. 150 if pq.items[i].priority == pq.items[j].priority { 151 return pq.items[i].feePerKB > pq.items[j].feePerKB 152 } 153 return pq.items[i].priority > pq.items[j].priority 154 155 } 156 157 // txPQByFee sorts a txPriorityQueue by fees per kilobyte and then transaction 158 // priority. 159 func txPQByFee(pq *txPriorityQueue, i, j int) bool { 160 // Using > here so that pop gives the highest fee item as opposed 161 // to the lowest. Sort by fee first, then priority. 162 if pq.items[i].feePerKB == pq.items[j].feePerKB { 163 return pq.items[i].priority > pq.items[j].priority 164 } 165 return pq.items[i].feePerKB > pq.items[j].feePerKB 166 } 167 168 // newTxPriorityQueue returns a new transaction priority queue that reserves the 169 // passed amount of space for the elements. The new priority queue uses either 170 // the txPQByPriority or the txPQByFee compare function depending on the 171 // sortByFee parameter and is already initialized for use with heap.Push/Pop. 172 // The priority queue can grow larger than the reserved space, but extra copies 173 // of the underlying array can be avoided by reserving a sane value. 174 func newTxPriorityQueue(reserve int, sortByFee bool) *txPriorityQueue { 175 pq := &txPriorityQueue{ 176 items: make([]*txPrioItem, 0, reserve), 177 } 178 if sortByFee { 179 pq.SetLessFunc(txPQByFee) 180 } else { 181 pq.SetLessFunc(txPQByPriority) 182 } 183 return pq 184 } 185 186 // BlockTemplate houses a block that has yet to be solved along with additional 187 // details about the fees and the number of signature operations for each 188 // transaction in the block. 189 type BlockTemplate struct { 190 // Block is a block that is ready to be solved by miners. Thus, it is 191 // completely valid with the exception of satisfying the proof-of-work 192 // requirement. 193 Block *wire.MsgBlock 194 195 // Fees contains the amount of fees each transaction in the generated 196 // template pays in base units. Since the first transaction is the 197 // coinbase, the first entry (offset 0) will contain the negative of the 198 // sum of the fees of all other transactions. 199 Fees []int64 200 201 // SigOpCosts contains the number of signature operations each 202 // transaction in the generated template performs. 203 SigOpCosts []int64 204 205 // Height is the height at which the block template connects to the main 206 // chain. 207 Height int32 208 209 // ValidPayAddress indicates whether or not the template coinbase pays 210 // to an address or is redeemable by anyone. See the documentation on 211 // NewBlockTemplate for details on which this can be useful to generate 212 // templates without a coinbase payment address. 213 ValidPayAddress bool 214 215 // WitnessCommitment is a commitment to the witness data (if any) 216 // within the block. This field will only be populted once segregated 217 // witness has been activated, and the block contains a transaction 218 // which has witness data. 219 WitnessCommitment []byte 220 } 221 222 // mergeUtxoView adds all of the entries in viewB to viewA. The result is that 223 // viewA will contain all of its original entries plus all of the entries 224 // in viewB. It will replace any entries in viewB which also exist in viewA 225 // if the entry in viewA is spent. 226 func mergeUtxoView(viewA *blockchain.UtxoViewpoint, viewB *blockchain.UtxoViewpoint) { 227 viewAEntries := viewA.Entries() 228 for outpoint, entryB := range viewB.Entries() { 229 if entryA, exists := viewAEntries[outpoint]; !exists || 230 entryA == nil || entryA.IsSpent() { 231 232 viewAEntries[outpoint] = entryB 233 } 234 } 235 } 236 237 // standardCoinbaseScript returns a standard script suitable for use as the 238 // signature script of the coinbase transaction of a new block. In particular, 239 // it starts with the block height that is required by version 2 blocks and adds 240 // the extra nonce as well as additional coinbase flags. 241 func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) { 242 return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)). 243 AddInt64(int64(extraNonce)).AddData([]byte(CoinbaseFlags)). 244 Script() 245 } 246 247 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy 248 // based on the passed block height to the provided address. When the address 249 // is nil, the coinbase transaction will instead be redeemable by anyone. 250 // 251 // See the comment for NewBlockTemplate for more information about why the nil 252 // address handling is useful. 253 func createCoinbaseTx(params *chaincfg.Params, coinbaseScript []byte, nextBlockHeight int32, addr palcutil.Address) (*palcutil.Tx, error) { 254 // Create the script to pay to the provided payment address if one was 255 // specified. Otherwise create a script that allows the coinbase to be 256 // redeemable by anyone. 257 var pkScript []byte 258 if addr != nil { 259 var err error 260 pkScript, err = txscript.PayToAddrScript(addr) 261 if err != nil { 262 return nil, err 263 } 264 } else { 265 var err error 266 scriptBuilder := txscript.NewScriptBuilder() 267 pkScript, err = scriptBuilder.AddOp(txscript.OP_TRUE).Script() 268 if err != nil { 269 return nil, err 270 } 271 } 272 273 tx := wire.NewMsgTx(wire.TxVersion) 274 tx.AddTxIn(&wire.TxIn{ 275 // Coinbase transactions have no inputs, so previous outpoint is 276 // zero hash and max index. 277 PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{}, 278 wire.MaxPrevOutIndex), 279 SignatureScript: coinbaseScript, 280 Sequence: wire.MaxTxInSequenceNum, 281 }) 282 tx.AddTxOut(&wire.TxOut{ 283 Value: blockchain.CalcBlockSubsidy(nextBlockHeight, params), 284 PkScript: pkScript, 285 }) 286 return palcutil.NewTx(tx), nil 287 } 288 289 // spendTransaction updates the passed view by marking the inputs to the passed 290 // transaction as spent. It also adds all outputs in the passed transaction 291 // which are not provably unspendable as available unspent transaction outputs. 292 func spendTransaction(utxoView *blockchain.UtxoViewpoint, tx *palcutil.Tx, height int32) error { 293 for _, txIn := range tx.MsgTx().TxIn { 294 entry := utxoView.LookupEntry(txIn.PreviousOutPoint) 295 if entry != nil { 296 entry.Spend() 297 } 298 } 299 300 utxoView.AddTxOuts(tx, height) 301 return nil 302 } 303 304 // logSkippedDeps logs any dependencies which are also skipped as a result of 305 // skipping a transaction while generating a block template at the trace level. 306 func logSkippedDeps(tx *palcutil.Tx, deps map[chainhash.Hash]*txPrioItem) { 307 if deps == nil { 308 return 309 } 310 311 for _, item := range deps { 312 log.Tracef("Skipping tx %s since it depends on %s\n", 313 item.tx.Hash(), tx.Hash()) 314 } 315 } 316 317 // MinimumMedianTime returns the minimum allowed timestamp for a block building 318 // on the end of the provided best chain. In particular, it is one second after 319 // the median timestamp of the last several blocks per the chain consensus 320 // rules. 321 func MinimumMedianTime(chainState *blockchain.BestState) time.Time { 322 return chainState.MedianTime.Add(time.Second) 323 } 324 325 // medianAdjustedTime returns the current time adjusted to ensure it is at least 326 // one second after the median timestamp of the last several blocks per the 327 // chain consensus rules. 328 func medianAdjustedTime(chainState *blockchain.BestState, timeSource blockchain.MedianTimeSource) time.Time { 329 // The timestamp for the block must not be before the median timestamp 330 // of the last several blocks. Thus, choose the maximum between the 331 // current time and one second after the past median time. The current 332 // timestamp is truncated to a second boundary before comparison since a 333 // block timestamp does not supported a precision greater than one 334 // second. 335 newTimestamp := timeSource.AdjustedTime() 336 minTimestamp := MinimumMedianTime(chainState) 337 if newTimestamp.Before(minTimestamp) { 338 newTimestamp = minTimestamp 339 } 340 341 return newTimestamp 342 } 343 344 // BlkTmplGenerator provides a type that can be used to generate block templates 345 // based on a given mining policy and source of transactions to choose from. 346 // It also houses additional state required in order to ensure the templates 347 // are built on top of the current best chain and adhere to the consensus rules. 348 type BlkTmplGenerator struct { 349 policy *Policy 350 chainParams *chaincfg.Params 351 txSource TxSource 352 chain *blockchain.BlockChain 353 timeSource blockchain.MedianTimeSource 354 sigCache *txscript.SigCache 355 hashCache *txscript.HashCache 356 } 357 358 // NewBlkTmplGenerator returns a new block template generator for the given 359 // policy using transactions from the provided transaction source. 360 // 361 // The additional state-related fields are required in order to ensure the 362 // templates are built on top of the current best chain and adhere to the 363 // consensus rules. 364 func NewBlkTmplGenerator(policy *Policy, params *chaincfg.Params, 365 txSource TxSource, chain *blockchain.BlockChain, 366 timeSource blockchain.MedianTimeSource, 367 sigCache *txscript.SigCache, 368 hashCache *txscript.HashCache) *BlkTmplGenerator { 369 370 return &BlkTmplGenerator{ 371 policy: policy, 372 chainParams: params, 373 txSource: txSource, 374 chain: chain, 375 timeSource: timeSource, 376 sigCache: sigCache, 377 hashCache: hashCache, 378 } 379 } 380 381 // NewBlockTemplate returns a new block template that is ready to be solved 382 // using the transactions from the passed transaction source pool and a coinbase 383 // that either pays to the passed address if it is not nil, or a coinbase that 384 // is redeemable by anyone if the passed address is nil. The nil address 385 // functionality is useful since there are cases such as the getblocktemplate 386 // RPC where external mining software is responsible for creating their own 387 // coinbase which will replace the one generated for the block template. Thus 388 // the need to have configured address can be avoided. 389 // 390 // The transactions selected and included are prioritized according to several 391 // factors. First, each transaction has a priority calculated based on its 392 // value, age of inputs, and size. Transactions which consist of larger 393 // amounts, older inputs, and small sizes have the highest priority. Second, a 394 // fee per kilobyte is calculated for each transaction. Transactions with a 395 // higher fee per kilobyte are preferred. Finally, the block generation related 396 // policy settings are all taken into account. 397 // 398 // Transactions which only spend outputs from other transactions already in the 399 // block chain are immediately added to a priority queue which either 400 // prioritizes based on the priority (then fee per kilobyte) or the fee per 401 // kilobyte (then priority) depending on whether or not the BlockPrioritySize 402 // policy setting allots space for high-priority transactions. Transactions 403 // which spend outputs from other transactions in the source pool are added to a 404 // dependency map so they can be added to the priority queue once the 405 // transactions they depend on have been included. 406 // 407 // Once the high-priority area (if configured) has been filled with 408 // transactions, or the priority falls below what is considered high-priority, 409 // the priority queue is updated to prioritize by fees per kilobyte (then 410 // priority). 411 // 412 // When the fees per kilobyte drop below the TxMinFreeFee policy setting, the 413 // transaction will be skipped unless the BlockMinSize policy setting is 414 // nonzero, in which case the block will be filled with the low-fee/free 415 // transactions until the block size reaches that minimum size. 416 // 417 // Any transactions which would cause the block to exceed the BlockMaxSize 418 // policy setting, exceed the maximum allowed signature operations per block, or 419 // otherwise cause the block to be invalid are skipped. 420 // 421 // Given the above, a block generated by this function is of the following form: 422 // 423 // ----------------------------------- -- -- 424 // | Coinbase Transaction | | | 425 // |-----------------------------------| | | 426 // | | | | ----- policy.BlockPrioritySize 427 // | High-priority Transactions | | | 428 // | | | | 429 // |-----------------------------------| | -- 430 // | | | 431 // | | | 432 // | | |--- policy.BlockMaxSize 433 // | Transactions prioritized by fee | | 434 // | until <= policy.TxMinFreeFee | | 435 // | | | 436 // | | | 437 // | | | 438 // |-----------------------------------| | 439 // | Low-fee/Non high-priority (free) | | 440 // | transactions (while block size | | 441 // | <= policy.BlockMinSize) | | 442 // ----------------------------------- -- 443 func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress palcutil.Address) (*BlockTemplate, error) { 444 // Extend the most recently known best block. 445 best := g.chain.BestSnapshot() 446 nextBlockHeight := best.Height + 1 447 448 // Create a standard coinbase transaction paying to the provided 449 // address. NOTE: The coinbase value will be updated to include the 450 // fees from the selected transactions later after they have actually 451 // been selected. It is created here to detect any errors early 452 // before potentially doing a lot of work below. The extra nonce helps 453 // ensure the transaction is not a duplicate transaction (paying the 454 // same value to the same public key address would otherwise be an 455 // identical transaction for block version 1). 456 extraNonce := uint64(0) 457 coinbaseScript, err := standardCoinbaseScript(nextBlockHeight, extraNonce) 458 if err != nil { 459 return nil, err 460 } 461 coinbaseTx, err := createCoinbaseTx(g.chainParams, coinbaseScript, 462 nextBlockHeight, payToAddress) 463 if err != nil { 464 return nil, err 465 } 466 coinbaseSigOpCost := int64(blockchain.CountSigOps(coinbaseTx)) * blockchain.WitnessScaleFactor 467 468 // Get the current source transactions and create a priority queue to 469 // hold the transactions which are ready for inclusion into a block 470 // along with some priority related and fee metadata. Reserve the same 471 // number of items that are available for the priority queue. Also, 472 // choose the initial sort order for the priority queue based on whether 473 // or not there is an area allocated for high-priority transactions. 474 sourceTxns := g.txSource.MiningDescs() 475 sortedByFee := g.policy.BlockPrioritySize == 0 476 priorityQueue := newTxPriorityQueue(len(sourceTxns), sortedByFee) 477 478 // Create a slice to hold the transactions to be included in the 479 // generated block with reserved space. Also create a utxo view to 480 // house all of the input transactions so multiple lookups can be 481 // avoided. 482 blockTxns := make([]*palcutil.Tx, 0, len(sourceTxns)) 483 blockTxns = append(blockTxns, coinbaseTx) 484 blockUtxos := blockchain.NewUtxoViewpoint() 485 486 // dependers is used to track transactions which depend on another 487 // transaction in the source pool. This, in conjunction with the 488 // dependsOn map kept with each dependent transaction helps quickly 489 // determine which dependent transactions are now eligible for inclusion 490 // in the block once each transaction has been included. 491 dependers := make(map[chainhash.Hash]map[chainhash.Hash]*txPrioItem) 492 493 // Create slices to hold the fees and number of signature operations 494 // for each of the selected transactions and add an entry for the 495 // coinbase. This allows the code below to simply append details about 496 // a transaction as it is selected for inclusion in the final block. 497 // However, since the total fees aren't known yet, use a dummy value for 498 // the coinbase fee which will be updated later. 499 txFees := make([]int64, 0, len(sourceTxns)) 500 txSigOpCosts := make([]int64, 0, len(sourceTxns)) 501 txFees = append(txFees, -1) // Updated once known 502 txSigOpCosts = append(txSigOpCosts, coinbaseSigOpCost) 503 504 log.Debugf("Considering %d transactions for inclusion to new block", 505 len(sourceTxns)) 506 507 mempoolLoop: 508 for _, txDesc := range sourceTxns { 509 // A block can't have more than one coinbase or contain 510 // non-finalized transactions. 511 tx := txDesc.Tx 512 if blockchain.IsCoinBase(tx) { 513 log.Tracef("Skipping coinbase tx %s", tx.Hash()) 514 continue 515 } 516 if !blockchain.IsFinalizedTransaction(tx, nextBlockHeight, 517 g.timeSource.AdjustedTime()) { 518 519 log.Tracef("Skipping non-finalized tx %s", tx.Hash()) 520 continue 521 } 522 523 // Fetch all of the utxos referenced by the this transaction. 524 // NOTE: This intentionally does not fetch inputs from the 525 // mempool since a transaction which depends on other 526 // transactions in the mempool must come after those 527 // dependencies in the final generated block. 528 utxos, err := g.chain.FetchUtxoView(tx) 529 if err != nil { 530 log.Warnf("Unable to fetch utxo view for tx %s: %v", 531 tx.Hash(), err) 532 continue 533 } 534 535 // Setup dependencies for any transactions which reference 536 // other transactions in the mempool so they can be properly 537 // ordered below. 538 prioItem := &txPrioItem{tx: tx} 539 for _, txIn := range tx.MsgTx().TxIn { 540 originHash := &txIn.PreviousOutPoint.Hash 541 entry := utxos.LookupEntry(txIn.PreviousOutPoint) 542 if entry == nil || entry.IsSpent() { 543 if !g.txSource.HaveTransaction(originHash) { 544 log.Tracef("Skipping tx %s because it "+ 545 "references unspent output %s "+ 546 "which is not available", 547 tx.Hash(), txIn.PreviousOutPoint) 548 continue mempoolLoop 549 } 550 551 // The transaction is referencing another 552 // transaction in the source pool, so setup an 553 // ordering dependency. 554 deps, exists := dependers[*originHash] 555 if !exists { 556 deps = make(map[chainhash.Hash]*txPrioItem) 557 dependers[*originHash] = deps 558 } 559 deps[*prioItem.tx.Hash()] = prioItem 560 if prioItem.dependsOn == nil { 561 prioItem.dependsOn = make( 562 map[chainhash.Hash]struct{}) 563 } 564 prioItem.dependsOn[*originHash] = struct{}{} 565 566 // Skip the check below. We already know the 567 // referenced transaction is available. 568 continue 569 } 570 } 571 572 // Calculate the final transaction priority using the input 573 // value age sum as well as the adjusted transaction size. The 574 // formula is: sum(inputValue * inputAge) / adjustedTxSize 575 prioItem.priority = CalcPriority(tx.MsgTx(), utxos, 576 nextBlockHeight) 577 578 // Calculate the fee in Satoshi/kB. 579 prioItem.feePerKB = txDesc.FeePerKB 580 prioItem.fee = txDesc.Fee 581 582 // Add the transaction to the priority queue to mark it ready 583 // for inclusion in the block unless it has dependencies. 584 if prioItem.dependsOn == nil { 585 heap.Push(priorityQueue, prioItem) 586 } 587 588 // Merge the referenced outputs from the input transactions to 589 // this transaction into the block utxo view. This allows the 590 // code below to avoid a second lookup. 591 mergeUtxoView(blockUtxos, utxos) 592 } 593 594 log.Tracef("Priority queue len %d, dependers len %d", 595 priorityQueue.Len(), len(dependers)) 596 597 // The starting block size is the size of the block header plus the max 598 // possible transaction count size, plus the size of the coinbase 599 // transaction. 600 blockWeight := uint32((blockHeaderOverhead * blockchain.WitnessScaleFactor) + 601 blockchain.GetTransactionWeight(coinbaseTx)) 602 blockSigOpCost := coinbaseSigOpCost 603 totalFees := int64(0) 604 605 // Query the version bits state to see if segwit has been activated, if 606 // so then this means that we'll include any transactions with witness 607 // data in the mempool, and also add the witness commitment as an 608 // OP_RETURN output in the coinbase transaction. 609 segwitState, err := g.chain.ThresholdState(chaincfg.DeploymentSegwit) 610 if err != nil { 611 return nil, err 612 } 613 segwitActive := segwitState == blockchain.ThresholdActive 614 615 witnessIncluded := false 616 617 // Choose which transactions make it into the block. 618 for priorityQueue.Len() > 0 { 619 // Grab the highest priority (or highest fee per kilobyte 620 // depending on the sort order) transaction. 621 prioItem := heap.Pop(priorityQueue).(*txPrioItem) 622 tx := prioItem.tx 623 624 switch { 625 // If segregated witness has not been activated yet, then we 626 // shouldn't include any witness transactions in the block. 627 case !segwitActive && tx.HasWitness(): 628 continue 629 630 // Otherwise, Keep track of if we've included a transaction 631 // with witness data or not. If so, then we'll need to include 632 // the witness commitment as the last output in the coinbase 633 // transaction. 634 case segwitActive && !witnessIncluded && tx.HasWitness(): 635 // If we're about to include a transaction bearing 636 // witness data, then we'll also need to include a 637 // witness commitment in the coinbase transaction. 638 // Therefore, we account for the additional weight 639 // within the block with a model coinbase tx with a 640 // witness commitment. 641 coinbaseCopy := palcutil.NewTx(coinbaseTx.MsgTx().Copy()) 642 coinbaseCopy.MsgTx().TxIn[0].Witness = [][]byte{ 643 bytes.Repeat([]byte("a"), 644 blockchain.CoinbaseWitnessDataLen), 645 } 646 coinbaseCopy.MsgTx().AddTxOut(&wire.TxOut{ 647 PkScript: bytes.Repeat([]byte("a"), 648 blockchain.CoinbaseWitnessPkScriptLength), 649 }) 650 651 // In order to accurately account for the weight 652 // addition due to this coinbase transaction, we'll add 653 // the difference of the transaction before and after 654 // the addition of the commitment to the block weight. 655 weightDiff := blockchain.GetTransactionWeight(coinbaseCopy) - 656 blockchain.GetTransactionWeight(coinbaseTx) 657 658 blockWeight += uint32(weightDiff) 659 660 witnessIncluded = true 661 } 662 663 // Grab any transactions which depend on this one. 664 deps := dependers[*tx.Hash()] 665 666 // Enforce maximum block size. Also check for overflow. 667 txWeight := uint32(blockchain.GetTransactionWeight(tx)) 668 blockPlusTxWeight := blockWeight + txWeight 669 if blockPlusTxWeight < blockWeight || 670 blockPlusTxWeight >= g.policy.BlockMaxWeight { 671 672 log.Tracef("Skipping tx %s because it would exceed "+ 673 "the max block weight", tx.Hash()) 674 logSkippedDeps(tx, deps) 675 continue 676 } 677 678 // Enforce maximum signature operation cost per block. Also 679 // check for overflow. 680 sigOpCost, err := blockchain.GetSigOpCost(tx, false, 681 blockUtxos, true, segwitActive) 682 if err != nil { 683 log.Tracef("Skipping tx %s due to error in "+ 684 "GetSigOpCost: %v", tx.Hash(), err) 685 logSkippedDeps(tx, deps) 686 continue 687 } 688 if blockSigOpCost+int64(sigOpCost) < blockSigOpCost || 689 blockSigOpCost+int64(sigOpCost) > blockchain.MaxBlockSigOpsCost { 690 log.Tracef("Skipping tx %s because it would "+ 691 "exceed the maximum sigops per block", tx.Hash()) 692 logSkippedDeps(tx, deps) 693 continue 694 } 695 696 // Skip free transactions once the block is larger than the 697 // minimum block size. 698 if sortedByFee && 699 prioItem.feePerKB < int64(g.policy.TxMinFreeFee) && 700 blockPlusTxWeight >= g.policy.BlockMinWeight { 701 702 log.Tracef("Skipping tx %s with feePerKB %d "+ 703 "< TxMinFreeFee %d and block weight %d >= "+ 704 "minBlockWeight %d", tx.Hash(), prioItem.feePerKB, 705 g.policy.TxMinFreeFee, blockPlusTxWeight, 706 g.policy.BlockMinWeight) 707 logSkippedDeps(tx, deps) 708 continue 709 } 710 711 // Prioritize by fee per kilobyte once the block is larger than 712 // the priority size or there are no more high-priority 713 // transactions. 714 if !sortedByFee && (blockPlusTxWeight >= g.policy.BlockPrioritySize || 715 prioItem.priority <= MinHighPriority) { 716 717 log.Tracef("Switching to sort by fees per "+ 718 "kilobyte blockSize %d >= BlockPrioritySize "+ 719 "%d || priority %.2f <= minHighPriority %.2f", 720 blockPlusTxWeight, g.policy.BlockPrioritySize, 721 prioItem.priority, MinHighPriority) 722 723 sortedByFee = true 724 priorityQueue.SetLessFunc(txPQByFee) 725 726 // Put the transaction back into the priority queue and 727 // skip it so it is re-priortized by fees if it won't 728 // fit into the high-priority section or the priority 729 // is too low. Otherwise this transaction will be the 730 // final one in the high-priority section, so just fall 731 // though to the code below so it is added now. 732 if blockPlusTxWeight > g.policy.BlockPrioritySize || 733 prioItem.priority < MinHighPriority { 734 735 heap.Push(priorityQueue, prioItem) 736 continue 737 } 738 } 739 740 // Ensure the transaction inputs pass all of the necessary 741 // preconditions before allowing it to be added to the block. 742 _, err = blockchain.CheckTransactionInputs(tx, nextBlockHeight, 743 blockUtxos, g.chainParams) 744 if err != nil { 745 log.Tracef("Skipping tx %s due to error in "+ 746 "CheckTransactionInputs: %v", tx.Hash(), err) 747 logSkippedDeps(tx, deps) 748 continue 749 } 750 err = blockchain.ValidateTransactionScripts(tx, blockUtxos, 751 txscript.StandardVerifyFlags, g.sigCache, 752 g.hashCache) 753 if err != nil { 754 log.Tracef("Skipping tx %s due to error in "+ 755 "ValidateTransactionScripts: %v", tx.Hash(), err) 756 logSkippedDeps(tx, deps) 757 continue 758 } 759 760 // Spend the transaction inputs in the block utxo view and add 761 // an entry for it to ensure any transactions which reference 762 // this one have it available as an input and can ensure they 763 // aren't double spending. 764 spendTransaction(blockUtxos, tx, nextBlockHeight) 765 766 // Add the transaction to the block, increment counters, and 767 // save the fees and signature operation counts to the block 768 // template. 769 blockTxns = append(blockTxns, tx) 770 blockWeight += txWeight 771 blockSigOpCost += int64(sigOpCost) 772 totalFees += prioItem.fee 773 txFees = append(txFees, prioItem.fee) 774 txSigOpCosts = append(txSigOpCosts, int64(sigOpCost)) 775 776 log.Tracef("Adding tx %s (priority %.2f, feePerKB %.2f)", 777 prioItem.tx.Hash(), prioItem.priority, prioItem.feePerKB) 778 779 // Add transactions which depend on this one (and also do not 780 // have any other unsatisified dependencies) to the priority 781 // queue. 782 for _, item := range deps { 783 // Add the transaction to the priority queue if there 784 // are no more dependencies after this one. 785 delete(item.dependsOn, *tx.Hash()) 786 if len(item.dependsOn) == 0 { 787 heap.Push(priorityQueue, item) 788 } 789 } 790 } 791 792 // Now that the actual transactions have been selected, update the 793 // block weight for the real transaction count and coinbase value with 794 // the total fees accordingly. 795 blockWeight -= wire.MaxVarIntPayload - 796 (uint32(wire.VarIntSerializeSize(uint64(len(blockTxns)))) * 797 blockchain.WitnessScaleFactor) 798 coinbaseTx.MsgTx().TxOut[0].Value += totalFees 799 txFees[0] = -totalFees 800 801 // If segwit is active and we included transactions with witness data, 802 // then we'll need to include a commitment to the witness data in an 803 // OP_RETURN output within the coinbase transaction. 804 var witnessCommitment []byte 805 if witnessIncluded { 806 witnessCommitment = AddWitnessCommitment(coinbaseTx, blockTxns) 807 } 808 809 // Calculate the required difficulty for the block. The timestamp 810 // is potentially adjusted to ensure it comes after the median time of 811 // the last several blocks per the chain consensus rules. 812 ts := medianAdjustedTime(best, g.timeSource) 813 reqDifficulty, err := g.chain.CalcNextRequiredDifficulty(ts) 814 if err != nil { 815 return nil, err 816 } 817 818 // Calculate the next expected block version based on the state of the 819 // rule change deployments. 820 nextBlockVersion, err := g.chain.CalcNextBlockVersion() 821 if err != nil { 822 return nil, err 823 } 824 825 // Create a new block ready to be solved. 826 merkles := blockchain.BuildMerkleTreeStore(blockTxns, false) 827 var msgBlock wire.MsgBlock 828 msgBlock.Header = wire.BlockHeader{ 829 Version: nextBlockVersion, 830 PrevBlock: best.Hash, 831 MerkleRoot: *merkles[len(merkles)-1], 832 Timestamp: ts, 833 Bits: reqDifficulty, 834 } 835 for _, tx := range blockTxns { 836 if err := msgBlock.AddTransaction(tx.MsgTx()); err != nil { 837 return nil, err 838 } 839 } 840 841 // Finally, perform a full check on the created block against the chain 842 // consensus rules to ensure it properly connects to the current best 843 // chain with no issues. 844 block := palcutil.NewBlock(&msgBlock) 845 block.SetHeight(nextBlockHeight) 846 if err := g.chain.CheckConnectBlockTemplate(block); err != nil { 847 return nil, err 848 } 849 850 log.Debugf("Created new block template (%d transactions, %d in "+ 851 "fees, %d signature operations cost, %d weight, target difficulty "+ 852 "%064x)", len(msgBlock.Transactions), totalFees, blockSigOpCost, 853 blockWeight, blockchain.CompactToBig(msgBlock.Header.Bits)) 854 855 return &BlockTemplate{ 856 Block: &msgBlock, 857 Fees: txFees, 858 SigOpCosts: txSigOpCosts, 859 Height: nextBlockHeight, 860 ValidPayAddress: payToAddress != nil, 861 WitnessCommitment: witnessCommitment, 862 }, nil 863 } 864 865 // AddWitnessCommitment adds the witness commitment as an OP_RETURN outpout 866 // within the coinbase tx. The raw commitment is returned. 867 func AddWitnessCommitment(coinbaseTx *palcutil.Tx, 868 blockTxns []*palcutil.Tx) []byte { 869 870 // The witness of the coinbase transaction MUST be exactly 32-bytes 871 // of all zeroes. 872 var witnessNonce [blockchain.CoinbaseWitnessDataLen]byte 873 coinbaseTx.MsgTx().TxIn[0].Witness = wire.TxWitness{witnessNonce[:]} 874 875 // Next, obtain the merkle root of a tree which consists of the 876 // wtxid of all transactions in the block. The coinbase 877 // transaction will have a special wtxid of all zeroes. 878 witnessMerkleTree := blockchain.BuildMerkleTreeStore(blockTxns, 879 true) 880 witnessMerkleRoot := witnessMerkleTree[len(witnessMerkleTree)-1] 881 882 // The preimage to the witness commitment is: 883 // witnessRoot || coinbaseWitness 884 var witnessPreimage [64]byte 885 copy(witnessPreimage[:32], witnessMerkleRoot[:]) 886 copy(witnessPreimage[32:], witnessNonce[:]) 887 888 // The witness commitment itself is the double-sha256 of the 889 // witness preimage generated above. With the commitment 890 // generated, the witness script for the output is: OP_RETURN 891 // OP_DATA_36 {0xaa21a9ed || witnessCommitment}. The leading 892 // prefix is referred to as the "witness magic bytes". 893 witnessCommitment := chainhash.DoubleHashB(witnessPreimage[:]) 894 witnessScript := append(blockchain.WitnessMagicBytes, witnessCommitment...) 895 896 // Finally, create the OP_RETURN carrying witness commitment 897 // output as an additional output within the coinbase. 898 commitmentOutput := &wire.TxOut{ 899 Value: 0, 900 PkScript: witnessScript, 901 } 902 coinbaseTx.MsgTx().TxOut = append(coinbaseTx.MsgTx().TxOut, 903 commitmentOutput) 904 905 return witnessCommitment 906 } 907 908 // UpdateBlockTime updates the timestamp in the header of the passed block to 909 // the current time while taking into account the median time of the last 910 // several blocks to ensure the new time is after that time per the chain 911 // consensus rules. Finally, it will update the target difficulty if needed 912 // based on the new time for the test networks since their target difficulty can 913 // change based upon time. 914 func (g *BlkTmplGenerator) UpdateBlockTime(msgBlock *wire.MsgBlock) error { 915 // The new timestamp is potentially adjusted to ensure it comes after 916 // the median time of the last several blocks per the chain consensus 917 // rules. 918 newTime := medianAdjustedTime(g.chain.BestSnapshot(), g.timeSource) 919 msgBlock.Header.Timestamp = newTime 920 921 // Recalculate the difficulty if running on a network that requires it. 922 if g.chainParams.ReduceMinDifficulty { 923 difficulty, err := g.chain.CalcNextRequiredDifficulty(newTime) 924 if err != nil { 925 return err 926 } 927 msgBlock.Header.Bits = difficulty 928 } 929 930 return nil 931 } 932 933 // UpdateExtraNonce updates the extra nonce in the coinbase script of the passed 934 // block by regenerating the coinbase script with the passed value and block 935 // height. It also recalculates and updates the new merkle root that results 936 // from changing the coinbase script. 937 func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int32, extraNonce uint64) error { 938 coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce) 939 if err != nil { 940 return err 941 } 942 if len(coinbaseScript) > blockchain.MaxCoinbaseScriptLen { 943 return fmt.Errorf("coinbase transaction script length "+ 944 "of %d is out of range (min: %d, max: %d)", 945 len(coinbaseScript), blockchain.MinCoinbaseScriptLen, 946 blockchain.MaxCoinbaseScriptLen) 947 } 948 msgBlock.Transactions[0].TxIn[0].SignatureScript = coinbaseScript 949 950 // TODO(davec): A palcutil.Block should use saved in the state to avoid 951 // recalculating all of the other transaction hashes. 952 // block.Transactions[0].InvalidateCache() 953 954 // Recalculate the merkle root with the updated extra nonce. 955 block := palcutil.NewBlock(msgBlock) 956 merkles := blockchain.BuildMerkleTreeStore(block.Transactions(), false) 957 msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1] 958 return nil 959 } 960 961 // BestSnapshot returns information about the current best chain block and 962 // related state as of the current point in time using the chain instance 963 // associated with the block template generator. The returned state must be 964 // treated as immutable since it is shared by all callers. 965 // 966 // This function is safe for concurrent access. 967 func (g *BlkTmplGenerator) BestSnapshot() *blockchain.BestState { 968 return g.chain.BestSnapshot() 969 } 970 971 // TxSource returns the associated transaction source. 972 // 973 // This function is safe for concurrent access. 974 func (g *BlkTmplGenerator) TxSource() TxSource { 975 return g.txSource 976 }