github.com/btcsuite/btcd@v0.24.0/mempool/mempool.go (about)

     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.
     4  
     5  package mempool
     6  
     7  import (
     8  	"container/list"
     9  	"fmt"
    10  	"math"
    11  	"sync"
    12  	"sync/atomic"
    13  	"time"
    14  
    15  	"github.com/btcsuite/btcd/blockchain"
    16  	"github.com/btcsuite/btcd/blockchain/indexers"
    17  	"github.com/btcsuite/btcd/btcjson"
    18  	"github.com/btcsuite/btcd/btcutil"
    19  	"github.com/btcsuite/btcd/chaincfg"
    20  	"github.com/btcsuite/btcd/chaincfg/chainhash"
    21  	"github.com/btcsuite/btcd/mining"
    22  	"github.com/btcsuite/btcd/txscript"
    23  	"github.com/btcsuite/btcd/wire"
    24  )
    25  
    26  const (
    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
    32  
    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
    35  	// next scan.
    36  	orphanTTL = time.Minute * 15
    37  
    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
    41  
    42  	// MaxRBFSequence is the maximum sequence number an input can use to
    43  	// signal that the transaction spending it can be replaced using the
    44  	// Replace-By-Fee (RBF) policy.
    45  	MaxRBFSequence = 0xfffffffd
    46  
    47  	// MaxReplacementEvictions is the maximum number of transactions that
    48  	// can be evicted from the mempool when accepting a transaction
    49  	// replacement.
    50  	MaxReplacementEvictions = 100
    51  )
    52  
    53  // Tag represents an identifier to use for tagging orphan transactions.  The
    54  // caller may choose any scheme it desires, however it is common to use peer IDs
    55  // so that orphans can be identified by which peer first relayed them.
    56  type Tag uint64
    57  
    58  // Config is a descriptor containing the memory pool configuration.
    59  type Config struct {
    60  	// Policy defines the various mempool configuration options related
    61  	// to policy.
    62  	Policy Policy
    63  
    64  	// ChainParams identifies which chain parameters the txpool is
    65  	// associated with.
    66  	ChainParams *chaincfg.Params
    67  
    68  	// FetchUtxoView defines the function to use to fetch unspent
    69  	// transaction output information.
    70  	FetchUtxoView func(*btcutil.Tx) (*blockchain.UtxoViewpoint, error)
    71  
    72  	// BestHeight defines the function to use to access the block height of
    73  	// the current best chain.
    74  	BestHeight func() int32
    75  
    76  	// MedianTimePast defines the function to use in order to access the
    77  	// median time past calculated from the point-of-view of the current
    78  	// chain tip within the best chain.
    79  	MedianTimePast func() time.Time
    80  
    81  	// CalcSequenceLock defines the function to use in order to generate
    82  	// the current sequence lock for the given transaction using the passed
    83  	// utxo view.
    84  	CalcSequenceLock func(*btcutil.Tx, *blockchain.UtxoViewpoint) (*blockchain.SequenceLock, error)
    85  
    86  	// IsDeploymentActive returns true if the target deploymentID is
    87  	// active, and false otherwise. The mempool uses this function to gauge
    88  	// if transactions using new to be soft-forked rules should be allowed
    89  	// into the mempool or not.
    90  	IsDeploymentActive func(deploymentID uint32) (bool, error)
    91  
    92  	// SigCache defines a signature cache to use.
    93  	SigCache *txscript.SigCache
    94  
    95  	// HashCache defines the transaction hash mid-state cache to use.
    96  	HashCache *txscript.HashCache
    97  
    98  	// AddrIndex defines the optional address index instance to use for
    99  	// indexing the unconfirmed transactions in the memory pool.
   100  	// This can be nil if the address index is not enabled.
   101  	AddrIndex *indexers.AddrIndex
   102  
   103  	// FeeEstimatator provides a feeEstimator. If it is not nil, the mempool
   104  	// records all new transactions it observes into the feeEstimator.
   105  	FeeEstimator *FeeEstimator
   106  }
   107  
   108  // Policy houses the policy (configuration parameters) which is used to
   109  // control the mempool.
   110  type Policy struct {
   111  	// MaxTxVersion is the transaction version that the mempool should
   112  	// accept.  All transactions above this version are rejected as
   113  	// non-standard.
   114  	MaxTxVersion int32
   115  
   116  	// DisableRelayPriority defines whether to relay free or low-fee
   117  	// transactions that do not have enough priority to be relayed.
   118  	DisableRelayPriority bool
   119  
   120  	// AcceptNonStd defines whether to accept non-standard transactions. If
   121  	// true, non-standard transactions will be accepted into the mempool.
   122  	// Otherwise, all non-standard transactions will be rejected.
   123  	AcceptNonStd bool
   124  
   125  	// FreeTxRelayLimit defines the given amount in thousands of bytes
   126  	// per minute that transactions with no fee are rate limited to.
   127  	FreeTxRelayLimit float64
   128  
   129  	// MaxOrphanTxs is the maximum number of orphan transactions
   130  	// that can be queued.
   131  	MaxOrphanTxs int
   132  
   133  	// MaxOrphanTxSize is the maximum size allowed for orphan transactions.
   134  	// This helps prevent memory exhaustion attacks from sending a lot of
   135  	// of big orphans.
   136  	MaxOrphanTxSize int
   137  
   138  	// MaxSigOpCostPerTx is the cumulative maximum cost of all the signature
   139  	// operations in a single transaction we will relay or mine.  It is a
   140  	// fraction of the max signature operations for a block.
   141  	MaxSigOpCostPerTx int
   142  
   143  	// MinRelayTxFee defines the minimum transaction fee in BTC/kB to be
   144  	// considered a non-zero fee.
   145  	MinRelayTxFee btcutil.Amount
   146  
   147  	// RejectReplacement, if true, rejects accepting replacement
   148  	// transactions using the Replace-By-Fee (RBF) signaling policy into
   149  	// the mempool.
   150  	RejectReplacement bool
   151  }
   152  
   153  // TxDesc is a descriptor containing a transaction in the mempool along with
   154  // additional metadata.
   155  type TxDesc struct {
   156  	mining.TxDesc
   157  
   158  	// StartingPriority is the priority of the transaction when it was added
   159  	// to the pool.
   160  	StartingPriority float64
   161  }
   162  
   163  // orphanTx is normal transaction that references an ancestor transaction
   164  // that is not yet available.  It also contains additional information related
   165  // to it such as an expiration time to help prevent caching the orphan forever.
   166  type orphanTx struct {
   167  	tx         *btcutil.Tx
   168  	tag        Tag
   169  	expiration time.Time
   170  }
   171  
   172  // TxPool is used as a source of transactions that need to be mined into blocks
   173  // and relayed to other peers.  It is safe for concurrent access from multiple
   174  // peers.
   175  type TxPool struct {
   176  	// The following variables must only be used atomically.
   177  	lastUpdated int64 // last time pool was updated
   178  
   179  	mtx           sync.RWMutex
   180  	cfg           Config
   181  	pool          map[chainhash.Hash]*TxDesc
   182  	orphans       map[chainhash.Hash]*orphanTx
   183  	orphansByPrev map[wire.OutPoint]map[chainhash.Hash]*btcutil.Tx
   184  	outpoints     map[wire.OutPoint]*btcutil.Tx
   185  	pennyTotal    float64 // exponentially decaying total for penny spends.
   186  	lastPennyUnix int64   // unix time of last ``penny spend''
   187  
   188  	// nextExpireScan is the time after which the orphan pool will be
   189  	// scanned in order to evict orphans.  This is NOT a hard deadline as
   190  	// the scan will only run when an orphan is added to the pool as opposed
   191  	// to on an unconditional timer.
   192  	nextExpireScan time.Time
   193  }
   194  
   195  // Ensure the TxPool type implements the mining.TxSource interface.
   196  var _ mining.TxSource = (*TxPool)(nil)
   197  
   198  // removeOrphan is the internal function which implements the public
   199  // RemoveOrphan.  See the comment for RemoveOrphan for more details.
   200  //
   201  // This function MUST be called with the mempool lock held (for writes).
   202  func (mp *TxPool) removeOrphan(tx *btcutil.Tx, removeRedeemers bool) {
   203  	// Nothing to do if passed tx is not an orphan.
   204  	txHash := tx.Hash()
   205  	otx, exists := mp.orphans[*txHash]
   206  	if !exists {
   207  		return
   208  	}
   209  
   210  	// Remove the reference from the previous orphan index.
   211  	for _, txIn := range otx.tx.MsgTx().TxIn {
   212  		orphans, exists := mp.orphansByPrev[txIn.PreviousOutPoint]
   213  		if exists {
   214  			delete(orphans, *txHash)
   215  
   216  			// Remove the map entry altogether if there are no
   217  			// longer any orphans which depend on it.
   218  			if len(orphans) == 0 {
   219  				delete(mp.orphansByPrev, txIn.PreviousOutPoint)
   220  			}
   221  		}
   222  	}
   223  
   224  	// Remove any orphans that redeem outputs from this one if requested.
   225  	if removeRedeemers {
   226  		prevOut := wire.OutPoint{Hash: *txHash}
   227  		for txOutIdx := range tx.MsgTx().TxOut {
   228  			prevOut.Index = uint32(txOutIdx)
   229  			for _, orphan := range mp.orphansByPrev[prevOut] {
   230  				mp.removeOrphan(orphan, true)
   231  			}
   232  		}
   233  	}
   234  
   235  	// Remove the transaction from the orphan pool.
   236  	delete(mp.orphans, *txHash)
   237  }
   238  
   239  // RemoveOrphan removes the passed orphan transaction from the orphan pool and
   240  // previous orphan index.
   241  //
   242  // This function is safe for concurrent access.
   243  func (mp *TxPool) RemoveOrphan(tx *btcutil.Tx) {
   244  	mp.mtx.Lock()
   245  	mp.removeOrphan(tx, false)
   246  	mp.mtx.Unlock()
   247  }
   248  
   249  // RemoveOrphansByTag removes all orphan transactions tagged with the provided
   250  // identifier.
   251  //
   252  // This function is safe for concurrent access.
   253  func (mp *TxPool) RemoveOrphansByTag(tag Tag) uint64 {
   254  	var numEvicted uint64
   255  	mp.mtx.Lock()
   256  	for _, otx := range mp.orphans {
   257  		if otx.tag == tag {
   258  			mp.removeOrphan(otx.tx, true)
   259  			numEvicted++
   260  		}
   261  	}
   262  	mp.mtx.Unlock()
   263  	return numEvicted
   264  }
   265  
   266  // limitNumOrphans limits the number of orphan transactions by evicting a random
   267  // orphan if adding a new one would cause it to overflow the max allowed.
   268  //
   269  // This function MUST be called with the mempool lock held (for writes).
   270  func (mp *TxPool) limitNumOrphans() error {
   271  	// Scan through the orphan pool and remove any expired orphans when it's
   272  	// time.  This is done for efficiency so the scan only happens
   273  	// periodically instead of on every orphan added to the pool.
   274  	if now := time.Now(); now.After(mp.nextExpireScan) {
   275  		origNumOrphans := len(mp.orphans)
   276  		for _, otx := range mp.orphans {
   277  			if now.After(otx.expiration) {
   278  				// Remove redeemers too because the missing
   279  				// parents are very unlikely to ever materialize
   280  				// since the orphan has already been around more
   281  				// than long enough for them to be delivered.
   282  				mp.removeOrphan(otx.tx, true)
   283  			}
   284  		}
   285  
   286  		// Set next expiration scan to occur after the scan interval.
   287  		mp.nextExpireScan = now.Add(orphanExpireScanInterval)
   288  
   289  		numOrphans := len(mp.orphans)
   290  		if numExpired := origNumOrphans - numOrphans; numExpired > 0 {
   291  			log.Debugf("Expired %d %s (remaining: %d)", numExpired,
   292  				pickNoun(numExpired, "orphan", "orphans"),
   293  				numOrphans)
   294  		}
   295  	}
   296  
   297  	// Nothing to do if adding another orphan will not cause the pool to
   298  	// exceed the limit.
   299  	if len(mp.orphans)+1 <= mp.cfg.Policy.MaxOrphanTxs {
   300  		return nil
   301  	}
   302  
   303  	// Remove a random entry from the map.  For most compilers, Go's
   304  	// range statement iterates starting at a random item although
   305  	// that is not 100% guaranteed by the spec.  The iteration order
   306  	// is not important here because an adversary would have to be
   307  	// able to pull off preimage attacks on the hashing function in
   308  	// order to target eviction of specific entries anyways.
   309  	for _, otx := range mp.orphans {
   310  		// Don't remove redeemers in the case of a random eviction since
   311  		// it is quite possible it might be needed again shortly.
   312  		mp.removeOrphan(otx.tx, false)
   313  		break
   314  	}
   315  
   316  	return nil
   317  }
   318  
   319  // addOrphan adds an orphan transaction to the orphan pool.
   320  //
   321  // This function MUST be called with the mempool lock held (for writes).
   322  func (mp *TxPool) addOrphan(tx *btcutil.Tx, tag Tag) {
   323  	// Nothing to do if no orphans are allowed.
   324  	if mp.cfg.Policy.MaxOrphanTxs <= 0 {
   325  		return
   326  	}
   327  
   328  	// Limit the number orphan transactions to prevent memory exhaustion.
   329  	// This will periodically remove any expired orphans and evict a random
   330  	// orphan if space is still needed.
   331  	mp.limitNumOrphans()
   332  
   333  	mp.orphans[*tx.Hash()] = &orphanTx{
   334  		tx:         tx,
   335  		tag:        tag,
   336  		expiration: time.Now().Add(orphanTTL),
   337  	}
   338  	for _, txIn := range tx.MsgTx().TxIn {
   339  		if _, exists := mp.orphansByPrev[txIn.PreviousOutPoint]; !exists {
   340  			mp.orphansByPrev[txIn.PreviousOutPoint] =
   341  				make(map[chainhash.Hash]*btcutil.Tx)
   342  		}
   343  		mp.orphansByPrev[txIn.PreviousOutPoint][*tx.Hash()] = tx
   344  	}
   345  
   346  	log.Debugf("Stored orphan transaction %v (total: %d)", tx.Hash(),
   347  		len(mp.orphans))
   348  }
   349  
   350  // maybeAddOrphan potentially adds an orphan to the orphan pool.
   351  //
   352  // This function MUST be called with the mempool lock held (for writes).
   353  func (mp *TxPool) maybeAddOrphan(tx *btcutil.Tx, tag Tag) error {
   354  	// Ignore orphan transactions that are too large.  This helps avoid
   355  	// a memory exhaustion attack based on sending a lot of really large
   356  	// orphans.  In the case there is a valid transaction larger than this,
   357  	// it will ultimtely be rebroadcast after the parent transactions
   358  	// have been mined or otherwise received.
   359  	//
   360  	// Note that the number of orphan transactions in the orphan pool is
   361  	// also limited, so this equates to a maximum memory used of
   362  	// mp.cfg.Policy.MaxOrphanTxSize * mp.cfg.Policy.MaxOrphanTxs (which is ~5MB
   363  	// using the default values at the time this comment was written).
   364  	serializedLen := tx.MsgTx().SerializeSize()
   365  	if serializedLen > mp.cfg.Policy.MaxOrphanTxSize {
   366  		str := fmt.Sprintf("orphan transaction size of %d bytes is "+
   367  			"larger than max allowed size of %d bytes",
   368  			serializedLen, mp.cfg.Policy.MaxOrphanTxSize)
   369  		return txRuleError(wire.RejectNonstandard, str)
   370  	}
   371  
   372  	// Add the orphan if the none of the above disqualified it.
   373  	mp.addOrphan(tx, tag)
   374  
   375  	return nil
   376  }
   377  
   378  // removeOrphanDoubleSpends removes all orphans which spend outputs spent by the
   379  // passed transaction from the orphan pool.  Removing those orphans then leads
   380  // to removing all orphans which rely on them, recursively.  This is necessary
   381  // when a transaction is added to the main pool because it may spend outputs
   382  // that orphans also spend.
   383  //
   384  // This function MUST be called with the mempool lock held (for writes).
   385  func (mp *TxPool) removeOrphanDoubleSpends(tx *btcutil.Tx) {
   386  	msgTx := tx.MsgTx()
   387  	for _, txIn := range msgTx.TxIn {
   388  		for _, orphan := range mp.orphansByPrev[txIn.PreviousOutPoint] {
   389  			mp.removeOrphan(orphan, true)
   390  		}
   391  	}
   392  }
   393  
   394  // isTransactionInPool returns whether or not the passed transaction already
   395  // exists in the main pool.
   396  //
   397  // This function MUST be called with the mempool lock held (for reads).
   398  func (mp *TxPool) isTransactionInPool(hash *chainhash.Hash) bool {
   399  	if _, exists := mp.pool[*hash]; exists {
   400  		return true
   401  	}
   402  
   403  	return false
   404  }
   405  
   406  // IsTransactionInPool returns whether or not the passed transaction already
   407  // exists in the main pool.
   408  //
   409  // This function is safe for concurrent access.
   410  func (mp *TxPool) IsTransactionInPool(hash *chainhash.Hash) bool {
   411  	// Protect concurrent access.
   412  	mp.mtx.RLock()
   413  	inPool := mp.isTransactionInPool(hash)
   414  	mp.mtx.RUnlock()
   415  
   416  	return inPool
   417  }
   418  
   419  // isOrphanInPool returns whether or not the passed transaction already exists
   420  // in the orphan pool.
   421  //
   422  // This function MUST be called with the mempool lock held (for reads).
   423  func (mp *TxPool) isOrphanInPool(hash *chainhash.Hash) bool {
   424  	if _, exists := mp.orphans[*hash]; exists {
   425  		return true
   426  	}
   427  
   428  	return false
   429  }
   430  
   431  // IsOrphanInPool returns whether or not the passed transaction already exists
   432  // in the orphan pool.
   433  //
   434  // This function is safe for concurrent access.
   435  func (mp *TxPool) IsOrphanInPool(hash *chainhash.Hash) bool {
   436  	// Protect concurrent access.
   437  	mp.mtx.RLock()
   438  	inPool := mp.isOrphanInPool(hash)
   439  	mp.mtx.RUnlock()
   440  
   441  	return inPool
   442  }
   443  
   444  // haveTransaction returns whether or not the passed transaction already exists
   445  // in the main pool or in the orphan pool.
   446  //
   447  // This function MUST be called with the mempool lock held (for reads).
   448  func (mp *TxPool) haveTransaction(hash *chainhash.Hash) bool {
   449  	return mp.isTransactionInPool(hash) || mp.isOrphanInPool(hash)
   450  }
   451  
   452  // HaveTransaction returns whether or not the passed transaction already exists
   453  // in the main pool or in the orphan pool.
   454  //
   455  // This function is safe for concurrent access.
   456  func (mp *TxPool) HaveTransaction(hash *chainhash.Hash) bool {
   457  	// Protect concurrent access.
   458  	mp.mtx.RLock()
   459  	haveTx := mp.haveTransaction(hash)
   460  	mp.mtx.RUnlock()
   461  
   462  	return haveTx
   463  }
   464  
   465  // removeTransaction is the internal function which implements the public
   466  // RemoveTransaction.  See the comment for RemoveTransaction for more details.
   467  //
   468  // This function MUST be called with the mempool lock held (for writes).
   469  func (mp *TxPool) removeTransaction(tx *btcutil.Tx, removeRedeemers bool) {
   470  	txHash := tx.Hash()
   471  	if removeRedeemers {
   472  		// Remove any transactions which rely on this one.
   473  		for i := uint32(0); i < uint32(len(tx.MsgTx().TxOut)); i++ {
   474  			prevOut := wire.OutPoint{Hash: *txHash, Index: i}
   475  			if txRedeemer, exists := mp.outpoints[prevOut]; exists {
   476  				mp.removeTransaction(txRedeemer, true)
   477  			}
   478  		}
   479  	}
   480  
   481  	// Remove the transaction if needed.
   482  	if txDesc, exists := mp.pool[*txHash]; exists {
   483  		// Remove unconfirmed address index entries associated with the
   484  		// transaction if enabled.
   485  		if mp.cfg.AddrIndex != nil {
   486  			mp.cfg.AddrIndex.RemoveUnconfirmedTx(txHash)
   487  		}
   488  
   489  		// Mark the referenced outpoints as unspent by the pool.
   490  		for _, txIn := range txDesc.Tx.MsgTx().TxIn {
   491  			delete(mp.outpoints, txIn.PreviousOutPoint)
   492  		}
   493  		delete(mp.pool, *txHash)
   494  		atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
   495  	}
   496  }
   497  
   498  // RemoveTransaction removes the passed transaction from the mempool. When the
   499  // removeRedeemers flag is set, any transactions that redeem outputs from the
   500  // removed transaction will also be removed recursively from the mempool, as
   501  // they would otherwise become orphans.
   502  //
   503  // This function is safe for concurrent access.
   504  func (mp *TxPool) RemoveTransaction(tx *btcutil.Tx, removeRedeemers bool) {
   505  	// Protect concurrent access.
   506  	mp.mtx.Lock()
   507  	mp.removeTransaction(tx, removeRedeemers)
   508  	mp.mtx.Unlock()
   509  }
   510  
   511  // RemoveDoubleSpends removes all transactions which spend outputs spent by the
   512  // passed transaction from the memory pool.  Removing those transactions then
   513  // leads to removing all transactions which rely on them, recursively.  This is
   514  // necessary when a block is connected to the main chain because the block may
   515  // contain transactions which were previously unknown to the memory pool.
   516  //
   517  // This function is safe for concurrent access.
   518  func (mp *TxPool) RemoveDoubleSpends(tx *btcutil.Tx) {
   519  	// Protect concurrent access.
   520  	mp.mtx.Lock()
   521  	for _, txIn := range tx.MsgTx().TxIn {
   522  		if txRedeemer, ok := mp.outpoints[txIn.PreviousOutPoint]; ok {
   523  			if !txRedeemer.Hash().IsEqual(tx.Hash()) {
   524  				mp.removeTransaction(txRedeemer, true)
   525  			}
   526  		}
   527  	}
   528  	mp.mtx.Unlock()
   529  }
   530  
   531  // addTransaction adds the passed transaction to the memory pool.  It should
   532  // not be called directly as it doesn't perform any validation.  This is a
   533  // helper for maybeAcceptTransaction.
   534  //
   535  // This function MUST be called with the mempool lock held (for writes).
   536  func (mp *TxPool) addTransaction(utxoView *blockchain.UtxoViewpoint, tx *btcutil.Tx, height int32, fee int64) *TxDesc {
   537  	// Add the transaction to the pool and mark the referenced outpoints
   538  	// as spent by the pool.
   539  	txD := &TxDesc{
   540  		TxDesc: mining.TxDesc{
   541  			Tx:       tx,
   542  			Added:    time.Now(),
   543  			Height:   height,
   544  			Fee:      fee,
   545  			FeePerKB: fee * 1000 / GetTxVirtualSize(tx),
   546  		},
   547  		StartingPriority: mining.CalcPriority(tx.MsgTx(), utxoView, height),
   548  	}
   549  
   550  	mp.pool[*tx.Hash()] = txD
   551  	for _, txIn := range tx.MsgTx().TxIn {
   552  		mp.outpoints[txIn.PreviousOutPoint] = tx
   553  	}
   554  	atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
   555  
   556  	// Add unconfirmed address index entries associated with the transaction
   557  	// if enabled.
   558  	if mp.cfg.AddrIndex != nil {
   559  		mp.cfg.AddrIndex.AddUnconfirmedTx(tx, utxoView)
   560  	}
   561  
   562  	// Record this tx for fee estimation if enabled.
   563  	if mp.cfg.FeeEstimator != nil {
   564  		mp.cfg.FeeEstimator.ObserveTransaction(txD)
   565  	}
   566  
   567  	return txD
   568  }
   569  
   570  // checkPoolDoubleSpend checks whether or not the passed transaction is
   571  // attempting to spend coins already spent by other transactions in the pool.
   572  // If it does, we'll check whether each of those transactions are signaling for
   573  // replacement. If just one of them isn't, an error is returned. Otherwise, a
   574  // boolean is returned signaling that the transaction is a replacement. Note it
   575  // does not check for double spends against transactions already in the main
   576  // chain.
   577  //
   578  // This function MUST be called with the mempool lock held (for reads).
   579  func (mp *TxPool) checkPoolDoubleSpend(tx *btcutil.Tx) (bool, error) {
   580  	var isReplacement bool
   581  	for _, txIn := range tx.MsgTx().TxIn {
   582  		conflict, ok := mp.outpoints[txIn.PreviousOutPoint]
   583  		if !ok {
   584  			continue
   585  		}
   586  
   587  		// Reject the transaction if we don't accept replacement
   588  		// transactions or if it doesn't signal replacement.
   589  		if mp.cfg.Policy.RejectReplacement ||
   590  			!mp.signalsReplacement(conflict, nil) {
   591  			str := fmt.Sprintf("output %v already spent by "+
   592  				"transaction %v in the memory pool",
   593  				txIn.PreviousOutPoint, conflict.Hash())
   594  			return false, txRuleError(wire.RejectDuplicate, str)
   595  		}
   596  
   597  		isReplacement = true
   598  	}
   599  
   600  	return isReplacement, nil
   601  }
   602  
   603  // signalsReplacement determines if a transaction is signaling that it can be
   604  // replaced using the Replace-By-Fee (RBF) policy. This policy specifies two
   605  // ways a transaction can signal that it is replaceable:
   606  //
   607  // Explicit signaling: A transaction is considered to have opted in to allowing
   608  // replacement of itself if any of its inputs have a sequence number less than
   609  // 0xfffffffe.
   610  //
   611  // Inherited signaling: Transactions that don't explicitly signal replaceability
   612  // are replaceable under this policy for as long as any one of their ancestors
   613  // signals replaceability and remains unconfirmed.
   614  //
   615  // The cache is optional and serves as an optimization to avoid visiting
   616  // transactions we've already determined don't signal replacement.
   617  //
   618  // This function MUST be called with the mempool lock held (for reads).
   619  func (mp *TxPool) signalsReplacement(tx *btcutil.Tx,
   620  	cache map[chainhash.Hash]struct{}) bool {
   621  
   622  	// If a cache was not provided, we'll initialize one now to use for the
   623  	// recursive calls.
   624  	if cache == nil {
   625  		cache = make(map[chainhash.Hash]struct{})
   626  	}
   627  
   628  	for _, txIn := range tx.MsgTx().TxIn {
   629  		if txIn.Sequence <= MaxRBFSequence {
   630  			return true
   631  		}
   632  
   633  		hash := txIn.PreviousOutPoint.Hash
   634  		unconfirmedAncestor, ok := mp.pool[hash]
   635  		if !ok {
   636  			continue
   637  		}
   638  
   639  		// If we've already determined the transaction doesn't signal
   640  		// replacement, we can avoid visiting it again.
   641  		if _, ok := cache[hash]; ok {
   642  			continue
   643  		}
   644  
   645  		if mp.signalsReplacement(unconfirmedAncestor.Tx, cache) {
   646  			return true
   647  		}
   648  
   649  		// Since the transaction doesn't signal replacement, we'll cache
   650  		// its result to ensure we don't attempt to determine so again.
   651  		cache[hash] = struct{}{}
   652  	}
   653  
   654  	return false
   655  }
   656  
   657  // txAncestors returns all of the unconfirmed ancestors of the given
   658  // transaction. Given transactions A, B, and C where C spends B and B spends A,
   659  // A and B are considered ancestors of C.
   660  //
   661  // The cache is optional and serves as an optimization to avoid visiting
   662  // transactions we've already determined ancestors of.
   663  //
   664  // This function MUST be called with the mempool lock held (for reads).
   665  func (mp *TxPool) txAncestors(tx *btcutil.Tx,
   666  	cache map[chainhash.Hash]map[chainhash.Hash]*btcutil.Tx) map[chainhash.Hash]*btcutil.Tx {
   667  
   668  	// If a cache was not provided, we'll initialize one now to use for the
   669  	// recursive calls.
   670  	if cache == nil {
   671  		cache = make(map[chainhash.Hash]map[chainhash.Hash]*btcutil.Tx)
   672  	}
   673  
   674  	ancestors := make(map[chainhash.Hash]*btcutil.Tx)
   675  	for _, txIn := range tx.MsgTx().TxIn {
   676  		parent, ok := mp.pool[txIn.PreviousOutPoint.Hash]
   677  		if !ok {
   678  			continue
   679  		}
   680  		ancestors[*parent.Tx.Hash()] = parent.Tx
   681  
   682  		// Determine if the ancestors of this ancestor have already been
   683  		// computed. If they haven't, we'll do so now and cache them to
   684  		// use them later on if necessary.
   685  		moreAncestors, ok := cache[*parent.Tx.Hash()]
   686  		if !ok {
   687  			moreAncestors = mp.txAncestors(parent.Tx, cache)
   688  			cache[*parent.Tx.Hash()] = moreAncestors
   689  		}
   690  
   691  		for hash, ancestor := range moreAncestors {
   692  			ancestors[hash] = ancestor
   693  		}
   694  	}
   695  
   696  	return ancestors
   697  }
   698  
   699  // txDescendants returns all of the unconfirmed descendants of the given
   700  // transaction. Given transactions A, B, and C where C spends B and B spends A,
   701  // B and C are considered descendants of A. A cache can be provided in order to
   702  // easily retrieve the descendants of transactions we've already determined the
   703  // descendants of.
   704  //
   705  // This function MUST be called with the mempool lock held (for reads).
   706  func (mp *TxPool) txDescendants(tx *btcutil.Tx,
   707  	cache map[chainhash.Hash]map[chainhash.Hash]*btcutil.Tx) map[chainhash.Hash]*btcutil.Tx {
   708  
   709  	// If a cache was not provided, we'll initialize one now to use for the
   710  	// recursive calls.
   711  	if cache == nil {
   712  		cache = make(map[chainhash.Hash]map[chainhash.Hash]*btcutil.Tx)
   713  	}
   714  
   715  	// We'll go through all of the outputs of the transaction to determine
   716  	// if they are spent by any other mempool transactions.
   717  	descendants := make(map[chainhash.Hash]*btcutil.Tx)
   718  	op := wire.OutPoint{Hash: *tx.Hash()}
   719  	for i := range tx.MsgTx().TxOut {
   720  		op.Index = uint32(i)
   721  		descendant, ok := mp.outpoints[op]
   722  		if !ok {
   723  			continue
   724  		}
   725  		descendants[*descendant.Hash()] = descendant
   726  
   727  		// Determine if the descendants of this descendant have already
   728  		// been computed. If they haven't, we'll do so now and cache
   729  		// them to use them later on if necessary.
   730  		moreDescendants, ok := cache[*descendant.Hash()]
   731  		if !ok {
   732  			moreDescendants = mp.txDescendants(descendant, cache)
   733  			cache[*descendant.Hash()] = moreDescendants
   734  		}
   735  
   736  		for _, moreDescendant := range moreDescendants {
   737  			descendants[*moreDescendant.Hash()] = moreDescendant
   738  		}
   739  	}
   740  
   741  	return descendants
   742  }
   743  
   744  // txConflicts returns all of the unconfirmed transactions that would become
   745  // conflicts if we were to accept the given transaction into the mempool. An
   746  // unconfirmed conflict is known as a transaction that spends an output already
   747  // spent by a different transaction within the mempool. Any descendants of these
   748  // transactions are also considered conflicts as they would no longer exist.
   749  // These are generally not allowed except for transactions that signal RBF
   750  // support.
   751  //
   752  // This function MUST be called with the mempool lock held (for reads).
   753  func (mp *TxPool) txConflicts(tx *btcutil.Tx) map[chainhash.Hash]*btcutil.Tx {
   754  	conflicts := make(map[chainhash.Hash]*btcutil.Tx)
   755  	for _, txIn := range tx.MsgTx().TxIn {
   756  		conflict, ok := mp.outpoints[txIn.PreviousOutPoint]
   757  		if !ok {
   758  			continue
   759  		}
   760  		conflicts[*conflict.Hash()] = conflict
   761  		for hash, descendant := range mp.txDescendants(conflict, nil) {
   762  			conflicts[hash] = descendant
   763  		}
   764  	}
   765  	return conflicts
   766  }
   767  
   768  // CheckSpend checks whether the passed outpoint is already spent by a
   769  // transaction in the mempool. If that's the case the spending transaction will
   770  // be returned, if not nil will be returned.
   771  func (mp *TxPool) CheckSpend(op wire.OutPoint) *btcutil.Tx {
   772  	mp.mtx.RLock()
   773  	txR := mp.outpoints[op]
   774  	mp.mtx.RUnlock()
   775  
   776  	return txR
   777  }
   778  
   779  // fetchInputUtxos loads utxo details about the input transactions referenced by
   780  // the passed transaction.  First, it loads the details form the viewpoint of
   781  // the main chain, then it adjusts them based upon the contents of the
   782  // transaction pool.
   783  //
   784  // This function MUST be called with the mempool lock held (for reads).
   785  func (mp *TxPool) fetchInputUtxos(tx *btcutil.Tx) (*blockchain.UtxoViewpoint, error) {
   786  	utxoView, err := mp.cfg.FetchUtxoView(tx)
   787  	if err != nil {
   788  		return nil, err
   789  	}
   790  
   791  	// Attempt to populate any missing inputs from the transaction pool.
   792  	for _, txIn := range tx.MsgTx().TxIn {
   793  		prevOut := &txIn.PreviousOutPoint
   794  		entry := utxoView.LookupEntry(*prevOut)
   795  		if entry != nil && !entry.IsSpent() {
   796  			continue
   797  		}
   798  
   799  		if poolTxDesc, exists := mp.pool[prevOut.Hash]; exists {
   800  			// AddTxOut ignores out of range index values, so it is
   801  			// safe to call without bounds checking here.
   802  			utxoView.AddTxOut(poolTxDesc.Tx, prevOut.Index,
   803  				mining.UnminedHeight)
   804  		}
   805  	}
   806  
   807  	return utxoView, nil
   808  }
   809  
   810  // FetchTransaction returns the requested transaction from the transaction pool.
   811  // This only fetches from the main transaction pool and does not include
   812  // orphans.
   813  //
   814  // This function is safe for concurrent access.
   815  func (mp *TxPool) FetchTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error) {
   816  	// Protect concurrent access.
   817  	mp.mtx.RLock()
   818  	txDesc, exists := mp.pool[*txHash]
   819  	mp.mtx.RUnlock()
   820  
   821  	if exists {
   822  		return txDesc.Tx, nil
   823  	}
   824  
   825  	return nil, fmt.Errorf("transaction is not in the pool")
   826  }
   827  
   828  // validateReplacement determines whether a transaction is deemed as a valid
   829  // replacement of all of its conflicts according to the RBF policy. If it is
   830  // valid, no error is returned. Otherwise, an error is returned indicating what
   831  // went wrong.
   832  //
   833  // This function MUST be called with the mempool lock held (for reads).
   834  func (mp *TxPool) validateReplacement(tx *btcutil.Tx,
   835  	txFee int64) (map[chainhash.Hash]*btcutil.Tx, error) {
   836  
   837  	// First, we'll make sure the set of conflicting transactions doesn't
   838  	// exceed the maximum allowed.
   839  	conflicts := mp.txConflicts(tx)
   840  	if len(conflicts) > MaxReplacementEvictions {
   841  		str := fmt.Sprintf("replacement transaction %v evicts more "+
   842  			"transactions than permitted: max is %v, evicts %v",
   843  			tx.Hash(), MaxReplacementEvictions, len(conflicts))
   844  		return nil, txRuleError(wire.RejectNonstandard, str)
   845  	}
   846  
   847  	// The set of conflicts (transactions we'll replace) and ancestors
   848  	// should not overlap, otherwise the replacement would be spending an
   849  	// output that no longer exists.
   850  	for ancestorHash := range mp.txAncestors(tx, nil) {
   851  		if _, ok := conflicts[ancestorHash]; !ok {
   852  			continue
   853  		}
   854  		str := fmt.Sprintf("replacement transaction %v spends parent "+
   855  			"transaction %v", tx.Hash(), ancestorHash)
   856  		return nil, txRuleError(wire.RejectInvalid, str)
   857  	}
   858  
   859  	// The replacement should have a higher fee rate than each of the
   860  	// conflicting transactions and a higher absolute fee than the fee sum
   861  	// of all the conflicting transactions.
   862  	//
   863  	// We usually don't want to accept replacements with lower fee rates
   864  	// than what they replaced as that would lower the fee rate of the next
   865  	// block. Requiring that the fee rate always be increased is also an
   866  	// easy-to-reason about way to prevent DoS attacks via replacements.
   867  	var (
   868  		txSize           = GetTxVirtualSize(tx)
   869  		txFeeRate        = txFee * 1000 / txSize
   870  		conflictsFee     int64
   871  		conflictsParents = make(map[chainhash.Hash]struct{})
   872  	)
   873  	for hash, conflict := range conflicts {
   874  		if txFeeRate <= mp.pool[hash].FeePerKB {
   875  			str := fmt.Sprintf("replacement transaction %v has an "+
   876  				"insufficient fee rate: needs more than %v, "+
   877  				"has %v", tx.Hash(), mp.pool[hash].FeePerKB,
   878  				txFeeRate)
   879  			return nil, txRuleError(wire.RejectInsufficientFee, str)
   880  		}
   881  
   882  		conflictsFee += mp.pool[hash].Fee
   883  
   884  		// We'll track each conflict's parents to ensure the replacement
   885  		// isn't spending any new unconfirmed inputs.
   886  		for _, txIn := range conflict.MsgTx().TxIn {
   887  			conflictsParents[txIn.PreviousOutPoint.Hash] = struct{}{}
   888  		}
   889  	}
   890  
   891  	// It should also have an absolute fee greater than all of the
   892  	// transactions it intends to replace and pay for its own bandwidth,
   893  	// which is determined by our minimum relay fee.
   894  	minFee := calcMinRequiredTxRelayFee(txSize, mp.cfg.Policy.MinRelayTxFee)
   895  	if txFee < conflictsFee+minFee {
   896  		str := fmt.Sprintf("replacement transaction %v has an "+
   897  			"insufficient absolute fee: needs %v, has %v",
   898  			tx.Hash(), conflictsFee+minFee, txFee)
   899  		return nil, txRuleError(wire.RejectInsufficientFee, str)
   900  	}
   901  
   902  	// Finally, it should not spend any new unconfirmed outputs, other than
   903  	// the ones already included in the parents of the conflicting
   904  	// transactions it'll replace.
   905  	for _, txIn := range tx.MsgTx().TxIn {
   906  		if _, ok := conflictsParents[txIn.PreviousOutPoint.Hash]; ok {
   907  			continue
   908  		}
   909  		// Confirmed outputs are valid to spend in the replacement.
   910  		if _, ok := mp.pool[txIn.PreviousOutPoint.Hash]; !ok {
   911  			continue
   912  		}
   913  		str := fmt.Sprintf("replacement transaction spends new "+
   914  			"unconfirmed input %v not found in conflicting "+
   915  			"transactions", txIn.PreviousOutPoint)
   916  		return nil, txRuleError(wire.RejectInvalid, str)
   917  	}
   918  
   919  	return conflicts, nil
   920  }
   921  
   922  // maybeAcceptTransaction is the internal function which implements the public
   923  // MaybeAcceptTransaction.  See the comment for MaybeAcceptTransaction for
   924  // more details.
   925  //
   926  // This function MUST be called with the mempool lock held (for writes).
   927  func (mp *TxPool) maybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit, rejectDupOrphans bool) ([]*chainhash.Hash, *TxDesc, error) {
   928  	txHash := tx.Hash()
   929  
   930  	// If a transaction has witness data, and segwit isn't active yet, If
   931  	// segwit isn't active yet, then we won't accept it into the mempool as
   932  	// it can't be mined yet.
   933  	if tx.MsgTx().HasWitness() {
   934  		segwitActive, err := mp.cfg.IsDeploymentActive(chaincfg.DeploymentSegwit)
   935  		if err != nil {
   936  			return nil, nil, err
   937  		}
   938  
   939  		if !segwitActive {
   940  			simnetHint := ""
   941  			if mp.cfg.ChainParams.Net == wire.SimNet {
   942  				bestHeight := mp.cfg.BestHeight()
   943  				simnetHint = fmt.Sprintf(" (The threshold for segwit activation is 300 blocks on simnet, "+
   944  					"current best height is %d)", bestHeight)
   945  			}
   946  			str := fmt.Sprintf("transaction %v has witness data, "+
   947  				"but segwit isn't active yet%s", txHash, simnetHint)
   948  			return nil, nil, txRuleError(wire.RejectNonstandard, str)
   949  		}
   950  	}
   951  
   952  	// Don't accept the transaction if it already exists in the pool.  This
   953  	// applies to orphan transactions as well when the reject duplicate
   954  	// orphans flag is set.  This check is intended to be a quick check to
   955  	// weed out duplicates.
   956  	if mp.isTransactionInPool(txHash) || (rejectDupOrphans &&
   957  		mp.isOrphanInPool(txHash)) {
   958  
   959  		str := fmt.Sprintf("already have transaction %v", txHash)
   960  		return nil, nil, txRuleError(wire.RejectDuplicate, str)
   961  	}
   962  
   963  	// Perform preliminary sanity checks on the transaction.  This makes
   964  	// use of blockchain which contains the invariant rules for what
   965  	// transactions are allowed into blocks.
   966  	err := blockchain.CheckTransactionSanity(tx)
   967  	if err != nil {
   968  		if cerr, ok := err.(blockchain.RuleError); ok {
   969  			return nil, nil, chainRuleError(cerr)
   970  		}
   971  		return nil, nil, err
   972  	}
   973  
   974  	// A standalone transaction must not be a coinbase transaction.
   975  	if blockchain.IsCoinBase(tx) {
   976  		str := fmt.Sprintf("transaction %v is an individual coinbase",
   977  			txHash)
   978  		return nil, nil, txRuleError(wire.RejectInvalid, str)
   979  	}
   980  
   981  	// Get the current height of the main chain.  A standalone transaction
   982  	// will be mined into the next block at best, so its height is at least
   983  	// one more than the current height.
   984  	bestHeight := mp.cfg.BestHeight()
   985  	nextBlockHeight := bestHeight + 1
   986  
   987  	medianTimePast := mp.cfg.MedianTimePast()
   988  
   989  	// Don't allow non-standard transactions if the network parameters
   990  	// forbid their acceptance.
   991  	if !mp.cfg.Policy.AcceptNonStd {
   992  		err = CheckTransactionStandard(tx, nextBlockHeight,
   993  			medianTimePast, mp.cfg.Policy.MinRelayTxFee,
   994  			mp.cfg.Policy.MaxTxVersion)
   995  		if err != nil {
   996  			// Attempt to extract a reject code from the error so
   997  			// it can be retained.  When not possible, fall back to
   998  			// a non standard error.
   999  			rejectCode, found := extractRejectCode(err)
  1000  			if !found {
  1001  				rejectCode = wire.RejectNonstandard
  1002  			}
  1003  			str := fmt.Sprintf("transaction %v is not standard: %v",
  1004  				txHash, err)
  1005  			return nil, nil, txRuleError(rejectCode, str)
  1006  		}
  1007  	}
  1008  
  1009  	// The transaction may not use any of the same outputs as other
  1010  	// transactions already in the pool as that would ultimately result in a
  1011  	// double spend, unless those transactions signal for RBF. This check is
  1012  	// intended to be quick and therefore only detects double spends within
  1013  	// the transaction pool itself. The transaction could still be double
  1014  	// spending coins from the main chain at this point. There is a more
  1015  	// in-depth check that happens later after fetching the referenced
  1016  	// transaction inputs from the main chain which examines the actual
  1017  	// spend data and prevents double spends.
  1018  	isReplacement, err := mp.checkPoolDoubleSpend(tx)
  1019  	if err != nil {
  1020  		return nil, nil, err
  1021  	}
  1022  
  1023  	// Fetch all of the unspent transaction outputs referenced by the inputs
  1024  	// to this transaction.  This function also attempts to fetch the
  1025  	// transaction itself to be used for detecting a duplicate transaction
  1026  	// without needing to do a separate lookup.
  1027  	utxoView, err := mp.fetchInputUtxos(tx)
  1028  	if err != nil {
  1029  		if cerr, ok := err.(blockchain.RuleError); ok {
  1030  			return nil, nil, chainRuleError(cerr)
  1031  		}
  1032  		return nil, nil, err
  1033  	}
  1034  
  1035  	// Don't allow the transaction if it exists in the main chain and is
  1036  	// already fully spent.
  1037  	prevOut := wire.OutPoint{Hash: *txHash}
  1038  	for txOutIdx := range tx.MsgTx().TxOut {
  1039  		prevOut.Index = uint32(txOutIdx)
  1040  		entry := utxoView.LookupEntry(prevOut)
  1041  		if entry != nil && !entry.IsSpent() {
  1042  			return nil, nil, txRuleError(wire.RejectDuplicate,
  1043  				"transaction already exists")
  1044  		}
  1045  		utxoView.RemoveEntry(prevOut)
  1046  	}
  1047  
  1048  	// Transaction is an orphan if any of the referenced transaction outputs
  1049  	// don't exist or are already spent.  Adding orphans to the orphan pool
  1050  	// is not handled by this function, and the caller should use
  1051  	// maybeAddOrphan if this behavior is desired.
  1052  	var missingParents []*chainhash.Hash
  1053  	for outpoint, entry := range utxoView.Entries() {
  1054  		if entry == nil || entry.IsSpent() {
  1055  			// Must make a copy of the hash here since the iterator
  1056  			// is replaced and taking its address directly would
  1057  			// result in all the entries pointing to the same
  1058  			// memory location and thus all be the final hash.
  1059  			hashCopy := outpoint.Hash
  1060  			missingParents = append(missingParents, &hashCopy)
  1061  		}
  1062  	}
  1063  	if len(missingParents) > 0 {
  1064  		return missingParents, nil, nil
  1065  	}
  1066  
  1067  	// Don't allow the transaction into the mempool unless its sequence
  1068  	// lock is active, meaning that it'll be allowed into the next block
  1069  	// with respect to its defined relative lock times.
  1070  	sequenceLock, err := mp.cfg.CalcSequenceLock(tx, utxoView)
  1071  	if err != nil {
  1072  		if cerr, ok := err.(blockchain.RuleError); ok {
  1073  			return nil, nil, chainRuleError(cerr)
  1074  		}
  1075  		return nil, nil, err
  1076  	}
  1077  	if !blockchain.SequenceLockActive(sequenceLock, nextBlockHeight,
  1078  		medianTimePast) {
  1079  		return nil, nil, txRuleError(wire.RejectNonstandard,
  1080  			"transaction's sequence locks on inputs not met")
  1081  	}
  1082  
  1083  	// Perform several checks on the transaction inputs using the invariant
  1084  	// rules in blockchain for what transactions are allowed into blocks.
  1085  	// Also returns the fees associated with the transaction which will be
  1086  	// used later.
  1087  	txFee, err := blockchain.CheckTransactionInputs(tx, nextBlockHeight,
  1088  		utxoView, mp.cfg.ChainParams)
  1089  	if err != nil {
  1090  		if cerr, ok := err.(blockchain.RuleError); ok {
  1091  			return nil, nil, chainRuleError(cerr)
  1092  		}
  1093  		return nil, nil, err
  1094  	}
  1095  
  1096  	// Don't allow transactions with non-standard inputs if the network
  1097  	// parameters forbid their acceptance.
  1098  	if !mp.cfg.Policy.AcceptNonStd {
  1099  		err := checkInputsStandard(tx, utxoView)
  1100  		if err != nil {
  1101  			// Attempt to extract a reject code from the error so
  1102  			// it can be retained.  When not possible, fall back to
  1103  			// a non-standard error.
  1104  			rejectCode, found := extractRejectCode(err)
  1105  			if !found {
  1106  				rejectCode = wire.RejectNonstandard
  1107  			}
  1108  			str := fmt.Sprintf("transaction %v has a non-standard "+
  1109  				"input: %v", txHash, err)
  1110  			return nil, nil, txRuleError(rejectCode, str)
  1111  		}
  1112  	}
  1113  
  1114  	// NOTE: if you modify this code to accept non-standard transactions,
  1115  	// you should add code here to check that the transaction does a
  1116  	// reasonable number of ECDSA signature verifications.
  1117  
  1118  	// Don't allow transactions with an excessive number of signature
  1119  	// operations which would result in making it impossible to mine.  Since
  1120  	// the coinbase address itself can contain signature operations, the
  1121  	// maximum allowed signature operations per transaction is less than
  1122  	// the maximum allowed signature operations per block.
  1123  	// TODO(roasbeef): last bool should be conditional on segwit activation
  1124  	sigOpCost, err := blockchain.GetSigOpCost(tx, false, utxoView, true, true)
  1125  	if err != nil {
  1126  		if cerr, ok := err.(blockchain.RuleError); ok {
  1127  			return nil, nil, chainRuleError(cerr)
  1128  		}
  1129  		return nil, nil, err
  1130  	}
  1131  	if sigOpCost > mp.cfg.Policy.MaxSigOpCostPerTx {
  1132  		str := fmt.Sprintf("transaction %v sigop cost is too high: %d > %d",
  1133  			txHash, sigOpCost, mp.cfg.Policy.MaxSigOpCostPerTx)
  1134  		return nil, nil, txRuleError(wire.RejectNonstandard, str)
  1135  	}
  1136  
  1137  	// Don't allow transactions with fees too low to get into a mined block.
  1138  	//
  1139  	// Most miners allow a free transaction area in blocks they mine to go
  1140  	// alongside the area used for high-priority transactions as well as
  1141  	// transactions with fees.  A transaction size of up to 1000 bytes is
  1142  	// considered safe to go into this section.  Further, the minimum fee
  1143  	// calculated below on its own would encourage several small
  1144  	// transactions to avoid fees rather than one single larger transaction
  1145  	// which is more desirable.  Therefore, as long as the size of the
  1146  	// transaction does not exceed 1000 less than the reserved space for
  1147  	// high-priority transactions, don't require a fee for it.
  1148  	serializedSize := GetTxVirtualSize(tx)
  1149  	minFee := calcMinRequiredTxRelayFee(serializedSize,
  1150  		mp.cfg.Policy.MinRelayTxFee)
  1151  	if serializedSize >= (DefaultBlockPrioritySize-1000) && txFee < minFee {
  1152  		str := fmt.Sprintf("transaction %v has %d fees which is under "+
  1153  			"the required amount of %d", txHash, txFee,
  1154  			minFee)
  1155  		return nil, nil, txRuleError(wire.RejectInsufficientFee, str)
  1156  	}
  1157  
  1158  	// Require that free transactions have sufficient priority to be mined
  1159  	// in the next block.  Transactions which are being added back to the
  1160  	// memory pool from blocks that have been disconnected during a reorg
  1161  	// are exempted.
  1162  	if isNew && !mp.cfg.Policy.DisableRelayPriority && txFee < minFee {
  1163  		currentPriority := mining.CalcPriority(tx.MsgTx(), utxoView,
  1164  			nextBlockHeight)
  1165  		if currentPriority <= mining.MinHighPriority {
  1166  			str := fmt.Sprintf("transaction %v has insufficient "+
  1167  				"priority (%g <= %g)", txHash,
  1168  				currentPriority, mining.MinHighPriority)
  1169  			return nil, nil, txRuleError(wire.RejectInsufficientFee, str)
  1170  		}
  1171  	}
  1172  
  1173  	// Free-to-relay transactions are rate limited here to prevent
  1174  	// penny-flooding with tiny transactions as a form of attack.
  1175  	if rateLimit && txFee < minFee {
  1176  		nowUnix := time.Now().Unix()
  1177  		// Decay passed data with an exponentially decaying ~10 minute
  1178  		// window - matches bitcoind handling.
  1179  		mp.pennyTotal *= math.Pow(1.0-1.0/600.0,
  1180  			float64(nowUnix-mp.lastPennyUnix))
  1181  		mp.lastPennyUnix = nowUnix
  1182  
  1183  		// Are we still over the limit?
  1184  		if mp.pennyTotal >= mp.cfg.Policy.FreeTxRelayLimit*10*1000 {
  1185  			str := fmt.Sprintf("transaction %v has been rejected "+
  1186  				"by the rate limiter due to low fees", txHash)
  1187  			return nil, nil, txRuleError(wire.RejectInsufficientFee, str)
  1188  		}
  1189  		oldTotal := mp.pennyTotal
  1190  
  1191  		mp.pennyTotal += float64(serializedSize)
  1192  		log.Tracef("rate limit: curTotal %v, nextTotal: %v, "+
  1193  			"limit %v", oldTotal, mp.pennyTotal,
  1194  			mp.cfg.Policy.FreeTxRelayLimit*10*1000)
  1195  	}
  1196  
  1197  	// If the transaction has any conflicts, and we've made it this far, then
  1198  	// we're processing a potential replacement.
  1199  	var conflicts map[chainhash.Hash]*btcutil.Tx
  1200  	if isReplacement {
  1201  		conflicts, err = mp.validateReplacement(tx, txFee)
  1202  		if err != nil {
  1203  			return nil, nil, err
  1204  		}
  1205  	}
  1206  
  1207  	// Verify crypto signatures for each input and reject the transaction if
  1208  	// any don't verify.
  1209  	err = blockchain.ValidateTransactionScripts(tx, utxoView,
  1210  		txscript.StandardVerifyFlags, mp.cfg.SigCache,
  1211  		mp.cfg.HashCache)
  1212  	if err != nil {
  1213  		if cerr, ok := err.(blockchain.RuleError); ok {
  1214  			return nil, nil, chainRuleError(cerr)
  1215  		}
  1216  		return nil, nil, err
  1217  	}
  1218  
  1219  	// Now that we've deemed the transaction as valid, we can add it to the
  1220  	// mempool. If it ended up replacing any transactions, we'll remove them
  1221  	// first.
  1222  	for _, conflict := range conflicts {
  1223  		log.Debugf("Replacing transaction %v (fee_rate=%v sat/kb) "+
  1224  			"with %v (fee_rate=%v sat/kb)\n", conflict.Hash(),
  1225  			mp.pool[*conflict.Hash()].FeePerKB, tx.Hash(),
  1226  			txFee*1000/serializedSize)
  1227  
  1228  		// The conflict set should already include the descendants for
  1229  		// each one, so we don't need to remove the redeemers within
  1230  		// this call as they'll be removed eventually.
  1231  		mp.removeTransaction(conflict, false)
  1232  	}
  1233  	txD := mp.addTransaction(utxoView, tx, bestHeight, txFee)
  1234  
  1235  	log.Debugf("Accepted transaction %v (pool size: %v)", txHash,
  1236  		len(mp.pool))
  1237  
  1238  	return nil, txD, nil
  1239  }
  1240  
  1241  // MaybeAcceptTransaction is the main workhorse for handling insertion of new
  1242  // free-standing transactions into a memory pool.  It includes functionality
  1243  // such as rejecting duplicate transactions, ensuring transactions follow all
  1244  // rules, detecting orphan transactions, and insertion into the memory pool.
  1245  //
  1246  // If the transaction is an orphan (missing parent transactions), the
  1247  // transaction is NOT added to the orphan pool, but each unknown referenced
  1248  // parent is returned.  Use ProcessTransaction instead if new orphans should
  1249  // be added to the orphan pool.
  1250  //
  1251  // This function is safe for concurrent access.
  1252  func (mp *TxPool) MaybeAcceptTransaction(tx *btcutil.Tx, isNew, rateLimit bool) ([]*chainhash.Hash, *TxDesc, error) {
  1253  	// Protect concurrent access.
  1254  	mp.mtx.Lock()
  1255  	hashes, txD, err := mp.maybeAcceptTransaction(tx, isNew, rateLimit, true)
  1256  	mp.mtx.Unlock()
  1257  
  1258  	return hashes, txD, err
  1259  }
  1260  
  1261  // processOrphans is the internal function which implements the public
  1262  // ProcessOrphans.  See the comment for ProcessOrphans for more details.
  1263  //
  1264  // This function MUST be called with the mempool lock held (for writes).
  1265  func (mp *TxPool) processOrphans(acceptedTx *btcutil.Tx) []*TxDesc {
  1266  	var acceptedTxns []*TxDesc
  1267  
  1268  	// Start with processing at least the passed transaction.
  1269  	processList := list.New()
  1270  	processList.PushBack(acceptedTx)
  1271  	for processList.Len() > 0 {
  1272  		// Pop the transaction to process from the front of the list.
  1273  		firstElement := processList.Remove(processList.Front())
  1274  		processItem := firstElement.(*btcutil.Tx)
  1275  
  1276  		prevOut := wire.OutPoint{Hash: *processItem.Hash()}
  1277  		for txOutIdx := range processItem.MsgTx().TxOut {
  1278  			// Look up all orphans that redeem the output that is
  1279  			// now available.  This will typically only be one, but
  1280  			// it could be multiple if the orphan pool contains
  1281  			// double spends.  While it may seem odd that the orphan
  1282  			// pool would allow this since there can only possibly
  1283  			// ultimately be a single redeemer, it's important to
  1284  			// track it this way to prevent malicious actors from
  1285  			// being able to purposely constructing orphans that
  1286  			// would otherwise make outputs unspendable.
  1287  			//
  1288  			// Skip to the next available output if there are none.
  1289  			prevOut.Index = uint32(txOutIdx)
  1290  			orphans, exists := mp.orphansByPrev[prevOut]
  1291  			if !exists {
  1292  				continue
  1293  			}
  1294  
  1295  			// Potentially accept an orphan into the tx pool.
  1296  			for _, tx := range orphans {
  1297  				missing, txD, err := mp.maybeAcceptTransaction(
  1298  					tx, true, true, false)
  1299  				if err != nil {
  1300  					// The orphan is now invalid, so there
  1301  					// is no way any other orphans which
  1302  					// redeem any of its outputs can be
  1303  					// accepted.  Remove them.
  1304  					mp.removeOrphan(tx, true)
  1305  					break
  1306  				}
  1307  
  1308  				// Transaction is still an orphan.  Try the next
  1309  				// orphan which redeems this output.
  1310  				if len(missing) > 0 {
  1311  					continue
  1312  				}
  1313  
  1314  				// Transaction was accepted into the main pool.
  1315  				//
  1316  				// Add it to the list of accepted transactions
  1317  				// that are no longer orphans, remove it from
  1318  				// the orphan pool, and add it to the list of
  1319  				// transactions to process so any orphans that
  1320  				// depend on it are handled too.
  1321  				acceptedTxns = append(acceptedTxns, txD)
  1322  				mp.removeOrphan(tx, false)
  1323  				processList.PushBack(tx)
  1324  
  1325  				// Only one transaction for this outpoint can be
  1326  				// accepted, so the rest are now double spends
  1327  				// and are removed later.
  1328  				break
  1329  			}
  1330  		}
  1331  	}
  1332  
  1333  	// Recursively remove any orphans that also redeem any outputs redeemed
  1334  	// by the accepted transactions since those are now definitive double
  1335  	// spends.
  1336  	mp.removeOrphanDoubleSpends(acceptedTx)
  1337  	for _, txD := range acceptedTxns {
  1338  		mp.removeOrphanDoubleSpends(txD.Tx)
  1339  	}
  1340  
  1341  	return acceptedTxns
  1342  }
  1343  
  1344  // ProcessOrphans determines if there are any orphans which depend on the passed
  1345  // transaction hash (it is possible that they are no longer orphans) and
  1346  // potentially accepts them to the memory pool.  It repeats the process for the
  1347  // newly accepted transactions (to detect further orphans which may no longer be
  1348  // orphans) until there are no more.
  1349  //
  1350  // It returns a slice of transactions added to the mempool.  A nil slice means
  1351  // no transactions were moved from the orphan pool to the mempool.
  1352  //
  1353  // This function is safe for concurrent access.
  1354  func (mp *TxPool) ProcessOrphans(acceptedTx *btcutil.Tx) []*TxDesc {
  1355  	mp.mtx.Lock()
  1356  	acceptedTxns := mp.processOrphans(acceptedTx)
  1357  	mp.mtx.Unlock()
  1358  
  1359  	return acceptedTxns
  1360  }
  1361  
  1362  // ProcessTransaction is the main workhorse for handling insertion of new
  1363  // free-standing transactions into the memory pool.  It includes functionality
  1364  // such as rejecting duplicate transactions, ensuring transactions follow all
  1365  // rules, orphan transaction handling, and insertion into the memory pool.
  1366  //
  1367  // It returns a slice of transactions added to the mempool.  When the
  1368  // error is nil, the list will include the passed transaction itself along
  1369  // with any additional orphan transactions that were added as a result of
  1370  // the passed one being accepted.
  1371  //
  1372  // This function is safe for concurrent access.
  1373  func (mp *TxPool) ProcessTransaction(tx *btcutil.Tx, allowOrphan, rateLimit bool, tag Tag) ([]*TxDesc, error) {
  1374  	log.Tracef("Processing transaction %v", tx.Hash())
  1375  
  1376  	// Protect concurrent access.
  1377  	mp.mtx.Lock()
  1378  	defer mp.mtx.Unlock()
  1379  
  1380  	// Potentially accept the transaction to the memory pool.
  1381  	missingParents, txD, err := mp.maybeAcceptTransaction(tx, true, rateLimit,
  1382  		true)
  1383  	if err != nil {
  1384  		return nil, err
  1385  	}
  1386  
  1387  	if len(missingParents) == 0 {
  1388  		// Accept any orphan transactions that depend on this
  1389  		// transaction (they may no longer be orphans if all inputs
  1390  		// are now available) and repeat for those accepted
  1391  		// transactions until there are no more.
  1392  		newTxs := mp.processOrphans(tx)
  1393  		acceptedTxs := make([]*TxDesc, len(newTxs)+1)
  1394  
  1395  		// Add the parent transaction first so remote nodes
  1396  		// do not add orphans.
  1397  		acceptedTxs[0] = txD
  1398  		copy(acceptedTxs[1:], newTxs)
  1399  
  1400  		return acceptedTxs, nil
  1401  	}
  1402  
  1403  	// The transaction is an orphan (has inputs missing).  Reject
  1404  	// it if the flag to allow orphans is not set.
  1405  	if !allowOrphan {
  1406  		// Only use the first missing parent transaction in
  1407  		// the error message.
  1408  		//
  1409  		// NOTE: RejectDuplicate is really not an accurate
  1410  		// reject code here, but it matches the reference
  1411  		// implementation and there isn't a better choice due
  1412  		// to the limited number of reject codes.  Missing
  1413  		// inputs is assumed to mean they are already spent
  1414  		// which is not really always the case.
  1415  		str := fmt.Sprintf("orphan transaction %v references "+
  1416  			"outputs of unknown or fully-spent "+
  1417  			"transaction %v", tx.Hash(), missingParents[0])
  1418  		return nil, txRuleError(wire.RejectDuplicate, str)
  1419  	}
  1420  
  1421  	// Potentially add the orphan transaction to the orphan pool.
  1422  	err = mp.maybeAddOrphan(tx, tag)
  1423  	return nil, err
  1424  }
  1425  
  1426  // Count returns the number of transactions in the main pool.  It does not
  1427  // include the orphan pool.
  1428  //
  1429  // This function is safe for concurrent access.
  1430  func (mp *TxPool) Count() int {
  1431  	mp.mtx.RLock()
  1432  	count := len(mp.pool)
  1433  	mp.mtx.RUnlock()
  1434  
  1435  	return count
  1436  }
  1437  
  1438  // TxHashes returns a slice of hashes for all the transactions in the memory
  1439  // pool.
  1440  //
  1441  // This function is safe for concurrent access.
  1442  func (mp *TxPool) TxHashes() []*chainhash.Hash {
  1443  	mp.mtx.RLock()
  1444  	hashes := make([]*chainhash.Hash, len(mp.pool))
  1445  	i := 0
  1446  	for hash := range mp.pool {
  1447  		hashCopy := hash
  1448  		hashes[i] = &hashCopy
  1449  		i++
  1450  	}
  1451  	mp.mtx.RUnlock()
  1452  
  1453  	return hashes
  1454  }
  1455  
  1456  // TxDescs returns a slice of descriptors for all the transactions in the pool.
  1457  // The descriptors are to be treated as read only.
  1458  //
  1459  // This function is safe for concurrent access.
  1460  func (mp *TxPool) TxDescs() []*TxDesc {
  1461  	mp.mtx.RLock()
  1462  	descs := make([]*TxDesc, len(mp.pool))
  1463  	i := 0
  1464  	for _, desc := range mp.pool {
  1465  		descs[i] = desc
  1466  		i++
  1467  	}
  1468  	mp.mtx.RUnlock()
  1469  
  1470  	return descs
  1471  }
  1472  
  1473  // MiningDescs returns a slice of mining descriptors for all the transactions
  1474  // in the pool.
  1475  //
  1476  // This is part of the mining.TxSource interface implementation and is safe for
  1477  // concurrent access as required by the interface contract.
  1478  func (mp *TxPool) MiningDescs() []*mining.TxDesc {
  1479  	mp.mtx.RLock()
  1480  	descs := make([]*mining.TxDesc, len(mp.pool))
  1481  	i := 0
  1482  	for _, desc := range mp.pool {
  1483  		descs[i] = &desc.TxDesc
  1484  		i++
  1485  	}
  1486  	mp.mtx.RUnlock()
  1487  
  1488  	return descs
  1489  }
  1490  
  1491  // RawMempoolVerbose returns all the entries in the mempool as a fully
  1492  // populated btcjson result.
  1493  //
  1494  // This function is safe for concurrent access.
  1495  func (mp *TxPool) RawMempoolVerbose() map[string]*btcjson.GetRawMempoolVerboseResult {
  1496  	mp.mtx.RLock()
  1497  	defer mp.mtx.RUnlock()
  1498  
  1499  	result := make(map[string]*btcjson.GetRawMempoolVerboseResult,
  1500  		len(mp.pool))
  1501  	bestHeight := mp.cfg.BestHeight()
  1502  
  1503  	for _, desc := range mp.pool {
  1504  		// Calculate the current priority based on the inputs to
  1505  		// the transaction.  Use zero if one or more of the
  1506  		// input transactions can't be found for some reason.
  1507  		tx := desc.Tx
  1508  		var currentPriority float64
  1509  		utxos, err := mp.fetchInputUtxos(tx)
  1510  		if err == nil {
  1511  			currentPriority = mining.CalcPriority(tx.MsgTx(), utxos,
  1512  				bestHeight+1)
  1513  		}
  1514  
  1515  		mpd := &btcjson.GetRawMempoolVerboseResult{
  1516  			Size:             int32(tx.MsgTx().SerializeSize()),
  1517  			Vsize:            int32(GetTxVirtualSize(tx)),
  1518  			Weight:           int32(blockchain.GetTransactionWeight(tx)),
  1519  			Fee:              btcutil.Amount(desc.Fee).ToBTC(),
  1520  			Time:             desc.Added.Unix(),
  1521  			Height:           int64(desc.Height),
  1522  			StartingPriority: desc.StartingPriority,
  1523  			CurrentPriority:  currentPriority,
  1524  			Depends:          make([]string, 0),
  1525  		}
  1526  		for _, txIn := range tx.MsgTx().TxIn {
  1527  			hash := &txIn.PreviousOutPoint.Hash
  1528  			if mp.haveTransaction(hash) {
  1529  				mpd.Depends = append(mpd.Depends,
  1530  					hash.String())
  1531  			}
  1532  		}
  1533  
  1534  		result[tx.Hash().String()] = mpd
  1535  	}
  1536  
  1537  	return result
  1538  }
  1539  
  1540  // LastUpdated returns the last time a transaction was added to or removed from
  1541  // the main pool.  It does not include the orphan pool.
  1542  //
  1543  // This function is safe for concurrent access.
  1544  func (mp *TxPool) LastUpdated() time.Time {
  1545  	return time.Unix(atomic.LoadInt64(&mp.lastUpdated), 0)
  1546  }
  1547  
  1548  // New returns a new memory pool for validating and storing standalone
  1549  // transactions until they are mined into a block.
  1550  func New(cfg *Config) *TxPool {
  1551  	return &TxPool{
  1552  		cfg:            *cfg,
  1553  		pool:           make(map[chainhash.Hash]*TxDesc),
  1554  		orphans:        make(map[chainhash.Hash]*orphanTx),
  1555  		orphansByPrev:  make(map[wire.OutPoint]map[chainhash.Hash]*btcutil.Tx),
  1556  		nextExpireScan: time.Now().Add(orphanExpireScanInterval),
  1557  		outpoints:      make(map[wire.OutPoint]*btcutil.Tx),
  1558  	}
  1559  }