forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mempool.go
1565 lines (1374 loc) · 51.7 KB
/
mempool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package mempool
import (
"container/list"
"fmt"
"math"
"sync"
"sync/atomic"
"time"
"github.com/decred/dcrd/blockchain"
"github.com/decred/dcrd/blockchain/indexers"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/mining"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
)
const (
// DefaultBlockPrioritySize is the default size in bytes for high-
// priority / low-fee transactions. It is used to help determine which
// are allowed into the mempool and consequently affects their relay and
// inclusion when generating block templates.
DefaultBlockPrioritySize = 20000
// MinHighPriority is the minimum priority value that allows a
// transaction to be considered high priority.
MinHighPriority = dcrutil.AtomsPerCoin * 144.0 / 250
// maxRelayFeeMultiplier is the factor that we disallow fees / kB above the
// minimum tx fee. At the current default minimum relay fee of 0.001
// DCR/kB, this results in a maximum allowed high fee of 1 DCR/kB.
maxRelayFeeMultiplier = 1000
// maxSSGensDoubleSpends is the maximum number of SSGen double spends
// allowed in the pool.
maxSSGensDoubleSpends = 5
// heightDiffToPruneTicket is the number of blocks to pass by in terms
// of height before old tickets are pruned.
// TODO Set this based up the stake difficulty retargeting interval?
heightDiffToPruneTicket = 288
// heightDiffToPruneVotes is the number of blocks to pass by in terms
// of height before SSGen relating to that block are pruned.
heightDiffToPruneVotes = 10
// If a vote is on a block whose height is before tip minus this
// amount, reject it from being added to the mempool.
maximumVoteAgeDelta = 1440
// maxNullDataOutputs is the maximum number of OP_RETURN null data
// pushes in a transaction, after which it is considered non-standard.
maxNullDataOutputs = 4
)
// Config is a descriptor containing the memory pool configuration.
type Config struct {
// Policy defines the various mempool configuration options related
// to policy.
Policy Policy
// ChainParams identifies which chain parameters the txpool is
// associated with.
ChainParams *chaincfg.Params
// NextStakeDifficulty defines the function to retrieve the stake
// difficulty for the block after the current best block.
//
// This function must be safe for concurrent access.
NextStakeDifficulty func() (int64, error)
// FetchUtxoView defines the function to use to fetch unspent
// transaction output information.
FetchUtxoView func(*dcrutil.Tx, bool) (*blockchain.UtxoViewpoint, error)
// BlockByHash defines the function use to fetch the block identified
// by the given hash.
BlockByHash func(*chainhash.Hash) (*dcrutil.Block, error)
// BestHash defines the function to use to access the block hash of
// the current best chain.
BestHash func() *chainhash.Hash
// BestHeight defines the function to use to access the block height of
// the current best chain.
BestHeight func() int64
// PastMedianTime defines the function to use in order to access the
// median time calculated from the point-of-view of the current chain
// tip within the best chain.
PastMedianTime func() time.Time
// CalcSequenceLock defines the function to use in order to generate
// the current sequence lock for the given transaction using the passed
// utxo view.
CalcSequenceLock func(*dcrutil.Tx, *blockchain.UtxoViewpoint) (*blockchain.SequenceLock, error)
// SubsidyCache defines a subsidy cache to use.
SubsidyCache *blockchain.SubsidyCache
// SigCache defines a signature cache to use.
SigCache *txscript.SigCache
// AddrIndex defines the optional address index instance to use for
// indexing the unconfirmed transactions in the memory pool.
// This can be nil if the address index is not enabled.
AddrIndex *indexers.AddrIndex
// ExistsAddrIndex defines the optional exists address index instance
// to use for indexing the unconfirmed transactions in the memory pool.
// This can be nil if the address index is not enabled.
ExistsAddrIndex *indexers.ExistsAddrIndex
}
// Policy houses the policy (configuration parameters) which is used to
// control the mempool.
type Policy struct {
// MaxTxVersion is the max transaction version that the mempool should
// accept. All transactions above this version are rejected as
// non-standard.
MaxTxVersion uint16
// DisableRelayPriority defines whether to relay free or low-fee
// transactions that do not have enough priority to be relayed.
DisableRelayPriority bool
// AcceptNonStd defines whether to accept and relay non-standard
// transactions to the network. If true, non-standard transactions
// will be accepted into the mempool and relayed to the rest of the
// network. Otherwise, all non-standard transactions will be rejected.
AcceptNonStd bool
// FreeTxRelayLimit defines the given amount in thousands of bytes
// per minute that transactions with no fee are rate limited to.
FreeTxRelayLimit float64
// MaxOrphanTxs is the maximum number of orphan transactions
// that can be queued.
MaxOrphanTxs int
// MaxOrphanTxSize is the maximum size allowed for orphan transactions.
// This helps prevent memory exhaustion attacks from sending a lot of
// of big orphans.
MaxOrphanTxSize int
// MaxSigOpsPerTx is the maximum number of signature operations
// in a single transaction we will relay or mine. It is a fraction
// of the max signature operations for a block.
MaxSigOpsPerTx int
// MinRelayTxFee defines the minimum transaction fee in BTC/kB to be
// considered a non-zero fee.
MinRelayTxFee dcrutil.Amount
// AllowOldVotes defines whether or not votes on old blocks will be
// admitted and relayed.
AllowOldVotes bool
// StandardVerifyFlags defines the function to retrieve the flags to
// use for verifying scripts for the block after the current best block.
// It must set the verification flags properly depending on the result
// of any agendas that affect them.
//
// This function must be safe for concurrent access.
StandardVerifyFlags func() (txscript.ScriptFlags, error)
}
// TxDesc is a descriptor containing a transaction in the mempool along with
// additional metadata.
type TxDesc struct {
mining.TxDesc
// StartingPriority is the priority of the transaction when it was added
// to the pool.
StartingPriority float64
}
// TxPool is used as a source of transactions that need to be mined into blocks
// and relayed to other peers. It is safe for concurrent access from multiple
// peers.
type TxPool struct {
// The following variables must only be used atomically.
lastUpdated int64 // last time pool was updated.
mtx sync.RWMutex
cfg Config
pool map[chainhash.Hash]*TxDesc
orphans map[chainhash.Hash]*dcrutil.Tx
orphansByPrev map[chainhash.Hash]map[chainhash.Hash]*dcrutil.Tx
outpoints map[wire.OutPoint]*dcrutil.Tx
// Votes on blocks.
votesMtx sync.RWMutex
votes map[chainhash.Hash][]mining.VoteDesc
pennyTotal float64 // exponentially decaying total for penny spends.
lastPennyUnix int64 // unix time of last ``penny spend''
}
// insertVote inserts a vote into the map of block votes.
//
// This function MUST be called with the vote mutex locked (for writes).
func (mp *TxPool) insertVote(ssgen *dcrutil.Tx) error {
msgTx := ssgen.MsgTx()
ticketHash := &msgTx.TxIn[1].PreviousOutPoint.Hash
// Get the block it is voting on; here we're agnostic of height.
blockHash, blockHeight := stake.SSGenBlockVotedOn(msgTx)
// If there are currently no votes for this block,
// start a new buffered slice and store it.
vts, exists := mp.votes[blockHash]
if !exists {
vts = make([]mining.VoteDesc, 0, mp.cfg.ChainParams.TicketsPerBlock)
}
// Nothing to do if a vote for the ticket is already known.
for _, vt := range vts {
if vt.TicketHash.IsEqual(ticketHash) {
return nil
}
}
voteHash := ssgen.Hash()
voteBits := stake.SSGenVoteBits(msgTx)
vote := dcrutil.IsFlagSet16(voteBits, dcrutil.BlockValid)
voteTx := mining.VoteDesc{
VoteHash: *voteHash,
TicketHash: *ticketHash,
ApprovesParent: vote,
}
// Append the new vote.
mp.votes[blockHash] = append(vts, voteTx)
log.Debugf("Accepted vote %v for block hash %v (height %v), voting "+
"%v on the transaction tree", voteHash, blockHash, blockHeight,
vote)
return nil
}
// VoteHashesForBlock returns the hashes for all votes on the provided block
// hash that are currently available in the mempool.
//
// This function is safe for concurrent access.
func (mp *TxPool) VoteHashesForBlock(blockHash *chainhash.Hash) []chainhash.Hash {
mp.votesMtx.RLock()
vts, exists := mp.votes[*blockHash]
mp.votesMtx.RUnlock()
// Lookup the vote metadata for the block.
if !exists || len(vts) == 0 {
return nil
}
// Copy the vote hashes from the vote metadata.
hashes := make([]chainhash.Hash, 0, len(vts))
for _, vt := range vts {
hashes = append(hashes, vt.VoteHash)
}
return hashes
}
// VotesForBlocks returns the vote metadata for all votes on the provided
// block hashes that are currently available in the mempool.
//
// This function is safe for concurrent access.
func (mp *TxPool) VotesForBlocks(hashes []chainhash.Hash) [][]mining.VoteDesc {
result := make([][]mining.VoteDesc, 0, len(hashes))
mp.votesMtx.RLock()
for _, hash := range hashes {
votes := mp.votes[hash]
result = append(result, votes)
}
mp.votesMtx.RUnlock()
return result
}
// TODO Pruning of the votes map DECRED
// Ensure the TxPool type implements the mining.TxSource interface.
var _ mining.TxSource = (*TxPool)(nil)
// removeOrphan is the internal function which implements the public
// RemoveOrphan. See the comment for RemoveOrphan for more details.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *TxPool) removeOrphan(txHash *chainhash.Hash) {
log.Tracef("Removing orphan transaction %v", txHash)
// Nothing to do if passed tx is not an orphan.
tx, exists := mp.orphans[*txHash]
if !exists {
return
}
// Remove the reference from the previous orphan index.
for _, txIn := range tx.MsgTx().TxIn {
originTxHash := txIn.PreviousOutPoint.Hash
if orphans, exists := mp.orphansByPrev[originTxHash]; exists {
delete(orphans, *tx.Hash())
// Remove the map entry altogether if there are no
// longer any orphans which depend on it.
if len(orphans) == 0 {
delete(mp.orphansByPrev, originTxHash)
}
}
}
// Remove the transaction from the orphan pool.
delete(mp.orphans, *txHash)
}
// RemoveOrphan removes the passed orphan transaction from the orphan pool and
// previous orphan index.
//
// This function is safe for concurrent access.
func (mp *TxPool) RemoveOrphan(txHash *chainhash.Hash) {
mp.mtx.Lock()
mp.removeOrphan(txHash)
mp.mtx.Unlock()
}
// limitNumOrphans limits the number of orphan transactions by evicting a random
// orphan if adding a new one would cause it to overflow the max allowed.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *TxPool) limitNumOrphans() error {
if len(mp.orphans)+1 <= mp.cfg.Policy.MaxOrphanTxs {
return nil
}
// Remove a random entry from the map. For most compilers, Go's
// range statement iterates starting at a random item although
// that is not 100% guaranteed by the spec. The iteration order
// is not important here because an adversary would have to be
// able to pull off preimage attacks on the hashing function in
// order to target eviction of specific entries anyways.
for txHash := range mp.orphans {
mp.removeOrphan(&txHash)
break
}
return nil
}
// addOrphan adds an orphan transaction to the orphan pool.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *TxPool) addOrphan(tx *dcrutil.Tx) {
// Nothing to do if no orphans are allowed.
if mp.cfg.Policy.MaxOrphanTxs <= 0 {
return
}
// Limit the number orphan transactions to prevent memory exhaustion. A
// random orphan is evicted to make room if needed.
mp.limitNumOrphans()
mp.orphans[*tx.Hash()] = tx
for _, txIn := range tx.MsgTx().TxIn {
originTxHash := txIn.PreviousOutPoint.Hash
if _, exists := mp.orphansByPrev[originTxHash]; !exists {
mp.orphansByPrev[originTxHash] =
make(map[chainhash.Hash]*dcrutil.Tx)
}
mp.orphansByPrev[originTxHash][*tx.Hash()] = tx
}
log.Debugf("Stored orphan transaction %v (total: %d)", tx.Hash(),
len(mp.orphans))
}
// maybeAddOrphan potentially adds an orphan to the orphan pool.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *TxPool) maybeAddOrphan(tx *dcrutil.Tx) error {
// Ignore orphan transactions that are too large. This helps avoid
// a memory exhaustion attack based on sending a lot of really large
// orphans. In the case there is a valid transaction larger than this,
// it will ultimtely be rebroadcast after the parent transactions
// have been mined or otherwise received.
//
// Note that the number of orphan transactions in the orphan pool is
// also limited, so this equates to a maximum memory used of
// mp.cfg.Policy.MaxOrphanTxSize * mp.cfg.Policy.MaxOrphanTxs (which is ~5MB
// using the default values at the time this comment was written).
serializedLen := tx.MsgTx().SerializeSize()
if serializedLen > mp.cfg.Policy.MaxOrphanTxSize {
str := fmt.Sprintf("orphan transaction size of %d bytes is "+
"larger than max allowed size of %d bytes",
serializedLen, mp.cfg.Policy.MaxOrphanTxSize)
return txRuleError(wire.RejectNonstandard, str)
}
// Add the orphan if the none of the above disqualified it.
mp.addOrphan(tx)
return nil
}
// isTransactionInPool returns whether or not the passed transaction already
// exists in the main pool.
//
// This function MUST be called with the mempool lock held (for reads).
func (mp *TxPool) isTransactionInPool(hash *chainhash.Hash) bool {
if _, exists := mp.pool[*hash]; exists {
return true
}
return false
}
// IsTransactionInPool returns whether or not the passed transaction already
// exists in the main pool.
//
// This function is safe for concurrent access.
func (mp *TxPool) IsTransactionInPool(hash *chainhash.Hash) bool {
// Protect concurrent access.
mp.mtx.RLock()
inPool := mp.isTransactionInPool(hash)
mp.mtx.RUnlock()
return inPool
}
// isOrphanInPool returns whether or not the passed transaction already exists
// in the orphan pool.
//
// This function MUST be called with the mempool lock held (for reads).
func (mp *TxPool) isOrphanInPool(hash *chainhash.Hash) bool {
if _, exists := mp.orphans[*hash]; exists {
return true
}
return false
}
// IsOrphanInPool returns whether or not the passed transaction already exists
// in the orphan pool.
//
// This function is safe for concurrent access.
func (mp *TxPool) IsOrphanInPool(hash *chainhash.Hash) bool {
// Protect concurrent access.
mp.mtx.RLock()
inPool := mp.isOrphanInPool(hash)
mp.mtx.RUnlock()
return inPool
}
// haveTransaction returns whether or not the passed transaction already exists
// in the main pool or in the orphan pool.
//
// This function MUST be called with the mempool lock held (for reads).
func (mp *TxPool) haveTransaction(hash *chainhash.Hash) bool {
return mp.isTransactionInPool(hash) || mp.isOrphanInPool(hash)
}
// HaveTransaction returns whether or not the passed transaction already exists
// in the main pool or in the orphan pool.
//
// This function is safe for concurrent access.
func (mp *TxPool) HaveTransaction(hash *chainhash.Hash) bool {
// Protect concurrent access.
mp.mtx.RLock()
haveTx := mp.haveTransaction(hash)
mp.mtx.RUnlock()
return haveTx
}
// haveTransactions returns whether or not the passed transactions already exist
// in the main pool or in the orphan pool.
//
// This function MUST be called with the mempool lock held (for reads).
func (mp *TxPool) haveTransactions(hashes []*chainhash.Hash) []bool {
have := make([]bool, len(hashes))
for i := range hashes {
have[i] = mp.haveTransaction(hashes[i])
}
return have
}
// HaveTransactions returns whether or not the passed transactions already exist
// in the main pool or in the orphan pool.
//
// This function is safe for concurrent access.
func (mp *TxPool) HaveTransactions(hashes []*chainhash.Hash) []bool {
// Protect concurrent access.
mp.mtx.RLock()
haveTxns := mp.haveTransactions(hashes)
mp.mtx.RUnlock()
return haveTxns
}
// HaveAllTransactions returns whether or not all of the passed transaction
// hashes exist in the mempool.
//
// This function is safe for concurrent access.
func (mp *TxPool) HaveAllTransactions(hashes []chainhash.Hash) bool {
mp.mtx.RLock()
inPool := true
for _, h := range hashes {
if _, exists := mp.pool[h]; !exists {
inPool = false
break
}
}
mp.mtx.RUnlock()
return inPool
}
// removeTransaction is the internal function which implements the public
// RemoveTransaction. See the comment for RemoveTransaction for more details.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *TxPool) removeTransaction(tx *dcrutil.Tx, removeRedeemers bool) {
log.Tracef("Removing transaction %v", tx.Hash())
msgTx := tx.MsgTx()
txHash := tx.Hash()
var txType stake.TxType
if removeRedeemers {
// Remove any transactions which rely on this one.
txType = stake.DetermineTxType(msgTx)
tree := wire.TxTreeRegular
if txType != stake.TxTypeRegular {
tree = wire.TxTreeStake
}
for i := uint32(0); i < uint32(len(msgTx.TxOut)); i++ {
outpoint := wire.NewOutPoint(txHash, i, tree)
if txRedeemer, exists := mp.outpoints[*outpoint]; exists {
mp.removeTransaction(txRedeemer, true)
}
}
}
// Remove the transaction if needed.
if txDesc, exists := mp.pool[*txHash]; exists {
// Remove unconfirmed address index entries associated with the
// transaction if enabled.
if mp.cfg.AddrIndex != nil {
mp.cfg.AddrIndex.RemoveUnconfirmedTx(txHash)
}
// Mark the referenced outpoints as unspent by the pool.
for _, txIn := range txDesc.Tx.MsgTx().TxIn {
delete(mp.outpoints, txIn.PreviousOutPoint)
}
delete(mp.pool, *txHash)
atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
}
}
// RemoveTransaction removes the passed transaction from the mempool. When the
// removeRedeemers flag is set, any transactions that redeem outputs from the
// removed transaction will also be removed recursively from the mempool, as
// they would otherwise become orphans.
//
// This function is safe for concurrent access.
func (mp *TxPool) RemoveTransaction(tx *dcrutil.Tx, removeRedeemers bool) {
// Protect concurrent access.
mp.mtx.Lock()
mp.removeTransaction(tx, removeRedeemers)
mp.mtx.Unlock()
}
// RemoveDoubleSpends removes all transactions which spend outputs spent by the
// passed transaction from the memory pool. Removing those transactions then
// leads to removing all transactions which rely on them, recursively. This is
// necessary when a block is connected to the main chain because the block may
// contain transactions which were previously unknown to the memory pool.
//
// This function is safe for concurrent access.
func (mp *TxPool) RemoveDoubleSpends(tx *dcrutil.Tx) {
// Protect concurrent access.
mp.mtx.Lock()
for _, txIn := range tx.MsgTx().TxIn {
if txRedeemer, ok := mp.outpoints[txIn.PreviousOutPoint]; ok {
if !txRedeemer.Hash().IsEqual(tx.Hash()) {
mp.removeTransaction(txRedeemer, true)
}
}
}
mp.mtx.Unlock()
}
// addTransaction adds the passed transaction to the memory pool. It should
// not be called directly as it doesn't perform any validation. This is a
// helper for maybeAcceptTransaction.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *TxPool) addTransaction(utxoView *blockchain.UtxoViewpoint,
tx *dcrutil.Tx, txType stake.TxType, height int64, fee int64) {
// Add the transaction to the pool and mark the referenced outpoints
// as spent by the pool.
msgTx := tx.MsgTx()
mp.pool[*tx.Hash()] = &TxDesc{
TxDesc: mining.TxDesc{
Tx: tx,
Type: txType,
Added: time.Now(),
Height: height,
Fee: fee,
},
StartingPriority: mining.CalcPriority(msgTx, utxoView, height),
}
for _, txIn := range msgTx.TxIn {
mp.outpoints[txIn.PreviousOutPoint] = tx
}
atomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())
// Add unconfirmed address index entries associated with the transaction
// if enabled.
if mp.cfg.AddrIndex != nil {
mp.cfg.AddrIndex.AddUnconfirmedTx(tx, utxoView)
}
if mp.cfg.ExistsAddrIndex != nil {
mp.cfg.ExistsAddrIndex.AddUnconfirmedTx(msgTx)
}
}
// checkPoolDoubleSpend checks whether or not the passed transaction is
// attempting to spend coins already spent by other transactions in the pool.
// Note it does not check for double spends against transactions already in the
// main chain.
//
// This function MUST be called with the mempool lock held (for reads).
func (mp *TxPool) checkPoolDoubleSpend(tx *dcrutil.Tx, txType stake.TxType) error {
for i, txIn := range tx.MsgTx().TxIn {
// We don't care about double spends of stake bases.
if (txType == stake.TxTypeSSGen || txType == stake.TxTypeSSRtx) &&
(i == 0) {
continue
}
if txR, exists := mp.outpoints[txIn.PreviousOutPoint]; exists {
str := fmt.Sprintf("transaction %v in the pool "+
"already spends the same coins", txR.Hash())
return txRuleError(wire.RejectDuplicate, str)
}
}
return nil
}
// IsTxTreeKnownInvalid returns whether or not the transaction tree of the
// provided hash is knwon to be invalid according to the votes currently in the
// memory pool.
//
// The function is safe for concurrent access.
func (mp *TxPool) IsTxTreeKnownInvalid(hash *chainhash.Hash) bool {
mp.votesMtx.RLock()
vts := mp.votes[*hash]
mp.votesMtx.RUnlock()
// There are not possibly enough votes to tell if the regular transaction
// tree is valid or not, so assume it's valid.
if len(vts) <= int(mp.cfg.ChainParams.TicketsPerBlock/2) {
return false
}
// Otherwise, tally the votes and determine if it's valid or not.
var yes, no int
for _, vote := range vts {
if vote.ApprovesParent {
yes++
} else {
no++
}
}
return yes <= no
}
// fetchInputUtxos loads utxo details about the input transactions referenced by
// the passed transaction. First, it loads the details form the viewpoint of
// the main chain, then it adjusts them based upon the contents of the
// transaction pool.
//
// This function MUST be called with the mempool lock held (for reads).
func (mp *TxPool) fetchInputUtxos(tx *dcrutil.Tx) (*blockchain.UtxoViewpoint, error) {
knownInvalid := mp.IsTxTreeKnownInvalid(mp.cfg.BestHash())
utxoView, err := mp.cfg.FetchUtxoView(tx, !knownInvalid)
if err != nil {
return nil, err
}
// Attempt to populate any missing inputs from the transaction pool.
for originHash, entry := range utxoView.Entries() {
if entry != nil && !entry.IsFullySpent() {
continue
}
if poolTxDesc, exists := mp.pool[originHash]; exists {
utxoView.AddTxOuts(poolTxDesc.Tx, mining.UnminedHeight,
wire.NullBlockIndex)
}
}
return utxoView, nil
}
// FetchTransaction returns the requested transaction from the transaction pool.
// This only fetches from the main transaction pool and does not include
// orphans.
//
// This function is safe for concurrent access.
func (mp *TxPool) FetchTransaction(txHash *chainhash.Hash, includeRecentBlock bool) (*dcrutil.Tx, error) {
// Protect concurrent access.
mp.mtx.RLock()
txDesc, exists := mp.pool[*txHash]
mp.mtx.RUnlock()
if exists {
return txDesc.Tx, nil
}
// For Decred, the latest block is considered "unconfirmed"
// for the regular transaction tree. Search that if the
// user indicates too, as well.
if includeRecentBlock {
bl, err := mp.cfg.BlockByHash(mp.cfg.BestHash())
if err != nil {
return nil, err
}
for _, tx := range bl.Transactions() {
if tx.Hash().IsEqual(txHash) {
return tx, nil
}
}
}
return nil, fmt.Errorf("transaction is not in the pool")
}
// maybeAcceptTransaction is the internal function which implements the public
// MaybeAcceptTransaction. See the comment for MaybeAcceptTransaction for
// more details.
//
// This function MUST be called with the mempool lock held (for writes).
// DECRED - TODO
// We need to make sure thing also assigns the TxType after it evaluates the tx,
// so that we can easily pick different stake tx types from the mempool later.
// This should probably be done at the bottom using "IsSStx" etc functions.
// It should also set the dcrutil tree type for the tx as well.
func (mp *TxPool) maybeAcceptTransaction(tx *dcrutil.Tx, isNew, rateLimit, allowHighFees bool) ([]*chainhash.Hash, error) {
msgTx := tx.MsgTx()
txHash := tx.Hash()
// Don't accept the transaction if it already exists in the pool. This
// applies to orphan transactions as well. This check is intended to
// be a quick check to weed out duplicates.
if mp.haveTransaction(txHash) {
str := fmt.Sprintf("already have transaction %v", txHash)
return nil, txRuleError(wire.RejectDuplicate, str)
}
// Perform preliminary sanity checks on the transaction. This makes
// use of chain which contains the invariant rules for what
// transactions are allowed into blocks.
err := blockchain.CheckTransactionSanity(msgTx, mp.cfg.ChainParams)
if err != nil {
if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr)
}
return nil, err
}
// A standalone transaction must not be a coinbase transaction.
if blockchain.IsCoinBase(tx) {
str := fmt.Sprintf("transaction %v is an individual coinbase",
txHash)
return nil, txRuleError(wire.RejectInvalid, str)
}
// Don't accept transactions with a lock time after the maximum int32
// value for now. This is an artifact of older bitcoind clients which
// treated this field as an int32 and would treat anything larger
// incorrectly (as negative).
if msgTx.LockTime > math.MaxInt32 {
str := fmt.Sprintf("transaction %v has a lock time after "+
"2038 which is not accepted yet", txHash)
return nil, txRuleError(wire.RejectNonstandard, str)
}
// Get the current height of the main chain. A standalone transaction
// will be mined into the next block at best, so its height is at least
// one more than the current height.
bestHeight := mp.cfg.BestHeight()
nextBlockHeight := bestHeight + 1
// Determine what type of transaction we're dealing with (regular or stake).
// Then, be sure to set the tx tree correctly as it's possible a use submitted
// it to the network with TxTreeUnknown.
txType := stake.DetermineTxType(msgTx)
if txType == stake.TxTypeRegular {
tx.SetTree(wire.TxTreeRegular)
} else {
tx.SetTree(wire.TxTreeStake)
}
// Don't allow non-standard transactions if the mempool config forbids
// their acceptance and relaying.
medianTime := mp.cfg.PastMedianTime()
if !mp.cfg.Policy.AcceptNonStd {
err := checkTransactionStandard(tx, txType, nextBlockHeight,
medianTime, mp.cfg.Policy.MinRelayTxFee,
mp.cfg.Policy.MaxTxVersion)
if err != nil {
// Attempt to extract a reject code from the error so
// it can be retained. When not possible, fall back to
// a non standard error.
rejectCode, found := extractRejectCode(err)
if !found {
rejectCode = wire.RejectNonstandard
}
str := fmt.Sprintf("transaction %v is not standard: %v",
txHash, err)
return nil, txRuleError(rejectCode, str)
}
}
// If the transaction is a ticket, ensure that it meets the next
// stake difficulty.
if txType == stake.TxTypeSStx {
sDiff, err := mp.cfg.NextStakeDifficulty()
if err != nil {
// This is an unexpected error so don't turn it into a
// rule error.
return nil, err
}
if msgTx.TxOut[0].Value < sDiff {
str := fmt.Sprintf("transaction %v has not enough funds "+
"to meet stake difficulty (ticket diff %v < next diff %v)",
txHash, msgTx.TxOut[0].Value, sDiff)
return nil, txRuleError(wire.RejectInsufficientFee, str)
}
}
// Handle stake transaction double spending exceptions.
if (txType == stake.TxTypeSSGen) || (txType == stake.TxTypeSSRtx) {
if txType == stake.TxTypeSSGen {
ssGenAlreadyFound := 0
for _, mpTx := range mp.pool {
if mpTx.Type == stake.TxTypeSSGen {
if mpTx.Tx.MsgTx().TxIn[1].PreviousOutPoint ==
msgTx.TxIn[1].PreviousOutPoint {
ssGenAlreadyFound++
}
}
if ssGenAlreadyFound > maxSSGensDoubleSpends {
str := fmt.Sprintf("transaction %v in the pool "+
"with more than %v ssgens",
msgTx.TxIn[1].PreviousOutPoint,
maxSSGensDoubleSpends)
return nil, txRuleError(wire.RejectDuplicate, str)
}
}
}
if txType == stake.TxTypeSSRtx {
for _, mpTx := range mp.pool {
if mpTx.Type == stake.TxTypeSSRtx {
if mpTx.Tx.MsgTx().TxIn[0].PreviousOutPoint ==
msgTx.TxIn[0].PreviousOutPoint {
str := fmt.Sprintf("transaction %v in the pool "+
" as a ssrtx. Only one ssrtx allowed.",
msgTx.TxIn[0].PreviousOutPoint)
return nil, txRuleError(wire.RejectDuplicate, str)
}
}
}
}
} else {
// The transaction may not use any of the same outputs as other
// transactions already in the pool as that would ultimately result in a
// double spend. This check is intended to be quick and therefore only
// detects double spends within the transaction pool itself. The
// transaction could still be double spending coins from the main chain
// at this point. There is a more in-depth check that happens later
// after fetching the referenced transaction inputs from the main chain
// which examines the actual spend data and prevents double spends.
err = mp.checkPoolDoubleSpend(tx, txType)
if err != nil {
return nil, err
}
}
// Votes that are on too old of blocks are rejected.
if txType == stake.TxTypeSSGen {
_, voteHeight := stake.SSGenBlockVotedOn(msgTx)
if (int64(voteHeight) < nextBlockHeight-maximumVoteAgeDelta) &&
!mp.cfg.Policy.AllowOldVotes {
str := fmt.Sprintf("transaction %v votes on old "+
"block height of %v which is before the "+
"current cutoff height of %v",
tx.Hash(), voteHeight, nextBlockHeight-maximumVoteAgeDelta)
return nil, txRuleError(wire.RejectNonstandard, str)
}
}
// Fetch all of the unspent transaction outputs referenced by the inputs
// to this transaction. This function also attempts to fetch the
// transaction itself to be used for detecting a duplicate transaction
// without needing to do a separate lookup.
utxoView, err := mp.fetchInputUtxos(tx)
if err != nil {
if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr)
}
return nil, err
}
// Don't allow the transaction if it exists in the main chain and is not
// not already fully spent.
txEntry := utxoView.LookupEntry(txHash)
if txEntry != nil && !txEntry.IsFullySpent() {
return nil, txRuleError(wire.RejectDuplicate,
"transaction already exists")
}
delete(utxoView.Entries(), *txHash)
// Transaction is an orphan if any of the inputs don't exist.
var missingParents []*chainhash.Hash
for i, txIn := range msgTx.TxIn {
if i == 0 && txType == stake.TxTypeSSGen {
continue
}
entry := utxoView.LookupEntry(&txIn.PreviousOutPoint.Hash)
if entry == nil || entry.IsFullySpent() {
// Must make a copy of the hash here since the iterator
// is replaced and taking its address directly would
// result in all of the entries pointing to the same
// memory location and thus all be the final hash.
hashCopy := txIn.PreviousOutPoint.Hash
missingParents = append(missingParents, &hashCopy)
// Prevent a panic in the logger by continuing here if the
// transaction input is nil.
if entry == nil {
log.Tracef("Transaction %v uses unknown input %v "+
"and will be considered an orphan", txHash,
txIn.PreviousOutPoint.Hash)
continue
}
if entry.IsFullySpent() {
log.Tracef("Transaction %v uses full spent input %v "+
"and will be considered an orphan", txHash,
txIn.PreviousOutPoint.Hash)
}
}
}
if len(missingParents) > 0 {
return missingParents, nil
}
// Don't allow the transaction into the mempool unless its sequence
// lock is active, meaning that it'll be allowed into the next block
// with respect to its defined relative lock times.
seqLock, err := mp.cfg.CalcSequenceLock(tx, utxoView)
if err != nil {
if cerr, ok := err.(blockchain.RuleError); ok {
return nil, chainRuleError(cerr)
}
return nil, err
}
if !blockchain.SequenceLockActive(seqLock, nextBlockHeight, medianTime) {
return nil, txRuleError(wire.RejectNonstandard,
"transaction sequence locks on inputs not met")
}
// Perform several checks on the transaction inputs using the invariant
// rules in chain for what transactions are allowed into blocks.
// Also returns the fees associated with the transaction which will be
// used later. The fraud proof is not checked because it will be
// filled in by the miner.
txFee, err := blockchain.CheckTransactionInputs(mp.cfg.SubsidyCache,
tx, nextBlockHeight, utxoView, false, mp.cfg.ChainParams)