OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / btcsuite / btcd / mempool / mempool.go
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/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"
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
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.
46 type Tag uint64
47
48 // Config is a descriptor containing the memory pool configuration.
49 type Config struct {
50         // Policy defines the various mempool configuration options related
51         // to policy.
52         Policy Policy
53
54         // ChainParams identifies which chain parameters the txpool is
55         // associated with.
56         ChainParams *chaincfg.Params
57
58         // FetchUtxoView defines the function to use to fetch unspent
59         // transaction output information.
60         FetchUtxoView func(*btcutil.Tx) (*blockchain.UtxoViewpoint, error)
61
62         // BestHeight defines the function to use to access the block height of
63         // the current best chain.
64         BestHeight func() int32
65
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
70
71         // CalcSequenceLock defines the function to use in order to generate
72         // the current sequence lock for the given transaction using the passed
73         // utxo view.
74         CalcSequenceLock func(*btcutil.Tx, *blockchain.UtxoViewpoint) (*blockchain.SequenceLock, error)
75
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)
81
82         // SigCache defines a signature cache to use.
83         SigCache *txscript.SigCache
84
85         // HashCache defines the transaction hash mid-state cache to use.
86         HashCache *txscript.HashCache
87
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
92 }
93
94 // Policy houses the policy (configuration parameters) which is used to
95 // control the mempool.
96 type Policy struct {
97         // MaxTxVersion is the transaction version that the mempool should
98         // accept.  All transactions above this version are rejected as
99         // non-standard.
100         MaxTxVersion int32
101
102         // DisableRelayPriority defines whether to relay free or low-fee
103         // transactions that do not have enough priority to be relayed.
104         DisableRelayPriority bool
105
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.
109         AcceptNonStd bool
110
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
114
115         // MaxOrphanTxs is the maximum number of orphan transactions
116         // that can be queued.
117         MaxOrphanTxs int
118
119         // MaxOrphanTxSize is the maximum size allowed for orphan transactions.
120         // This helps prevent memory exhaustion attacks from sending a lot of
121         // of big orphans.
122         MaxOrphanTxSize int
123
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
128
129         // MinRelayTxFee defines the minimum transaction fee in BTC/kB to be
130         // considered a non-zero fee.
131         MinRelayTxFee btcutil.Amount
132 }
133
134 // TxDesc is a descriptor containing a transaction in the mempool along with
135 // additional metadata.
136 type TxDesc struct {
137         mining.TxDesc
138
139         // StartingPriority is the priority of the transaction when it was added
140         // to the pool.
141         StartingPriority float64
142 }
143
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 {
148         tx         *btcutil.Tx
149         tag        Tag
150         expiration time.Time
151 }
152
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
155 // peers.
156 type TxPool struct {
157         // The following variables must only be used atomically.
158         lastUpdated int64 // last time pool was updated
159
160         mtx           sync.RWMutex
161         cfg           Config
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''
168
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
174 }
175
176 // Ensure the TxPool type implements the mining.TxSource interface.
177 var _ mining.TxSource = (*TxPool)(nil)
178
179 // removeOrphan is the internal function which implements the public
180 // RemoveOrphan.  See the comment for RemoveOrphan for more details.
181 //
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.
185         txHash := tx.Hash()
186         otx, exists := mp.orphans[*txHash]
187         if !exists {
188                 return
189         }
190
191         // Remove the reference from the previous orphan index.
192         for _, txIn := range otx.tx.MsgTx().TxIn {
193                 orphans, exists := mp.orphansByPrev[txIn.PreviousOutPoint]
194                 if exists {
195                         delete(orphans, *txHash)
196
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)
201                         }
202                 }
203         }
204
205         // Remove any orphans that redeem outputs from this one if requested.
206         if removeRedeemers {
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)
212                         }
213                 }
214         }
215
216         // Remove the transaction from the orphan pool.
217         delete(mp.orphans, *txHash)
218 }
219
220 // RemoveOrphan removes the passed orphan transaction from the orphan pool and
221 // previous orphan index.
222 //
223 // This function is safe for concurrent access.
224 func (mp *TxPool) RemoveOrphan(tx *btcutil.Tx) {
225         mp.mtx.Lock()
226         mp.removeOrphan(tx, false)
227         mp.mtx.Unlock()
228 }
229
230 // RemoveOrphansByTag removes all orphan transactions tagged with the provided
231 // identifier.
232 //
233 // This function is safe for concurrent access.
234 func (mp *TxPool) RemoveOrphansByTag(tag Tag) uint64 {
235         var numEvicted uint64
236         mp.mtx.Lock()
237         for _, otx := range mp.orphans {
238                 if otx.tag == tag {
239                         mp.removeOrphan(otx.tx, true)
240                         numEvicted++
241                 }
242         }
243         mp.mtx.Unlock()
244         return numEvicted
245 }
246
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.
249 //
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)
264                         }
265                 }
266
267                 // Set next expiration scan to occur after the scan interval.
268                 mp.nextExpireScan = now.Add(orphanExpireScanInterval)
269
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"),
274                                 numOrphans)
275                 }
276         }
277
278         // Nothing to do if adding another orphan will not cause the pool to
279         // exceed the limit.
280         if len(mp.orphans)+1 <= mp.cfg.Policy.MaxOrphanTxs {
281                 return nil
282         }
283
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)
294                 break
295         }
296
297         return nil
298 }
299
300 // addOrphan adds an orphan transaction to the orphan pool.
301 //
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 {
306                 return
307         }
308
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.
312         mp.limitNumOrphans()
313
314         mp.orphans[*tx.Hash()] = &orphanTx{
315                 tx:         tx,
316                 tag:        tag,
317                 expiration: time.Now().Add(orphanTTL),
318         }
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)
323                 }
324                 mp.orphansByPrev[txIn.PreviousOutPoint][*tx.Hash()] = tx
325         }
326
327         log.Debugf("Stored orphan transaction %v (total: %d)", tx.Hash(),
328                 len(mp.orphans))
329 }
330
331 // maybeAddOrphan potentially adds an orphan to the orphan pool.
332 //
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.
340         //
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)
351         }
352
353         // Add the orphan if the none of the above disqualified it.
354         mp.addOrphan(tx, tag)
355
356         return nil
357 }
358
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.
364 //
365 // This function MUST be called with the mempool lock held (for writes).
366 func (mp *TxPool) removeOrphanDoubleSpends(tx *btcutil.Tx) {
367         msgTx := tx.MsgTx()
368         for _, txIn := range msgTx.TxIn {
369                 for _, orphan := range mp.orphansByPrev[txIn.PreviousOutPoint] {
370                         mp.removeOrphan(orphan, true)
371                 }
372         }
373 }
374
375 // isTransactionInPool returns whether or not the passed transaction already
376 // exists in the main pool.
377 //
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 {
381                 return true
382         }
383
384         return false
385 }
386
387 // IsTransactionInPool returns whether or not the passed transaction already
388 // exists in the main pool.
389 //
390 // This function is safe for concurrent access.
391 func (mp *TxPool) IsTransactionInPool(hash *chainhash.Hash) bool {
392         // Protect concurrent access.
393         mp.mtx.RLock()
394         inPool := mp.isTransactionInPool(hash)
395         mp.mtx.RUnlock()
396
397         return inPool
398 }
399
400 // isOrphanInPool returns whether or not the passed transaction already exists
401 // in the orphan pool.
402 //
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 {
406                 return true
407         }
408
409         return false
410 }
411
412 // IsOrphanInPool returns whether or not the passed transaction already exists
413 // in the orphan pool.
414 //
415 // This function is safe for concurrent access.
416 func (mp *TxPool) IsOrphanInPool(hash *chainhash.Hash) bool {
417         // Protect concurrent access.
418         mp.mtx.RLock()
419         inPool := mp.isOrphanInPool(hash)
420         mp.mtx.RUnlock()
421
422         return inPool
423 }
424
425 // haveTransaction returns whether or not the passed transaction already exists
426 // in the main pool or in the orphan pool.
427 //
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)
431 }
432
433 // HaveTransaction returns whether or not the passed transaction already exists
434 // in the main pool or in the orphan pool.
435 //
436 // This function is safe for concurrent access.
437 func (mp *TxPool) HaveTransaction(hash *chainhash.Hash) bool {
438         // Protect concurrent access.
439         mp.mtx.RLock()
440         haveTx := mp.haveTransaction(hash)
441         mp.mtx.RUnlock()
442
443         return haveTx
444 }
445
446 // removeTransaction is the internal function which implements the public
447 // RemoveTransaction.  See the comment for RemoveTransaction for more details.
448 //
449 // This function MUST be called with the mempool lock held (for writes).
450 func (mp *TxPool) removeTransaction(tx *btcutil.Tx, removeRedeemers bool) {
451         txHash := tx.Hash()
452         if removeRedeemers {
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)
458                         }
459                 }
460         }
461
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)
468                 }
469
470                 // Mark the referenced outpoints as unspent by the pool.
471                 for _, txIn := range txDesc.Tx.MsgTx().TxIn {
472                         delete(mp.outpoints, txIn.PreviousOutPoint)
473                 }
474                 delete(mp.pool, *txHash)
475                 atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
476         }
477 }
478
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.
483 //
484 // This function is safe for concurrent access.
485 func (mp *TxPool) RemoveTransaction(tx *btcutil.Tx, removeRedeemers bool) {
486         // Protect concurrent access.
487         mp.mtx.Lock()
488         mp.removeTransaction(tx, removeRedeemers)
489         mp.mtx.Unlock()
490 }
491
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.
497 //
498 // This function is safe for concurrent access.
499 func (mp *TxPool) RemoveDoubleSpends(tx *btcutil.Tx) {
500         // Protect concurrent access.
501         mp.mtx.Lock()
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)
506                         }
507                 }
508         }
509         mp.mtx.Unlock()
510 }
511
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.
515 //
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.
520         txD := &TxDesc{
521                 TxDesc: mining.TxDesc{
522                         Tx:       tx,
523                         Added:    time.Now(),
524                         Height:   height,
525                         Fee:      fee,
526                         FeePerKB: fee * 1000 / int64(tx.MsgTx().SerializeSize()),
527                 },
528                 StartingPriority: mining.CalcPriority(tx.MsgTx(), utxoView, height),
529         }
530         mp.pool[*tx.Hash()] = txD
531
532         for _, txIn := range tx.MsgTx().TxIn {
533                 mp.outpoints[txIn.PreviousOutPoint] = tx
534         }
535         atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
536
537         // Add unconfirmed address index entries associated with the transaction
538         // if enabled.
539         if mp.cfg.AddrIndex != nil {
540                 mp.cfg.AddrIndex.AddUnconfirmedTx(tx, utxoView)
541         }
542
543         return txD
544 }
545
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
549 // main chain.
550 //
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)
559                 }
560         }
561
562         return nil
563 }
564
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
568 // transaction pool.
569 //
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)
573         if err != nil {
574                 return nil, err
575         }
576
577         // Attempt to populate any missing inputs from the transaction pool.
578         for originHash, entry := range utxoView.Entries() {
579                 if entry != nil && !entry.IsFullySpent() {
580                         continue
581                 }
582
583                 if poolTxDesc, exists := mp.pool[originHash]; exists {
584                         utxoView.AddTxOuts(poolTxDesc.Tx, mining.UnminedHeight)
585                 }
586         }
587         return utxoView, nil
588 }
589
590 // FetchTransaction returns the requested transaction from the transaction pool.
591 // This only fetches from the main transaction pool and does not include
592 // orphans.
593 //
594 // This function is safe for concurrent access.
595 func (mp *TxPool) FetchTransaction(txHash *chainhash.Hash) (*btcutil.Tx, error) {
596         // Protect concurrent access.
597         mp.mtx.RLock()
598         txDesc, exists := mp.pool[*txHash]
599         mp.mtx.RUnlock()
600
601         if exists {
602                 return txDesc.Tx, nil
603         }
604
605         return nil, fmt.Errorf("transaction is not in the pool")
606 }
607
608 // maybeAcceptTransaction is the internal function which implements the public
609 // MaybeAcceptTransaction.  See the comment for MaybeAcceptTransaction for
610 // more details.
611 //
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) {
614         txHash := tx.Hash()
615
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)
621                 if err != nil {
622                         return nil, nil, err
623                 }
624
625                 if !segwitActive {
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)
629                 }
630         }
631
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)) {
638
639                 str := fmt.Sprintf("already have transaction %v", txHash)
640                 return nil, nil, txRuleError(wire.RejectDuplicate, str)
641         }
642
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)
647         if err != nil {
648                 if cerr, ok := err.(blockchain.RuleError); ok {
649                         return nil, nil, chainRuleError(cerr)
650                 }
651                 return nil, nil, err
652         }
653
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",
657                         txHash)
658                 return nil, nil, txRuleError(wire.RejectInvalid, str)
659         }
660
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
666
667         medianTimePast := mp.cfg.MedianTimePast()
668
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)
675                 if err != nil {
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)
680                         if !found {
681                                 rejectCode = wire.RejectNonstandard
682                         }
683                         str := fmt.Sprintf("transaction %v is not standard: %v",
684                                 txHash, err)
685                         return nil, nil, txRuleError(rejectCode, str)
686                 }
687         }
688
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)
698         if err != nil {
699                 return nil, nil, err
700         }
701
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)
707         if err != nil {
708                 if cerr, ok := err.(blockchain.RuleError); ok {
709                         return nil, nil, chainRuleError(cerr)
710                 }
711                 return nil, nil, err
712         }
713
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")
720         }
721         delete(utxoView.Entries(), *txHash)
722
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)
736                 }
737         }
738         if len(missingParents) > 0 {
739                 return missingParents, nil, nil
740         }
741
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)
746         if err != nil {
747                 if cerr, ok := err.(blockchain.RuleError); ok {
748                         return nil, nil, chainRuleError(cerr)
749                 }
750                 return nil, nil, err
751         }
752         if !blockchain.SequenceLockActive(sequenceLock, nextBlockHeight,
753                 medianTimePast) {
754                 return nil, nil, txRuleError(wire.RejectNonstandard,
755                         "transaction's sequence locks on inputs not met")
756         }
757
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
761         // used later.
762         txFee, err := blockchain.CheckTransactionInputs(tx, nextBlockHeight,
763                 utxoView, mp.cfg.ChainParams)
764         if err != nil {
765                 if cerr, ok := err.(blockchain.RuleError); ok {
766                         return nil, nil, chainRuleError(cerr)
767                 }
768                 return nil, nil, err
769         }
770
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)
775                 if err != nil {
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)
780                         if !found {
781                                 rejectCode = wire.RejectNonstandard
782                         }
783                         str := fmt.Sprintf("transaction %v has a non-standard "+
784                                 "input: %v", txHash, err)
785                         return nil, nil, txRuleError(rejectCode, str)
786                 }
787         }
788
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.
792
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)
800         if err != nil {
801                 if cerr, ok := err.(blockchain.RuleError); ok {
802                         return nil, nil, chainRuleError(cerr)
803                 }
804                 return nil, nil, err
805         }
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)
810         }
811
812         // Don't allow transactions with fees too low to get into a mined block.
813         //
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,
829                         minFee)
830                 return nil, nil, txRuleError(wire.RejectInsufficientFee, str)
831         }
832
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
836         // are exempted.
837         if isNew && !mp.cfg.Policy.DisableRelayPriority && txFee < minFee {
838                 currentPriority := mining.CalcPriority(tx.MsgTx(), utxoView,
839                         nextBlockHeight)
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)
845                 }
846         }
847
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
857
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)
863                 }
864                 oldTotal := mp.pennyTotal
865
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)
870         }
871
872         // Verify crypto signatures for each input and reject the transaction if
873         // any don't verify.
874         err = blockchain.ValidateTransactionScripts(tx, utxoView,
875                 txscript.StandardVerifyFlags, mp.cfg.SigCache,
876                 mp.cfg.HashCache)
877         if err != nil {
878                 if cerr, ok := err.(blockchain.RuleError); ok {
879                         return nil, nil, chainRuleError(cerr)
880                 }
881                 return nil, nil, err
882         }
883
884         // Add to transaction pool.
885         txD := mp.addTransaction(utxoView, tx, bestHeight, txFee)
886
887         log.Debugf("Accepted transaction %v (pool size: %v)", txHash,
888                 len(mp.pool))
889
890         return nil, txD, nil
891 }
892
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.
897 //
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.
902 //
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.
906         mp.mtx.Lock()
907         hashes, txD, err := mp.maybeAcceptTransaction(tx, isNew, rateLimit, true)
908         mp.mtx.Unlock()
909
910         return hashes, txD, err
911 }
912
913 // processOrphans is the internal function which implements the public
914 // ProcessOrphans.  See the comment for ProcessOrphans for more details.
915 //
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
919
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)
927
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.
939                         //
940                         // Skip to the next available output if there are none.
941                         prevOut.Index = uint32(txOutIdx)
942                         orphans, exists := mp.orphansByPrev[prevOut]
943                         if !exists {
944                                 continue
945                         }
946
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)
951                                 if err != nil {
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)
957                                         break
958                                 }
959
960                                 // Transaction is still an orphan.  Try the next
961                                 // orphan which redeems this output.
962                                 if len(missing) > 0 {
963                                         continue
964                                 }
965
966                                 // Transaction was accepted into the main pool.
967                                 //
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)
976
977                                 // Only one transaction for this outpoint can be
978                                 // accepted, so the rest are now double spends
979                                 // and are removed later.
980                                 break
981                         }
982                 }
983         }
984
985         // Recursively remove any orphans that also redeem any outputs redeemed
986         // by the accepted transactions since those are now definitive double
987         // spends.
988         mp.removeOrphanDoubleSpends(acceptedTx)
989         for _, txD := range acceptedTxns {
990                 mp.removeOrphanDoubleSpends(txD.Tx)
991         }
992
993         return acceptedTxns
994 }
995
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.
1001 //
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.
1004 //
1005 // This function is safe for concurrent access.
1006 func (mp *TxPool) ProcessOrphans(acceptedTx *btcutil.Tx) []*TxDesc {
1007         mp.mtx.Lock()
1008         acceptedTxns := mp.processOrphans(acceptedTx)
1009         mp.mtx.Unlock()
1010
1011         return acceptedTxns
1012 }
1013
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.
1018 //
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.
1023 //
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())
1027
1028         // Protect concurrent access.
1029         mp.mtx.Lock()
1030         defer mp.mtx.Unlock()
1031
1032         // Potentially accept the transaction to the memory pool.
1033         missingParents, txD, err := mp.maybeAcceptTransaction(tx, true, rateLimit,
1034                 true)
1035         if err != nil {
1036                 return nil, err
1037         }
1038
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)
1046
1047                 // Add the parent transaction first so remote nodes
1048                 // do not add orphans.
1049                 acceptedTxs[0] = txD
1050                 copy(acceptedTxs[1:], newTxs)
1051
1052                 return acceptedTxs, nil
1053         }
1054
1055         // The transaction is an orphan (has inputs missing).  Reject
1056         // it if the flag to allow orphans is not set.
1057         if !allowOrphan {
1058                 // Only use the first missing parent transaction in
1059                 // the error message.
1060                 //
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)
1071         }
1072
1073         // Potentially add the orphan transaction to the orphan pool.
1074         err = mp.maybeAddOrphan(tx, tag)
1075         return nil, err
1076 }
1077
1078 // Count returns the number of transactions in the main pool.  It does not
1079 // include the orphan pool.
1080 //
1081 // This function is safe for concurrent access.
1082 func (mp *TxPool) Count() int {
1083         mp.mtx.RLock()
1084         count := len(mp.pool)
1085         mp.mtx.RUnlock()
1086
1087         return count
1088 }
1089
1090 // TxHashes returns a slice of hashes for all of the transactions in the memory
1091 // pool.
1092 //
1093 // This function is safe for concurrent access.
1094 func (mp *TxPool) TxHashes() []*chainhash.Hash {
1095         mp.mtx.RLock()
1096         hashes := make([]*chainhash.Hash, len(mp.pool))
1097         i := 0
1098         for hash := range mp.pool {
1099                 hashCopy := hash
1100                 hashes[i] = &hashCopy
1101                 i++
1102         }
1103         mp.mtx.RUnlock()
1104
1105         return hashes
1106 }
1107
1108 // TxDescs returns a slice of descriptors for all the transactions in the pool.
1109 // The descriptors are to be treated as read only.
1110 //
1111 // This function is safe for concurrent access.
1112 func (mp *TxPool) TxDescs() []*TxDesc {
1113         mp.mtx.RLock()
1114         descs := make([]*TxDesc, len(mp.pool))
1115         i := 0
1116         for _, desc := range mp.pool {
1117                 descs[i] = desc
1118                 i++
1119         }
1120         mp.mtx.RUnlock()
1121
1122         return descs
1123 }
1124
1125 // MiningDescs returns a slice of mining descriptors for all the transactions
1126 // in the pool.
1127 //
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 {
1131         mp.mtx.RLock()
1132         descs := make([]*mining.TxDesc, len(mp.pool))
1133         i := 0
1134         for _, desc := range mp.pool {
1135                 descs[i] = &desc.TxDesc
1136                 i++
1137         }
1138         mp.mtx.RUnlock()
1139
1140         return descs
1141 }
1142
1143 // RawMempoolVerbose returns all of the entries in the mempool as a fully
1144 // populated btcjson result.
1145 //
1146 // This function is safe for concurrent access.
1147 func (mp *TxPool) RawMempoolVerbose() map[string]*btcjson.GetRawMempoolVerboseResult {
1148         mp.mtx.RLock()
1149         defer mp.mtx.RUnlock()
1150
1151         result := make(map[string]*btcjson.GetRawMempoolVerboseResult,
1152                 len(mp.pool))
1153         bestHeight := mp.cfg.BestHeight()
1154
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.
1159                 tx := desc.Tx
1160                 var currentPriority float64
1161                 utxos, err := mp.fetchInputUtxos(tx)
1162                 if err == nil {
1163                         currentPriority = mining.CalcPriority(tx.MsgTx(), utxos,
1164                                 bestHeight+1)
1165                 }
1166
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),
1176                 }
1177                 for _, txIn := range tx.MsgTx().TxIn {
1178                         hash := &txIn.PreviousOutPoint.Hash
1179                         if mp.haveTransaction(hash) {
1180                                 mpd.Depends = append(mpd.Depends,
1181                                         hash.String())
1182                         }
1183                 }
1184
1185                 result[tx.Hash().String()] = mpd
1186         }
1187
1188         return result
1189 }
1190
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.
1193 //
1194 // This function is safe for concurrent access.
1195 func (mp *TxPool) LastUpdated() time.Time {
1196         return time.Unix(atomic.LoadInt64(&mp.lastUpdated), 0)
1197 }
1198
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 {
1202         return &TxPool{
1203                 cfg:            *cfg,
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),
1209         }
1210 }