Skip to content

Commit 953b5ac

Browse files
authored
Merge pull request #16720 from rjl493456442/PreTxsEvent
all: collate new transaction events together
2 parents f9c456e + 49719e2 commit 953b5ac

19 files changed

Lines changed: 172 additions & 121 deletions

File tree

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*ty
454454
return logs, nil
455455
}
456456

457-
func (fb *filterBackend) SubscribeTxPreEvent(ch chan<- core.TxPreEvent) event.Subscription {
457+
func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
458458
return event.NewSubscription(func(quit <-chan struct{}) error {
459459
<-quit
460460
return nil

‎core/events.go‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ import (
2121
"github.com/ethereum/go-ethereum/core/types"
2222
)
2323

24-
// TxPreEvent is posted when a transaction enters the transaction pool.
25-
type TxPreEvent struct{ Tx *types.Transaction }
24+
// NewTxsEvent is posted when a batch of transactions enter the transaction pool.
25+
type NewTxsEvent struct{ Txs []*types.Transaction }
2626

2727
// PendingLogsEvent is posted pre mining and notifies of pending logs.
2828
type PendingLogsEvent struct {
@@ -35,9 +35,6 @@ type PendingStateEvent struct{}
3535
// NewMinedBlockEvent is posted when a block has been imported.
3636
type NewMinedBlockEvent struct{ Block *types.Block }
3737

38-
// RemovedTransactionEvent is posted when a reorg happens
39-
type RemovedTransactionEvent struct{ Txs types.Transactions }
40-
4138
// RemovedLogsEvent is posted when a reorg happens
4239
type RemovedLogsEvent struct{ Logs []*types.Log }
4340

‎core/tx_journal.go‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ func newTxJournal(path string) *txJournal {
5656

5757
// load parses a transaction journal dump from disk, loading its contents into
5858
// the specified pool.
59-
func (journal *txJournal) load(add func(*types.Transaction) error) error {
59+
func (journal *txJournal) load(add func([]*types.Transaction) []error) error {
6060
// Skip the parsing if the journal file doens't exist at all
6161
if _, err := os.Stat(journal.path); os.IsNotExist(err) {
6262
return nil
@@ -76,22 +76,39 @@ func (journal *txJournal) load(add func(*types.Transaction) error) error {
7676
stream := rlp.NewStream(input, 0)
7777
total, dropped := 0, 0
7878

79-
var failure error
79+
// Create a method to load a limited batch of transactions and bump the
80+
// appropriate progress counters. Then use this method to load all the
81+
// journalled transactions in small-ish batches.
82+
loadBatch := func(txs types.Transactions) {
83+
for _, err := range add(txs) {
84+
if err != nil {
85+
log.Debug("Failed to add journaled transaction", "err", err)
86+
dropped++
87+
}
88+
}
89+
}
90+
var (
91+
failure error
92+
batch types.Transactions
93+
)
8094
for {
8195
// Parse the next transaction and terminate on error
8296
tx := new(types.Transaction)
8397
if err = stream.Decode(tx); err != nil {
8498
if err != io.EOF {
8599
failure = err
86100
}
101+
if batch.Len() > 0 {
102+
loadBatch(batch)
103+
}
87104
break
88105
}
89-
// Import the transaction and bump the appropriate progress counters
106+
// New transaction parsed, queue up for later, import if threnshold is reached
90107
total++
91-
if err = add(tx); err != nil {
92-
log.Debug("Failed to add journaled transaction", "err", err)
93-
dropped++
94-
continue
108+
109+
if batch = append(batch, tx); batch.Len() > 1024 {
110+
loadBatch(batch)
111+
batch = batch[:0]
95112
}
96113
}
97114
log.Info("Loaded local transaction journal", "transactions", total, "dropped", dropped)

‎core/tx_pool.go‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain block
238238
if !config.NoLocals && config.Journal != "" {
239239
pool.journal = newTxJournal(config.Journal)
240240

241-
if err := pool.journal.load(pool.AddLocal); err != nil {
241+
if err := pool.journal.load(pool.AddLocals); err != nil {
242242
log.Warn("Failed to load transaction journal", "err", err)
243243
}
244244
if err := pool.journal.rotate(pool.local()); err != nil {
@@ -444,9 +444,9 @@ func (pool *TxPool) Stop() {
444444
log.Info("Transaction pool stopped")
445445
}
446446

447-
// SubscribeTxPreEvent registers a subscription of TxPreEvent and
447+
// SubscribeNewTxsEvent registers a subscription of NewTxsEvent and
448448
// starts sending event to the given channel.
449-
func (pool *TxPool) SubscribeTxPreEvent(ch chan<- TxPreEvent) event.Subscription {
449+
func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription {
450450
return pool.scope.Track(pool.txFeed.Subscribe(ch))
451451
}
452452

@@ -653,7 +653,7 @@ func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) {
653653
log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
654654

655655
// We've directly injected a replacement transaction, notify subsystems
656-
go pool.txFeed.Send(TxPreEvent{tx})
656+
go pool.txFeed.Send(NewTxsEvent{types.Transactions{tx}})
657657

658658
return old != nil, nil
659659
}
@@ -712,10 +712,11 @@ func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
712712
}
713713
}
714714

715-
// promoteTx adds a transaction to the pending (processable) list of transactions.
715+
// promoteTx adds a transaction to the pending (processable) list of transactions
716+
// and returns whether it was inserted or an older was better.
716717
//
717718
// Note, this method assumes the pool lock is held!
718-
func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) {
719+
func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool {
719720
// Try to insert the transaction into the pending queue
720721
if pool.pending[addr] == nil {
721722
pool.pending[addr] = newTxList(true)
@@ -729,7 +730,7 @@ func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.T
729730
pool.priced.Removed()
730731

731732
pendingDiscardCounter.Inc(1)
732-
return
733+
return false
733734
}
734735
// Otherwise discard any previous transaction and mark this
735736
if old != nil {
@@ -747,7 +748,7 @@ func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.T
747748
pool.beats[addr] = time.Now()
748749
pool.pendingState.SetNonce(addr, tx.Nonce()+1)
749750

750-
go pool.txFeed.Send(TxPreEvent{tx})
751+
return true
751752
}
752753

753754
// AddLocal enqueues a single transaction into the pool if it is valid, marking
@@ -907,6 +908,9 @@ func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) {
907908
// future queue to the set of pending transactions. During this process, all
908909
// invalidated transactions (low nonce, low balance) are deleted.
909910
func (pool *TxPool) promoteExecutables(accounts []common.Address) {
911+
// Track the promoted transactions to broadcast them at once
912+
var promoted []*types.Transaction
913+
910914
// Gather all the accounts potentially needing updates
911915
if accounts == nil {
912916
accounts = make([]common.Address, 0, len(pool.queue))
@@ -939,8 +943,10 @@ func (pool *TxPool) promoteExecutables(accounts []common.Address) {
939943
// Gather all executable transactions and promote them
940944
for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
941945
hash := tx.Hash()
942-
log.Trace("Promoting queued transaction", "hash", hash)
943-
pool.promoteTx(addr, hash, tx)
946+
if pool.promoteTx(addr, hash, tx) {
947+
log.Trace("Promoting queued transaction", "hash", hash)
948+
promoted = append(promoted, tx)
949+
}
944950
}
945951
// Drop all transactions over the allowed limit
946952
if !pool.locals.contains(addr) {
@@ -957,6 +963,10 @@ func (pool *TxPool) promoteExecutables(accounts []common.Address) {
957963
delete(pool.queue, addr)
958964
}
959965
}
966+
// Notify subsystem for new promoted transactions.
967+
if len(promoted) > 0 {
968+
pool.txFeed.Send(NewTxsEvent{promoted})
969+
}
960970
// If the pending limit is overflown, start equalizing allowances
961971
pending := uint64(0)
962972
for _, list := range pool.pending {

‎core/tx_pool_test.go‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -118,21 +118,27 @@ func validateTxPoolInternals(pool *TxPool) error {
118118

119119
// validateEvents checks that the correct number of transaction addition events
120120
// were fired on the pool's event feed.
121-
func validateEvents(events chan TxPreEvent, count int) error {
122-
for i := 0; i < count; i++ {
121+
func validateEvents(events chan NewTxsEvent, count int) error {
122+
var received []*types.Transaction
123+
124+
for len(received) < count {
123125
select {
124-
case <-events:
126+
case ev := <-events:
127+
received = append(received, ev.Txs...)
125128
case <-time.After(time.Second):
126-
return fmt.Errorf("event #%d not fired", i)
129+
return fmt.Errorf("event #%d not fired", received)
127130
}
128131
}
132+
if len(received) > count {
133+
return fmt.Errorf("more than %d events fired: %v", count, received[count:])
134+
}
129135
select {
130-
case tx := <-events:
131-
return fmt.Errorf("more than %d events fired: %v", count, tx.Tx)
136+
case ev := <-events:
137+
return fmt.Errorf("more than %d events fired: %v", count, ev.Txs)
132138

133139
case <-time.After(50 * time.Millisecond):
134140
// This branch should be "default", but it's a data race between goroutines,
135-
// reading the event channel and pushng into it, so better wait a bit ensuring
141+
// reading the event channel and pushing into it, so better wait a bit ensuring
136142
// really nothing gets injected.
137143
}
138144
return nil
@@ -669,7 +675,7 @@ func TestTransactionGapFilling(t *testing.T) {
669675
pool.currentState.AddBalance(account, big.NewInt(1000000))
670676

671677
// Keep track of transaction events to ensure all executables get announced
672-
events := make(chan TxPreEvent, testTxPoolConfig.AccountQueue+5)
678+
events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
673679
sub := pool.txFeed.Subscribe(events)
674680
defer sub.Unsubscribe()
675681

@@ -920,7 +926,7 @@ func TestTransactionPendingLimiting(t *testing.T) {
920926
pool.currentState.AddBalance(account, big.NewInt(1000000))
921927

922928
// Keep track of transaction events to ensure all executables get announced
923-
events := make(chan TxPreEvent, testTxPoolConfig.AccountQueue+5)
929+
events := make(chan NewTxsEvent, testTxPoolConfig.AccountQueue+5)
924930
sub := pool.txFeed.Subscribe(events)
925931
defer sub.Unsubscribe()
926932

@@ -1140,7 +1146,7 @@ func TestTransactionPoolRepricing(t *testing.T) {
11401146
defer pool.Stop()
11411147

11421148
// Keep track of transaction events to ensure all executables get announced
1143-
events := make(chan TxPreEvent, 32)
1149+
events := make(chan NewTxsEvent, 32)
11441150
sub := pool.txFeed.Subscribe(events)
11451151
defer sub.Unsubscribe()
11461152

@@ -1327,7 +1333,7 @@ func TestTransactionPoolUnderpricing(t *testing.T) {
13271333
defer pool.Stop()
13281334

13291335
// Keep track of transaction events to ensure all executables get announced
1330-
events := make(chan TxPreEvent, 32)
1336+
events := make(chan NewTxsEvent, 32)
13311337
sub := pool.txFeed.Subscribe(events)
13321338
defer sub.Unsubscribe()
13331339

@@ -1433,7 +1439,7 @@ func TestTransactionPoolStableUnderpricing(t *testing.T) {
14331439
defer pool.Stop()
14341440

14351441
// Keep track of transaction events to ensure all executables get announced
1436-
events := make(chan TxPreEvent, 32)
1442+
events := make(chan NewTxsEvent, 32)
14371443
sub := pool.txFeed.Subscribe(events)
14381444
defer sub.Unsubscribe()
14391445

@@ -1495,7 +1501,7 @@ func TestTransactionReplacement(t *testing.T) {
14951501
defer pool.Stop()
14961502

14971503
// Keep track of transaction events to ensure all executables get announced
1498-
events := make(chan TxPreEvent, 32)
1504+
events := make(chan NewTxsEvent, 32)
14991505
sub := pool.txFeed.Subscribe(events)
15001506
defer sub.Unsubscribe()
15011507

‎eth/api_backend.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,8 +188,8 @@ func (b *EthAPIBackend) TxPoolContent() (map[common.Address]types.Transactions,
188188
return b.eth.TxPool().Content()
189189
}
190190

191-
func (b *EthAPIBackend) SubscribeTxPreEvent(ch chan<- core.TxPreEvent) event.Subscription {
192-
return b.eth.TxPool().SubscribeTxPreEvent(ch)
191+
func (b *EthAPIBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
192+
return b.eth.TxPool().SubscribeNewTxsEvent(ch)
193193
}
194194

195195
func (b *EthAPIBackend) Downloader() *downloader.Downloader {

‎eth/filters/api.go‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ func (api *PublicFilterAPI) timeoutLoop() {
104104
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newpendingtransactionfilter
105105
func (api *PublicFilterAPI) NewPendingTransactionFilter() rpc.ID {
106106
var (
107-
pendingTxs = make(chan common.Hash)
108-
pendingTxSub = api.events.SubscribePendingTxEvents(pendingTxs)
107+
pendingTxs = make(chan []common.Hash)
108+
pendingTxSub = api.events.SubscribePendingTxs(pendingTxs)
109109
)
110110

111111
api.filtersMu.Lock()
@@ -118,7 +118,7 @@ func (api *PublicFilterAPI) NewPendingTransactionFilter() rpc.ID {
118118
case ph := <-pendingTxs:
119119
api.filtersMu.Lock()
120120
if f, found := api.filters[pendingTxSub.ID]; found {
121-
f.hashes = append(f.hashes, ph)
121+
f.hashes = append(f.hashes, ph...)
122122
}
123123
api.filtersMu.Unlock()
124124
case <-pendingTxSub.Err():
@@ -144,13 +144,17 @@ func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Su
144144
rpcSub := notifier.CreateSubscription()
145145

146146
go func() {
147-
txHashes := make(chan common.Hash)
148-
pendingTxSub := api.events.SubscribePendingTxEvents(txHashes)
147+
txHashes := make(chan []common.Hash, 128)
148+
pendingTxSub := api.events.SubscribePendingTxs(txHashes)
149149

150150
for {
151151
select {
152-
case h := <-txHashes:
153-
notifier.Notify(rpcSub.ID, h)
152+
case hashes := <-txHashes:
153+
// To keep the original behaviour, send a single tx hash in one notification.
154+
// TODO(rjl493456442) Send a batch of tx hashes in one notification
155+
for _, h := range hashes {
156+
notifier.Notify(rpcSub.ID, h)
157+
}
154158
case <-rpcSub.Err():
155159
pendingTxSub.Unsubscribe()
156160
return

‎eth/filters/filter.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ type Backend interface {
3636
GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
3737
GetLogs(ctx context.Context, blockHash common.Hash) ([][]*types.Log, error)
3838

39-
SubscribeTxPreEvent(chan<- core.TxPreEvent) event.Subscription
39+
SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
4040
SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
4141
SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription
4242
SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription

0 commit comments

Comments
 (0)