This repository has been archived by the owner on Sep 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathpool.go
2305 lines (2103 loc) · 71.7 KB
/
pool.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 2021 Erigon contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package txpool
import (
"bytes"
"container/heap"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"math"
"runtime"
"sort"
"sync"
"time"
"github.com/VictoriaMetrics/metrics"
"github.com/go-stack/stack"
"github.com/google/btree"
"github.com/hashicorp/golang-lru/simplelru"
"github.com/holiman/uint256"
"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/fixedgas"
"github.com/ledgerwatch/erigon-lib/gointerfaces"
"github.com/ledgerwatch/erigon-lib/gointerfaces/grpcutil"
"github.com/ledgerwatch/erigon-lib/gointerfaces/remote"
proto_txpool "github.com/ledgerwatch/erigon-lib/gointerfaces/txpool"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon-lib/kv/kvcache"
"github.com/ledgerwatch/erigon-lib/kv/mdbx"
"github.com/ledgerwatch/log/v3"
"go.uber.org/atomic"
)
var (
processBatchTxsTimer = metrics.NewSummary(`pool_process_remote_txs`)
addRemoteTxsTimer = metrics.NewSummary(`pool_add_remote_txs`)
newBlockTimer = metrics.NewSummary(`pool_new_block`)
writeToDbTimer = metrics.NewSummary(`pool_write_to_db`)
propagateToNewPeerTimer = metrics.NewSummary(`pool_propagate_to_new_peer`)
propagateNewTxsTimer = metrics.NewSummary(`pool_propagate_new_txs`)
writeToDbBytesCounter = metrics.GetOrCreateCounter(`pool_write_to_db_bytes`)
)
const ASSERT = false
type Config struct {
DBDir string
SyncToNewPeersEvery time.Duration
ProcessRemoteTxsEvery time.Duration
CommitEvery time.Duration
LogEvery time.Duration
PendingSubPoolLimit int
BaseFeeSubPoolLimit int
QueuedSubPoolLimit int
MinFeeCap uint64
AccountSlots uint64 // Number of executable transaction slots guaranteed per account
PriceBump uint64 // Price bump percentage to replace an already existing transaction
TracedSenders []string // List of senders for which tx pool should print out debugging info
}
var DefaultConfig = Config{
SyncToNewPeersEvery: 2 * time.Minute,
ProcessRemoteTxsEvery: 100 * time.Millisecond,
CommitEvery: 15 * time.Second,
LogEvery: 30 * time.Second,
PendingSubPoolLimit: 10_000,
BaseFeeSubPoolLimit: 10_000,
QueuedSubPoolLimit: 10_000,
MinFeeCap: 1,
AccountSlots: 16, //TODO: to choose right value (16 to be compat with Geth)
PriceBump: 10, // Price bump percentage to replace an already existing transaction
}
// Pool is interface for the transaction pool
// This interface exists for the convinience of testing, and not yet because
// there are multiple implementations
type Pool interface {
ValidateSerializedTxn(serializedTxn []byte) error
// Handle 3 main events - new remote txs from p2p, new local txs from RPC, new blocks from execution layer
AddRemoteTxs(ctx context.Context, newTxs TxSlots)
AddLocalTxs(ctx context.Context, newTxs TxSlots) ([]DiscardReason, error)
OnNewBlock(ctx context.Context, stateChanges *remote.StateChangeBatch, unwindTxs, minedTxs TxSlots, tx kv.Tx) error
// IdHashKnown check whether transaction with given Id hash is known to the pool
IdHashKnown(tx kv.Tx, hash []byte) (bool, error)
Started() bool
GetRlp(tx kv.Tx, hash []byte) ([]byte, error)
AddNewGoodPeer(peerID PeerID)
}
var _ Pool = (*TxPool)(nil) // compile-time interface check
// SubPoolMarker ordered bitset responsible to sort transactions by sub-pools. Bits meaning:
// 1. Minimum fee requirement. Set to 1 if feeCap of the transaction is no less than in-protocol parameter of minimal base fee. Set to 0 if feeCap is less than minimum base fee, which means this transaction will never be included into this particular chain.
// 2. Absence of nonce gaps. Set to 1 for transactions whose nonce is N, state nonce for the sender is M, and there are transactions for all nonces between M and N from the same sender. Set to 0 is the transaction's nonce is divided from the state nonce by one or more nonce gaps.
// 3. Sufficient balance for gas. Set to 1 if the balance of sender's account in the state is B, nonce of the sender in the state is M, nonce of the transaction is N, and the sum of feeCap x gasLimit + transferred_value of all transactions from this sender with nonces N+1 ... M is no more than B. Set to 0 otherwise. In other words, this bit is set if there is currently a guarantee that the transaction and all its required prior transactions will be able to pay for gas.
// 4. Dynamic fee requirement. Set to 1 if feeCap of the transaction is no less than baseFee of the currently pending block. Set to 0 otherwise.
// 5. Local transaction. Set to 1 if transaction is local.
type SubPoolMarker uint8
const (
EnoughFeeCapProtocol = 0b100000
NoNonceGaps = 0b010000
EnoughBalance = 0b001000
NotTooMuchGas = 0b000100
EnoughFeeCapBlock = 0b000010
IsLocal = 0b000001
BaseFeePoolBits = EnoughFeeCapProtocol + NoNonceGaps + EnoughBalance + NotTooMuchGas
QueuedPoolBits = EnoughFeeCapProtocol
)
type DiscardReason uint8
const (
NotSet DiscardReason = 0 // analog of "nil-value", means it will be set in future
Success DiscardReason = 1
AlreadyKnown DiscardReason = 2
Mined DiscardReason = 3
ReplacedByHigherTip DiscardReason = 4
UnderPriced DiscardReason = 5
ReplaceUnderpriced DiscardReason = 6 // if a transaction is attempted to be replaced with a different one without the required price bump.
FeeTooLow DiscardReason = 7
OversizedData DiscardReason = 8
InvalidSender DiscardReason = 9
NegativeValue DiscardReason = 10 // ensure no one is able to specify a transaction with a negative value.
Spammer DiscardReason = 11
PendingPoolOverflow DiscardReason = 12
BaseFeePoolOverflow DiscardReason = 13
QueuedPoolOverflow DiscardReason = 14
GasUintOverflow DiscardReason = 15
IntrinsicGas DiscardReason = 16
RLPTooLong DiscardReason = 17
NonceTooLow DiscardReason = 18
InsufficientFunds DiscardReason = 19
NotReplaced DiscardReason = 20 // There was an existing transaction with the same sender and nonce, not enough price bump to replace
DuplicateHash DiscardReason = 21 // There was an existing transaction with the same hash
)
func (r DiscardReason) String() string {
switch r {
case NotSet:
return "not set"
case Success:
return "success"
case AlreadyKnown:
return "already known"
case Mined:
return "mined"
case ReplacedByHigherTip:
return "replaced by transaction with higher tip"
case UnderPriced:
return "underpriced"
case ReplaceUnderpriced:
return "replacement transaction underpriced"
case FeeTooLow:
return "fee too low"
case OversizedData:
return "oversized data"
case InvalidSender:
return "invalid sender"
case NegativeValue:
return "negative value"
case PendingPoolOverflow:
return "pending sub-pool is full"
case BaseFeePoolOverflow:
return "baseFee sub-pool is full"
case QueuedPoolOverflow:
return "queued sub-pool is full"
case GasUintOverflow:
return "GasUintOverflow"
case IntrinsicGas:
return "IntrinsicGas"
case RLPTooLong:
return "RLPTooLong"
case NonceTooLow:
return "nonce too low"
case InsufficientFunds:
return "insufficient funds"
case NotReplaced:
return "could not replace existing tx"
case DuplicateHash:
return "existing tx with same hash"
default:
panic(fmt.Sprintf("discard reason: %d", r))
}
}
// metaTx holds transaction and some metadata
type metaTx struct {
Tx *TxSlot
subPool SubPoolMarker
nonceDistance uint64 // how far their nonces are from the state's nonce for the sender
cumulativeBalanceDistance uint64 // how far their cumulativeRequiredBalance are from the state's balance for the sender
minFeeCap uint64
minTip uint64
bestIndex int
worstIndex int
currentSubPool SubPoolType
timestamp uint64 // when it was added to pool
}
func newMetaTx(slot *TxSlot, isLocal bool, timestmap uint64) *metaTx {
mt := &metaTx{Tx: slot, worstIndex: -1, bestIndex: -1, timestamp: timestmap}
if isLocal {
mt.subPool = IsLocal
}
return mt
}
type SubPoolType uint8
const PendingSubPool SubPoolType = 1
const BaseFeeSubPool SubPoolType = 2
const QueuedSubPool SubPoolType = 3
func (sp SubPoolType) String() string {
switch sp {
case PendingSubPool:
return "Pending"
case BaseFeeSubPool:
return "BaseFee"
case QueuedSubPool:
return "Queued"
}
return fmt.Sprintf("Unknown:%d", sp)
}
// sender - immutable structure which stores only nonce and balance of account
type sender struct {
balance uint256.Int
nonce uint64
}
func newSender(nonce uint64, balance uint256.Int) *sender {
return &sender{nonce: nonce, balance: balance}
}
var emptySender = newSender(0, *uint256.NewInt(0))
type sortByNonce struct{ *metaTx }
func (i sortByNonce) Less(than btree.Item) bool {
if i.metaTx.Tx.senderID != than.(sortByNonce).metaTx.Tx.senderID {
return i.metaTx.Tx.senderID < than.(sortByNonce).metaTx.Tx.senderID
}
return i.metaTx.Tx.nonce < than.(sortByNonce).metaTx.Tx.nonce
}
func calcProtocolBaseFee(baseFee uint64) uint64 {
return 7
}
// TxPool - holds all pool-related data structures and lock-based tiny methods
// most of logic implemented by pure tests-friendly functions
//
// txpool doesn't start any goroutines - "leave concurrency to user" design
// txpool has no DB or TX fields - "leave db transactions management to user" design
// txpool has _chainDB field - but it must maximize local state cache hit-rate - and perform minimum _chainDB transactions
//
// It preserve TxSlot objects immutable
type TxPool struct {
lock *sync.RWMutex
started atomic.Bool
lastSeenBlock atomic.Uint64
pendingBaseFee atomic.Uint64
blockGasLimit atomic.Uint64
// batch processing of remote transactions
// handling works fast without batching, but batching allow:
// - reduce amount of _chainDB transactions
// - batch notifications about new txs (reduce P2P spam to other nodes about txs propagation)
// - and as a result reducing pool.RWLock contention
unprocessedRemoteTxs *TxSlots
unprocessedRemoteByHash map[string]int // to reject duplicates
byHash map[string]*metaTx // tx_hash => tx : only not committed to db yet records
discardReasonsLRU *simplelru.LRU // tx_hash => discard_reason : non-persisted
pending *PendingPool
baseFee, queued *SubPool
isLocalLRU *simplelru.LRU // tx_hash => is_local : to restore isLocal flag of unwinded transactions
newPendingTxs chan Hashes // notifications about new txs in Pending sub-pool
deletedTxs []*metaTx // list of discarded txs since last db commit
all *BySenderAndNonce // senderID => (sorted map of tx nonce => *metaTx)
promoted Hashes // pre-allocated temporary buffer to write promoted to pending pool txn hashes
_chainDB kv.RoDB // remote db - use it wisely
_stateCache kvcache.Cache
cfg Config
recentlyConnectedPeers *recentlyConnectedPeers // all txs will be propagated to this peers eventually, and clear list
senders *sendersBatch
chainID uint256.Int
}
func New(newTxs chan Hashes, coreDB kv.RoDB, cfg Config, cache kvcache.Cache, chainID uint256.Int) (*TxPool, error) {
localsHistory, err := simplelru.NewLRU(10_000, nil)
if err != nil {
return nil, err
}
discardHistory, err := simplelru.NewLRU(10_000, nil)
if err != nil {
return nil, err
}
byNonce := &BySenderAndNonce{
tree: btree.New(32),
search: sortByNonce{&metaTx{Tx: &TxSlot{}}},
senderIDTxnCount: map[uint64]int{},
}
tracedSenders := make(map[string]struct{})
for _, sender := range cfg.TracedSenders {
tracedSenders[sender] = struct{}{}
}
return &TxPool{
lock: &sync.RWMutex{},
byHash: map[string]*metaTx{},
isLocalLRU: localsHistory,
discardReasonsLRU: discardHistory,
all: byNonce,
recentlyConnectedPeers: &recentlyConnectedPeers{},
pending: NewPendingSubPool(PendingSubPool, cfg.PendingSubPoolLimit),
baseFee: NewSubPool(BaseFeeSubPool, cfg.BaseFeeSubPoolLimit),
queued: NewSubPool(QueuedSubPool, cfg.QueuedSubPoolLimit),
newPendingTxs: newTxs,
_stateCache: cache,
senders: newSendersCache(tracedSenders),
_chainDB: coreDB,
cfg: cfg,
chainID: chainID,
unprocessedRemoteTxs: &TxSlots{},
unprocessedRemoteByHash: map[string]int{},
promoted: make(Hashes, 0, 32*1024),
}, nil
}
func (p *TxPool) OnNewBlock(ctx context.Context, stateChanges *remote.StateChangeBatch, unwindTxs, minedTxs TxSlots, tx kv.Tx) error {
defer newBlockTimer.UpdateDuration(time.Now())
//t := time.Now()
cache := p.cache()
cache.OnNewBlock(stateChanges)
coreTx, err := p.coreDB().BeginRo(ctx)
if err != nil {
return err
}
defer coreTx.Rollback()
p.lock.Lock()
defer p.lock.Unlock()
p.lastSeenBlock.Store(stateChanges.ChangeBatch[len(stateChanges.ChangeBatch)-1].BlockHeight)
if !p.started.Load() {
if err := p.fromDB(ctx, tx, coreTx); err != nil {
return fmt.Errorf("loading txs from DB: %w", err)
}
}
cacheView, err := cache.View(ctx, coreTx)
if err != nil {
return err
}
if ASSERT {
if _, err := kvcache.AssertCheckValues(ctx, coreTx, cache); err != nil {
log.Error("AssertCheckValues", "err", err, "stack", stack.Trace().String())
}
}
if err := minedTxs.Valid(); err != nil {
return err
}
baseFee := stateChanges.PendingBlockBaseFee
pendingBaseFee, baseFeeChanged := p.setBaseFee(baseFee)
// Update pendingBase for all pool queues and slices
if baseFeeChanged {
p.pending.best.pendingBaseFee = pendingBaseFee
p.pending.worst.pendingBaseFee = pendingBaseFee
p.baseFee.best.pendingBastFee = pendingBaseFee
p.baseFee.worst.pendingBaseFee = pendingBaseFee
p.queued.best.pendingBastFee = pendingBaseFee
p.queued.worst.pendingBaseFee = pendingBaseFee
}
p.blockGasLimit.Store(stateChanges.BlockGasLimit)
if err := p.senders.onNewBlock(stateChanges, unwindTxs, minedTxs); err != nil {
return err
}
_, unwindTxs, err = p.validateTxs(&unwindTxs, cacheView)
if err != nil {
return err
}
if ASSERT {
for _, txn := range unwindTxs.txs {
if txn.senderID == 0 {
panic(fmt.Errorf("onNewBlock.unwindTxs: senderID can't be zero"))
}
}
for _, txn := range minedTxs.txs {
if txn.senderID == 0 {
panic(fmt.Errorf("onNewBlock.minedTxs: senderID can't be zero"))
}
}
}
if err := removeMined(p.all, minedTxs.txs, p.pending, p.baseFee, p.queued, p.discardLocked); err != nil {
return err
}
//log.Debug("[txpool] new block", "unwinded", len(unwindTxs.txs), "mined", len(minedTxs.txs), "baseFee", baseFee, "blockHeight", blockHeight)
p.pending.resetAddedHashes()
p.baseFee.resetAddedHashes()
if err := addTxsOnNewBlock(p.lastSeenBlock.Load(), cacheView, stateChanges, p.senders, unwindTxs,
pendingBaseFee, stateChanges.BlockGasLimit,
p.pending, p.baseFee, p.queued, p.all, p.byHash, p.addLocked, p.discardLocked); err != nil {
return err
}
p.pending.EnforceWorstInvariants()
p.baseFee.EnforceInvariants()
p.queued.EnforceInvariants()
promote(p.pending, p.baseFee, p.queued, pendingBaseFee, p.discardLocked)
p.pending.EnforceBestInvariants()
p.promoted = p.pending.appendAddedHashes(p.promoted[:0])
p.promoted = p.baseFee.appendAddedHashes(p.promoted)
if p.started.CAS(false, true) {
log.Info("[txpool] Started")
}
if p.promoted.Len() > 0 {
select {
case p.newPendingTxs <- common.Copy(p.promoted):
default:
}
}
//log.Info("[txpool] new block", "number", p.lastSeenBlock.Load(), "pendngBaseFee", pendingBaseFee, "in", time.Since(t))
return nil
}
func (p *TxPool) processRemoteTxs(ctx context.Context) error {
if !p.started.Load() {
return fmt.Errorf("txpool not started yet")
}
cache := p.cache()
defer processBatchTxsTimer.UpdateDuration(time.Now())
coreTx, err := p.coreDB().BeginRo(ctx)
if err != nil {
return err
}
defer coreTx.Rollback()
cacheView, err := cache.View(ctx, coreTx)
if err != nil {
return err
}
//t := time.Now()
p.lock.Lock()
defer p.lock.Unlock()
l := len(p.unprocessedRemoteTxs.txs)
if l == 0 {
return nil
}
err = p.senders.registerNewSenders(p.unprocessedRemoteTxs)
if err != nil {
return err
}
_, newTxs, err := p.validateTxs(p.unprocessedRemoteTxs, cacheView)
if err != nil {
return err
}
p.pending.resetAddedHashes()
p.baseFee.resetAddedHashes()
if _, err := addTxs(p.lastSeenBlock.Load(), cacheView, p.senders, newTxs,
p.pendingBaseFee.Load(), p.blockGasLimit.Load(), p.pending, p.baseFee, p.queued, p.all, p.byHash, p.addLocked, p.discardLocked); err != nil {
return err
}
p.promoted = p.pending.appendAddedHashes(p.promoted[:0])
p.promoted = p.baseFee.appendAddedHashes(p.promoted)
if p.promoted.Len() > 0 {
select {
case <-ctx.Done():
return nil
case p.newPendingTxs <- common.Copy(p.promoted):
default:
}
}
p.unprocessedRemoteTxs.Resize(0)
p.unprocessedRemoteByHash = map[string]int{}
//log.Info("[txpool] on new txs", "amount", len(newPendingTxs.txs), "in", time.Since(t))
return nil
}
func (p *TxPool) getRlpLocked(tx kv.Tx, hash []byte) (rlpTxn []byte, sender []byte, isLocal bool, err error) {
txn, ok := p.byHash[string(hash)]
if ok && txn.Tx.rlp != nil {
return txn.Tx.rlp, p.senders.senderID2Addr[txn.Tx.senderID], txn.subPool&IsLocal > 0, nil
}
v, err := tx.GetOne(kv.PoolTransaction, hash)
if err != nil {
return nil, nil, false, err
}
if v == nil {
return nil, nil, false, nil
}
return v[20:], v[:20], txn != nil && txn.subPool&IsLocal > 0, nil
}
func (p *TxPool) GetRlp(tx kv.Tx, hash []byte) ([]byte, error) {
p.lock.RLock()
defer p.lock.RUnlock()
rlpTx, _, _, err := p.getRlpLocked(tx, hash)
return common.Copy(rlpTx), err
}
func (p *TxPool) AppendLocalHashes(buf []byte) []byte {
p.lock.RLock()
defer p.lock.RUnlock()
for hash, txn := range p.byHash {
if txn.subPool&IsLocal == 0 {
continue
}
buf = append(buf, hash...)
}
return buf
}
func (p *TxPool) AppendRemoteHashes(buf []byte) []byte {
p.lock.RLock()
defer p.lock.RUnlock()
for hash, txn := range p.byHash {
if txn.subPool&IsLocal != 0 {
continue
}
buf = append(buf, hash...)
}
for hash := range p.unprocessedRemoteByHash {
buf = append(buf, hash...)
}
return buf
}
func (p *TxPool) AppendAllHashes(buf []byte) []byte {
buf = p.AppendLocalHashes(buf)
buf = p.AppendRemoteHashes(buf)
return buf
}
func (p *TxPool) IdHashKnown(tx kv.Tx, hash []byte) (bool, error) {
p.lock.RLock()
defer p.lock.RUnlock()
if _, ok := p.discardReasonsLRU.Get(string(hash)); ok {
return true, nil
}
if _, ok := p.unprocessedRemoteByHash[string(hash)]; ok {
return true, nil
}
if _, ok := p.byHash[string(hash)]; ok {
return true, nil
}
return tx.Has(kv.PoolTransaction, hash)
}
func (p *TxPool) IsLocal(idHash []byte) bool {
p.lock.RLock()
defer p.lock.RUnlock()
return p.isLocalLRU.Contains(string(idHash))
}
func (p *TxPool) AddNewGoodPeer(peerID PeerID) { p.recentlyConnectedPeers.AddPeer(peerID) }
func (p *TxPool) Started() bool { return p.started.Load() }
// Best - returns top `n` elements of pending queue
// id doesn't perform full copy of txs, hovewer underlying elements are immutable
func (p *TxPool) Best(n uint16, txs *TxsRlp, tx kv.Tx) error {
p.lock.RLock()
defer p.lock.RUnlock()
txs.Resize(uint(min(uint64(n), uint64(len(p.pending.best.ms)))))
best := p.pending.best
for i, j := 0, 0; j < int(n) && i < len(best.ms); i++ {
if best.ms[i].Tx.gas >= p.blockGasLimit.Load() {
// Skip transactions with very large gas limit
continue
}
rlpTx, sender, isLocal, err := p.getRlpLocked(tx, best.ms[i].Tx.IdHash[:])
if err != nil {
return err
}
if len(rlpTx) == 0 {
continue
}
txs.Txs[j] = rlpTx
copy(txs.Senders.At(j), sender)
txs.IsLocal[j] = isLocal
j++
}
return nil
}
func (p *TxPool) CountContent() (int, int, int) {
p.lock.RLock()
defer p.lock.RUnlock()
return p.pending.Len(), p.baseFee.Len(), p.queued.Len()
}
func (p *TxPool) AddRemoteTxs(_ context.Context, newTxs TxSlots) {
defer addRemoteTxsTimer.UpdateDuration(time.Now())
p.lock.Lock()
defer p.lock.Unlock()
for i, txn := range newTxs.txs {
_, ok := p.unprocessedRemoteByHash[string(txn.IdHash[:])]
if ok {
continue
}
p.unprocessedRemoteTxs.Append(txn, newTxs.senders.At(i), false)
}
}
func (p *TxPool) validateTx(txn *TxSlot, isLocal bool, stateCache kvcache.CacheView) DiscardReason {
// Drop non-local transactions under our own minimal accepted gas price or tip
if !isLocal && txn.feeCap < p.cfg.MinFeeCap {
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: validateTx underpriced idHash=%x local=%t, feeCap=%d, cfg.MinFeeCap=%d", txn.IdHash, isLocal, txn.feeCap, p.cfg.MinFeeCap))
}
return UnderPriced
}
gas, reason := CalcIntrinsicGas(uint64(txn.dataLen), uint64(txn.dataNonZeroLen), nil, txn.creation, true, true)
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: validateTx intrinsic gas idHash=%x gas=%d", txn.IdHash, gas))
}
if reason != Success {
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: validateTx intrinsic gas calculated failed idHash=%x reason=%s", txn.IdHash, reason))
}
return reason
}
if gas > txn.gas {
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: validateTx intrinsic gas > txn.gas idHash=%x gas=%d, txn.gas=%d", txn.IdHash, gas, txn.gas))
}
return IntrinsicGas
}
if uint64(p.all.count(txn.senderID)) > p.cfg.AccountSlots {
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: validateTx marked as spamming idHash=%x slots=%d, limit=%d", txn.IdHash, p.all.count(txn.senderID), p.cfg.AccountSlots))
}
return Spammer
}
// check nonce and balance
senderNonce, senderBalance, _ := p.senders.info(stateCache, txn.senderID)
if senderNonce > txn.nonce {
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: validateTx nonce too low idHash=%x nonce in state=%d, txn.nonce=%d", txn.IdHash, senderNonce, txn.nonce))
}
return NonceTooLow
}
// Transactor should have enough funds to cover the costs
total := uint256.NewInt(txn.gas)
total.Mul(total, uint256.NewInt(txn.tip))
total.Add(total, &txn.value)
if senderBalance.Cmp(total) < 0 {
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: validateTx insufficient funds idHash=%x balance in state=%d, txn.gas*txn.tip=%d", txn.IdHash, senderBalance, total))
}
return InsufficientFunds
}
return Success
}
func (p *TxPool) ValidateSerializedTxn(serializedTxn []byte) error {
const (
// txSlotSize is used to calculate how many data slots a single transaction
// takes up based on its size. The slots are used as DoS protection, ensuring
// that validating a new transaction remains a constant operation (in reality
// O(maxslots), where max slots are 4 currently).
txSlotSize = 32 * 1024
// txMaxSize is the maximum size a single transaction can have. This field has
// non-trivial consequences: larger transactions are significantly harder and
// more expensive to propagate; larger transactions also take more resources
// to validate whether they fit into the pool or not.
txMaxSize = 4 * txSlotSize // 128KB
)
if len(serializedTxn) > txMaxSize {
return fmt.Errorf(RLPTooLong.String())
}
return nil
}
func (p *TxPool) validateTxs(txs *TxSlots, stateCache kvcache.CacheView) (reasons []DiscardReason, goodTxs TxSlots, err error) {
// reasons is pre-sized for direct indexing, with the default zero
// value DiscardReason of NotSet
reasons = make([]DiscardReason, len(txs.txs))
if err := txs.Valid(); err != nil {
return reasons, goodTxs, err
}
goodCount := 0
for i, txn := range txs.txs {
reason := p.validateTx(txn, txs.isLocal[i], stateCache)
if reason == Success {
goodCount++
// Success here means no DiscardReason yet, so leave it NotSet
continue
}
if reason == Spammer {
p.punishSpammer(txn.senderID)
}
reasons[i] = reason
}
goodTxs.Resize(uint(goodCount))
j := 0
for i, txn := range txs.txs {
if reasons[i] == NotSet {
goodTxs.txs[j] = txn
goodTxs.isLocal[j] = txs.isLocal[i]
copy(goodTxs.senders.At(j), txs.senders.At(i))
j++
}
}
return reasons, goodTxs, nil
}
// punishSpammer by drop half of it's transactions with high nonce
func (p *TxPool) punishSpammer(spammer uint64) {
count := p.all.count(spammer) / 2
if count > 0 {
txsToDelete := make([]*metaTx, 0, count)
p.all.descend(spammer, func(mt *metaTx) bool {
txsToDelete = append(txsToDelete, mt)
count--
return count > 0
})
for _, mt := range txsToDelete {
p.discardLocked(mt, Spammer) // can't call it while iterating by all
}
}
}
func fillDiscardReasons(reasons []DiscardReason, newTxs TxSlots, discardReasonsLRU *simplelru.LRU) []DiscardReason {
for i := range reasons {
if reasons[i] != NotSet {
continue
}
reason, ok := discardReasonsLRU.Get(string(newTxs.txs[i].IdHash[:]))
if ok {
reasons[i] = reason.(DiscardReason)
} else {
reasons[i] = Success
}
}
return reasons
}
func (p *TxPool) AddLocalTxs(ctx context.Context, newTransactions TxSlots) ([]DiscardReason, error) {
coreTx, err := p.coreDB().BeginRo(ctx)
if err != nil {
return nil, err
}
defer coreTx.Rollback()
cacheView, err := p.cache().View(ctx, coreTx)
if err != nil {
return nil, err
}
if !p.Started() {
return nil, fmt.Errorf("pool not started yet")
}
p.lock.Lock()
defer p.lock.Unlock()
if err = p.senders.registerNewSenders(&newTransactions); err != nil {
return nil, err
}
reasons, newTxs, err := p.validateTxs(&newTransactions, cacheView)
if err != nil {
return nil, err
}
p.pending.resetAddedHashes()
p.baseFee.resetAddedHashes()
if addReasons, err := addTxs(p.lastSeenBlock.Load(), cacheView, p.senders, newTxs,
p.pendingBaseFee.Load(), p.blockGasLimit.Load(), p.pending, p.baseFee, p.queued, p.all, p.byHash, p.addLocked, p.discardLocked); err == nil {
for i, reason := range addReasons {
if reason != NotSet {
reasons[i] = reason
}
}
} else {
return nil, err
}
p.promoted = p.pending.appendAddedHashes(p.promoted[:0])
p.promoted = p.baseFee.appendAddedHashes(p.promoted)
reasons = fillDiscardReasons(reasons, newTxs, p.discardReasonsLRU)
for i, reason := range reasons {
if reason == Success {
txn := newTxs.txs[i]
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: AddLocalTxs promotes idHash=%x, senderId=%d", txn.IdHash, txn.senderID))
}
p.promoted = append(p.promoted, txn.IdHash[:]...)
}
}
if p.promoted.Len() > 0 {
select {
case p.newPendingTxs <- common.Copy(p.promoted):
default:
}
}
return reasons, nil
}
func (p *TxPool) coreDB() kv.RoDB {
p.lock.RLock()
defer p.lock.RUnlock()
return p._chainDB
}
func (p *TxPool) cache() kvcache.Cache {
p.lock.RLock()
defer p.lock.RUnlock()
return p._stateCache
}
func addTxs(blockNum uint64, cacheView kvcache.CacheView, senders *sendersBatch,
newTxs TxSlots, pendingBaseFee, blockGasLimit uint64,
pending *PendingPool, baseFee, queued *SubPool,
byNonce *BySenderAndNonce, byHash map[string]*metaTx, add func(*metaTx) DiscardReason, discard func(*metaTx, DiscardReason)) ([]DiscardReason, error) {
protocolBaseFee := calcProtocolBaseFee(pendingBaseFee)
if ASSERT {
for _, txn := range newTxs.txs {
if txn.senderID == 0 {
panic(fmt.Errorf("senderID can't be zero"))
}
}
}
// This can be thought of a reverse operation from the one described before.
// When a block that was deemed "the best" of its height, is no longer deemed "the best", the
// transactions contained in it, are now viable for inclusion in other blocks, and therefore should
// be returned into the transaction pool.
// An interesting note here is that if the block contained any transactions local to the node,
// by being first removed from the pool (from the "local" part of it), and then re-injected,
// they effective lose their priority over the "remote" transactions. In order to prevent that,
// somehow the fact that certain transactions were local, needs to be remembered for some
// time (up to some "immutability threshold").
sendersWithChangedState := map[uint64]struct{}{}
discardReasons := make([]DiscardReason, len(newTxs.txs))
for i, txn := range newTxs.txs {
if found, ok := byHash[string(txn.IdHash[:])]; ok {
discardReasons[i] = DuplicateHash
// In case if the transation is stuck, "poke" it to rebroadcast
// TODO refactor to return the list of promoted hashes instead of using added inside the pool
if newTxs.isLocal[i] {
switch found.currentSubPool {
case PendingSubPool:
if pending.adding {
pending.added = append(pending.added, found.Tx.IdHash[:]...)
}
case BaseFeeSubPool:
if baseFee.adding {
baseFee.added = append(baseFee.added, found.Tx.IdHash[:]...)
}
}
}
continue
}
mt := newMetaTx(txn, newTxs.isLocal[i], blockNum)
if reason := add(mt); reason != NotSet {
discardReasons[i] = reason
continue
}
discardReasons[i] = NotSet
if txn.traced {
log.Info(fmt.Sprintf("TX TRACING: schedule sendersWithChangedState idHash=%x senderId=%d", txn.IdHash, mt.Tx.senderID))
}
sendersWithChangedState[mt.Tx.senderID] = struct{}{}
}
for senderID := range sendersWithChangedState {
nonce, balance, err := senders.info(cacheView, senderID)
if err != nil {
return discardReasons, err
}
onSenderStateChange(senderID, nonce, balance, byNonce,
protocolBaseFee, blockGasLimit, pending, baseFee, queued, discard)
}
promote(pending, baseFee, queued, pendingBaseFee, discard)
pending.EnforceBestInvariants()
return discardReasons, nil
}
func addTxsOnNewBlock(blockNum uint64, cacheView kvcache.CacheView, stateChanges *remote.StateChangeBatch,
senders *sendersBatch, newTxs TxSlots, pendingBaseFee uint64, blockGasLimit uint64,
pending *PendingPool, baseFee, queued *SubPool,
byNonce *BySenderAndNonce, byHash map[string]*metaTx, add func(*metaTx) DiscardReason, discard func(*metaTx, DiscardReason)) error {
protocolBaseFee := calcProtocolBaseFee(pendingBaseFee)
if ASSERT {
for _, txn := range newTxs.txs {
if txn.senderID == 0 {
panic(fmt.Errorf("senderID can't be zero"))
}
}
}
// This can be thought of a reverse operation from the one described before.
// When a block that was deemed "the best" of its height, is no longer deemed "the best", the
// transactions contained in it, are now viable for inclusion in other blocks, and therefore should
// be returned into the transaction pool.
// An interesting note here is that if the block contained any transactions local to the node,
// by being first removed from the pool (from the "local" part of it), and then re-injected,
// they effective lose their priority over the "remote" transactions. In order to prevent that,
// somehow the fact that certain transactions were local, needs to be remembered for some
// time (up to some "immutability threshold").
sendersWithChangedState := map[uint64]struct{}{}
for i, txn := range newTxs.txs {
if _, ok := byHash[string(txn.IdHash[:])]; ok {
continue
}
mt := newMetaTx(txn, newTxs.isLocal[i], blockNum)
if reason := add(mt); reason != NotSet {
discard(mt, reason)
continue
}
sendersWithChangedState[mt.Tx.senderID] = struct{}{}
}
// add senders changed in state to `sendersWithChangedState` list
for _, changesList := range stateChanges.ChangeBatch {
for _, change := range changesList.Changes {
switch change.Action {
case remote.Action_UPSERT, remote.Action_UPSERT_CODE:
if change.Incarnation > 0 {
continue
}
addr := gointerfaces.ConvertH160toAddress(change.Address)
id, ok := senders.getID(addr[:])
if !ok {
continue
}
sendersWithChangedState[id] = struct{}{}
}
}
}
for senderID := range sendersWithChangedState {
nonce, balance, err := senders.info(cacheView, senderID)
if err != nil {
return err
}
onSenderStateChange(senderID, nonce, balance, byNonce,
protocolBaseFee, blockGasLimit, pending, baseFee, queued, discard)
}
return nil
}
func (p *TxPool) setBaseFee(baseFee uint64) (uint64, bool) {
changed := false
if baseFee > 0 {
changed = baseFee != p.pendingBaseFee.Load()
p.pendingBaseFee.Store(baseFee)
}
return p.pendingBaseFee.Load(), changed
}
func (p *TxPool) addLocked(mt *metaTx) DiscardReason {