1 // Copyright (c) 2013-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.
15 "github.com/btcsuite/btcd/blockchain"
16 "github.com/btcsuite/btcd/blockchain/indexers"
17 "github.com/btcsuite/btcd/btcjson"
18 "github.com/btcsuite/btcd/chaincfg"
19 "github.com/btcsuite/btcd/chaincfg/chainhash"
20 "github.com/btcsuite/btcd/mining"
21 "github.com/btcsuite/btcd/txscript"
22 "github.com/btcsuite/btcd/wire"
23 "github.com/btcsuite/btcutil"
27 // DefaultBlockPrioritySize is the default size in bytes for high-
28 // priority / low-fee transactions. It is used to help determine which
29 // are allowed into the mempool and consequently affects their relay and
30 // inclusion when generating block templates.
31 DefaultBlockPrioritySize = 50000
33 // orphanTTL is the maximum amount of time an orphan is allowed to
34 // stay in the orphan pool before it expires and is evicted during the
36 orphanTTL = time.Minute * 15
38 // orphanExpireScanInterval is the minimum amount of time in between
39 // scans of the orphan pool to evict expired transactions.
40 orphanExpireScanInterval = time.Minute * 5
43 // Tag represents an identifier to use for tagging orphan transactions. The
44 // caller may choose any scheme it desires, however it is common to use peer IDs
45 // so that orphans can be identified by which peer first relayed them.
48 // Config is a descriptor containing the memory pool configuration.
50 // Policy defines the various mempool configuration options related
54 // ChainParams identifies which chain parameters the txpool is
56 ChainParams *chaincfg.Params
58 // FetchUtxoView defines the function to use to fetch unspent
59 // transaction output information.
60 FetchUtxoView func(*btcutil.Tx) (*blockchain.UtxoViewpoint, error)
62 // BestHeight defines the function to use to access the block height of
63 // the current best chain.
64 BestHeight func() int32
66 // MedianTimePast defines the function to use in order to access the
67 // median time past calculated from the point-of-view of the current
68 // chain tip within the best chain.
69 MedianTimePast func() time.Time
71 // CalcSequenceLock defines the function to use in order to generate
72 // the current sequence lock for the given transaction using the passed
74 CalcSequenceLock func(*btcutil.Tx, *blockchain.UtxoViewpoint) (*blockchain.SequenceLock, error)
76 // IsDeploymentActive returns true if the target deploymentID is
77 // active, and false otherwise. The mempool uses this function to gauge
78 // if transactions using new to be soft-forked rules should be allowed
79 // into the mempool or not.
80 IsDeploymentActive func(deploymentID uint32) (bool, error)
82 // SigCache defines a signature cache to use.
83 SigCache *txscript.SigCache
85 // HashCache defines the transaction hash mid-state cache to use.
86 HashCache *txscript.HashCache
88 // AddrIndex defines the optional address index instance to use for
89 // indexing the unconfirmed transactions in the memory pool.
90 // This can be nil if the address index is not enabled.
91 AddrIndex *indexers.AddrIndex
94 // Policy houses the policy (configuration parameters) which is used to
95 // control the mempool.
97 // MaxTxVersion is the transaction version that the mempool should
98 // accept. All transactions above this version are rejected as
102 // DisableRelayPriority defines whether to relay free or low-fee
103 // transactions that do not have enough priority to be relayed.
104 DisableRelayPriority bool
106 // AcceptNonStd defines whether to accept non-standard transactions. If
107 // true, non-standard transactions will be accepted into the mempool.
108 // Otherwise, all non-standard transactions will be rejected.
111 // FreeTxRelayLimit defines the given amount in thousands of bytes
112 // per minute that transactions with no fee are rate limited to.
113 FreeTxRelayLimit float64
115 // MaxOrphanTxs is the maximum number of orphan transactions
116 // that can be queued.
119 // MaxOrphanTxSize is the maximum size allowed for orphan transactions.
120 // This helps prevent memory exhaustion attacks from sending a lot of
124 // MaxSigOpCostPerTx is the cumulative maximum cost of all the signature
125 // operations in a single transaction we will relay or mine. It is a
126 // fraction of the max signature operations for a block.
127 MaxSigOpCostPerTx int
129 // MinRelayTxFee defines the minimum transaction fee in BTC/kB to be
130 // considered a non-zero fee.
131 MinRelayTxFee btcutil.Amount
134 // TxDesc is a descriptor containing a transaction in the mempool along with
135 // additional metadata.
139 // StartingPriority is the priority of the transaction when it was added
141 StartingPriority float64
144 // orphanTx is normal transaction that references an ancestor transaction
145 // that is not yet available. It also contains additional information related
146 // to it such as an expiration time to help prevent caching the orphan forever.
147 type orphanTx struct {
153 // TxPool is used as a source of transactions that need to be mined into blocks
154 // and relayed to other peers. It is safe for concurrent access from multiple
157 // The following variables must only be used atomically.
158 lastUpdated int64 // last time pool was updated
162 pool map[chainhash.Hash]*TxDesc
163 orphans map[chainhash.Hash]*orphanTx
164 orphansByPrev map[wire.OutPoint]map[chainhash.Hash]*btcutil.Tx
165 outpoints map[wire.OutPoint]*btcutil.Tx
166 pennyTotal float64 // exponentially decaying total for penny spends.
167 lastPennyUnix int64 // unix time of last ``penny spend''
169 // nextExpireScan is the time after which the orphan pool will be
170 // scanned in order to evict orphans. This is NOT a hard deadline as
171 // the scan will only run when an orphan is added to the pool as opposed
172 // to on an unconditional timer.
173 nextExpireScan time.Time
176 // Ensure the TxPool type implements the mining.TxSource interface.
177 var _ mining.TxSource = (*TxPool)(nil)
179 // removeOrphan is the internal function which implements the public
180 // RemoveOrphan. See the comment for RemoveOrphan for more details.
182 // This function MUST be called with the mempool lock held (for writes).
183 func (mp *TxPool) removeOrphan(tx *btcutil.Tx, removeRedeemers bool) {
184 // Nothing to do if passed tx is not an orphan.
186 otx, exists := mp.orphans[*txHash]
191 // Remove the reference from the previous orphan index.
192 for _, txIn := range otx.tx.MsgTx().TxIn {
193 orphans, exists := mp.orphansByPrev[txIn.PreviousOutPoint]
195 delete(orphans, *txHash)
197 // Remove the map entry altogether if there are no
198 // longer any orphans which depend on it.
199 if len(orphans) == 0 {
200 delete(mp.orphansByPrev, txIn.PreviousOutPoint)
205 // Remove any orphans that redeem outputs from this one if requested.
207 prevOut := wire.OutPoint{Hash: *txHash}
208 for txOutIdx := range tx.MsgTx().TxOut {
209 prevOut.Index = uint32(txOutIdx)
210 for _, orphan := range mp.orphansByPrev[prevOut] {
211 mp.removeOrphan(orphan, true)
216 // Remove the transaction from the orphan pool.
217 delete(mp.orphans, *txHash)
220 // RemoveOrphan removes the passed orphan transaction from the orphan pool and
221 // previous orphan index.
223 // This function is safe for concurrent access.
224 func (mp *TxPool) RemoveOrphan(tx *btcutil.Tx) {
226 mp.removeOrphan(tx, false)
230 // RemoveOrphansByTag removes all orphan transactions tagged with the provided
233 // This function is safe for concurrent access.
234 func (mp *TxPool) RemoveOrphansByTag(tag Tag) uint64 {
235 var numEvicted uint64
237 for _, otx := range mp.orphans {
239 mp.removeOrphan(otx.tx, true)
247 // limitNumOrphans limits the number of orphan transactions by evicting a random
248 // orphan if adding a new one would cause it to overflow the max allowed.
250 // This function MUST be called with the mempool lock held (for writes).
251 func (mp *TxPool) limitNumOrphans() error {
252 // Scan through the orphan pool and remove any expired orphans when it's
253 // time. This is done for efficiency so the scan only happens
254 // periodically instead of on every orphan added to the pool.
255 if now := time.Now(); now.After(mp.nextExpireScan) {
256 origNumOrphans := len(mp.orphans)
257 for _, otx := range mp.orphans {
258 if now.After(otx.expiration) {
259 // Remove redeemers too because the missing
260 // parents are very unlikely to ever materialize
261 // since the orphan has already been around more
262 // than long enough for them to be delivered.
263 mp.removeOrphan(otx.tx, true)
267 // Set next expiration scan to occur after the scan interval.
268 mp.nextExpireScan = now.Add(orphanExpireScanInterval)
270 numOrphans := len(mp.orphans)
271 if numExpired := origNumOrphans - numOrphans; numExpired > 0 {
272 log.Debugf("Expired %d %s (remaining: %d)", numExpired,
273 pickNoun(numExpired, "orphan", "orphans"),
278 // Nothing to do if adding another orphan will not cause the pool to
280 if len(mp.orphans)+1 <= mp.cfg.Policy.MaxOrphanTxs {
284 // Remove a random entry from the map. For most compilers, Go's
285 // range statement iterates starting at a random item although
286 // that is not 100% guaranteed by the spec. The iteration order
287 // is not important here because an adversary would have to be
288 // able to pull off preimage attacks on the hashing function in
289 // order to target eviction of specific entries anyways.
290 for _, otx := range mp.orphans {
291 // Don't remove redeemers in the case of a random eviction since
292 // it is quite possible it might be needed again shortly.
293 mp.removeOrphan(otx.tx, false)
300 // addOrphan adds an orphan transaction to the orphan pool.
302 // This function MUST be called with the mempool lock held (for writes).
303 func (mp *TxPool) addOrphan(tx *btcutil.Tx, tag Tag) {
304 // Nothing to do if no orphans are allowed.
305 if mp.cfg.Policy.MaxOrphanTxs <= 0 {
309 // Limit the number orphan transactions to prevent memory exhaustion.
310 // This will periodically remove any expired orphans and evict a random
311 // orphan if space is still needed.
314 mp.orphans[*tx.Hash()] = &orphanTx{
317 expiration: time.Now().Add(orphanTTL),
319 for _, txIn := range tx.MsgTx().TxIn {
320 if _, exists := mp.orphansByPrev[txIn.PreviousOutPoint]; !exists {
321 mp.orphansByPrev[txIn.PreviousOutPoint] =
322 make(map[chainhash.Hash]*btcutil.Tx)
324 mp.orphansByPrev[txIn.PreviousOutPoint][*tx.Hash()] = tx
327 log.Debugf("Stored orphan transaction %v (total: %d)", tx.Hash(),
331 // maybeAddOrphan potentially adds an orphan to the orphan pool.
333 // This function MUST be called with the mempool lock held (for writes).
334 func (mp *TxPool) maybeAddOrphan(tx *btcutil.Tx, tag Tag) error {
335 // Ignore orphan transactions that are too large. This helps avoid
336 // a memory exhaustion attack based on sending a lot of really large
337 // orphans. In the case there is a valid transaction larger than this,
338 // it will ultimtely be rebroadcast after the parent transactions
339 // have been mined or otherwise received.
341 // Note that the number of orphan transactions in the orphan pool is
342 // also limited, so this equates to a maximum memory used of
343 // mp.cfg.Policy.MaxOrphanTxSize * mp.cfg.Policy.MaxOrphanTxs (which is ~5MB
344 // using the default values at the time this comment was written).
345 serializedLen := tx.MsgTx().SerializeSize()
346 if serializedLen > mp.cfg.Policy.MaxOrphanTxSize {
347 str := fmt.Sprintf("orphan transaction size of %d bytes is "+
348 "larger than max allowed size of %d bytes",
349 serializedLen, mp.cfg.Policy.MaxOrphanTxSize)
350 return txRuleError(wire.RejectNonstandard, str)
353 // Add the orphan if the none of the above disqualified it.
354 mp.addOrphan(tx, tag)
359 // removeOrphanDoubleSpends removes all orphans which spend outputs spent by the
360 // passed transaction from the orphan pool. Removing those orphans then leads
361 // to removing all orphans which rely on them, recursively. This is necessary
362 // when a transaction is added to the main pool because it may spend outputs
363 // that orphans also spend.
365 // This function MUST be called with the mempool lock held (for writes).
366 func (mp *TxPool) removeOrphanDoubleSpends(tx *btcutil.Tx) {
368 for _, txIn := range msgTx.TxIn {
369 for _, orphan := range mp.orphansByPrev[txIn.PreviousOutPoint] {
370 mp.removeOrphan(orphan, true)
375 // isTransactionInPool returns whether or not the passed transaction already
376 // exists in the main pool.
378 // This function MUST be called with the mempool lock held (for reads).
379 func (mp *TxPool) isTransactionInPool(hash *chainhash.Hash) bool {
380 if _, exists := mp.pool[*hash]; exists {
387 // IsTransactionInPool returns whether or not the passed transaction already
388 // exists in the main pool.
390 // This function is safe for concurrent access.
391 func (mp *TxPool) IsTransactionInPool(hash *chainhash.Hash) bool {
392 // Protect concurrent access.
394 inPool := mp.isTransactionInPool(hash)
400 // isOrphanInPool returns whether or not the passed transaction already exists
401 // in the orphan pool.
403 // This function MUST be called with the mempool lock held (for reads).
404 func (mp *TxPool) isOrphanInPool(hash *chainhash.Hash) bool {
405 if _, exists := mp.orphans[*hash]; exists {
412 // IsOrphanInPool returns whether or not the passed transaction already exists
413 // in the orphan pool.
415 // This function is safe for concurrent access.
416 func (mp *TxPool) IsOrphanInPool(hash *chainhash.Hash) bool {
417 // Protect concurrent access.
419 inPool := mp.isOrphanInPool(hash)
425 // haveTransaction returns whether or not the passed transaction already exists
426 // in the main pool or in the orphan pool.
428 // This function MUST be called with the mempool lock held (for reads).
429 func (mp *TxPool) haveTransaction(hash *chainhash.Hash) bool {
430 return mp.isTransactionInPool(hash) || mp.isOrphanInPool(hash)
433 // HaveTransaction returns whether or not the passed transaction already exists
434 // in the main pool or in the orphan pool.
436 // This function is safe for concurrent access.
437 func (mp *TxPool) HaveTransaction(hash *chainhash.Hash) bool {
438 // Protect concurrent access.
440 haveTx := mp.haveTransaction(hash)
446 // removeTransaction is the internal function which implements the public
447 // RemoveTransaction. See the comment for RemoveTransaction for more details.
449 // This function MUST be called with the mempool lock held (for writes).
450 func (mp *TxPool) removeTransaction(tx *btcutil.Tx, removeRedeemers bool) {
453 // Remove any transactions which rely on this one.
454 for i := uint32(0); i < uint32(len(tx.MsgTx().TxOut)); i++ {
455 prevOut := wire.OutPoint{Hash: *txHash, Index: i}
456 if txRedeemer, exists := mp.outpoints[prevOut]; exists {
457 mp.removeTransaction(txRedeemer, true)
462 // Remove the transaction if needed.
463 if txDesc, exists := mp.pool[*txHash]; exists {
464 // Remove unconfirmed address index entries associated with the
465 // transaction if enabled.
466 if mp.cfg.AddrIndex != nil {
467 mp.cfg.AddrIndex.RemoveUnconfirmedTx(txHash)
470 // Mark the referenced outpoints as unspent by the pool.
471 for _, txIn := range txDesc.Tx.MsgTx().TxIn {
472 delete(mp.outpoints, txIn.PreviousOutPoint)
474 delete(mp.pool, *txHash)
475 atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
479 // RemoveTransaction removes the passed transaction from the mempool. When the
480 // removeRedeemers flag is set, any transactions that redeem outputs from the
481 // removed transaction will also be removed recursively from the mempool, as
482 // they would otherwise become orphans.
484 // This function is safe for concurrent access.
485 func (mp *TxPool) RemoveTransaction(tx *btcutil.Tx, removeRedeemers bool) {
486 // Protect concurrent access.
488 mp.removeTransaction(tx, removeRedeemers)
492 // RemoveDoubleSpends removes all transactions which spend outputs spent by the
493 // passed transaction from the memory pool. Removing those transactions then
494 // leads to removing all transactions which rely on them, recursively. This is
495 // necessary when a block is connected to the main chain because the block may
496 // contain transactions which were previously unknown to the memory pool.
498 // This function is safe for concurrent access.
499 func (mp *TxPool) RemoveDoubleSpends(tx *btcutil.Tx) {
500 // Protect concurrent access.
502 for _, txIn := range tx.MsgTx().TxIn {
503 if txRedeemer, ok := mp.outpoints[txIn.PreviousOutPoint]; ok {
504 if !txRedeemer.Hash().IsEqual(tx.Hash()) {
505 mp.removeTransaction(txRedeemer, true)
512 // addTransaction adds the passed transaction to the memory pool. It should
513 // not be called directly as it doesn't perform any validation. This is a
514 // helper for maybeAcceptTransaction.
516 // This function MUST be called with the mempool lock held (for writes).
517 func (mp *TxPool) addTransaction(utxoView *blockchain.UtxoViewpoint, tx *btcutil.Tx, height int32, fee int64) *TxDesc {
518 // Add the transaction to the pool and mark the referenced outpoints
519 // as spent by the pool.
521 TxDesc: mining.TxDesc{
526 FeePerKB: fee * 1000 / int64(tx.MsgTx().SerializeSize()),
528 StartingPriority: mining.CalcPriority(tx.MsgTx(), utxoView, height),
530 mp.pool[*tx.Hash()] = txD
532 for _, txIn := range tx.MsgTx().TxIn {
533 mp.outpoints[txIn.PreviousOutPoint] = tx
535 atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
537 // Add unconfirmed address index entries associated with the transaction
539 if mp.cfg.AddrIndex != nil {
540 mp.cfg.AddrIndex.AddUnconfirmedTx(tx, utxoView)
546 // checkPoolDoubleSpend checks whether or not the passed transaction is
547 // attempting to spend coins already spent by other transactions in the pool.
548 // Note it does not check for double spends against transactions already in the
551 // This function MUST be called with the mempool lock held (for reads).
552 func (mp *TxPool) checkPoolDoubleSpend(tx *btcutil.Tx) error {
553 for _, txIn := range tx.MsgTx().TxIn {
554 if txR, exists := mp.outpoints[txIn.PreviousOutPoint]; exists {
555 str := fmt.Sprintf("output %v already spent by "+
556 "transaction %v in the memory pool",
557 txIn.PreviousOutPoint, txR.Hash())
558 return txRuleError(wire.RejectDuplicate, str)
565 // fetchInputUtxos loads utxo details about the input transactions referenced by
566 // the passed transaction. First, it loads the details form the viewpoint of
567 // the main chain, then it adjusts them based upon the contents of the
570 // This function MUST be called with the mempool lock held (for reads).
571 func (mp *TxPool) fetchInputUtxos(tx *btcutil.Tx) (*blockchain.UtxoViewpoint, error) {
572 utxoView, err := mp.cfg.FetchUtxoView(tx)
577 // Attempt to populate any missing inputs from the transaction pool.
578 for originHash, entry := range utxoView.Entries() {
579 if entry != nil && !entry.IsFullySpent() {
583 if poolTxDesc, exists := mp.pool[originHash]; exists {
584 utxoView.AddTxOuts(poolTxDesc.Tx, mining.UnminedHeight)
590 // FetchTransaction returns the requested transaction from the transaction pool.
591 // This only fetches from the main transaction pool and does not include
594 // This function is safe for concurrent access.
595 func (mp *TxPool) FetchTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error) {
596 // Protect concurrent access.
598 txDesc, exists := mp.pool[*txHash]
602 return txDesc.Tx, nil
605 return nil, fmt.Errorf("transaction is not in the pool")
608 // maybeAcceptTransaction is the internal function which implements the public
609 // MaybeAcceptTransaction. See the comment for MaybeAcceptTransaction for
612 // This function MUST be called with the mempool lock held (for writes).
613 func (mp *TxPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit, rejectDupOrphans bool) ([]*chainhash.Hash, *TxDesc, error) {
616 // If a transaction has iwtness data, and segwit isn't active yet, If
617 // segwit isn't active yet, then we won't accept it into the mempool as
618 // it can't be mined yet.
619 if tx.MsgTx().HasWitness() {
620 segwitActive, err := mp.cfg.IsDeploymentActive(chaincfg.DeploymentSegwit)
626 str := fmt.Sprintf("transaction %v has witness data, "+
627 "but segwit isn't active yet", txHash)
628 return nil, nil, txRuleError(wire.RejectNonstandard, str)
632 // Don't accept the transaction if it already exists in the pool. This
633 // applies to orphan transactions as well when the reject duplicate
634 // orphans flag is set. This check is intended to be a quick check to
635 // weed out duplicates.
636 if mp.isTransactionInPool(txHash) || (rejectDupOrphans &&
637 mp.isOrphanInPool(txHash)) {
639 str := fmt.Sprintf("already have transaction %v", txHash)
640 return nil, nil, txRuleError(wire.RejectDuplicate, str)
643 // Perform preliminary sanity checks on the transaction. This makes
644 // use of blockchain which contains the invariant rules for what
645 // transactions are allowed into blocks.
646 err := blockchain.CheckTransactionSanity(tx)
648 if cerr, ok := err.(blockchain.RuleError); ok {
649 return nil, nil, chainRuleError(cerr)
654 // A standalone transaction must not be a coinbase transaction.
655 if blockchain.IsCoinBase(tx) {
656 str := fmt.Sprintf("transaction %v is an individual coinbase",
658 return nil, nil, txRuleError(wire.RejectInvalid, str)
661 // Get the current height of the main chain. A standalone transaction
662 // will be mined into the next block at best, so its height is at least
663 // one more than the current height.
664 bestHeight := mp.cfg.BestHeight()
665 nextBlockHeight := bestHeight + 1
667 medianTimePast := mp.cfg.MedianTimePast()
669 // Don't allow non-standard transactions if the network parameters
670 // forbid their acceptance.
671 if !mp.cfg.Policy.AcceptNonStd {
672 err = checkTransactionStandard(tx, nextBlockHeight,
673 medianTimePast, mp.cfg.Policy.MinRelayTxFee,
674 mp.cfg.Policy.MaxTxVersion)
676 // Attempt to extract a reject code from the error so
677 // it can be retained. When not possible, fall back to
678 // a non standard error.
679 rejectCode, found := extractRejectCode(err)
681 rejectCode = wire.RejectNonstandard
683 str := fmt.Sprintf("transaction %v is not standard: %v",
685 return nil, nil, txRuleError(rejectCode, str)
689 // The transaction may not use any of the same outputs as other
690 // transactions already in the pool as that would ultimately result in a
691 // double spend. This check is intended to be quick and therefore only
692 // detects double spends within the transaction pool itself. The
693 // transaction could still be double spending coins from the main chain
694 // at this point. There is a more in-depth check that happens later
695 // after fetching the referenced transaction inputs from the main chain
696 // which examines the actual spend data and prevents double spends.
697 err = mp.checkPoolDoubleSpend(tx)
702 // Fetch all of the unspent transaction outputs referenced by the inputs
703 // to this transaction. This function also attempts to fetch the
704 // transaction itself to be used for detecting a duplicate transaction
705 // without needing to do a separate lookup.
706 utxoView, err := mp.fetchInputUtxos(tx)
708 if cerr, ok := err.(blockchain.RuleError); ok {
709 return nil, nil, chainRuleError(cerr)
714 // Don't allow the transaction if it exists in the main chain and is not
715 // not already fully spent.
716 txEntry := utxoView.LookupEntry(txHash)
717 if txEntry != nil && !txEntry.IsFullySpent() {
718 return nil, nil, txRuleError(wire.RejectDuplicate,
719 "transaction already exists")
721 delete(utxoView.Entries(), *txHash)
723 // Transaction is an orphan if any of the referenced input transactions
724 // don't exist. Adding orphans to the orphan pool is not handled by
725 // this function, and the caller should use maybeAddOrphan if this
726 // behavior is desired.
727 var missingParents []*chainhash.Hash
728 for originHash, entry := range utxoView.Entries() {
729 if entry == nil || entry.IsFullySpent() {
730 // Must make a copy of the hash here since the iterator
731 // is replaced and taking its address directly would
732 // result in all of the entries pointing to the same
733 // memory location and thus all be the final hash.
734 hashCopy := originHash
735 missingParents = append(missingParents, &hashCopy)
738 if len(missingParents) > 0 {
739 return missingParents, nil, nil
742 // Don't allow the transaction into the mempool unless its sequence
743 // lock is active, meaning that it'll be allowed into the next block
744 // with respect to its defined relative lock times.
745 sequenceLock, err := mp.cfg.CalcSequenceLock(tx, utxoView)
747 if cerr, ok := err.(blockchain.RuleError); ok {
748 return nil, nil, chainRuleError(cerr)
752 if !blockchain.SequenceLockActive(sequenceLock, nextBlockHeight,
754 return nil, nil, txRuleError(wire.RejectNonstandard,
755 "transaction's sequence locks on inputs not met")
758 // Perform several checks on the transaction inputs using the invariant
759 // rules in blockchain for what transactions are allowed into blocks.
760 // Also returns the fees associated with the transaction which will be
762 txFee, err := blockchain.CheckTransactionInputs(tx, nextBlockHeight,
763 utxoView, mp.cfg.ChainParams)
765 if cerr, ok := err.(blockchain.RuleError); ok {
766 return nil, nil, chainRuleError(cerr)
771 // Don't allow transactions with non-standard inputs if the network
772 // parameters forbid their acceptance.
773 if !mp.cfg.Policy.AcceptNonStd {
774 err := checkInputsStandard(tx, utxoView)
776 // Attempt to extract a reject code from the error so
777 // it can be retained. When not possible, fall back to
778 // a non standard error.
779 rejectCode, found := extractRejectCode(err)
781 rejectCode = wire.RejectNonstandard
783 str := fmt.Sprintf("transaction %v has a non-standard "+
784 "input: %v", txHash, err)
785 return nil, nil, txRuleError(rejectCode, str)
789 // NOTE: if you modify this code to accept non-standard transactions,
790 // you should add code here to check that the transaction does a
791 // reasonable number of ECDSA signature verifications.
793 // Don't allow transactions with an excessive number of signature
794 // operations which would result in making it impossible to mine. Since
795 // the coinbase address itself can contain signature operations, the
796 // maximum allowed signature operations per transaction is less than
797 // the maximum allowed signature operations per block.
798 // TODO(roasbeef): last bool should be conditional on segwit activation
799 sigOpCost, err := blockchain.GetSigOpCost(tx, false, utxoView, true, true)
801 if cerr, ok := err.(blockchain.RuleError); ok {
802 return nil, nil, chainRuleError(cerr)
806 if sigOpCost > mp.cfg.Policy.MaxSigOpCostPerTx {
807 str := fmt.Sprintf("transaction %v sigop cost is too high: %d > %d",
808 txHash, sigOpCost, mp.cfg.Policy.MaxSigOpCostPerTx)
809 return nil, nil, txRuleError(wire.RejectNonstandard, str)
812 // Don't allow transactions with fees too low to get into a mined block.
814 // Most miners allow a free transaction area in blocks they mine to go
815 // alongside the area used for high-priority transactions as well as
816 // transactions with fees. A transaction size of up to 1000 bytes is
817 // considered safe to go into this section. Further, the minimum fee
818 // calculated below on its own would encourage several small
819 // transactions to avoid fees rather than one single larger transaction
820 // which is more desirable. Therefore, as long as the size of the
821 // transaction does not exceeed 1000 less than the reserved space for
822 // high-priority transactions, don't require a fee for it.
823 serializedSize := GetTxVirtualSize(tx)
824 minFee := calcMinRequiredTxRelayFee(serializedSize,
825 mp.cfg.Policy.MinRelayTxFee)
826 if serializedSize >= (DefaultBlockPrioritySize-1000) && txFee < minFee {
827 str := fmt.Sprintf("transaction %v has %d fees which is under "+
828 "the required amount of %d", txHash, txFee,
830 return nil, nil, txRuleError(wire.RejectInsufficientFee, str)
833 // Require that free transactions have sufficient priority to be mined
834 // in the next block. Transactions which are being added back to the
835 // memory pool from blocks that have been disconnected during a reorg
837 if isNew && !mp.cfg.Policy.DisableRelayPriority && txFee < minFee {
838 currentPriority := mining.CalcPriority(tx.MsgTx(), utxoView,
840 if currentPriority <= mining.MinHighPriority {
841 str := fmt.Sprintf("transaction %v has insufficient "+
842 "priority (%g <= %g)", txHash,
843 currentPriority, mining.MinHighPriority)
844 return nil, nil, txRuleError(wire.RejectInsufficientFee, str)
848 // Free-to-relay transactions are rate limited here to prevent
849 // penny-flooding with tiny transactions as a form of attack.
850 if rateLimit && txFee < minFee {
851 nowUnix := time.Now().Unix()
852 // Decay passed data with an exponentially decaying ~10 minute
853 // window - matches bitcoind handling.
854 mp.pennyTotal *= math.Pow(1.0-1.0/600.0,
855 float64(nowUnix-mp.lastPennyUnix))
856 mp.lastPennyUnix = nowUnix
858 // Are we still over the limit?
859 if mp.pennyTotal >= mp.cfg.Policy.FreeTxRelayLimit*10*1000 {
860 str := fmt.Sprintf("transaction %v has been rejected "+
861 "by the rate limiter due to low fees", txHash)
862 return nil, nil, txRuleError(wire.RejectInsufficientFee, str)
864 oldTotal := mp.pennyTotal
866 mp.pennyTotal += float64(serializedSize)
867 log.Tracef("rate limit: curTotal %v, nextTotal: %v, "+
868 "limit %v", oldTotal, mp.pennyTotal,
869 mp.cfg.Policy.FreeTxRelayLimit*10*1000)
872 // Verify crypto signatures for each input and reject the transaction if
874 err = blockchain.ValidateTransactionScripts(tx, utxoView,
875 txscript.StandardVerifyFlags, mp.cfg.SigCache,
878 if cerr, ok := err.(blockchain.RuleError); ok {
879 return nil, nil, chainRuleError(cerr)
884 // Add to transaction pool.
885 txD := mp.addTransaction(utxoView, tx, bestHeight, txFee)
887 log.Debugf("Accepted transaction %v (pool size: %v)", txHash,
893 // MaybeAcceptTransaction is the main workhorse for handling insertion of new
894 // free-standing transactions into a memory pool. It includes functionality
895 // such as rejecting duplicate transactions, ensuring transactions follow all
896 // rules, detecting orphan transactions, and insertion into the memory pool.
898 // If the transaction is an orphan (missing parent transactions), the
899 // transaction is NOT added to the orphan pool, but each unknown referenced
900 // parent is returned. Use ProcessTransaction instead if new orphans should
901 // be added to the orphan pool.
903 // This function is safe for concurrent access.
904 func (mp *TxPool) MaybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit bool) ([]*chainhash.Hash, *TxDesc, error) {
905 // Protect concurrent access.
907 hashes, txD, err := mp.maybeAcceptTransaction(tx, isNew, rateLimit, true)
910 return hashes, txD, err
913 // processOrphans is the internal function which implements the public
914 // ProcessOrphans. See the comment for ProcessOrphans for more details.
916 // This function MUST be called with the mempool lock held (for writes).
917 func (mp *TxPool) processOrphans(acceptedTx *btcutil.Tx) []*TxDesc {
918 var acceptedTxns []*TxDesc
920 // Start with processing at least the passed transaction.
921 processList := list.New()
922 processList.PushBack(acceptedTx)
923 for processList.Len() > 0 {
924 // Pop the transaction to process from the front of the list.
925 firstElement := processList.Remove(processList.Front())
926 processItem := firstElement.(*btcutil.Tx)
928 prevOut := wire.OutPoint{Hash: *processItem.Hash()}
929 for txOutIdx := range processItem.MsgTx().TxOut {
930 // Look up all orphans that redeem the output that is
931 // now available. This will typically only be one, but
932 // it could be multiple if the orphan pool contains
933 // double spends. While it may seem odd that the orphan
934 // pool would allow this since there can only possibly
935 // ultimately be a single redeemer, it's important to
936 // track it this way to prevent malicious actors from
937 // being able to purposely constructing orphans that
938 // would otherwise make outputs unspendable.
940 // Skip to the next available output if there are none.
941 prevOut.Index = uint32(txOutIdx)
942 orphans, exists := mp.orphansByPrev[prevOut]
947 // Potentially accept an orphan into the tx pool.
948 for _, tx := range orphans {
949 missing, txD, err := mp.maybeAcceptTransaction(
950 tx, true, true, false)
952 // The orphan is now invalid, so there
953 // is no way any other orphans which
954 // redeem any of its outputs can be
955 // accepted. Remove them.
956 mp.removeOrphan(tx, true)
960 // Transaction is still an orphan. Try the next
961 // orphan which redeems this output.
962 if len(missing) > 0 {
966 // Transaction was accepted into the main pool.
968 // Add it to the list of accepted transactions
969 // that are no longer orphans, remove it from
970 // the orphan pool, and add it to the list of
971 // transactions to process so any orphans that
972 // depend on it are handled too.
973 acceptedTxns = append(acceptedTxns, txD)
974 mp.removeOrphan(tx, false)
975 processList.PushBack(tx)
977 // Only one transaction for this outpoint can be
978 // accepted, so the rest are now double spends
979 // and are removed later.
985 // Recursively remove any orphans that also redeem any outputs redeemed
986 // by the accepted transactions since those are now definitive double
988 mp.removeOrphanDoubleSpends(acceptedTx)
989 for _, txD := range acceptedTxns {
990 mp.removeOrphanDoubleSpends(txD.Tx)
996 // ProcessOrphans determines if there are any orphans which depend on the passed
997 // transaction hash (it is possible that they are no longer orphans) and
998 // potentially accepts them to the memory pool. It repeats the process for the
999 // newly accepted transactions (to detect further orphans which may no longer be
1000 // orphans) until there are no more.
1002 // It returns a slice of transactions added to the mempool. A nil slice means
1003 // no transactions were moved from the orphan pool to the mempool.
1005 // This function is safe for concurrent access.
1006 func (mp *TxPool) ProcessOrphans(acceptedTx *btcutil.Tx) []*TxDesc {
1008 acceptedTxns := mp.processOrphans(acceptedTx)
1014 // ProcessTransaction is the main workhorse for handling insertion of new
1015 // free-standing transactions into the memory pool. It includes functionality
1016 // such as rejecting duplicate transactions, ensuring transactions follow all
1017 // rules, orphan transaction handling, and insertion into the memory pool.
1019 // It returns a slice of transactions added to the mempool. When the
1020 // error is nil, the list will include the passed transaction itself along
1021 // with any additional orphan transaactions that were added as a result of
1022 // the passed one being accepted.
1024 // This function is safe for concurrent access.
1025 func (mp *TxPool) ProcessTransaction(tx *btcutil.Tx, allowOrphan, rateLimit bool, tag Tag) ([]*TxDesc, error) {
1026 log.Tracef("Processing transaction %v", tx.Hash())
1028 // Protect concurrent access.
1030 defer mp.mtx.Unlock()
1032 // Potentially accept the transaction to the memory pool.
1033 missingParents, txD, err := mp.maybeAcceptTransaction(tx, true, rateLimit,
1039 if len(missingParents) == 0 {
1040 // Accept any orphan transactions that depend on this
1041 // transaction (they may no longer be orphans if all inputs
1042 // are now available) and repeat for those accepted
1043 // transactions until there are no more.
1044 newTxs := mp.processOrphans(tx)
1045 acceptedTxs := make([]*TxDesc, len(newTxs)+1)
1047 // Add the parent transaction first so remote nodes
1048 // do not add orphans.
1049 acceptedTxs[0] = txD
1050 copy(acceptedTxs[1:], newTxs)
1052 return acceptedTxs, nil
1055 // The transaction is an orphan (has inputs missing). Reject
1056 // it if the flag to allow orphans is not set.
1058 // Only use the first missing parent transaction in
1059 // the error message.
1061 // NOTE: RejectDuplicate is really not an accurate
1062 // reject code here, but it matches the reference
1063 // implementation and there isn't a better choice due
1064 // to the limited number of reject codes. Missing
1065 // inputs is assumed to mean they are already spent
1066 // which is not really always the case.
1067 str := fmt.Sprintf("orphan transaction %v references "+
1068 "outputs of unknown or fully-spent "+
1069 "transaction %v", tx.Hash(), missingParents[0])
1070 return nil, txRuleError(wire.RejectDuplicate, str)
1073 // Potentially add the orphan transaction to the orphan pool.
1074 err = mp.maybeAddOrphan(tx, tag)
1078 // Count returns the number of transactions in the main pool. It does not
1079 // include the orphan pool.
1081 // This function is safe for concurrent access.
1082 func (mp *TxPool) Count() int {
1084 count := len(mp.pool)
1090 // TxHashes returns a slice of hashes for all of the transactions in the memory
1093 // This function is safe for concurrent access.
1094 func (mp *TxPool) TxHashes() []*chainhash.Hash {
1096 hashes := make([]*chainhash.Hash, len(mp.pool))
1098 for hash := range mp.pool {
1100 hashes[i] = &hashCopy
1108 // TxDescs returns a slice of descriptors for all the transactions in the pool.
1109 // The descriptors are to be treated as read only.
1111 // This function is safe for concurrent access.
1112 func (mp *TxPool) TxDescs() []*TxDesc {
1114 descs := make([]*TxDesc, len(mp.pool))
1116 for _, desc := range mp.pool {
1125 // MiningDescs returns a slice of mining descriptors for all the transactions
1128 // This is part of the mining.TxSource interface implementation and is safe for
1129 // concurrent access as required by the interface contract.
1130 func (mp *TxPool) MiningDescs() []*mining.TxDesc {
1132 descs := make([]*mining.TxDesc, len(mp.pool))
1134 for _, desc := range mp.pool {
1135 descs[i] = &desc.TxDesc
1143 // RawMempoolVerbose returns all of the entries in the mempool as a fully
1144 // populated btcjson result.
1146 // This function is safe for concurrent access.
1147 func (mp *TxPool) RawMempoolVerbose() map[string]*btcjson.GetRawMempoolVerboseResult {
1149 defer mp.mtx.RUnlock()
1151 result := make(map[string]*btcjson.GetRawMempoolVerboseResult,
1153 bestHeight := mp.cfg.BestHeight()
1155 for _, desc := range mp.pool {
1156 // Calculate the current priority based on the inputs to
1157 // the transaction. Use zero if one or more of the
1158 // input transactions can't be found for some reason.
1160 var currentPriority float64
1161 utxos, err := mp.fetchInputUtxos(tx)
1163 currentPriority = mining.CalcPriority(tx.MsgTx(), utxos,
1167 mpd := &btcjson.GetRawMempoolVerboseResult{
1168 Size: int32(tx.MsgTx().SerializeSize()),
1169 Vsize: int32(GetTxVirtualSize(tx)),
1170 Fee: btcutil.Amount(desc.Fee).ToBTC(),
1171 Time: desc.Added.Unix(),
1172 Height: int64(desc.Height),
1173 StartingPriority: desc.StartingPriority,
1174 CurrentPriority: currentPriority,
1175 Depends: make([]string, 0),
1177 for _, txIn := range tx.MsgTx().TxIn {
1178 hash := &txIn.PreviousOutPoint.Hash
1179 if mp.haveTransaction(hash) {
1180 mpd.Depends = append(mpd.Depends,
1185 result[tx.Hash().String()] = mpd
1191 // LastUpdated returns the last time a transaction was added to or removed from
1192 // the main pool. It does not include the orphan pool.
1194 // This function is safe for concurrent access.
1195 func (mp *TxPool) LastUpdated() time.Time {
1196 return time.Unix(atomic.LoadInt64(&mp.lastUpdated), 0)
1199 // New returns a new memory pool for validating and storing standalone
1200 // transactions until they are mined into a block.
1201 func New(cfg *Config) *TxPool {
1204 pool: make(map[chainhash.Hash]*TxDesc),
1205 orphans: make(map[chainhash.Hash]*orphanTx),
1206 orphansByPrev: make(map[wire.OutPoint]map[chainhash.Hash]*btcutil.Tx),
1207 nextExpireScan: time.Now().Add(orphanExpireScanInterval),
1208 outpoints: make(map[wire.OutPoint]*btcutil.Tx),