From e7a29375ebe90972152bcb03d7b46c04a0163747 Mon Sep 17 00:00:00 2001 From: milen <94537774+taratorio@users.noreply.github.com> Date: Wed, 20 Nov 2024 10:33:14 +0000 Subject: [PATCH] txpool: more tx to txn renames (#12801) last part of "tx" to "txn" renames to stick to our convention of using "txn" for blockchain transactions instead of "tx" for db transactions there is some more pending inside core/types package but planning to do those at some point in the future (might also move those transaction types outside of core/types and into a sub-package in txnprovider) --- cmd/devnet/transactions/tx.go | 2 +- cmd/integration/commands/state_stages.go | 2 +- core/types/transaction_test.go | 4 +- core/types/typestest/test_data.go | 2 +- txnprovider/txpool/README.md | 2 +- txnprovider/txpool/fetch.go | 46 +-- txnprovider/txpool/fetch_test.go | 47 +-- txnprovider/txpool/metrics.go | 6 +- txnprovider/txpool/pending_pool.go | 2 +- txnprovider/txpool/pool.go | 346 +++++++++--------- txnprovider/txpool/{db.go => pool_db.go} | 0 txnprovider/txpool/pool_fuzz_test.go | 158 ++++---- txnprovider/txpool/pool_test.go | 310 ++++++++-------- .../{txn_packets.go => pool_txn_packets.go} | 66 ++-- ..._test.go => pool_txn_packets_fuzz_test.go} | 8 +- ...ckets_test.go => pool_txn_packets_test.go} | 36 +- .../txpool/{txn.go => pool_txn_parser.go} | 62 ++-- .../{txn_test.go => pool_txn_parser_test.go} | 210 +++++------ ...zz_test.go => pool_txn_types_fuzz_test.go} | 0 txnprovider/txpool/send.go | 32 +- txnprovider/txpool/senders.go | 22 +- txnprovider/txpool/txpool_grpc_server.go | 8 +- txnprovider/txpool/txpoolcfg/txpoolcfg.go | 28 +- .../txpool/txpoolutil/all_components.go | 4 +- 24 files changed, 702 insertions(+), 701 deletions(-) rename txnprovider/txpool/{db.go => pool_db.go} (100%) rename txnprovider/txpool/{txn_packets.go => pool_txn_packets.go} (76%) rename txnprovider/txpool/{txn_packets_fuzz_test.go => pool_txn_packets_fuzz_test.go} (93%) rename txnprovider/txpool/{txn_packets_test.go => pool_txn_packets_test.go} (93%) rename txnprovider/txpool/{txn.go => pool_txn_parser.go} (95%) rename txnprovider/txpool/{txn_test.go => pool_txn_parser_test.go} (81%) rename txnprovider/txpool/{txn_types_fuzz_test.go => pool_txn_types_fuzz_test.go} (100%) diff --git a/cmd/devnet/transactions/tx.go b/cmd/devnet/transactions/tx.go index c97a2ffb2ce..3b86a8e6052 100644 --- a/cmd/devnet/transactions/tx.go +++ b/cmd/devnet/transactions/tx.go @@ -160,7 +160,7 @@ func SendTxLoad(ctx context.Context, to, from string, amount uint64, txPerSec ui tx, err := CreateManyEIP1559TransactionsHigherThanBaseFee(ctx, to, from, int(batchCount)) if err != nil { - logger.Error("failed Create Txs", "error", err) + logger.Error("failed Create Txns", "error", err) return err } diff --git a/cmd/integration/commands/state_stages.go b/cmd/integration/commands/state_stages.go index 0065cee9855..6d8e170a55c 100644 --- a/cmd/integration/commands/state_stages.go +++ b/cmd/integration/commands/state_stages.go @@ -326,7 +326,7 @@ func syncBySmallSteps(db kv.RwDB, miningConfig params.MiningConfig, ctx context. return err }) //miningStages.MockExecFunc(stages.MiningFinish, func(s *stagedsync.StageState, u stagedsync.Unwinder) error { - //debugprint.Transactions(nextBlock.Transactions(), miningWorld.Block.Txs) + //debugprint.Transactions(nextBlock.Transactions(), miningWorld.Block.Txns) //debugprint.Receipts(miningWorld.Block.Receipts, receiptsInDB) //return stagedsync.SpawnMiningFinishStage(s, tx, miningWorld.Block, cc.Engine(), chainConfig, quit) //}) diff --git a/core/types/transaction_test.go b/core/types/transaction_test.go index cb8deb08bbe..dde277fe879 100644 --- a/core/types/transaction_test.go +++ b/core/types/transaction_test.go @@ -735,7 +735,7 @@ func TestBlobTxEncodeDecode(t *testing.T) { } func TestShortUnwrap(t *testing.T) { - blobTxRlp, _ := typestest.MakeBlobTxRlp() + blobTxRlp, _ := typestest.MakeBlobTxnRlp() shortRlp, err := UnwrapTxPlayloadRlp(blobTxRlp) if err != nil { t.Errorf("short rlp stripping failed: %v", err) @@ -747,7 +747,7 @@ func TestShortUnwrap(t *testing.T) { t.Errorf("short rlp decoding failed : %v", err) } wrappedBlobTx := BlobTxWrapper{} - blockTxRlp2, _ := typestest.MakeBlobTxRlp() + blockTxRlp2, _ := typestest.MakeBlobTxnRlp() err = wrappedBlobTx.DecodeRLP(rlp.NewStream(bytes.NewReader(blockTxRlp2[1:]), 0)) if err != nil { t.Errorf("long rlp decoding failed: %v", err) diff --git a/core/types/typestest/test_data.go b/core/types/typestest/test_data.go index bf507d695a6..ebb0d2fd491 100644 --- a/core/types/typestest/test_data.go +++ b/core/types/typestest/test_data.go @@ -25,7 +25,7 @@ import ( "github.com/erigontech/erigon-lib/crypto/kzg" ) -func MakeBlobTxRlp() ([]byte, []gokzg4844.KZGCommitment) { +func MakeBlobTxnRlp() ([]byte, []gokzg4844.KZGCommitment) { bodyRlp := hexutility.MustDecodeHex(BodyRlpHex) blobsRlpPrefix := hexutility.MustDecodeHex("fa040008") diff --git a/txnprovider/txpool/README.md b/txnprovider/txpool/README.md index fec482aeb9b..c9ec4e127c2 100644 --- a/txnprovider/txpool/README.md +++ b/txnprovider/txpool/README.md @@ -77,7 +77,7 @@ tx_hashes, pending_pool, queued_pool, local_transactions => pending_pool`, queue where modified pending pool and queued pool, and local transactions do not contain given transaction hashes anymore. -In code can find production of such event by `p.newPendingTxs <-`, and handling of this event by `announcements := <-newTxs` [here](pool.go#L1746) +In code can find production of such event by `p.newPendingTxns <-`, and handling of this event by `announcements := <-newTxns` [here](pool.go#L1746) ## Reinject transactions into the transaction pool on unwinding a block 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. We can describe this function as: diff --git a/txnprovider/txpool/fetch.go b/txnprovider/txpool/fetch.go index be8afd9c34a..21838e85798 100644 --- a/txnprovider/txpool/fetch.go +++ b/txnprovider/txpool/fetch.go @@ -48,10 +48,10 @@ type Fetch struct { stateChangesClient StateChangesClient wg *sync.WaitGroup // used for synchronisation in the tests (nil when not in tests) stateChangesParseCtx *TxnParseContext - pooledTxsParseCtx *TxnParseContext + pooledTxnsParseCtx *TxnParseContext sentryClients []sentry.SentryClient // sentry clients that will be used for accessing the network stateChangesParseCtxLock sync.Mutex - pooledTxsParseCtxLock sync.Mutex + pooledTxnsParseCtxLock sync.Mutex logger log.Logger } @@ -72,10 +72,10 @@ func NewFetch(ctx context.Context, sentryClients []sentry.SentryClient, pool Poo db: db, stateChangesClient: stateChangesClient, stateChangesParseCtx: NewTxnParseContext(chainID).ChainIDRequired(), //TODO: change ctx if rules changed - pooledTxsParseCtx: NewTxnParseContext(chainID).ChainIDRequired(), + pooledTxnsParseCtx: NewTxnParseContext(chainID).ChainIDRequired(), logger: logger, } - f.pooledTxsParseCtx.ValidateRLP(f.pool.ValidateSerializedTxn) + f.pooledTxnsParseCtx.ValidateRLP(f.pool.ValidateSerializedTxn) f.stateChangesParseCtx.ValidateRLP(f.pool.ValidateSerializedTxn) return f @@ -86,9 +86,9 @@ func (f *Fetch) SetWaitGroup(wg *sync.WaitGroup) { } func (f *Fetch) threadSafeParsePooledTxn(cb func(*TxnParseContext) error) error { - f.pooledTxsParseCtxLock.Lock() - defer f.pooledTxsParseCtxLock.Unlock() - return cb(f.pooledTxsParseCtx) + f.pooledTxnsParseCtxLock.Lock() + defer f.pooledTxnsParseCtxLock.Unlock() + return cb(f.pooledTxnsParseCtx) } func (f *Fetch) threadSafeParseStateChangeTxn(cb func(*TxnParseContext) error) error { @@ -282,7 +282,7 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes const hashSize = 32 hashes = hashes[:min(len(hashes), 256*hashSize)] - var txs [][]byte + var txns [][]byte responseSize := 0 processed := len(hashes) @@ -302,11 +302,11 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes continue } - txs = append(txs, txn) + txns = append(txns, txn) responseSize += len(txn) } - encodedRequest = EncodePooledTransactions66(txs, requestID, nil) + encodedRequest = EncodePooledTransactions66(txns, requestID, nil) if len(encodedRequest) > p2pTxPacketLimit { log.Trace("txpool.Fetch.handleInboundMessage PooledTransactions reply exceeds p2pTxPacketLimit", "requested", len(hashes), "processed", processed) } @@ -318,7 +318,7 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes return err } case sentry.MessageId_POOLED_TRANSACTIONS_66, sentry.MessageId_TRANSACTIONS_66: - txs := TxnSlots{} + txns := TxnSlots{} if err := f.threadSafeParsePooledTxn(func(parseContext *TxnParseContext) error { return nil }); err != nil { @@ -328,7 +328,7 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes switch req.Id { case sentry.MessageId_TRANSACTIONS_66: if err := f.threadSafeParsePooledTxn(func(parseContext *TxnParseContext) error { - if _, err := ParseTransactions(req.Data, 0, parseContext, &txs, func(hash []byte) error { + if _, err := ParseTransactions(req.Data, 0, parseContext, &txns, func(hash []byte) error { known, err := f.pool.IdHashKnown(tx, hash) if err != nil { return err @@ -346,7 +346,7 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes } case sentry.MessageId_POOLED_TRANSACTIONS_66: if err := f.threadSafeParsePooledTxn(func(parseContext *TxnParseContext) error { - if _, _, err := ParsePooledTransactions66(req.Data, 0, parseContext, &txs, func(hash []byte) error { + if _, _, err := ParsePooledTransactions66(req.Data, 0, parseContext, &txns, func(hash []byte) error { known, err := f.pool.IdHashKnown(tx, hash) if err != nil { return err @@ -365,10 +365,10 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes default: return fmt.Errorf("unexpected message: %s", req.Id.String()) } - if len(txs.Txs) == 0 { + if len(txns.Txns) == 0 { return nil } - f.pool.AddRemoteTxns(ctx, txs) + f.pool.AddRemoteTxns(ctx, txns) default: defer f.logger.Trace("[txpool] dropped p2p message", "id", req.Id) } @@ -472,14 +472,14 @@ func (f *Fetch) handleStateChanges(ctx context.Context, client StateChangesClien } func (f *Fetch) handleStateChangesRequest(ctx context.Context, req *remote.StateChangeBatch) error { - var unwindTxs, unwindBlobTxs, minedTxs TxnSlots + var unwindTxns, unwindBlobTxns, minedTxns TxnSlots for _, change := range req.ChangeBatch { if change.Direction == remote.Direction_FORWARD { - minedTxs.Resize(uint(len(change.Txs))) + minedTxns.Resize(uint(len(change.Txs))) for i := range change.Txs { - minedTxs.Txs[i] = &TxnSlot{} + minedTxns.Txns[i] = &TxnSlot{} if err := f.threadSafeParseStateChangeTxn(func(parseContext *TxnParseContext) error { - _, err := parseContext.ParseTransaction(change.Txs[i], 0, minedTxs.Txs[i], minedTxs.Senders.At(i), false /* hasEnvelope */, false /* wrappedWithBlobs */, nil) + _, err := parseContext.ParseTransaction(change.Txs[i], 0, minedTxns.Txns[i], minedTxns.Senders.At(i), false /* hasEnvelope */, false /* wrappedWithBlobs */, nil) return err }); err != nil && !errors.Is(err, context.Canceled) { f.logger.Warn("[txpool.fetch] stream.Recv", "err", err) @@ -495,10 +495,10 @@ func (f *Fetch) handleStateChangesRequest(ctx context.Context, req *remote.State if err != nil { return err } - if utx.Type == BlobTxType { - unwindBlobTxs.Append(utx, sender, false) + if utx.Type == BlobTxnType { + unwindBlobTxns.Append(utx, sender, false) } else { - unwindTxs.Append(utx, sender, false) + unwindTxns.Append(utx, sender, false) } return nil }); err != nil && !errors.Is(err, context.Canceled) { @@ -509,7 +509,7 @@ func (f *Fetch) handleStateChangesRequest(ctx context.Context, req *remote.State } } - if err := f.pool.OnNewBlock(ctx, req, unwindTxs, unwindBlobTxs, minedTxs); err != nil && !errors.Is(err, context.Canceled) { + if err := f.pool.OnNewBlock(ctx, req, unwindTxns, unwindBlobTxns, minedTxns); err != nil && !errors.Is(err, context.Canceled) { return err } return nil diff --git a/txnprovider/txpool/fetch_test.go b/txnprovider/txpool/fetch_test.go index 93ac4519ca8..609d3122bec 100644 --- a/txnprovider/txpool/fetch_test.go +++ b/txnprovider/txpool/fetch_test.go @@ -102,14 +102,14 @@ func TestSendTxPropagate(t *testing.T) { m := NewMockSentry(ctx, sentryServer) send := NewSend(ctx, []sentryproto.SentryClient{direct.NewSentryClientDirect(direct.ETH68, m)}, nil, log.New()) - send.BroadcastPooledTxs(testRlps(2), 100) - send.AnnouncePooledTxs([]byte{0, 1}, []uint32{10, 15}, toHashes(1, 42), 100) + send.BroadcastPooledTxns(testRlps(2), 100) + send.AnnouncePooledTxns([]byte{0, 1}, []uint32{10, 15}, toHashes(1, 42), 100) require.Equal(t, 2, len(requests)) - txsMessage := requests[0].Data - assert.Equal(t, sentryproto.MessageId_TRANSACTIONS_66, txsMessage.Id) - assert.Equal(t, 3, len(txsMessage.Data)) + txnsMessage := requests[0].Data + assert.Equal(t, sentryproto.MessageId_TRANSACTIONS_66, txnsMessage.Id) + assert.Equal(t, 3, len(txnsMessage.Data)) txnHashesMessage := requests[1].Data assert.Equal(t, sentryproto.MessageId_NEW_POOLED_TRANSACTION_HASHES_68, txnHashesMessage.Id) @@ -137,14 +137,14 @@ func TestSendTxPropagate(t *testing.T) { b := []byte(fmt.Sprintf("%x", i)) copy(list[i:i+32], b) } - send.BroadcastPooledTxs(testRlps(len(list)/32), 100) - send.AnnouncePooledTxs([]byte{0, 1, 2}, []uint32{10, 12, 14}, list, 100) + send.BroadcastPooledTxns(testRlps(len(list)/32), 100) + send.AnnouncePooledTxns([]byte{0, 1, 2}, []uint32{10, 12, 14}, list, 100) require.Equal(t, 2, len(requests)) - txsMessage := requests[0].Data - require.Equal(t, sentryproto.MessageId_TRANSACTIONS_66, txsMessage.Id) - require.True(t, len(txsMessage.Data) > 0) + txnsMessage := requests[0].Data + require.Equal(t, sentryproto.MessageId_TRANSACTIONS_66, txnsMessage.Id) + require.True(t, len(txnsMessage.Data) > 0) txnHashesMessage := requests[1].Data require.Equal(t, sentryproto.MessageId_NEW_POOLED_TRANSACTION_HASHES_68, txnHashesMessage.Id) @@ -167,14 +167,14 @@ func TestSendTxPropagate(t *testing.T) { m := NewMockSentry(ctx, sentryServer) send := NewSend(ctx, []sentryproto.SentryClient{direct.NewSentryClientDirect(direct.ETH68, m)}, nil, log.New()) - send.BroadcastPooledTxs(testRlps(2), 100) - send.AnnouncePooledTxs([]byte{0, 1}, []uint32{10, 15}, toHashes(1, 42), 100) + send.BroadcastPooledTxns(testRlps(2), 100) + send.AnnouncePooledTxns([]byte{0, 1}, []uint32{10, 15}, toHashes(1, 42), 100) require.Equal(t, 2, len(requests)) - txsMessage := requests[0].Data - assert.Equal(t, sentryproto.MessageId_TRANSACTIONS_66, txsMessage.Id) - assert.True(t, len(txsMessage.Data) > 0) + txnsMessage := requests[0].Data + assert.Equal(t, sentryproto.MessageId_TRANSACTIONS_66, txnsMessage.Id) + assert.True(t, len(txnsMessage.Data) > 0) txnHashesMessage := requests[1].Data assert.Equal(t, sentryproto.MessageId_NEW_POOLED_TRANSACTION_HASHES_68, txnHashesMessage.Id) @@ -208,7 +208,7 @@ func TestSendTxPropagate(t *testing.T) { m := NewMockSentry(ctx, sentryServer) send := NewSend(ctx, []sentryproto.SentryClient{direct.NewSentryClientDirect(direct.ETH68, m)}, nil, log.New()) expectPeers := toPeerIDs(1, 2, 42) - send.PropagatePooledTxsToPeersList(expectPeers, []byte{0, 1}, []uint32{10, 15}, toHashes(1, 42)) + send.PropagatePooledTxnsToPeersList(expectPeers, []byte{0, 1}, []uint32{10, 15}, toHashes(1, 42)) require.Equal(t, 3, len(requests)) for i, req := range requests { @@ -226,6 +226,7 @@ func decodeHex(in string) []byte { } return payload } + func TestOnNewBlock(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -246,9 +247,9 @@ func TestOnNewBlock(t *testing.T) { ChangeBatch: []*remote.StateChange{ { Txs: [][]byte{ - decodeHex(TxParseMainnetTests[0].PayloadStr), - decodeHex(TxParseMainnetTests[1].PayloadStr), - decodeHex(TxParseMainnetTests[2].PayloadStr), + decodeHex(TxnParseMainnetTests[0].PayloadStr), + decodeHex(TxnParseMainnetTests[1].PayloadStr), + decodeHex(TxnParseMainnetTests[2].PayloadStr), }, BlockHeight: 1, BlockHash: gointerfaces.ConvertHashToH256([32]byte{}), @@ -275,11 +276,11 @@ func TestOnNewBlock(t *testing.T) { }). Times(3) - var minedTxs TxnSlots + var minedTxns TxnSlots pool.EXPECT(). OnNewBlock(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - DoAndReturn(func(_ context.Context, _ *remote.StateChangeBatch, _ TxnSlots, _ TxnSlots, minedTxsArg TxnSlots) error { - minedTxs = minedTxsArg + DoAndReturn(func(_ context.Context, _ *remote.StateChangeBatch, _ TxnSlots, _ TxnSlots, minedTxnsArg TxnSlots) error { + minedTxns = minedTxnsArg return nil }). Times(1) @@ -287,7 +288,7 @@ func TestOnNewBlock(t *testing.T) { fetch := NewFetch(ctx, nil, pool, stateChanges, coreDB, db, *u256.N1, log.New()) err := fetch.handleStateChanges(ctx, stateChanges) assert.ErrorIs(t, io.EOF, err) - assert.Equal(t, 3, len(minedTxs.Txs)) + assert.Equal(t, 3, len(minedTxns.Txns)) } type MockSentry struct { diff --git a/txnprovider/txpool/metrics.go b/txnprovider/txpool/metrics.go index b7c2b03ce14..3c7b5daa10a 100644 --- a/txnprovider/txpool/metrics.go +++ b/txnprovider/txpool/metrics.go @@ -19,12 +19,12 @@ package txpool import "github.com/erigontech/erigon-lib/metrics" var ( - processBatchTxsTimer = metrics.NewSummary(`pool_process_remote_txs`) - addRemoteTxsTimer = metrics.NewSummary(`pool_add_remote_txs`) + processBatchTxnsTimer = metrics.NewSummary(`pool_process_remote_txs`) + addRemoteTxnsTimer = 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`) + propagateNewTxnsTimer = metrics.NewSummary(`pool_propagate_new_txs`) writeToDBBytesCounter = metrics.GetOrCreateGauge(`pool_write_to_db_bytes`) pendingSubCounter = metrics.GetOrCreateGauge(`txpool_pending`) queuedSubCounter = metrics.GetOrCreateGauge(`txpool_queued`) diff --git a/txnprovider/txpool/pending_pool.go b/txnprovider/txpool/pending_pool.go index 84ede20e038..0bfac382503 100644 --- a/txnprovider/txpool/pending_pool.go +++ b/txnprovider/txpool/pending_pool.go @@ -26,7 +26,7 @@ import ( // PendingPool - is different from other pools - it's best is Slice instead of Heap // It's more expensive to maintain "slice sort" invariant, but it allow do cheap copy of -// pending.best slice for mining (because we consider txs and metaTxn are immutable) +// pending.best slice for mining (because we consider txns and metaTxn are immutable) type PendingPool struct { best *bestSlice worst *WorstQueue diff --git a/txnprovider/txpool/pool.go b/txnprovider/txpool/pool.go index d890b5e81dc..55a18014857 100644 --- a/txnprovider/txpool/pool.go +++ b/txnprovider/txpool/pool.go @@ -73,7 +73,7 @@ const txMaxBroadcastSize = 4 * 1024 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 + // Handle 3 main events - new remote txns from p2p, new local txns from RPC, new blocks from execution layer AddRemoteTxns(ctx context.Context, newTxns TxnSlots) AddLocalTxns(ctx context.Context, newTxns TxnSlots) ([]txpoolcfg.DiscardReason, error) OnNewBlock(ctx context.Context, stateChanges *remote.StateChangeBatch, unwindTxns, unwindBlobTxns, minedTxns TxnSlots) error @@ -100,12 +100,12 @@ type TxPool struct { _chainDB kv.RoDB // remote db - use it wisely _stateCache kvcache.Cache lock *sync.Mutex - recentlyConnectedPeers *recentlyConnectedPeers // all txs will be propagated to this peers eventually, and clear list + recentlyConnectedPeers *recentlyConnectedPeers // all txns will be propagated to this peers eventually, and clear list senders *sendersBatch // batch processing of remote transactions // handling is fast enough without batching, but batching allows: // - fewer _chainDB transactions - // - batch notifications about new txs (reduced P2P spam to other nodes about txs propagation) + // - batch notifications about new txns (reduced P2P spam to other nodes about txns propagation) // - and as a result reducing lock contention unprocessedRemoteTxns *TxnSlots unprocessedRemoteByHash map[string]int // to reject duplicates @@ -114,12 +114,12 @@ type TxPool struct { pending *PendingPool baseFee *SubPool queued *SubPool - minedBlobTxsByBlock map[uint64][]*metaTxn // (blockNum => slice): cache of recently mined blobs - minedBlobTxsByHash map[string]*metaTxn // (hash => mt): map of recently mined blobs + minedBlobTxnsByBlock map[uint64][]*metaTxn // (blockNum => slice): cache of recently mined blobs + minedBlobTxnsByHash map[string]*metaTxn // (hash => mt): map of recently mined blobs isLocalLRU *simplelru.LRU[string, struct{}] // txn_hash => is_local : to restore isLocal flag of unwinded transactions - newPendingTxs chan Announcements // notifications about new txs in Pending sub-pool + newPendingTxns chan Announcements // notifications about new txns in Pending sub-pool all *BySenderAndNonce // senderID => (sorted map of txn nonce => *metaTxn) - deletedTxs []*metaTxn // list of discarded txs since last db commit + deletedTxns []*metaTxn // list of discarded txns since last db commit promoted Announcements cfg txpoolcfg.Config chainID uint256.Int @@ -149,7 +149,7 @@ type FeeCalculator interface { } func New( - newTxs chan Announcements, + newTxns chan Announcements, coreDB kv.RoDB, cfg txpoolcfg.Config, cache kvcache.Cache, @@ -195,7 +195,7 @@ func New( pending: NewPendingSubPool(PendingSubPool, cfg.PendingSubPoolLimit), baseFee: NewSubPool(BaseFeeSubPool, cfg.BaseFeeSubPoolLimit), queued: NewSubPool(QueuedSubPool, cfg.QueuedSubPoolLimit), - newPendingTxs: newTxs, + newPendingTxns: newTxns, _stateCache: cache, senders: newSendersBatch(tracedSenders), _chainDB: coreDB, @@ -203,8 +203,8 @@ func New( chainID: chainID, unprocessedRemoteTxns: &TxnSlots{}, unprocessedRemoteByHash: map[string]int{}, - minedBlobTxsByBlock: map[uint64][]*metaTxn{}, - minedBlobTxsByHash: map[string]*metaTxn{}, + minedBlobTxnsByBlock: map[uint64][]*metaTxn{}, + minedBlobTxnsByHash: map[string]*metaTxn{}, maxBlobsPerBlock: maxBlobsPerBlock, feeCalculator: feeCalculator, logger: logger, @@ -286,7 +286,7 @@ func (p *TxPool) OnNewBlock(ctx context.Context, stateChanges *remote.StateChang available := len(p.pending.best.ms) defer func() { - p.logger.Debug("[txpool] New block", "block", block, "unwound", len(unwindTxns.Txs), "mined", len(minedTxns.Txs), "baseFee", baseFee, "pending-pre", available, "pending", p.pending.Len(), "baseFee", p.baseFee.Len(), "queued", p.queued.Len(), "err", err) + p.logger.Debug("[txpool] New block", "block", block, "unwound", len(unwindTxns.Txns), "mined", len(minedTxns.Txns), "baseFee", baseFee, "pending-pre", available, "pending", p.pending.Len(), "baseFee", p.baseFee.Len(), "queued", p.queued.Len(), "err", err) }() if err = minedTxns.Valid(); err != nil { @@ -360,8 +360,8 @@ func (p *TxPool) OnNewBlock(ctx context.Context, stateChanges *remote.StateChang }) } - for i, txn := range unwindBlobTxns.Txs { - if txn.Type == BlobTxType { + for i, txn := range unwindBlobTxns.Txns { + if txn.Type == BlobTxnType { knownBlobTxn, err := p.getCachedBlobTxnLocked(coreTx, txn.IDHash[:]) if err != nil { return err @@ -375,35 +375,35 @@ func (p *TxPool) OnNewBlock(ctx context.Context, stateChanges *remote.StateChang return err } - _, unwindTxns, err = p.validateTxs(&unwindTxns, cacheView) + _, unwindTxns, err = p.validateTxns(&unwindTxns, cacheView) if err != nil { return err } if assert.Enable { - for _, txn := range unwindTxns.Txs { + for _, txn := range unwindTxns.Txns { if txn.SenderID == 0 { - panic("onNewBlock.unwindTxs: senderID can't be zero") + panic("onNewBlock.unwindTxns: senderID can't be zero") } } - for _, txn := range minedTxns.Txs { + for _, txn := range minedTxns.Txns { if txn.SenderID == 0 { - panic("onNewBlock.minedTxs: senderID can't be zero") + panic("onNewBlock.minedTxns: senderID can't be zero") } } } - if err = p.processMinedFinalizedBlobs(coreTx, minedTxns.Txs, stateChanges.FinalizedBlock); err != nil { + if err = p.processMinedFinalizedBlobs(minedTxns.Txns, stateChanges.FinalizedBlock); err != nil { return err } - if err = p.removeMined(p.all, minedTxns.Txs); err != nil { + if err = p.removeMined(p.all, minedTxns.Txns); err != nil { return err } var announcements Announcements - announcements, err = p.addTxsOnNewBlock(block, cacheView, stateChanges, p.senders, unwindTxns, /* newTxs */ + announcements, err = p.addTxnsOnNewBlock(block, cacheView, stateChanges, p.senders, unwindTxns, /* newTxns */ pendingBaseFee, stateChanges.BlockGasLimit, p.logger) if err != nil { return err @@ -419,7 +419,7 @@ func (p *TxPool) OnNewBlock(ctx context.Context, stateChanges *remote.StateChang if p.promoted.Len() > 0 { select { - case p.newPendingTxs <- p.promoted.Copy(): + case p.newPendingTxns <- p.promoted.Copy(): default: } } @@ -427,7 +427,7 @@ func (p *TxPool) OnNewBlock(ctx context.Context, stateChanges *remote.StateChang return nil } -func (p *TxPool) processRemoteTxs(ctx context.Context) (err error) { +func (p *TxPool) processRemoteTxns(ctx context.Context) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("panic: %v\n%s", r, stack.Trace().String()) @@ -438,7 +438,7 @@ func (p *TxPool) processRemoteTxs(ctx context.Context) (err error) { return errors.New("txpool not started yet") } - defer processBatchTxsTimer.ObserveDuration(time.Now()) + defer processBatchTxnsTimer.ObserveDuration(time.Now()) coreDB, cache := p.coreDBWithCache() coreTx, err := coreDB.BeginRo(ctx) if err != nil { @@ -453,7 +453,7 @@ func (p *TxPool) processRemoteTxs(ctx context.Context) (err error) { p.lock.Lock() defer p.lock.Unlock() - l := len(p.unprocessedRemoteTxns.Txs) + l := len(p.unprocessedRemoteTxns.Txns) if l == 0 { return nil } @@ -463,12 +463,12 @@ func (p *TxPool) processRemoteTxs(ctx context.Context) (err error) { return err } - _, newTxs, err := p.validateTxs(p.unprocessedRemoteTxns, cacheView) + _, newTxns, err := p.validateTxns(p.unprocessedRemoteTxns, cacheView) if err != nil { return err } - announcements, _, err := p.addTxs(p.lastSeenBlock.Load(), cacheView, p.senders, newTxs, + announcements, _, err := p.addTxns(p.lastSeenBlock.Load(), cacheView, p.senders, newTxns, p.pendingBaseFee.Load(), p.pendingBlobFee.Load(), p.blockGasLimit.Load(), true, p.logger) if err != nil { return err @@ -480,7 +480,7 @@ func (p *TxPool) processRemoteTxs(ctx context.Context) (err error) { select { case <-ctx.Done(): return nil - case p.newPendingTxs <- p.promoted.Copy(): + case p.newPendingTxns <- p.promoted.Copy(): default: } } @@ -540,9 +540,9 @@ func (p *TxPool) AppendRemoteAnnouncements(types []byte, sizes []uint32, hashes hashes = append(hashes, hash...) } for hash, txIdx := range p.unprocessedRemoteByHash { - txSlot := p.unprocessedRemoteTxns.Txs[txIdx] - types = append(types, txSlot.Type) - sizes = append(sizes, txSlot.Size) + txnSlot := p.unprocessedRemoteTxns.Txns[txIdx] + types = append(types, txnSlot.Type) + sizes = append(sizes, txnSlot.Size) hashes = append(hashes, hash...) } return types, sizes, hashes @@ -564,7 +564,7 @@ func (p *TxPool) idHashKnown(tx kv.Tx, hash []byte, hashS string) (bool, error) if _, ok := p.byHash[hashS]; ok { return true, nil } - if _, ok := p.minedBlobTxsByHash[hashS]; ok { + if _, ok := p.minedBlobTxnsByHash[hashS]; ok { return true, nil } return tx.Has(kv.PoolTransaction, hash) @@ -594,14 +594,14 @@ func (p *TxPool) FilterKnownIdHashes(tx kv.Tx, hashes Hashes) (unknownHashes Has func (p *TxPool) getUnprocessedTxn(hashS string) (*TxnSlot, bool) { if i, ok := p.unprocessedRemoteByHash[hashS]; ok { - return p.unprocessedRemoteTxns.Txs[i], true + return p.unprocessedRemoteTxns.Txns[i], true } return nil, false } func (p *TxPool) getCachedBlobTxnLocked(tx kv.Tx, hash []byte) (*metaTxn, error) { hashS := string(hash) - if mt, ok := p.minedBlobTxsByHash[hashS]; ok { + if mt, ok := p.minedBlobTxnsByHash[hashS]; ok { return mt, nil } if txn, ok := p.getUnprocessedTxn(hashS); ok { @@ -617,12 +617,12 @@ func (p *TxPool) getCachedBlobTxnLocked(tx kv.Tx, hash []byte) (*metaTxn, error) if len(v) == 0 { return nil, nil } - txRlp := common.Copy(v[20:]) + txnRlp := common.Copy(v[20:]) parseCtx := NewTxnParseContext(p.chainID) parseCtx.WithSender(false) - txSlot := &TxnSlot{} - parseCtx.ParseTransaction(txRlp, 0, txSlot, nil, false, true, nil) - return newMetaTxn(txSlot, false, 0), nil + txnSlot := &TxnSlot{} + parseCtx.ParseTransaction(txnRlp, 0, txnSlot, nil, false, true, nil) + return newMetaTxn(txnSlot, false, 0), nil } func (p *TxPool) IsLocal(idHash []byte) bool { @@ -722,13 +722,13 @@ func (p *TxPool) best(n uint16, txns *TxnsRlp, tx kv.Tx, onTopOf, availableGas, return true, count, nil } -func (p *TxPool) YieldBest(n uint16, txs *TxnsRlp, tx kv.Tx, onTopOf, availableGas, availableBlobGas uint64, toSkip mapset.Set[[32]byte]) (bool, int, error) { - return p.best(n, txs, tx, onTopOf, availableGas, availableBlobGas, toSkip) +func (p *TxPool) YieldBest(n uint16, txns *TxnsRlp, tx kv.Tx, onTopOf, availableGas, availableBlobGas uint64, toSkip mapset.Set[[32]byte]) (bool, int, error) { + return p.best(n, txns, tx, onTopOf, availableGas, availableBlobGas, toSkip) } -func (p *TxPool) PeekBest(n uint16, txs *TxnsRlp, tx kv.Tx, onTopOf, availableGas, availableBlobGas uint64) (bool, error) { +func (p *TxPool) PeekBest(n uint16, txns *TxnsRlp, tx kv.Tx, onTopOf, availableGas, availableBlobGas uint64) (bool, error) { set := mapset.NewThreadUnsafeSet[[32]byte]() - onTime, _, err := p.YieldBest(n, txs, tx, onTopOf, availableGas, availableBlobGas, set) + onTime, _, err := p.YieldBest(n, txns, tx, onTopOf, availableGas, availableBlobGas, set) return onTime, err } @@ -746,16 +746,16 @@ func (p *TxPool) AddRemoteTxns(_ context.Context, newTxns TxnSlots) { return } - defer addRemoteTxsTimer.ObserveDuration(time.Now()) + defer addRemoteTxnsTimer.ObserveDuration(time.Now()) p.lock.Lock() defer p.lock.Unlock() - for i, txn := range newTxns.Txs { + for i, txn := range newTxns.Txns { hashS := string(txn.IDHash[:]) _, ok := p.unprocessedRemoteByHash[hashS] if ok { continue } - p.unprocessedRemoteByHash[hashS] = len(p.unprocessedRemoteTxns.Txs) + p.unprocessedRemoteByHash[hashS] = len(p.unprocessedRemoteTxns.Txns) p.unprocessedRemoteTxns.Append(txn, newTxns.Senders.At(i), false) } } @@ -775,7 +775,7 @@ func (p *TxPool) validateTx(txn *TxnSlot, isLocal bool, stateCache kvcache.Cache if isShanghai && txn.Creation && txn.DataLen > fixedgas.MaxInitCodeSize { return txpoolcfg.InitCodeTooLarge // EIP-3860 } - if txn.Type == BlobTxType { + if txn.Type == BlobTxnType { if !p.isCancun() { return txpoolcfg.TypeNotActivated } @@ -825,7 +825,7 @@ func (p *TxPool) validateTx(txn *TxnSlot, isLocal bool, stateCache kvcache.Cache } authorizationLen := len(txn.Authorizations) - if txn.Type == SetCodeTxType { + if txn.Type == SetCodeTxnType { if !p.isPrague() { return txpoolcfg.TypeNotActivated } @@ -994,28 +994,28 @@ func (p *TxPool) isPrague() bool { // Check that the serialized txn should not exceed a certain max size func (p *TxPool) ValidateSerializedTxn(serializedTxn []byte) error { const ( - // txSlotSize is used to calculate how many data slots a single transaction + // txnSlotSize 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 + txnSlotSize = 32 * 1024 - // txMaxSize is the maximum size a single transaction can have. This field has + // txnMaxSize 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 + txnMaxSize = 4 * txnSlotSize // 128KB // Should be enough for a transaction with 6 blobs - blobTxMaxSize = 800_000 + blobTxnMaxSize = 800_000 ) - txType, err := PeekTransactionType(serializedTxn) + txnType, err := PeekTransactionType(serializedTxn) if err != nil { return err } - maxSize := txMaxSize - if txType == BlobTxType { - maxSize = blobTxMaxSize + maxSize := txnMaxSize + if txnType == BlobTxnType { + maxSize = blobTxnMaxSize } if len(serializedTxn) > maxSize { return ErrRlpTooBig @@ -1023,18 +1023,18 @@ func (p *TxPool) ValidateSerializedTxn(serializedTxn []byte) error { return nil } -func (p *TxPool) validateTxs(txs *TxnSlots, stateCache kvcache.CacheView) (reasons []txpoolcfg.DiscardReason, goodTxs TxnSlots, err error) { +func (p *TxPool) validateTxns(txns *TxnSlots, stateCache kvcache.CacheView) (reasons []txpoolcfg.DiscardReason, goodTxns TxnSlots, err error) { // reasons is pre-sized for direct indexing, with the default zero // value DiscardReason of NotSet - reasons = make([]txpoolcfg.DiscardReason, len(txs.Txs)) + reasons = make([]txpoolcfg.DiscardReason, len(txns.Txns)) - if err := txs.Valid(); err != nil { - return reasons, goodTxs, err + if err := txns.Valid(); err != nil { + return reasons, goodTxns, err } goodCount := 0 - for i, txn := range txs.Txs { - reason := p.validateTx(txn, txs.IsLocal[i], stateCache) + for i, txn := range txns.Txns { + reason := p.validateTx(txn, txns.IsLocal[i], stateCache) if reason == txpoolcfg.Success { goodCount++ // Success here means no DiscardReason yet, so leave it NotSet @@ -1046,32 +1046,32 @@ func (p *TxPool) validateTxs(txs *TxnSlots, stateCache kvcache.CacheView) (reaso reasons[i] = reason } - goodTxs.Resize(uint(goodCount)) + goodTxns.Resize(uint(goodCount)) j := 0 - for i, txn := range txs.Txs { + for i, txn := range txns.Txns { if reasons[i] == txpoolcfg.NotSet { - goodTxs.Txs[j] = txn - goodTxs.IsLocal[j] = txs.IsLocal[i] - copy(goodTxs.Senders.At(j), txs.Senders.At(i)) + goodTxns.Txns[j] = txn + goodTxns.IsLocal[j] = txns.IsLocal[i] + copy(goodTxns.Senders.At(j), txns.Senders.At(i)) j++ } } - return reasons, goodTxs, nil + return reasons, goodTxns, 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([]*metaTxn, 0, count) + txnsToDelete := make([]*metaTxn, 0, count) p.all.descend(spammer, func(mt *metaTxn) bool { - txsToDelete = append(txsToDelete, mt) + txnsToDelete = append(txnsToDelete, mt) count-- return count > 0 }) - for _, mt := range txsToDelete { + for _, mt := range txnsToDelete { switch mt.currentSubPool { case PendingSubPool: p.pending.Remove(mt, "punishSpammer", p.logger) @@ -1088,12 +1088,12 @@ func (p *TxPool) punishSpammer(spammer uint64) { } } -func fillDiscardReasons(reasons []txpoolcfg.DiscardReason, newTxs TxnSlots, discardReasonsLRU *simplelru.LRU[string, txpoolcfg.DiscardReason]) []txpoolcfg.DiscardReason { +func fillDiscardReasons(reasons []txpoolcfg.DiscardReason, newTxns TxnSlots, discardReasonsLRU *simplelru.LRU[string, txpoolcfg.DiscardReason]) []txpoolcfg.DiscardReason { for i := range reasons { if reasons[i] != txpoolcfg.NotSet { continue } - reason, ok := discardReasonsLRU.Get(string(newTxs.Txs[i].IDHash[:])) + reason, ok := discardReasonsLRU.Get(string(newTxns.Txns[i].IDHash[:])) if ok { reasons[i] = reason } else { @@ -1123,12 +1123,12 @@ func (p *TxPool) AddLocalTxns(ctx context.Context, newTxns TxnSlots) ([]txpoolcf return nil, err } - reasons, newTxs, err := p.validateTxs(&newTxns, cacheView) + reasons, newTxns, err := p.validateTxns(&newTxns, cacheView) if err != nil { return nil, err } - announcements, addReasons, err := p.addTxs(p.lastSeenBlock.Load(), cacheView, p.senders, newTxs, + announcements, addReasons, err := p.addTxns(p.lastSeenBlock.Load(), cacheView, p.senders, newTxns, p.pendingBaseFee.Load(), p.pendingBlobFee.Load(), p.blockGasLimit.Load(), true, p.logger) if err == nil { for i, reason := range addReasons { @@ -1142,10 +1142,10 @@ func (p *TxPool) AddLocalTxns(ctx context.Context, newTxns TxnSlots) ([]txpoolcf p.promoted.Reset() p.promoted.AppendOther(announcements) - reasons = fillDiscardReasons(reasons, newTxs, p.discardReasonsLRU) + reasons = fillDiscardReasons(reasons, newTxns, p.discardReasonsLRU) for i, reason := range reasons { if reason == txpoolcfg.Success { - txn := newTxs.Txs[i] + txn := newTxns.Txns[i] if txn.Traced { p.logger.Info(fmt.Sprintf("TX TRACING: AddLocalTxns promotes idHash=%x, senderId=%d", txn.IDHash, txn.SenderID)) } @@ -1154,7 +1154,7 @@ func (p *TxPool) AddLocalTxns(ctx context.Context, newTxns TxnSlots) ([]txpoolcf } if p.promoted.Len() > 0 { select { - case p.newPendingTxs <- p.promoted.Copy(): + case p.newPendingTxns <- p.promoted.Copy(): default: } } @@ -1167,10 +1167,10 @@ func (p *TxPool) coreDBWithCache() (kv.RoDB, kvcache.Cache) { return p._chainDB, p._stateCache } -func (p *TxPool) addTxs(blockNum uint64, cacheView kvcache.CacheView, senders *sendersBatch, - newTxs TxnSlots, pendingBaseFee, pendingBlobFee, blockGasLimit uint64, collect bool, logger log.Logger) (Announcements, []txpoolcfg.DiscardReason, error) { +func (p *TxPool) addTxns(blockNum uint64, cacheView kvcache.CacheView, senders *sendersBatch, + newTxns TxnSlots, pendingBaseFee, pendingBlobFee, blockGasLimit uint64, collect bool, logger log.Logger) (Announcements, []txpoolcfg.DiscardReason, error) { if assert.Enable { - for _, txn := range newTxs.Txs { + for _, txn := range newTxns.Txns { if txn.SenderID == 0 { panic("senderID can't be zero") } @@ -1187,18 +1187,18 @@ func (p *TxPool) addTxs(blockNum uint64, cacheView kvcache.CacheView, senders *s // 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([]txpoolcfg.DiscardReason, len(newTxs.Txs)) + discardReasons := make([]txpoolcfg.DiscardReason, len(newTxns.Txns)) announcements := Announcements{} - for i, txn := range newTxs.Txs { + for i, txn := range newTxns.Txns { if found, ok := p.byHash[string(txn.IDHash[:])]; ok { discardReasons[i] = txpoolcfg.DuplicateHash // In case if the transition is stuck, "poke" it to rebroadcast - if collect && newTxs.IsLocal[i] && (found.currentSubPool == PendingSubPool || found.currentSubPool == BaseFeeSubPool) { + if collect && newTxns.IsLocal[i] && (found.currentSubPool == PendingSubPool || found.currentSubPool == BaseFeeSubPool) { announcements.Append(found.TxnSlot.Type, found.TxnSlot.Size, found.TxnSlot.IDHash[:]) } continue } - mt := newMetaTxn(txn, newTxs.IsLocal[i], blockNum) + mt := newMetaTxn(txn, newTxns.IsLocal[i], blockNum) if reason := p.addLocked(mt, &announcements); reason != txpoolcfg.NotSet { discardReasons[i] = reason continue @@ -1225,10 +1225,10 @@ func (p *TxPool) addTxs(blockNum uint64, cacheView kvcache.CacheView, senders *s } // TODO: Looks like a copy of the above -func (p *TxPool) addTxsOnNewBlock(blockNum uint64, cacheView kvcache.CacheView, stateChanges *remote.StateChangeBatch, - senders *sendersBatch, newTxs TxnSlots, pendingBaseFee uint64, blockGasLimit uint64, logger log.Logger) (Announcements, error) { +func (p *TxPool) addTxnsOnNewBlock(blockNum uint64, cacheView kvcache.CacheView, stateChanges *remote.StateChangeBatch, + senders *sendersBatch, newTxns TxnSlots, pendingBaseFee uint64, blockGasLimit uint64, logger log.Logger) (Announcements, error) { if assert.Enable { - for _, txn := range newTxs.Txs { + for _, txn := range newTxns.Txns { if txn.SenderID == 0 { panic("senderID can't be zero") } @@ -1245,11 +1245,11 @@ func (p *TxPool) addTxsOnNewBlock(blockNum uint64, cacheView kvcache.CacheView, // time (up to some "immutability threshold"). sendersWithChangedState := map[uint64]struct{}{} announcements := Announcements{} - for i, txn := range newTxs.Txs { + for i, txn := range newTxns.Txns { if _, ok := p.byHash[string(txn.IDHash[:])]; ok { continue } - mt := newMetaTxn(txn, newTxs.IsLocal[i], blockNum) + mt := newMetaTxn(txn, newTxns.IsLocal[i], blockNum) if reason := p.addLocked(mt, &announcements); reason != txpoolcfg.NotSet { p.discardLocked(mt, reason) continue @@ -1304,13 +1304,13 @@ func (p *TxPool) addLocked(mt *metaTxn, announcements *Announcements) txpoolcfg. // Insert to pending pool, if pool doesn't have txn with same Nonce and bigger Tip found := p.all.get(mt.TxnSlot.SenderID, mt.TxnSlot.Nonce) if found != nil { - if found.TxnSlot.Type == BlobTxType && mt.TxnSlot.Type != BlobTxType { + if found.TxnSlot.Type == BlobTxnType && mt.TxnSlot.Type != BlobTxnType { return txpoolcfg.BlobTxReplace } priceBump := p.cfg.PriceBump //Blob txn threshold checks for replace txn - if mt.TxnSlot.Type == BlobTxType { + if mt.TxnSlot.Type == BlobTxnType { priceBump = p.cfg.BlobPriceBump blobFeeThreshold, overflow := (&uint256.Int{}).MulDivOverflow( &found.TxnSlot.BlobFeeCap, @@ -1359,7 +1359,7 @@ func (p *TxPool) addLocked(mt *metaTxn, announcements *Announcements) txpoolcfg. } // Don't add blob txn to queued if it's less than current pending blob base fee - if mt.TxnSlot.Type == BlobTxType && mt.TxnSlot.BlobFeeCap.LtUint64(p.pendingBlobFee.Load()) { + if mt.TxnSlot.Type == BlobTxnType && mt.TxnSlot.BlobFeeCap.LtUint64(p.pendingBlobFee.Load()) { return txpoolcfg.FeeTooLow } @@ -1377,7 +1377,7 @@ func (p *TxPool) addLocked(mt *metaTxn, announcements *Announcements) txpoolcfg. } // All transactions are first added to the queued pool and then immediately promoted from there if required p.queued.Add(mt, "addLocked", p.logger) - if mt.TxnSlot.Type == BlobTxType { + if mt.TxnSlot.Type == BlobTxnType { t := p.totalBlobsInPool.Load() p.totalBlobsInPool.Store(t + (uint64(len(mt.TxnSlot.BlobHashes)))) } @@ -1392,56 +1392,56 @@ func (p *TxPool) addLocked(mt *metaTxn, announcements *Announcements) txpoolcfg. func (p *TxPool) discardLocked(mt *metaTxn, reason txpoolcfg.DiscardReason) { hashStr := string(mt.TxnSlot.IDHash[:]) delete(p.byHash, hashStr) - p.deletedTxs = append(p.deletedTxs, mt) + p.deletedTxns = append(p.deletedTxns, mt) p.all.delete(mt, reason, p.logger) p.discardReasonsLRU.Add(hashStr, reason) - if mt.TxnSlot.Type == BlobTxType { + if mt.TxnSlot.Type == BlobTxnType { t := p.totalBlobsInPool.Load() p.totalBlobsInPool.Store(t - uint64(len(mt.TxnSlot.BlobHashes))) } } // Cache recently mined blobs in anticipation of reorg, delete finalized ones -func (p *TxPool) processMinedFinalizedBlobs(coreTx kv.Tx, minedTxs []*TxnSlot, finalizedBlock uint64) error { +func (p *TxPool) processMinedFinalizedBlobs(minedTxns []*TxnSlot, finalizedBlock uint64) error { p.lastFinalizedBlock.Store(finalizedBlock) // Remove blobs in the finalized block and older, loop through all entries - for l := len(p.minedBlobTxsByBlock); l > 0 && finalizedBlock > 0; l-- { + for l := len(p.minedBlobTxnsByBlock); l > 0 && finalizedBlock > 0; l-- { // delete individual hashes - for _, mt := range p.minedBlobTxsByBlock[finalizedBlock] { - delete(p.minedBlobTxsByHash, string(mt.TxnSlot.IDHash[:])) + for _, mt := range p.minedBlobTxnsByBlock[finalizedBlock] { + delete(p.minedBlobTxnsByHash, string(mt.TxnSlot.IDHash[:])) } // delete the map entry for this block num - delete(p.minedBlobTxsByBlock, finalizedBlock) + delete(p.minedBlobTxnsByBlock, finalizedBlock) // move on to older blocks, if present finalizedBlock-- } // Add mined blobs minedBlock := p.lastSeenBlock.Load() - p.minedBlobTxsByBlock[minedBlock] = make([]*metaTxn, 0) - for _, txn := range minedTxs { - if txn.Type == BlobTxType { + p.minedBlobTxnsByBlock[minedBlock] = make([]*metaTxn, 0) + for _, txn := range minedTxns { + if txn.Type == BlobTxnType { mt := &metaTxn{TxnSlot: txn, minedBlockNum: minedBlock} - p.minedBlobTxsByBlock[minedBlock] = append(p.minedBlobTxsByBlock[minedBlock], mt) - mt.bestIndex = len(p.minedBlobTxsByBlock[minedBlock]) - 1 - p.minedBlobTxsByHash[string(txn.IDHash[:])] = mt + p.minedBlobTxnsByBlock[minedBlock] = append(p.minedBlobTxnsByBlock[minedBlock], mt) + mt.bestIndex = len(p.minedBlobTxnsByBlock[minedBlock]) - 1 + p.minedBlobTxnsByHash[string(txn.IDHash[:])] = mt } } return nil } -// Delete individual hash entries from minedBlobTxs cache +// Delete individual hash entries from minedBlobTxns cache func (p *TxPool) deleteMinedBlobTxn(hash string) { - mt, exists := p.minedBlobTxsByHash[hash] + mt, exists := p.minedBlobTxnsByHash[hash] if !exists { return } - l := len(p.minedBlobTxsByBlock[mt.minedBlockNum]) + l := len(p.minedBlobTxnsByBlock[mt.minedBlockNum]) if l > 1 { - p.minedBlobTxsByBlock[mt.minedBlockNum][mt.bestIndex] = p.minedBlobTxsByBlock[mt.minedBlockNum][l-1] + p.minedBlobTxnsByBlock[mt.minedBlockNum][mt.bestIndex] = p.minedBlobTxnsByBlock[mt.minedBlockNum][l-1] } - p.minedBlobTxsByBlock[mt.minedBlockNum] = p.minedBlobTxsByBlock[mt.minedBlockNum][:l-1] - delete(p.minedBlobTxsByHash, hash) + p.minedBlobTxnsByBlock[mt.minedBlockNum] = p.minedBlobTxnsByBlock[mt.minedBlockNum][:l-1] + delete(p.minedBlobTxnsByHash, hash) } func (p *TxPool) NonceFromAddress(addr [20]byte) (nonce uint64, inPool bool) { @@ -1461,9 +1461,9 @@ func (p *TxPool) NonceFromAddress(addr [20]byte) (nonce uint64, inPool bool) { // modify state_balance and state_nonce, potentially remove some elements (if transaction with some nonce is // included into a block), and finally, walk over the transaction records and update SubPool fields depending on // the actual presence of nonce gaps and what the balance is. -func (p *TxPool) removeMined(byNonce *BySenderAndNonce, minedTxs []*TxnSlot) error { +func (p *TxPool) removeMined(byNonce *BySenderAndNonce, minedTxns []*TxnSlot) error { noncesToRemove := map[uint64]uint64{} - for _, txn := range minedTxs { + for _, txn := range minedTxns { nonce, ok := noncesToRemove[txn.SenderID] if !ok || txn.Nonce > nonce { noncesToRemove[txn.SenderID] = txn.Nonce @@ -1539,7 +1539,7 @@ func (p *TxPool) onSenderStateChange(senderID uint64, senderNonce uint64, sender deleteAndContinueReasonLog := "" if senderNonce > mt.TxnSlot.Nonce { deleteAndContinueReasonLog = "low nonce" - } else if mt.TxnSlot.Nonce != noGapsNonce && mt.TxnSlot.Type == BlobTxType { // Discard nonce-gapped blob txns + } else if mt.TxnSlot.Nonce != noGapsNonce && mt.TxnSlot.Type == BlobTxnType { // Discard nonce-gapped blob txns deleteAndContinueReasonLog = "nonce-gapped blob txn" } if deleteAndContinueReasonLog != "" { @@ -1637,7 +1637,7 @@ func (p *TxPool) onSenderStateChange(senderID uint64, senderNonce uint64, sender // being promoted to the pending or basefee pool, for re-broadcasting func (p *TxPool) promote(pendingBaseFee uint64, pendingBlobFee uint64, announcements *Announcements, logger log.Logger) { // Demote worst transactions that do not qualify for pending sub pool anymore, to other sub pools, or discard - for worst := p.pending.Worst(); p.pending.Len() > 0 && (worst.subPool < BaseFeePoolBits || worst.minFeeCap.LtUint64(pendingBaseFee) || (worst.TxnSlot.Type == BlobTxType && worst.TxnSlot.BlobFeeCap.LtUint64(pendingBlobFee))); worst = p.pending.Worst() { + for worst := p.pending.Worst(); p.pending.Len() > 0 && (worst.subPool < BaseFeePoolBits || worst.minFeeCap.LtUint64(pendingBaseFee) || (worst.TxnSlot.Type == BlobTxnType && worst.TxnSlot.BlobFeeCap.LtUint64(pendingBlobFee))); worst = p.pending.Worst() { if worst.subPool >= BaseFeePoolBits { tx := p.pending.PopWorst() announcements.Append(tx.TxnSlot.Type, tx.TxnSlot.Size, tx.TxnSlot.IDHash[:]) @@ -1648,7 +1648,7 @@ func (p *TxPool) promote(pendingBaseFee uint64, pendingBlobFee uint64, announcem } // Promote best transactions from base fee pool to pending pool while they qualify - for best := p.baseFee.Best(); p.baseFee.Len() > 0 && best.subPool >= BaseFeePoolBits && best.minFeeCap.CmpUint64(pendingBaseFee) >= 0 && (best.TxnSlot.Type != BlobTxType || best.TxnSlot.BlobFeeCap.CmpUint64(pendingBlobFee) >= 0); best = p.baseFee.Best() { + for best := p.baseFee.Best(); p.baseFee.Len() > 0 && best.subPool >= BaseFeePoolBits && best.minFeeCap.CmpUint64(pendingBaseFee) >= 0 && (best.TxnSlot.Type != BlobTxnType || best.TxnSlot.BlobFeeCap.CmpUint64(pendingBlobFee) >= 0); best = p.baseFee.Best() { tx := p.baseFee.PopBest() announcements.Append(tx.TxnSlot.Type, tx.TxnSlot.Size, tx.TxnSlot.IDHash[:]) p.pending.Add(tx, logger) @@ -1697,11 +1697,11 @@ func (p *TxPool) promote(pendingBaseFee uint64, pendingBlobFee uint64, announcem // // promote/demote transactions // reorgs -func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan Announcements, send *Send, newSlotsStreams *NewSlotsStreams, notifyMiningAboutNewSlots func()) { +func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxns chan Announcements, send *Send, newSlotsStreams *NewSlotsStreams, notifyMiningAboutNewSlots func()) { syncToNewPeersEvery := time.NewTicker(p.cfg.SyncToNewPeersEvery) defer syncToNewPeersEvery.Stop() - processRemoteTxsEvery := time.NewTicker(p.cfg.ProcessRemoteTxsEvery) - defer processRemoteTxsEvery.Stop() + processRemoteTxnsEvery := time.NewTicker(p.cfg.ProcessRemoteTxnsEvery) + defer processRemoteTxnsEvery.Stop() commitEvery := time.NewTicker(p.cfg.CommitEvery) defer commitEvery.Stop() logEvery := time.NewTicker(p.cfg.LogEvery) @@ -1719,18 +1719,18 @@ func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan Announceme return case <-logEvery.C: p.logStats() - case <-processRemoteTxsEvery.C: + case <-processRemoteTxnsEvery.C: if !p.Started() { continue } - if err := p.processRemoteTxs(ctx); err != nil { + if err := p.processRemoteTxns(ctx); err != nil { if grpcutil.IsRetryLater(err) || grpcutil.IsEndOfStream(err) { time.Sleep(3 * time.Second) continue } - p.logger.Error("[txpool] process batch remote txs", "err", err) + p.logger.Error("[txpool] process batch remote txns", "err", err) } case <-commitEvery.C: if db != nil && p.Started() { @@ -1743,11 +1743,11 @@ func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan Announceme writeToDBBytesCounter.SetUint64(written) p.logger.Debug("[txpool] Commit", "written_kb", written/1024, "in", time.Since(t)) } - case announcements := <-newTxs: + case announcements := <-newTxns: go func() { for i := 0; i < 16; i++ { // drain more events from channel, then merge and dedup them select { - case a := <-newTxs: + case a := <-newTxns: announcements.AppendOther(a) continue default: @@ -1757,28 +1757,28 @@ func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan Announceme if announcements.Len() == 0 { return } - defer propagateNewTxsTimer.ObserveDuration(time.Now()) + defer propagateNewTxnsTimer.ObserveDuration(time.Now()) announcements = announcements.DedupCopy() notifyMiningAboutNewSlots() if p.cfg.NoGossip { - // drain newTxs for emptying newTx channel - // newTx channel will be filled only with local transactions + // drain newTxns for emptying newTxn channel + // newTxn channel will be filled only with local transactions // early return to avoid outbound transaction propagation log.Debug("[txpool] txn gossip disabled", "state", "drain new transactions") return } - var localTxTypes []byte - var localTxSizes []uint32 - var localTxHashes Hashes - var localTxRlps [][]byte - var remoteTxTypes []byte - var remoteTxSizes []uint32 - var remoteTxHashes Hashes - var remoteTxRlps [][]byte + var localTxnTypes []byte + var localTxnSizes []uint32 + var localTxnHashes Hashes + var localTxnRlps [][]byte + var remoteTxnTypes []byte + var remoteTxnSizes []uint32 + var remoteTxnHashes Hashes + var remoteTxnRlps [][]byte var broadcastHashes Hashes slotsRlp := make([][]byte, 0, announcements.Len()) @@ -1801,23 +1801,23 @@ func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan Announceme // Empty rlp can happen if a transaction we want to broadcast has just been mined, for example slotsRlp = append(slotsRlp, slotRlp) if p.IsLocal(hash) { - localTxTypes = append(localTxTypes, t) - localTxSizes = append(localTxSizes, size) - localTxHashes = append(localTxHashes, hash...) + localTxnTypes = append(localTxnTypes, t) + localTxnSizes = append(localTxnSizes, size) + localTxnHashes = append(localTxnHashes, hash...) // "Nodes MUST NOT automatically broadcast blob transactions to their peers" - EIP-4844 - if t != BlobTxType { - localTxRlps = append(localTxRlps, slotRlp) + if t != BlobTxnType { + localTxnRlps = append(localTxnRlps, slotRlp) broadcastHashes = append(broadcastHashes, hash...) } } else { - remoteTxTypes = append(remoteTxTypes, t) - remoteTxSizes = append(remoteTxSizes, size) - remoteTxHashes = append(remoteTxHashes, hash...) + remoteTxnTypes = append(remoteTxnTypes, t) + remoteTxnSizes = append(remoteTxnSizes, size) + remoteTxnHashes = append(remoteTxnHashes, hash...) // "Nodes MUST NOT automatically broadcast blob transactions to their peers" - EIP-4844 - if t != BlobTxType && len(slotRlp) < txMaxBroadcastSize { - remoteTxRlps = append(remoteTxRlps, slotRlp) + if t != BlobTxnType && len(slotRlp) < txMaxBroadcastSize { + remoteTxnRlps = append(remoteTxnRlps, slotRlp) } } } @@ -1831,21 +1831,21 @@ func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan Announceme } // broadcast local transactions - const localTxsBroadcastMaxPeers uint64 = 10 - txSentTo := send.BroadcastPooledTxs(localTxRlps, localTxsBroadcastMaxPeers) - for i, peer := range txSentTo { + const localTxnsBroadcastMaxPeers uint64 = 10 + txnSentTo := send.BroadcastPooledTxns(localTxnRlps, localTxnsBroadcastMaxPeers) + for i, peer := range txnSentTo { p.logger.Trace("Local txn broadcast", "txHash", hex.EncodeToString(broadcastHashes.At(i)), "to peer", peer) } - hashSentTo := send.AnnouncePooledTxs(localTxTypes, localTxSizes, localTxHashes, localTxsBroadcastMaxPeers*2) - for i := 0; i < localTxHashes.Len(); i++ { - hash := localTxHashes.At(i) + hashSentTo := send.AnnouncePooledTxns(localTxnTypes, localTxnSizes, localTxnHashes, localTxnsBroadcastMaxPeers*2) + for i := 0; i < localTxnHashes.Len(); i++ { + hash := localTxnHashes.At(i) p.logger.Trace("Local txn announced", "txHash", hex.EncodeToString(hash), "to peer", hashSentTo[i], "baseFee", p.pendingBaseFee.Load()) } // broadcast remote transactions - const remoteTxsBroadcastMaxPeers uint64 = 3 - send.BroadcastPooledTxs(remoteTxRlps, remoteTxsBroadcastMaxPeers) - send.AnnouncePooledTxs(remoteTxTypes, remoteTxSizes, remoteTxHashes, remoteTxsBroadcastMaxPeers*2) + const remoteTxnsBroadcastMaxPeers uint64 = 3 + send.BroadcastPooledTxns(remoteTxnRlps, remoteTxnsBroadcastMaxPeers) + send.AnnouncePooledTxns(remoteTxnTypes, remoteTxnSizes, remoteTxnHashes, remoteTxnsBroadcastMaxPeers*2) }() case <-syncToNewPeersEvery.C: // new peer newPeers := p.recentlyConnectedPeers.GetAndClean() @@ -1862,7 +1862,7 @@ func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan Announceme var types []byte var sizes []uint32 types, sizes, hashes = p.AppendAllAnnouncements(types, sizes, hashes[:0]) - go send.PropagatePooledTxsToPeersList(newPeers, types, sizes, hashes) + go send.PropagatePooledTxnsToPeersList(newPeers, types, sizes, hashes) propagateToNewPeerTimer.ObserveDuration(t) } } @@ -1916,10 +1916,10 @@ func (p *TxPool) flush(ctx context.Context, db kv.RwDB) (written uint64, err err } func (p *TxPool) flushLocked(tx kv.RwTx) (err error) { - for i, mt := range p.deletedTxs { + for i, mt := range p.deletedTxns { id := mt.TxnSlot.SenderID idHash := mt.TxnSlot.IDHash[:] - if !p.all.hasTxs(id) { + if !p.all.hasTxns(id) { addr, ok := p.senders.senderID2Addr[id] if ok { delete(p.senders.senderID2Addr, id) @@ -1936,7 +1936,7 @@ func (p *TxPool) flushLocked(tx kv.RwTx) (err error) { return err } } - p.deletedTxs[i] = nil // for gc + p.deletedTxns[i] = nil // for gc } txHashes := p.isLocalLRU.Keys() @@ -1994,7 +1994,7 @@ func (p *TxPool) flushLocked(tx kv.RwTx) (err error) { // clean - in-memory data structure as later as possible - because if during this txn will happen error, // DB will stay consistent but some in-memory structures may be already cleaned, and retry will not work // failed write transaction must not create side-effects - p.deletedTxs = p.deletedTxs[:0] + p.deletedTxns = p.deletedTxns[:0] return nil } @@ -2040,7 +2040,7 @@ func (p *TxPool) fromDB(ctx context.Context, tx kv.Tx, coreTx kv.Tx) error { p.isLocalLRU.Add(string(v), struct{}{}) } - txs := TxnSlots{} + txns := TxnSlots{} parseCtx := NewTxnParseContext(p.chainID) parseCtx.WithSender(false) @@ -2054,13 +2054,13 @@ func (p *TxPool) fromDB(ctx context.Context, tx kv.Tx, coreTx kv.Tx) error { if err != nil { return err } - addr, txRlp := *(*[20]byte)(v[:20]), v[20:] + addr, txnRlp := *(*[20]byte)(v[:20]), v[20:] txn := &TxnSlot{} // TODO(eip-4844) ensure wrappedWithBlobs when transactions are saved to the DB - _, err = parseCtx.ParseTransaction(txRlp, 0, txn, nil, false /* hasEnvelope */, true /*wrappedWithBlobs*/, nil) + _, err = parseCtx.ParseTransaction(txnRlp, 0, txn, nil, false /* hasEnvelope */, true /*wrappedWithBlobs*/, nil) if err != nil { - err = fmt.Errorf("err: %w, rlp: %x", err, txRlp) + err = fmt.Errorf("err: %w, rlp: %x", err, txnRlp) p.logger.Warn("[txpool] fromDB: parseTransaction", "err", err) continue } @@ -2070,12 +2070,12 @@ func (p *TxPool) fromDB(ctx context.Context, tx kv.Tx, coreTx kv.Tx) error { isLocalTx := p.isLocalLRU.Contains(string(k)) if reason := p.validateTx(txn, isLocalTx, cacheView); reason != txpoolcfg.NotSet && reason != txpoolcfg.Success { - return nil // TODO: Clarify - if one of the txs has the wrong reason, no pooled txs! + return nil // TODO: Clarify - if one of the txns has the wrong reason, no pooled txns! } - txs.Resize(uint(i + 1)) - txs.Txs[i] = txn - txs.IsLocal[i] = isLocalTx - copy(txs.Senders.At(i), addr[:]) + txns.Resize(uint(i + 1)) + txns.Txns[i] = txn + txns.IsLocal[i] = isLocalTx + copy(txns.Senders.At(i), addr[:]) i++ } @@ -2118,11 +2118,11 @@ func (p *TxPool) fromDB(ctx context.Context, tx kv.Tx, coreTx kv.Tx) error { blockGasLimit = DefaultBlockGasLimit } - err = p.senders.registerNewSenders(&txs, p.logger) + err = p.senders.registerNewSenders(&txns, p.logger) if err != nil { return err } - if _, _, err := p.addTxs(p.lastSeenBlock.Load(), cacheView, p.senders, txs, + if _, _, err := p.addTxns(p.lastSeenBlock.Load(), cacheView, p.senders, txns, pendingBaseFee, pendingBlobFee, blockGasLimit, false, p.logger); err != nil { return err } diff --git a/txnprovider/txpool/db.go b/txnprovider/txpool/pool_db.go similarity index 100% rename from txnprovider/txpool/db.go rename to txnprovider/txpool/pool_db.go diff --git a/txnprovider/txpool/pool_fuzz_test.go b/txnprovider/txpool/pool_fuzz_test.go index 9beb2b453b5..6024e6aa8fb 100644 --- a/txnprovider/txpool/pool_fuzz_test.go +++ b/txnprovider/txpool/pool_fuzz_test.go @@ -176,26 +176,26 @@ func parseSenders(in []byte) (nonces []uint64, balances []uint256.Int) { return } -func poolsFromFuzzBytes(rawTxNonce, rawValues, rawTips, rawFeeCap, rawSender []byte) (sendersInfo map[uint64]*sender, senderIDs map[common.Address]uint64, txs TxnSlots, ok bool) { - if len(rawTxNonce) < 1 || len(rawValues) < 1 || len(rawTips) < 1 || len(rawFeeCap) < 1 || len(rawSender) < 1+1 { - return nil, nil, txs, false +func poolsFromFuzzBytes(rawTxnNonce, rawValues, rawTips, rawFeeCap, rawSender []byte) (sendersInfo map[uint64]*sender, senderIDs map[common.Address]uint64, txns TxnSlots, ok bool) { + if len(rawTxnNonce) < 1 || len(rawValues) < 1 || len(rawTips) < 1 || len(rawFeeCap) < 1 || len(rawSender) < 1+1 { + return nil, nil, txns, false } senderNonce, senderBalance := parseSenders(rawSender) - txNonce, ok := u8Slice(rawTxNonce) + txnNonce, ok := u8Slice(rawTxnNonce) if !ok { - return nil, nil, txs, false + return nil, nil, txns, false } feeCap, ok := u8Slice(rawFeeCap) if !ok { - return nil, nil, txs, false + return nil, nil, txns, false } tips, ok := u8Slice(rawTips) if !ok { - return nil, nil, txs, false + return nil, nil, txns, false } values, ok := u256Slice(rawValues) if !ok { - return nil, nil, txs, false + return nil, nil, txns, false } sendersInfo = map[uint64]*sender{} @@ -207,30 +207,30 @@ func poolsFromFuzzBytes(rawTxNonce, rawValues, rawTips, rawFeeCap, rawSender []b sendersInfo[senderID] = newSender(senderNonce[i], senderBalance[i%len(senderBalance)]) senderIDs[senders.AddressAt(i%senders.Len())] = senderID } - txs.Txs = make([]*TxnSlot, len(txNonce)) + txns.Txns = make([]*TxnSlot, len(txnNonce)) parseCtx := NewTxnParseContext(*u256.N1) parseCtx.WithSender(false) - for i := range txNonce { - txs.Txs[i] = &TxnSlot{ - Nonce: txNonce[i], + for i := range txnNonce { + txns.Txns[i] = &TxnSlot{ + Nonce: txnNonce[i], Value: values[i%len(values)], Tip: *uint256.NewInt(tips[i%len(tips)]), FeeCap: *uint256.NewInt(feeCap[i%len(feeCap)]), } - txRlp := fakeRlpTx(txs.Txs[i], senders.At(i%senders.Len())) - _, err := parseCtx.ParseTransaction(txRlp, 0, txs.Txs[i], nil, false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) + txnRlp := fakeRlpTxn(txns.Txns[i], senders.At(i%senders.Len())) + _, err := parseCtx.ParseTransaction(txnRlp, 0, txns.Txns[i], nil, false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) if err != nil { panic(err) } - txs.Senders = append(txs.Senders, senders.At(i%senders.Len())...) - txs.IsLocal = append(txs.IsLocal, true) + txns.Senders = append(txns.Senders, senders.At(i%senders.Len())...) + txns.IsLocal = append(txns.IsLocal, true) } - return sendersInfo, senderIDs, txs, true + return sendersInfo, senderIDs, txns, true } -// fakeRlpTx add anything what identifying txn to `data` to make hash unique -func fakeRlpTx(slot *TxnSlot, data []byte) []byte { +// fakeRlpTxn add anything what identifying txn to `data` to make hash unique +func fakeRlpTxn(slot *TxnSlot, data []byte) []byte { dataLen := rlp.U64Len(1) + //chainID rlp.U64Len(slot.Nonce) + rlp.U256Len(&slot.Tip) + rlp.U256Len(&slot.FeeCap) + rlp.U64Len(0) + // gas @@ -241,7 +241,7 @@ func fakeRlpTx(slot *TxnSlot, data []byte) []byte { +3 // v,r,s buf := make([]byte, 1+rlp.ListPrefixLen(dataLen)+dataLen) - buf[0] = DynamicFeeTxType + buf[0] = DynamicFeeTxnType p := 1 p += rlp.EncodeListPrefix(dataLen, buf[p:]) p += rlp.EncodeU64(1, buf[p:]) //chainID @@ -266,7 +266,7 @@ func fakeRlpTx(slot *TxnSlot, data []byte) []byte { return buf[:] } -func iterateSubPoolUnordered(subPool *SubPool, f func(tx *metaTxn)) { +func iterateSubPoolUnordered(subPool *SubPool, f func(txn *metaTxn)) { for i := 0; i < subPool.best.Len(); i++ { f((subPool.best.ms)[i]) } @@ -274,21 +274,21 @@ func iterateSubPoolUnordered(subPool *SubPool, f func(tx *metaTxn)) { func splitDataset(in TxnSlots) (TxnSlots, TxnSlots, TxnSlots, TxnSlots) { p1, p2, p3, p4 := TxnSlots{}, TxnSlots{}, TxnSlots{}, TxnSlots{} - l := len(in.Txs) / 4 + l := len(in.Txns) / 4 - p1.Txs = in.Txs[:l] + p1.Txns = in.Txns[:l] p1.IsLocal = in.IsLocal[:l] p1.Senders = in.Senders[:l*20] - p2.Txs = in.Txs[l : 2*l] + p2.Txns = in.Txns[l : 2*l] p2.IsLocal = in.IsLocal[l : 2*l] p2.Senders = in.Senders[l*20 : 2*l*20] - p3.Txs = in.Txs[2*l : 3*l] + p3.Txns = in.Txns[2*l : 3*l] p3.IsLocal = in.IsLocal[2*l : 3*l] p3.Senders = in.Senders[2*l*20 : 3*l*20] - p4.Txs = in.Txs[3*l : 4*l] + p4.Txns = in.Txns[3*l : 4*l] p4.IsLocal = in.IsLocal[3*l : 4*l] p4.Senders = in.Senders[3*l*20 : 4*l*20] @@ -309,13 +309,13 @@ func FuzzOnNewBlocks(f *testing.F) { if pendingBaseFee == 0 { t.Skip() } - senders, senderIDs, txs, ok := poolsFromFuzzBytes(txNonce, values, tips, feeCap, senderAddr) + senders, senderIDs, txns, ok := poolsFromFuzzBytes(txNonce, values, tips, feeCap, senderAddr) if !ok { t.Skip() } assert, require := assert.New(t), require.New(t) - assert.NoError(txs.Valid()) + assert.NoError(txns.Valid()) var prevHashes Hashes ch := make(chan Announcements, 100) @@ -336,7 +336,7 @@ func FuzzOnNewBlocks(f *testing.F) { pool.senders.senderID2Addr[id] = addr } pool.senders.senderID = uint64(len(senderIDs)) - check := func(unwindTxs, minedTxs TxnSlots, msg string) { + check := func(unwindTxns, minedTxns TxnSlots, msg string) { pending, baseFee, queued := pool.pending, pool.baseFee, pool.queued best, worst := pending.Best(), pending.Worst() assert.LessOrEqual(pending.Len(), cfg.PendingSubPoolLimit) @@ -354,19 +354,19 @@ func FuzzOnNewBlocks(f *testing.F) { assert.LessOrEqual(pendingBaseFee, txn.TxnSlot.FeeCap, msg) } - // side data structures must have all txs + // side data structures must have all txns assert.True(pool.all.has(txn), msg) _, ok = pool.byHash[string(i.IDHash[:])] assert.True(ok) // pools can't have more then 1 txn with same SenderID+Nonce - iterateSubPoolUnordered(baseFee, func(mtx2 *metaTxn) { - tx2 := mtx2.TxnSlot - assert.False(tx2.SenderID == i.SenderID && tx2.Nonce == i.Nonce, msg) + iterateSubPoolUnordered(baseFee, func(mtxn2 *metaTxn) { + txn2 := mtxn2.TxnSlot + assert.False(txn2.SenderID == i.SenderID && txn2.Nonce == i.Nonce, msg) }) - iterateSubPoolUnordered(queued, func(mtx2 *metaTxn) { - tx2 := mtx2.TxnSlot - assert.False(tx2.SenderID == i.SenderID && tx2.Nonce == i.Nonce, msg) + iterateSubPoolUnordered(queued, func(mtxn2 *metaTxn) { + txn2 := mtxn2.TxnSlot + assert.False(txn2.SenderID == i.SenderID && txn2.Nonce == i.Nonce, msg) }) } @@ -378,16 +378,16 @@ func FuzzOnNewBlocks(f *testing.F) { if worst != nil && worst.subPool < 0b1100 { t.Fatalf("baseFee worst too small %b", worst.subPool) } - iterateSubPoolUnordered(baseFee, func(tx *metaTxn) { - i := tx.TxnSlot - if tx.subPool&NoNonceGaps > 0 { + iterateSubPoolUnordered(baseFee, func(txn *metaTxn) { + i := txn.TxnSlot + if txn.subPool&NoNonceGaps > 0 { assert.GreaterOrEqual(i.Nonce, senders[i.SenderID].nonce, msg) } - if tx.subPool&EnoughFeeCapBlock > 0 { - assert.LessOrEqual(pendingBaseFee, tx.TxnSlot.FeeCap, msg) + if txn.subPool&EnoughFeeCapBlock > 0 { + assert.LessOrEqual(pendingBaseFee, txn.TxnSlot.FeeCap, msg) } - assert.True(pool.all.has(tx), msg) + assert.True(pool.all.has(txn), msg) _, ok = pool.byHash[string(i.IDHash[:])] assert.True(ok, msg) }) @@ -396,22 +396,22 @@ func FuzzOnNewBlocks(f *testing.F) { assert.LessOrEqual(queued.Len(), cfg.QueuedSubPoolLimit) assert.False(worst != nil && best == nil, msg) assert.False(worst == nil && best != nil, msg) - iterateSubPoolUnordered(queued, func(tx *metaTxn) { - i := tx.TxnSlot - if tx.subPool&NoNonceGaps > 0 { + iterateSubPoolUnordered(queued, func(txn *metaTxn) { + i := txn.TxnSlot + if txn.subPool&NoNonceGaps > 0 { assert.GreaterOrEqual(i.Nonce, senders[i.SenderID].nonce, msg, i.SenderID, senders[i.SenderID].nonce) } - if tx.subPool&EnoughFeeCapBlock > 0 { - assert.LessOrEqual(pendingBaseFee, tx.TxnSlot.FeeCap, msg) + if txn.subPool&EnoughFeeCapBlock > 0 { + assert.LessOrEqual(pendingBaseFee, txn.TxnSlot.FeeCap, msg) } - assert.True(pool.all.has(tx), "%s, %d, %x", msg, tx.TxnSlot.Nonce, tx.TxnSlot.IDHash) + assert.True(pool.all.has(txn), "%s, %d, %x", msg, txn.TxnSlot.Nonce, txn.TxnSlot.IDHash) _, ok = pool.byHash[string(i.IDHash[:])] assert.True(ok, msg) - assert.GreaterOrEqual(tx.TxnSlot.FeeCap, pool.cfg.MinFeeCap) + assert.GreaterOrEqual(txn.TxnSlot.FeeCap, pool.cfg.MinFeeCap) }) - // all txs in side data structures must be in some queue + // all txns in side data structures must be in some queue for _, txn := range pool.byHash { require.True(txn.bestIndex >= 0, msg) assert.True(txn.worstIndex >= 0, msg) @@ -425,9 +425,9 @@ func FuzzOnNewBlocks(f *testing.F) { }) } - // mined txs must be removed - for i := range minedTxs.Txs { - _, ok = pool.byHash[string(minedTxs.Txs[i].IDHash[:])] + // mined txns must be removed + for i := range minedTxns.Txns { + _, ok = pool.byHash[string(minedTxns.Txns[i].IDHash[:])] assert.False(ok, msg) } @@ -440,26 +440,26 @@ func FuzzOnNewBlocks(f *testing.F) { } } - checkNotify := func(unwindTxs, minedTxs TxnSlots, msg string) { + checkNotify := func(unwindTxns, minedTxns TxnSlots, msg string) { select { case newAnnouncements := <-ch: assert.Greater(newAnnouncements.Len(), 0) for i := 0; i < newAnnouncements.Len(); i++ { _, _, newHash := newAnnouncements.At(i) - for j := range unwindTxs.Txs { - if bytes.Equal(unwindTxs.Txs[j].IDHash[:], newHash) { - mt := pool.all.get(unwindTxs.Txs[j].SenderID, unwindTxs.Txs[j].Nonce) + for j := range unwindTxns.Txns { + if bytes.Equal(unwindTxns.Txns[j].IDHash[:], newHash) { + mt := pool.all.get(unwindTxns.Txns[j].SenderID, unwindTxns.Txns[j].Nonce) require.True(mt != nil && mt.currentSubPool == PendingSubPool, msg) } } - for j := range minedTxs.Txs { - if bytes.Equal(minedTxs.Txs[j].IDHash[:], newHash) { - mt := pool.all.get(unwindTxs.Txs[j].SenderID, unwindTxs.Txs[j].Nonce) + for j := range minedTxns.Txns { + if bytes.Equal(minedTxns.Txns[j].IDHash[:], newHash) { + mt := pool.all.get(unwindTxns.Txns[j].SenderID, unwindTxns.Txns[j].Nonce) require.True(mt != nil && mt.currentSubPool == PendingSubPool, msg) } } } - default: // no notifications - means pools must be unchanged or drop some txs + default: // no notifications - means pools must be unchanged or drop some txns pendingHashes := copyHashes(pool.pending) require.Zero(extractNewHashes(pendingHashes, prevHashes).Len()) } @@ -495,13 +495,13 @@ func FuzzOnNewBlocks(f *testing.F) { }) } // go to first fork - txs1, txs2, p2pReceived, txs3 := splitDataset(txs) - err = pool.OnNewBlock(ctx, change, txs1, TxnSlots{}, TxnSlots{}) + txns1, txns2, p2pReceived, txns3 := splitDataset(txns) + err = pool.OnNewBlock(ctx, change, txns1, TxnSlots{}, TxnSlots{}) assert.NoError(err) - check(txs1, TxnSlots{}, "fork1") - checkNotify(txs1, TxnSlots{}, "fork1") + check(txns1, TxnSlots{}, "fork1") + checkNotify(txns1, TxnSlots{}, "fork1") - _, _, _ = p2pReceived, txs2, txs3 + _, _, _ = p2pReceived, txns2, txns3 change = &remote.StateChangeBatch{ StateVersionId: txID, PendingBlockBaseFee: pendingBaseFee, @@ -509,10 +509,10 @@ func FuzzOnNewBlocks(f *testing.F) { {BlockHeight: 1, BlockHash: h0}, }, } - err = pool.OnNewBlock(ctx, change, TxnSlots{}, TxnSlots{}, txs2) + err = pool.OnNewBlock(ctx, change, TxnSlots{}, TxnSlots{}, txns2) assert.NoError(err) - check(TxnSlots{}, txs2, "fork1 mined") - checkNotify(TxnSlots{}, txs2, "fork1 mined") + check(TxnSlots{}, txns2, "fork1 mined") + checkNotify(TxnSlots{}, txns2, "fork1 mined") // unwind everything and switch to new fork (need unwind mined now) change = &remote.StateChangeBatch{ @@ -522,10 +522,10 @@ func FuzzOnNewBlocks(f *testing.F) { {BlockHeight: 0, BlockHash: h0, Direction: remote.Direction_UNWIND}, }, } - err = pool.OnNewBlock(ctx, change, txs2, TxnSlots{}, TxnSlots{}) + err = pool.OnNewBlock(ctx, change, txns2, TxnSlots{}, TxnSlots{}) assert.NoError(err) - check(txs2, TxnSlots{}, "fork2") - checkNotify(txs2, TxnSlots{}, "fork2") + check(txns2, TxnSlots{}, "fork2") + checkNotify(txns2, TxnSlots{}, "fork2") change = &remote.StateChangeBatch{ StateVersionId: txID, @@ -534,14 +534,14 @@ func FuzzOnNewBlocks(f *testing.F) { {BlockHeight: 1, BlockHash: h22}, }, } - err = pool.OnNewBlock(ctx, change, TxnSlots{}, TxnSlots{}, txs3) + err = pool.OnNewBlock(ctx, change, TxnSlots{}, TxnSlots{}, txns3) assert.NoError(err) - check(TxnSlots{}, txs3, "fork2 mined") - checkNotify(TxnSlots{}, txs3, "fork2 mined") + check(TxnSlots{}, txns3, "fork2 mined") + checkNotify(TxnSlots{}, txns3, "fork2 mined") - // add some remote txs from p2p + // add some remote txns from p2p pool.AddRemoteTxns(ctx, p2pReceived) - err = pool.processRemoteTxs(ctx) + err = pool.processRemoteTxns(ctx) assert.NoError(err) check(p2pReceived, TxnSlots{}, "p2pmsg1") checkNotify(p2pReceived, TxnSlots{}, "p2pmsg1") @@ -561,8 +561,8 @@ func FuzzOnNewBlocks(f *testing.F) { assert.Nil(txn.TxnSlot.Rlp) } - check(txs2, TxnSlots{}, "fromDB") - checkNotify(txs2, TxnSlots{}, "fromDB") + check(txns2, TxnSlots{}, "fromDB") + checkNotify(txns2, TxnSlots{}, "fromDB") assert.Equal(pool.senders.senderID, p2.senders.senderID) assert.Equal(pool.lastSeenBlock.Load(), p2.lastSeenBlock.Load()) assert.Equal(pool.pending.Len(), p2.pending.Len()) diff --git a/txnprovider/txpool/pool_test.go b/txnprovider/txpool/pool_test.go index 5ef8e21dc50..2a1ca45ee64 100644 --- a/txnprovider/txpool/pool_test.go +++ b/txnprovider/txpool/pool_test.go @@ -86,17 +86,17 @@ func TestNonceFromAddress(t *testing.T) { assert.NoError(err) { - var txSlots TxnSlots - txSlot1 := &TxnSlot{ + var txnSlots TxnSlots + txnSlot1 := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 3, } - txSlot1.IDHash[0] = 1 - txSlots.Append(txSlot1, addr[:], true) + txnSlot1.IDHash[0] = 1 + txnSlots.Append(txnSlot1, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -104,24 +104,24 @@ func TestNonceFromAddress(t *testing.T) { } { - txSlots := TxnSlots{} - txSlot2 := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot2 := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 4, } - txSlot2.IDHash[0] = 2 - txSlot3 := &TxnSlot{ + txnSlot2.IDHash[0] = 2 + txnSlot3 := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 6, } - txSlot3.IDHash[0] = 3 - txSlots.Append(txSlot2, addr[:], true) - txSlots.Append(txSlot3, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot3.IDHash[0] = 3 + txnSlots.Append(txnSlot2, addr[:], true) + txnSlots.Append(txnSlot3, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -132,16 +132,16 @@ func TestNonceFromAddress(t *testing.T) { } // test too expensive tx { - var txSlots TxnSlots - txSlot1 := &TxnSlot{ + var txnSlots TxnSlots + txnSlot1 := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(9 * common.Ether), Gas: 100000, Nonce: 3, } - txSlot1.IDHash[0] = 4 - txSlots.Append(txSlot1, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot1.IDHash[0] = 4 + txnSlots.Append(txnSlot1, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.InsufficientFunds, reason, reason.String()) @@ -150,16 +150,16 @@ func TestNonceFromAddress(t *testing.T) { // test too low nonce { - var txSlots TxnSlots - txSlot1 := &TxnSlot{ + var txnSlots TxnSlots + txnSlot1 := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 1, } - txSlot1.IDHash[0] = 5 - txSlots.Append(txSlot1, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot1.IDHash[0] = 5 + txnSlots.Append(txnSlot1, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.NonceTooLow, reason, reason.String()) @@ -208,17 +208,17 @@ func TestReplaceWithHigherFee(t *testing.T) { assert.NoError(err) { - var txSlots TxnSlots - txSlot := &TxnSlot{ + var txnSlots TxnSlots + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 3, } - txSlot.IDHash[0] = 1 - txSlots.Append(txSlot, addr[:], true) + txnSlot.IDHash[0] = 1 + txnSlots.Append(txnSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -226,16 +226,16 @@ func TestReplaceWithHigherFee(t *testing.T) { } // Bumped only feeCap, transaction not accepted { - txSlots := TxnSlots{} - txSlot := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(3000000), Gas: 100000, Nonce: 3, } - txSlot.IDHash[0] = 2 - txSlots.Append(txSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot.IDHash[0] = 2 + txnSlots.Append(txnSlot, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.NotReplaced, reason, reason.String()) @@ -246,16 +246,16 @@ func TestReplaceWithHigherFee(t *testing.T) { } // Bumped only tip, transaction not accepted { - txSlots := TxnSlots{} - txSlot := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(3000000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 3, } - txSlot.IDHash[0] = 3 - txSlots.Append(txSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot.IDHash[0] = 3 + txnSlots.Append(txnSlot, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.NotReplaced, reason, reason.String()) @@ -266,16 +266,16 @@ func TestReplaceWithHigherFee(t *testing.T) { } // Bumped both tip and feeCap by 10%, txn accepted { - txSlots := TxnSlots{} - txSlot := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(330000), FeeCap: *uint256.NewInt(330000), Gas: 100000, Nonce: 3, } - txSlot.IDHash[0] = 4 - txSlots.Append(txSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot.IDHash[0] = 4 + txnSlots.Append(txnSlot, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -327,17 +327,17 @@ func TestReverseNonces(t *testing.T) { assert.NoError(err) // 1. Send high fee transaction with nonce gap { - var txSlots TxnSlots - txSlot := &TxnSlot{ + var txnSlots TxnSlots + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(500_000), FeeCap: *uint256.NewInt(3_000_000), Gas: 100000, Nonce: 3, } - txSlot.IDHash[0] = 1 - txSlots.Append(txSlot, addr[:], true) + txnSlot.IDHash[0] = 1 + txnSlots.Append(txnSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -354,17 +354,17 @@ func TestReverseNonces(t *testing.T) { } // 2. Send low fee (below base fee) transaction without nonce gap { - var txSlots TxnSlots - txSlot := &TxnSlot{ + var txnSlots TxnSlots + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(500_000), FeeCap: *uint256.NewInt(500_000), Gas: 100000, Nonce: 2, } - txSlot.IDHash[0] = 2 - txSlots.Append(txSlot, addr[:], true) + txnSlot.IDHash[0] = 2 + txnSlots.Append(txnSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -381,17 +381,17 @@ func TestReverseNonces(t *testing.T) { } { - var txSlots TxnSlots - txSlot := &TxnSlot{ + var txnSlots TxnSlots + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(600_000), FeeCap: *uint256.NewInt(3_000_000), Gas: 100000, Nonce: 2, } - txSlot.IDHash[0] = 3 - txSlots.Append(txSlot, addr[:], true) + txnSlot.IDHash[0] = 3 + txnSlots.Append(txnSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -454,18 +454,18 @@ func TestTxPoke(t *testing.T) { var idHash Hashes { - var txSlots TxnSlots - txSlot := &TxnSlot{ + var txnSlots TxnSlots + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 2, } - txSlot.IDHash[0] = 1 - idHash = append(idHash, txSlot.IDHash[:]...) - txSlots.Append(txSlot, addr[:], true) + txnSlot.IDHash[0] = 1 + idHash = append(idHash, txnSlot.IDHash[:]...) + txnSlots.Append(txnSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -482,16 +482,16 @@ func TestTxPoke(t *testing.T) { } // Send the same transaction, not accepted { - txSlots := TxnSlots{} - txSlot := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 2, } - txSlot.IDHash[0] = 1 - txSlots.Append(txSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot.IDHash[0] = 1 + txnSlots.Append(txnSlot, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.DuplicateHash, reason, reason.String()) @@ -511,16 +511,16 @@ func TestTxPoke(t *testing.T) { } // Send different transaction, but only with tip bumped { - txSlots := TxnSlots{} - txSlot := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(3000000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 2, } - txSlot.IDHash[0] = 2 - txSlots.Append(txSlot, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlot.IDHash[0] = 2 + txnSlots.Append(txnSlot, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.NotReplaced, reason, reason.String()) @@ -541,16 +541,16 @@ func TestTxPoke(t *testing.T) { // Send the same transaction, but as remote { - txSlots := TxnSlots{} - txSlot := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100000, Nonce: 2, } - txSlot.IDHash[0] = 1 - txSlots.Append(txSlot, addr[:], true) - pool.AddRemoteTxns(ctx, txSlots) + txnSlot.IDHash[0] = 1 + txnSlots.Append(txnSlot, addr[:], true) + pool.AddRemoteTxns(ctx, txnSlots) nonce, ok := pool.NonceFromAddress(addr) assert.True(ok) assert.Equal(uint64(2), nonce) @@ -563,16 +563,16 @@ func TestTxPoke(t *testing.T) { } // Send different transaction, but only with tip bumped, as a remote { - txSlots := TxnSlots{} - txSlot := &TxnSlot{ + txnSlots := TxnSlots{} + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(3000000), FeeCap: *uint256.NewInt(3000000), Gas: 100000, Nonce: 2, } - txSlot.IDHash[0] = 2 - txSlots.Append(txSlot, addr[:], true) - pool.AddRemoteTxns(ctx, txSlots) + txnSlot.IDHash[0] = 2 + txnSlots.Append(txnSlot, addr[:], true) + pool.AddRemoteTxns(ctx, txnSlots) nonce, ok := pool.NonceFromAddress(addr) assert.True(ok) assert.Equal(uint64(2), nonce) @@ -649,7 +649,7 @@ func TestShanghaiIntrinsicGas(t *testing.T) { } } -func TestShanghaiValidateTx(t *testing.T) { +func TestShanghaiValidateTxn(t *testing.T) { asrt := assert.New(t) tests := map[string]struct { expected txpoolcfg.DiscardReason @@ -732,7 +732,7 @@ func TestShanghaiValidateTx(t *testing.T) { } txns := TxnSlots{ - Txs: append([]*TxnSlot{}, txn), + Txns: append([]*TxnSlot{}, txn), Senders: Addresses{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, } err = pool.senders.registerNewSenders(&txns, logger) @@ -749,7 +749,7 @@ func TestShanghaiValidateTx(t *testing.T) { } } -func TestSetCodeTxValidationWithLargeAuthorizationValues(t *testing.T) { +func TestSetCodeTxnValidationWithLargeAuthorizationValues(t *testing.T) { maxUint256 := new(uint256.Int).SetAllOne() ch := make(chan Announcements, 1) @@ -776,7 +776,7 @@ func TestSetCodeTxValidationWithLargeAuthorizationValues(t *testing.T) { FeeCap: *uint256.NewInt(21000), Gas: 500000, SenderID: 0, - Type: SetCodeTxType, + Type: SetCodeTxnType, Authorizations: make([]Signature, 1), } txn.Authorizations[0].ChainID = chainID @@ -785,7 +785,7 @@ func TestSetCodeTxValidationWithLargeAuthorizationValues(t *testing.T) { txn.Authorizations[0].S.Set(maxUint256) txns := TxnSlots{ - Txs: append([]*TxnSlot{}, txn), + Txns: append([]*TxnSlot{}, txn), Senders: Addresses{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, } err = pool.senders.registerNewSenders(&txns, logger) @@ -798,7 +798,7 @@ func TestSetCodeTxValidationWithLargeAuthorizationValues(t *testing.T) { } // Blob gas price bump + other requirements to replace existing txns in the pool -func TestBlobTxReplacement(t *testing.T) { +func TestBlobTxnReplacement(t *testing.T) { t.Skip("TODO") assert, require := assert.New(t), require.New(t) ch := make(chan Announcements, 5) @@ -845,13 +845,13 @@ func TestBlobTxReplacement(t *testing.T) { //add a blob txn to the pool { - txSlots := TxnSlots{} - blobTxn := makeBlobTx() + txnSlots := TxnSlots{} + blobTxn := makeBlobTxn() blobTxn.IDHash[0] = 0x00 blobTxn.Nonce = 0x2 - txSlots.Append(&blobTxn, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlots.Append(&blobTxn, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) t.Logf("Reasons %v", reasons) for _, reason := range reasons { @@ -861,16 +861,16 @@ func TestBlobTxReplacement(t *testing.T) { { // try to replace it with 5% extra blob gas, 2x higher txn fee - should fail - txSlots := TxnSlots{} - blobTxn := makeBlobTx() + txnSlots := TxnSlots{} + blobTxn := makeBlobTxn() blobTxn.Nonce = 0x2 blobTxn.FeeCap.Mul(uint256.NewInt(2), feeCap) blobTxn.Tip.Mul(uint256.NewInt(2), tip) //increase blobFeeCap by 10% - no good blobTxn.BlobFeeCap.Add(blobFeeCap, uint256.NewInt(1).Div(blobFeeCap, uint256.NewInt(10))) blobTxn.IDHash[0] = 0x01 - txSlots.Append(&blobTxn, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlots.Append(&blobTxn, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) t.Logf("Reasons %v", reasons) for _, reason := range reasons { @@ -879,9 +879,9 @@ func TestBlobTxReplacement(t *testing.T) { } { - txSlots := TxnSlots{} + txnSlots := TxnSlots{} //try to replace it with a regular txn - should fail - regularTx := TxnSlot{ + regularTxn := TxnSlot{ DataLen: 32, FeeCap: *uint256.NewInt(1).Mul(uint256.NewInt(10), feeCap), //10x the previous Tip: *uint256.NewInt(1).Mul(uint256.NewInt(10), tip), @@ -891,9 +891,9 @@ func TestBlobTxReplacement(t *testing.T) { Creation: true, Nonce: 0x2, } - regularTx.IDHash[0] = 0x02 - txSlots.Append(®ularTx, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + regularTxn.IDHash[0] = 0x02 + txnSlots.Append(®ularTxn, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) t.Logf("Reasons %v", reasons) for _, reason := range reasons { @@ -903,74 +903,74 @@ func TestBlobTxReplacement(t *testing.T) { // Try to replace it with required price bump (configured in pool.cfg.BlobPriceBump for blob txns) to all transaction fields - should be successful only if all are bumped { - blobTxn := makeBlobTx() + blobTxn := makeBlobTxn() origTip := blobTxn.Tip origFee := blobTxn.FeeCap blobTxn.Nonce = 0x2 blobTxn.IDHash[0] = 0x03 - txSlots := TxnSlots{} - txSlots.Append(&blobTxn, addr[:], true) + txnSlots := TxnSlots{} + txnSlots.Append(&blobTxn, addr[:], true) // Get the config of the pool for BlobPriceBump and bump prices requiredPriceBump := pool.cfg.BlobPriceBump // Bump the tip only blobTxn.Tip.MulDivOverflow(tip, uint256.NewInt(requiredPriceBump+100), uint256.NewInt(100)) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) assert.Equal(txpoolcfg.ReplaceUnderpriced, reasons[0], reasons[0].String()) // Bump the fee + tip blobTxn.FeeCap.MulDivOverflow(feeCap, uint256.NewInt(requiredPriceBump+100), uint256.NewInt(100)) - reasons, err = pool.AddLocalTxns(ctx, txSlots) + reasons, err = pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) assert.Equal(txpoolcfg.ReplaceUnderpriced, reasons[0], reasons[0].String()) // Bump only Feecap blobTxn.Tip = origTip - reasons, err = pool.AddLocalTxns(ctx, txSlots) + reasons, err = pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) assert.Equal(txpoolcfg.ReplaceUnderpriced, reasons[0], reasons[0].String()) // Bump fee cap + blobFee cap blobTxn.BlobFeeCap.MulDivOverflow(blobFeeCap, uint256.NewInt(requiredPriceBump+100), uint256.NewInt(100)) - reasons, err = pool.AddLocalTxns(ctx, txSlots) + reasons, err = pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) assert.Equal(txpoolcfg.NotReplaced, reasons[0], reasons[0].String()) // Bump only blobFee cap blobTxn.FeeCap = origFee - reasons, err = pool.AddLocalTxns(ctx, txSlots) + reasons, err = pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) assert.Equal(txpoolcfg.NotReplaced, reasons[0], reasons[0].String()) // Bump all prices blobTxn.Tip.MulDivOverflow(tip, uint256.NewInt(requiredPriceBump+100), uint256.NewInt(100)) blobTxn.FeeCap.MulDivOverflow(feeCap, uint256.NewInt(requiredPriceBump+100), uint256.NewInt(100)) - reasons, err = pool.AddLocalTxns(ctx, txSlots) + reasons, err = pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) assert.Equal(txpoolcfg.Success, reasons[0], reasons[0].String()) } } // Todo, make the txn more realistic with good values -func makeBlobTx() TxnSlot { - wrapperRlp, commitments := typestest.MakeBlobTxRlp() +func makeBlobTxn() TxnSlot { + wrapperRlp, commitments := typestest.MakeBlobTxnRlp() commitment0 := commitments[0] commitment1 := commitments[1] tip, feeCap, blobFeeCap := uint256.NewInt(100_000), uint256.NewInt(200_000), uint256.NewInt(200_000) - blobTx := TxnSlot{} + blobTxn := TxnSlot{} tctx := NewTxnParseContext(*uint256.NewInt(5)) tctx.WithSender(false) - tctx.ParseTransaction(wrapperRlp, 0, &blobTx, nil, false, true, nil) - blobTx.BlobHashes = make([]common.Hash, 2) - blobTx.BlobHashes[0] = common.Hash(kzg.KZGToVersionedHash(commitment0)) - blobTx.BlobHashes[1] = common.Hash(kzg.KZGToVersionedHash(commitment1)) - - blobTx.Tip = *tip - blobTx.FeeCap = *feeCap - blobTx.BlobFeeCap = *blobFeeCap - return blobTx + tctx.ParseTransaction(wrapperRlp, 0, &blobTxn, nil, false, true, nil) + blobTxn.BlobHashes = make([]common.Hash, 2) + blobTxn.BlobHashes[0] = common.Hash(kzg.KZGToVersionedHash(commitment0)) + blobTxn.BlobHashes[1] = common.Hash(kzg.KZGToVersionedHash(commitment1)) + + blobTxn.Tip = *tip + blobTxn.FeeCap = *feeCap + blobTxn.BlobFeeCap = *blobFeeCap + return blobTxn } func TestDropRemoteAtNoGossip(t *testing.T) { @@ -986,13 +986,13 @@ func TestDropRemoteAtNoGossip(t *testing.T) { logger := log.New() sendersCache := kvcache.New(kvcache.DefaultCoherentConfig) - txPool, err := New(ch, coreDB, cfg, sendersCache, *u256.N1, big.NewInt(0), big.NewInt(0), nil, nil, fixedgas.DefaultMaxBlobsPerBlock, nil, logger) + txnPool, err := New(ch, coreDB, cfg, sendersCache, *u256.N1, big.NewInt(0), big.NewInt(0), nil, nil, fixedgas.DefaultMaxBlobsPerBlock, nil, logger) assert.NoError(err) - require.True(txPool != nil) + require.True(txnPool != nil) ctx := context.Background() - err = txPool.Start(ctx, db) + err = txnPool.Start(ctx, db) assert.NoError(err) var stateVersionID uint64 = 0 @@ -1019,21 +1019,21 @@ func TestDropRemoteAtNoGossip(t *testing.T) { tx, err := db.BeginRw(ctx) require.NoError(err) defer tx.Rollback() - err = txPool.OnNewBlock(ctx, change, TxnSlots{}, TxnSlots{}, TxnSlots{}) + err = txnPool.OnNewBlock(ctx, change, TxnSlots{}, TxnSlots{}, TxnSlots{}) assert.NoError(err) // 1. Try Local TxnSlot { - var txSlots TxnSlots - txSlot := &TxnSlot{ + var txnSlots TxnSlots + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(500_000), FeeCap: *uint256.NewInt(3_000_000), Gas: 100000, Nonce: 3, } - txSlot.IDHash[0] = 1 - txSlots.Append(txSlot, addr[:], true) + txnSlot.IDHash[0] = 1 + txnSlots.Append(txnSlot, addr[:], true) - reasons, err := txPool.AddLocalTxns(ctx, txSlots) + reasons, err := txnPool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -1051,24 +1051,24 @@ func TestDropRemoteAtNoGossip(t *testing.T) { // 2. Try same TxnSlot, but as remote; txn must be dropped { - var txSlots TxnSlots - txSlot := &TxnSlot{ + var txnSlots TxnSlots + txnSlot := &TxnSlot{ Tip: *uint256.NewInt(500_000), FeeCap: *uint256.NewInt(3_000_000), Gas: 100000, Nonce: 3, } - txSlot.IDHash[0] = 1 - txSlots.Append(txSlot, addr[:], true) + txnSlot.IDHash[0] = 1 + txnSlots.Append(txnSlot, addr[:], true) - txPool.AddRemoteTxns(ctx, txSlots) + txnPool.AddRemoteTxns(ctx, txnSlots) } // empty because AddRemoteTxns logic is intentionally empty - assert.Equal(0, len(txPool.unprocessedRemoteByHash)) - assert.Equal(0, len(txPool.unprocessedRemoteTxns.Txs)) + assert.Equal(0, len(txnPool.unprocessedRemoteByHash)) + assert.Equal(0, len(txnPool.unprocessedRemoteTxns.Txns)) - assert.NoError(txPool.processRemoteTxs(ctx)) + assert.NoError(txnPool.processRemoteTxns(ctx)) checkAnnouncementEmpty := func() bool { select { @@ -1133,13 +1133,13 @@ func TestBlobSlots(t *testing.T) { //Adding 20 blobs from 10 different accounts for i := 0; i < int(cfg.TotalBlobPoolLimit/2); i++ { - txSlots := TxnSlots{} + txnSlots := TxnSlots{} addr[0] = uint8(i + 1) - blobTxn := makeBlobTx() // makes a txn with 2 blobs + blobTxn := makeBlobTxn() // makes a txn with 2 blobs blobTxn.IDHash[0] = uint8(2*i + 1) blobTxn.Nonce = 0 - txSlots.Append(&blobTxn, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlots.Append(&blobTxn, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) @@ -1147,14 +1147,14 @@ func TestBlobSlots(t *testing.T) { } // Adding another blob txn should reject - txSlots := TxnSlots{} + txnSlots := TxnSlots{} addr[0] = 11 - blobTxn := makeBlobTx() + blobTxn := makeBlobTxn() blobTxn.IDHash[0] = uint8(21) blobTxn.Nonce = 0 - txSlots.Append(&blobTxn, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + txnSlots.Append(&blobTxn, addr[:], true) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.BlobPoolOverflow, reason, reason.String()) @@ -1202,23 +1202,23 @@ func TestGasLimitChanged(t *testing.T) { err = pool.OnNewBlock(ctx, change, TxnSlots{}, TxnSlots{}, TxnSlots{}) assert.NoError(err) - var txSlots TxnSlots - txSlot1 := &TxnSlot{ + var txnSlots TxnSlots + txnSlot1 := &TxnSlot{ Tip: *uint256.NewInt(300000), FeeCap: *uint256.NewInt(300000), Gas: 100_000, Nonce: 3, } - txSlot1.IDHash[0] = 1 - txSlots.Append(txSlot1, addr[:], true) + txnSlot1.IDHash[0] = 1 + txnSlots.Append(txnSlot1, addr[:], true) - reasons, err := pool.AddLocalTxns(ctx, txSlots) + reasons, err := pool.AddLocalTxns(ctx, txnSlots) assert.NoError(err) for _, reason := range reasons { assert.Equal(txpoolcfg.Success, reason, reason.String()) } - mtx, ok := pool.byHash[string(txSlot1.IDHash[:])] + mtx, ok := pool.byHash[string(txnSlot1.IDHash[:])] assert.True(ok) assert.Zero(mtx.subPool&NotTooMuchGas, "Should be insufficient block space for the tx") diff --git a/txnprovider/txpool/txn_packets.go b/txnprovider/txpool/pool_txn_packets.go similarity index 76% rename from txnprovider/txpool/txn_packets.go rename to txnprovider/txpool/pool_txn_packets.go index a27ff439a80..25cf5a28c4a 100644 --- a/txnprovider/txpool/txn_packets.go +++ b/txnprovider/txpool/pool_txn_packets.go @@ -109,32 +109,32 @@ func ParseGetPooledTransactions66(payload []byte, pos int, hashbuf []byte) (requ // == Pooled transactions == // TODO(eip-4844) wrappedWithBlobs = true? -func EncodePooledTransactions66(txsRlp [][]byte, requestID uint64, encodeBuf []byte) []byte { +func EncodePooledTransactions66(txnsRlp [][]byte, requestID uint64, encodeBuf []byte) []byte { pos := 0 - txsRlpLen := 0 - for i := range txsRlp { - _, _, isLegacy, _ := rlp.Prefix(txsRlp[i], 0) + txnsRlpLen := 0 + for i := range txnsRlp { + _, _, isLegacy, _ := rlp.Prefix(txnsRlp[i], 0) if isLegacy { - txsRlpLen += len(txsRlp[i]) + txnsRlpLen += len(txnsRlp[i]) } else { - txsRlpLen += rlp.StringLen(txsRlp[i]) + txnsRlpLen += rlp.StringLen(txnsRlp[i]) } } - dataLen := rlp.U64Len(requestID) + rlp.ListPrefixLen(txsRlpLen) + txsRlpLen + dataLen := rlp.U64Len(requestID) + rlp.ListPrefixLen(txnsRlpLen) + txnsRlpLen encodeBuf = common.EnsureEnoughSize(encodeBuf, rlp.ListPrefixLen(dataLen)+dataLen) // Length Prefix for the entire structure pos += rlp.EncodeListPrefix(dataLen, encodeBuf[pos:]) pos += rlp.EncodeU64(requestID, encodeBuf[pos:]) - pos += rlp.EncodeListPrefix(txsRlpLen, encodeBuf[pos:]) - for i := range txsRlp { - _, _, isLegacy, _ := rlp.Prefix(txsRlp[i], 0) + pos += rlp.EncodeListPrefix(txnsRlpLen, encodeBuf[pos:]) + for i := range txnsRlp { + _, _, isLegacy, _ := rlp.Prefix(txnsRlp[i], 0) if isLegacy { - copy(encodeBuf[pos:], txsRlp[i]) - pos += len(txsRlp[i]) + copy(encodeBuf[pos:], txnsRlp[i]) + pos += len(txnsRlp[i]) } else { - pos += rlp.EncodeString(txsRlp[i], encodeBuf[pos:]) + pos += rlp.EncodeString(txnsRlp[i], encodeBuf[pos:]) } } _ = pos @@ -142,47 +142,47 @@ func EncodePooledTransactions66(txsRlp [][]byte, requestID uint64, encodeBuf []b } // TODO(eip-4844) wrappedWithBlobs = false? -func EncodeTransactions(txsRlp [][]byte, encodeBuf []byte) []byte { +func EncodeTransactions(txnsRlp [][]byte, encodeBuf []byte) []byte { pos := 0 dataLen := 0 - for i := range txsRlp { - _, _, isLegacy, _ := rlp.Prefix(txsRlp[i], 0) + for i := range txnsRlp { + _, _, isLegacy, _ := rlp.Prefix(txnsRlp[i], 0) if isLegacy { - dataLen += len(txsRlp[i]) + dataLen += len(txnsRlp[i]) } else { - dataLen += rlp.StringLen(txsRlp[i]) + dataLen += rlp.StringLen(txnsRlp[i]) } } encodeBuf = common.EnsureEnoughSize(encodeBuf, rlp.ListPrefixLen(dataLen)+dataLen) // Length Prefix for the entire structure pos += rlp.EncodeListPrefix(dataLen, encodeBuf[pos:]) - for i := range txsRlp { - _, _, isLegacy, _ := rlp.Prefix(txsRlp[i], 0) + for i := range txnsRlp { + _, _, isLegacy, _ := rlp.Prefix(txnsRlp[i], 0) if isLegacy { - copy(encodeBuf[pos:], txsRlp[i]) - pos += len(txsRlp[i]) + copy(encodeBuf[pos:], txnsRlp[i]) + pos += len(txnsRlp[i]) } else { - pos += rlp.EncodeString(txsRlp[i], encodeBuf[pos:]) + pos += rlp.EncodeString(txnsRlp[i], encodeBuf[pos:]) } } _ = pos return encodeBuf } -func ParseTransactions(payload []byte, pos int, ctx *TxnParseContext, txSlots *TxnSlots, validateHash func([]byte) error) (newPos int, err error) { +func ParseTransactions(payload []byte, pos int, ctx *TxnParseContext, txnSlots *TxnSlots, validateHash func([]byte) error) (newPos int, err error) { pos, _, err = rlp.List(payload, pos) if err != nil { return 0, err } for i := 0; pos < len(payload); i++ { - txSlots.Resize(uint(i + 1)) - txSlots.Txs[i] = &TxnSlot{} - pos, err = ctx.ParseTransaction(payload, pos, txSlots.Txs[i], txSlots.Senders.At(i), true /* hasEnvelope */, true /* wrappedWithBlobs */, validateHash) + txnSlots.Resize(uint(i + 1)) + txnSlots.Txns[i] = &TxnSlot{} + pos, err = ctx.ParseTransaction(payload, pos, txnSlots.Txns[i], txnSlots.Senders.At(i), true /* hasEnvelope */, true /* wrappedWithBlobs */, validateHash) if err != nil { if errors.Is(err, ErrRejected) { - txSlots.Resize(uint(i)) + txnSlots.Resize(uint(i)) i-- continue } @@ -192,7 +192,7 @@ func ParseTransactions(payload []byte, pos int, ctx *TxnParseContext, txSlots *T return pos, nil } -func ParsePooledTransactions66(payload []byte, pos int, ctx *TxnParseContext, txSlots *TxnSlots, validateHash func([]byte) error) (requestID uint64, newPos int, err error) { +func ParsePooledTransactions66(payload []byte, pos int, ctx *TxnParseContext, txnSlots *TxnSlots, validateHash func([]byte) error) (requestID uint64, newPos int, err error) { p, _, err := rlp.List(payload, pos) if err != nil { return requestID, 0, err @@ -207,12 +207,12 @@ func ParsePooledTransactions66(payload []byte, pos int, ctx *TxnParseContext, tx } for i := 0; p < len(payload); i++ { - txSlots.Resize(uint(i + 1)) - txSlots.Txs[i] = &TxnSlot{} - p, err = ctx.ParseTransaction(payload, p, txSlots.Txs[i], txSlots.Senders.At(i), true /* hasEnvelope */, true /* wrappedWithBlobs */, validateHash) + txnSlots.Resize(uint(i + 1)) + txnSlots.Txns[i] = &TxnSlot{} + p, err = ctx.ParseTransaction(payload, p, txnSlots.Txns[i], txnSlots.Senders.At(i), true /* hasEnvelope */, true /* wrappedWithBlobs */, validateHash) if err != nil { if errors.Is(err, ErrRejected) { - txSlots.Resize(uint(i)) + txnSlots.Resize(uint(i)) i-- continue } diff --git a/txnprovider/txpool/txn_packets_fuzz_test.go b/txnprovider/txpool/pool_txn_packets_fuzz_test.go similarity index 93% rename from txnprovider/txpool/txn_packets_fuzz_test.go rename to txnprovider/txpool/pool_txn_packets_fuzz_test.go index 3e09be00c50..aa8cdbeff1c 100644 --- a/txnprovider/txpool/txn_packets_fuzz_test.go +++ b/txnprovider/txpool/pool_txn_packets_fuzz_test.go @@ -39,11 +39,11 @@ func FuzzPooledTransactions66(f *testing.F) { t.Skip() } - var rlpTxs [][]byte - for i := range slots.Txs { - rlpTxs = append(rlpTxs, slots.Txs[i].Rlp) + var rlpTxns [][]byte + for i := range slots.Txns { + rlpTxns = append(rlpTxns, slots.Txns[i].Rlp) } - _ = EncodePooledTransactions66(rlpTxs, reqId, nil) + _ = EncodePooledTransactions66(rlpTxns, reqId, nil) if err != nil { t.Skip() } diff --git a/txnprovider/txpool/txn_packets_test.go b/txnprovider/txpool/pool_txn_packets_test.go similarity index 93% rename from txnprovider/txpool/txn_packets_test.go rename to txnprovider/txpool/pool_txn_packets_test.go index 07489a381d8..0c25b8c811a 100644 --- a/txnprovider/txpool/txn_packets_test.go +++ b/txnprovider/txpool/pool_txn_packets_test.go @@ -105,20 +105,20 @@ func TestEncodeGPT66(t *testing.T) { } var ptp66EncodeTests = []struct { - txs [][]byte + txns [][]byte encoded string requestID uint64 chainID uint64 expectedErr bool }{ { - txs: [][]byte{ + txns: [][]byte{ hexutility.MustDecodeHex("02f870051b8477359400847735940a82520894c388750a661cc0b99784bab2c55e1f38ff91643b861319718a500080c080a028bf802cf4be66f51ab0570fa9fc06365c1b816b8a7ffe40bc05f9a0d2d12867a012c2ce1fc908e7a903b750388c8c2ae82383a476bc345b7c2826738fc321fcab"), }, encoded: "f88088a4e61e8ad32f4845f875b87302f870051b8477359400847735940a82520894c388750a661cc0b99784bab2c55e1f38ff91643b861319718a500080c080a028bf802cf4be66f51ab0570fa9fc06365c1b816b8a7ffe40bc05f9a0d2d12867a012c2ce1fc908e7a903b750388c8c2ae82383a476bc345b7c2826738fc321fcab", requestID: 11882218248461043781, expectedErr: false, chainID: 5, }, { - txs: [][]byte{ + txns: [][]byte{ hexutility.MustDecodeHex("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10"), hexutility.MustDecodeHex("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb"), }, @@ -140,7 +140,7 @@ func TestPooledTransactionsPacket66(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { require := require.New(t) var encodeBuf []byte - encodeBuf = EncodePooledTransactions66(tt.txs, tt.requestID, encodeBuf) + encodeBuf = EncodePooledTransactions66(tt.txns, tt.requestID, encodeBuf) require.Equal(tt.encoded, fmt.Sprintf("%x", encodeBuf)) ctx := NewTxnParseContext(*uint256.NewInt(tt.chainID)) @@ -148,9 +148,9 @@ func TestPooledTransactionsPacket66(t *testing.T) { requestID, _, err := ParsePooledTransactions66(encodeBuf, 0, ctx, slots, nil) require.NoError(err) require.Equal(tt.requestID, requestID) - require.Equal(len(tt.txs), len(slots.Txs)) - for i, txn := range tt.txs { - require.Equal(fmt.Sprintf("%x", txn), fmt.Sprintf("%x", slots.Txs[i].Rlp)) + require.Equal(len(tt.txns), len(slots.Txns)) + for i, txn := range tt.txns { + require.Equal(fmt.Sprintf("%x", txn), fmt.Sprintf("%x", slots.Txns[i].Rlp)) } }) } @@ -158,7 +158,7 @@ func TestPooledTransactionsPacket66(t *testing.T) { t.Run("reject_all_"+strconv.Itoa(i), func(t *testing.T) { require := require.New(t) var encodeBuf []byte - encodeBuf = EncodePooledTransactions66(tt.txs, tt.requestID, encodeBuf) + encodeBuf = EncodePooledTransactions66(tt.txns, tt.requestID, encodeBuf) require.Equal(tt.encoded, fmt.Sprintf("%x", encodeBuf)) chainID := uint256.NewInt(tt.chainID) @@ -167,7 +167,7 @@ func TestPooledTransactionsPacket66(t *testing.T) { requestID, _, err := ParsePooledTransactions66(encodeBuf, 0, ctx, slots, func(bytes []byte) error { return ErrRejected }) require.NoError(err) require.Equal(tt.requestID, requestID) - require.Equal(0, len(slots.Txs)) + require.Equal(0, len(slots.Txns)) require.Equal(0, slots.Senders.Len()) require.Equal(0, len(slots.IsLocal)) }) @@ -175,19 +175,19 @@ func TestPooledTransactionsPacket66(t *testing.T) { } var tpEncodeTests = []struct { - txs [][]byte + txns [][]byte encoded string chainID uint64 expectedErr bool }{ { - txs: [][]byte{ + txns: [][]byte{ hexutility.MustDecodeHex("02f870051b8477359400847735940a82520894c388750a661cc0b99784bab2c55e1f38ff91643b861319718a500080c080a028bf802cf4be66f51ab0570fa9fc06365c1b816b8a7ffe40bc05f9a0d2d12867a012c2ce1fc908e7a903b750388c8c2ae82383a476bc345b7c2826738fc321fcab"), }, encoded: "f875b87302f870051b8477359400847735940a82520894c388750a661cc0b99784bab2c55e1f38ff91643b861319718a500080c080a028bf802cf4be66f51ab0570fa9fc06365c1b816b8a7ffe40bc05f9a0d2d12867a012c2ce1fc908e7a903b750388c8c2ae82383a476bc345b7c2826738fc321fcab", expectedErr: false, chainID: 5, }, { - txs: [][]byte{ + txns: [][]byte{ hexutility.MustDecodeHex("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10"), hexutility.MustDecodeHex("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb"), }, @@ -200,16 +200,16 @@ func TestTransactionsPacket(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { require := require.New(t) var encodeBuf []byte - encodeBuf = EncodeTransactions(tt.txs, encodeBuf) + encodeBuf = EncodeTransactions(tt.txns, encodeBuf) require.Equal(tt.encoded, fmt.Sprintf("%x", encodeBuf)) ctx := NewTxnParseContext(*uint256.NewInt(tt.chainID)) slots := &TxnSlots{} _, err := ParseTransactions(encodeBuf, 0, ctx, slots, nil) require.NoError(err) - require.Equal(len(tt.txs), len(slots.Txs)) - for i, txn := range tt.txs { - require.Equal(fmt.Sprintf("%x", txn), fmt.Sprintf("%x", slots.Txs[i].Rlp)) + require.Equal(len(tt.txns), len(slots.Txns)) + for i, txn := range tt.txns { + require.Equal(fmt.Sprintf("%x", txn), fmt.Sprintf("%x", slots.Txns[i].Rlp)) } }) } @@ -217,7 +217,7 @@ func TestTransactionsPacket(t *testing.T) { t.Run("reject_all_"+strconv.Itoa(i), func(t *testing.T) { require := require.New(t) var encodeBuf []byte - encodeBuf = EncodeTransactions(tt.txs, encodeBuf) + encodeBuf = EncodeTransactions(tt.txns, encodeBuf) require.Equal(tt.encoded, fmt.Sprintf("%x", encodeBuf)) chainID := uint256.NewInt(tt.chainID) @@ -225,7 +225,7 @@ func TestTransactionsPacket(t *testing.T) { slots := &TxnSlots{} _, err := ParseTransactions(encodeBuf, 0, ctx, slots, func(bytes []byte) error { return ErrRejected }) require.NoError(err) - require.Equal(0, len(slots.Txs)) + require.Equal(0, len(slots.Txns)) require.Equal(0, slots.Senders.Len()) require.Equal(0, len(slots.IsLocal)) }) diff --git a/txnprovider/txpool/txn.go b/txnprovider/txpool/pool_txn_parser.go similarity index 95% rename from txnprovider/txpool/txn.go rename to txnprovider/txpool/pool_txn_parser.go index 9cfe3915573..645658a6312 100644 --- a/txnprovider/txpool/txn.go +++ b/txnprovider/txpool/pool_txn_parser.go @@ -38,11 +38,11 @@ import ( ) const ( - LegacyTxType byte = 0 - AccessListTxType byte = 1 // EIP-2930 - DynamicFeeTxType byte = 2 // EIP-1559 - BlobTxType byte = 3 // EIP-4844 - SetCodeTxType byte = 4 // EIP-7702 + LegacyTxnType byte = 0 + AccessListTxnType byte = 1 // EIP-2930 + DynamicFeeTxnType byte = 2 // EIP-1559 + BlobTxnType byte = 3 // EIP-4844 + SetCodeTxnType byte = 4 // EIP-7702 ) var ErrParseTxn = fmt.Errorf("%w transaction", rlp.ErrParse) @@ -110,10 +110,10 @@ func (ctx *TxnParseContext) ChainIDRequired() *TxnParseContext { func PeekTransactionType(serialized []byte) (byte, error) { dataPos, _, legacy, err := rlp.Prefix(serialized, 0) if err != nil { - return LegacyTxType, fmt.Errorf("%w: size Prefix: %s", ErrParseTxn, err) //nolint + return LegacyTxnType, fmt.Errorf("%w: size Prefix: %s", ErrParseTxn, err) //nolint } if legacy { - return LegacyTxType, nil + return LegacyTxnType, nil } return serialized[dataPos], nil } @@ -153,12 +153,12 @@ func (ctx *TxnParseContext) ParseTransaction(payload []byte, pos int, slot *TxnS // If it is non-legacy transaction, the transaction type follows, and then the list if !legacy { slot.Type = payload[p] - if slot.Type > SetCodeTxType { + if slot.Type > SetCodeTxnType { return 0, fmt.Errorf("%w: unknown transaction type: %d", ErrParseTxn, slot.Type) } p++ if p >= len(payload) { - return 0, fmt.Errorf("%w: unexpected end of payload after txType", ErrParseTxn) + return 0, fmt.Errorf("%w: unexpected end of payload after txnType", ErrParseTxn) } dataPos, dataLen, err = rlp.List(payload, p) if err != nil { @@ -168,7 +168,7 @@ func (ctx *TxnParseContext) ParseTransaction(payload []byte, pos int, slot *TxnS // whereas for non-legacy, only the content of the envelope (start with position p) slot.Rlp = payload[p-1 : dataPos+dataLen] - if slot.Type == BlobTxType && wrappedWithBlobs { + if slot.Type == BlobTxnType && wrappedWithBlobs { p = dataPos wrapperDataPos = dataPos wrapperDataLen = dataLen @@ -178,7 +178,7 @@ func (ctx *TxnParseContext) ParseTransaction(payload []byte, pos int, slot *TxnS } } } else { - slot.Type = LegacyTxType + slot.Type = LegacyTxnType slot.Rlp = payload[pos : dataPos+dataLen] } @@ -187,7 +187,7 @@ func (ctx *TxnParseContext) ParseTransaction(payload []byte, pos int, slot *TxnS return p, err } - if slot.Type == BlobTxType && wrappedWithBlobs { + if slot.Type == BlobTxnType && wrappedWithBlobs { if p != dataPos+dataLen { return 0, fmt.Errorf("%w: unexpected leftover after blob txn body", ErrParseTxn) } @@ -310,7 +310,7 @@ func parseSignature(payload []byte, pos int, legacy bool, cfgChainId *uint256.In func (ctx *TxnParseContext) parseTransactionBody(payload []byte, pos, p0 int, slot *TxnSlot, sender []byte, validateHash func([]byte) error) (p int, err error) { p = p0 - legacy := slot.Type == LegacyTxType + legacy := slot.Type == LegacyTxnType // Compute transaction hash ctx.Keccak1.Reset() @@ -369,7 +369,7 @@ func (ctx *TxnParseContext) parseTransactionBody(payload []byte, pos, p0 int, sl } // Next follows feeCap, but only for dynamic fee transactions, for legacy transaction, it is // equal to tip - if slot.Type < DynamicFeeTxType { + if slot.Type < DynamicFeeTxnType { slot.FeeCap = slot.Tip } else { p, err = rlp.U256(payload, p, &slot.FeeCap) @@ -462,7 +462,7 @@ func (ctx *TxnParseContext) parseTransactionBody(payload []byte, pos, p0 int, sl } p = dataPos + dataLen } - if slot.Type == SetCodeTxType { + if slot.Type == SetCodeTxnType { dataPos, dataLen, err = rlp.List(payload, p) if err != nil { return 0, fmt.Errorf("%w: authorizations len: %s", ErrParseTxn, err) //nolint @@ -508,7 +508,7 @@ func (ctx *TxnParseContext) parseTransactionBody(payload []byte, pos, p0 int, sl } p = dataPos + dataLen } - if slot.Type == BlobTxType { + if slot.Type == BlobTxnType { p, err = rlp.U256(payload, p, &slot.BlobFeeCap) if err != nil { return 0, fmt.Errorf("%w: blob fee cap: %s", ErrParseTxn, err) //nolint @@ -694,17 +694,17 @@ func (tx *TxnSlot) PrintDebug(prefix string) { } type TxnSlots struct { - Txs []*TxnSlot + Txns []*TxnSlot Senders Addresses IsLocal []bool } func (s *TxnSlots) Valid() error { - if len(s.Txs) != len(s.IsLocal) { - return fmt.Errorf("TxnSlots: expect equal len of isLocal=%d and txs=%d", len(s.IsLocal), len(s.Txs)) + if len(s.Txns) != len(s.IsLocal) { + return fmt.Errorf("TxnSlots: expect equal len of isLocal=%d and txns=%d", len(s.IsLocal), len(s.Txns)) } - if len(s.Txs) != s.Senders.Len() { - return fmt.Errorf("TxnSlots: expect equal len of senders=%d and txs=%d", s.Senders.Len(), len(s.Txs)) + if len(s.Txns) != s.Senders.Len() { + return fmt.Errorf("TxnSlots: expect equal len of senders=%d and txns=%d", s.Senders.Len(), len(s.Txns)) } return nil } @@ -713,8 +713,8 @@ var zeroAddr = make([]byte, 20) // Resize internal arrays to len=targetSize, shrinks if need. It rely on `append` algorithm to realloc func (s *TxnSlots) Resize(targetSize uint) { - for uint(len(s.Txs)) < targetSize { - s.Txs = append(s.Txs, nil) + for uint(len(s.Txns)) < targetSize { + s.Txns = append(s.Txns, nil) } for uint(s.Senders.Len()) < targetSize { s.Senders = append(s.Senders, addressesGrowth...) @@ -722,11 +722,11 @@ func (s *TxnSlots) Resize(targetSize uint) { for uint(len(s.IsLocal)) < targetSize { s.IsLocal = append(s.IsLocal, false) } - //todo: set nil to overflow txs - oldLen := uint(len(s.Txs)) - s.Txs = s.Txs[:targetSize] + //todo: set nil to overflow txns + oldLen := uint(len(s.Txns)) + s.Txns = s.Txns[:targetSize] for i := oldLen; i < targetSize; i++ { - s.Txs[i] = nil + s.Txns[i] = nil } s.Senders = s.Senders[:length.Addr*targetSize] for i := oldLen; i < targetSize; i++ { @@ -739,9 +739,9 @@ func (s *TxnSlots) Resize(targetSize uint) { } func (s *TxnSlots) Append(slot *TxnSlot, sender []byte, isLocal bool) { - n := len(s.Txs) - s.Resize(uint(len(s.Txs) + 1)) - s.Txs[n] = slot + n := len(s.Txns) + s.Resize(uint(len(s.Txns) + 1)) + s.Txns[n] = slot s.IsLocal[n] = isLocal copy(s.Senders.At(n), sender) } @@ -779,7 +779,7 @@ func (r *TxnsRlp) Resize(targetSize uint) { for uint(len(r.IsLocal)) < targetSize { r.IsLocal = append(r.IsLocal, false) } - //todo: set nil to overflow txs + //todo: set nil to overflow txns r.Txns = r.Txns[:targetSize] r.Senders = r.Senders[:length.Addr*targetSize] r.IsLocal = r.IsLocal[:targetSize] diff --git a/txnprovider/txpool/txn_test.go b/txnprovider/txpool/pool_txn_parser_test.go similarity index 81% rename from txnprovider/txpool/txn_test.go rename to txnprovider/txpool/pool_txn_parser_test.go index f45e1bf8a14..aeca9ab91d3 100644 --- a/txnprovider/txpool/txn_test.go +++ b/txnprovider/txpool/pool_txn_parser_test.go @@ -37,12 +37,12 @@ func TestParseTransactionRLP(t *testing.T) { t.Run(strconv.Itoa(int(testSet.chainID.Uint64())), func(t *testing.T) { require := require.New(t) ctx := NewTxnParseContext(testSet.chainID) - tx, txSender := &TxnSlot{}, [20]byte{} + txn, txnSender := &TxnSlot{}, [20]byte{} for i, tt := range testSet.tests { tt := tt t.Run(strconv.Itoa(i), func(t *testing.T) { payload := hexutility.MustDecodeHex(tt.PayloadStr) - parseEnd, err := ctx.ParseTransaction(payload, 0, tx, txSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) + parseEnd, err := ctx.ParseTransaction(payload, 0, txn, txnSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) require.NoError(err) require.Equal(len(payload), parseEnd) if tt.SignHashStr != "" { @@ -53,17 +53,17 @@ func TestParseTransactionRLP(t *testing.T) { } if tt.IdHashStr != "" { idHash := hexutility.MustDecodeHex(tt.IdHashStr) - if !bytes.Equal(idHash, tx.IDHash[:]) { - t.Errorf("IdHash expected %x, got %x", idHash, tx.IDHash) + if !bytes.Equal(idHash, txn.IDHash[:]) { + t.Errorf("IdHash expected %x, got %x", idHash, txn.IDHash) } } if tt.SenderStr != "" { expectSender := hexutility.MustDecodeHex(tt.SenderStr) - if !bytes.Equal(expectSender, txSender[:]) { - t.Errorf("expectSender expected %x, got %x", expectSender, txSender) + if !bytes.Equal(expectSender, txnSender[:]) { + t.Errorf("expectSender expected %x, got %x", expectSender, txnSender) } } - require.Equal(tt.Nonce, tx.Nonce) + require.Equal(tt.Nonce, txn.Nonce) }) } }) @@ -75,21 +75,21 @@ func TestTransactionSignatureValidity1(t *testing.T) { ctx := NewTxnParseContext(*chainId) ctx.WithAllowPreEip2s(true) - tx, txSender := &TxnSlot{}, [20]byte{} + txn, txnSender := &TxnSlot{}, [20]byte{} validTxn := hexutility.MustDecodeHex("f83f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870b801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a3664935301") - _, err := ctx.ParseTransaction(validTxn, 0, tx, txSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) + _, err := ctx.ParseTransaction(validTxn, 0, txn, txnSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) assert.NoError(t, err) preEip2Txn := hexutility.MustDecodeHex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870b801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a07fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1") - _, err = ctx.ParseTransaction(preEip2Txn, 0, tx, txSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) + _, err = ctx.ParseTransaction(preEip2Txn, 0, txn, txnSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) assert.NoError(t, err) // Now enforce EIP-2 ctx.WithAllowPreEip2s(false) - _, err = ctx.ParseTransaction(validTxn, 0, tx, txSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) + _, err = ctx.ParseTransaction(validTxn, 0, txn, txnSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) assert.NoError(t, err) - _, err = ctx.ParseTransaction(preEip2Txn, 0, tx, txSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) + _, err = ctx.ParseTransaction(preEip2Txn, 0, txn, txnSender[:], false /* hasEnvelope */, true /* wrappedWithBlobs */, nil) assert.Error(t, err) } @@ -108,26 +108,26 @@ func TestTransactionSignatureValidity2(t *testing.T) { assert.Error(t, err) } -func TestTxSlotsGrowth(t *testing.T) { +func TestTxnSlotsGrowth(t *testing.T) { assert := assert.New(t) s := &TxnSlots{} s.Resize(11) - assert.Equal(11, len(s.Txs)) + assert.Equal(11, len(s.Txns)) assert.Equal(11, s.Senders.Len()) s.Resize(23) - assert.Equal(23, len(s.Txs)) + assert.Equal(23, len(s.Txns)) assert.Equal(23, s.Senders.Len()) - s = &TxnSlots{Txs: make([]*TxnSlot, 20), Senders: make(Addresses, 20*20)} + s = &TxnSlots{Txns: make([]*TxnSlot, 20), Senders: make(Addresses, 20*20)} s.Resize(20) - assert.Equal(20, len(s.Txs)) + assert.Equal(20, len(s.Txns)) assert.Equal(20, s.Senders.Len()) s.Resize(23) - assert.Equal(23, len(s.Txs)) + assert.Equal(23, len(s.Txns)) assert.Equal(23, s.Senders.Len()) s.Resize(2) - assert.Equal(2, len(s.Txs)) + assert.Equal(2, len(s.Txns)) assert.Equal(2, s.Senders.Len()) } @@ -179,7 +179,7 @@ func toHashes(h ...byte) (out Hashes) { return out } -func TestBlobTxParsing(t *testing.T) { +func TestBlobTxnParsing(t *testing.T) { // First parse a blob transaction body (no blobs/commitments/proofs) wrappedWithBlobs := false // Some arbitrary hardcoded example @@ -197,27 +197,27 @@ func TestBlobTxParsing(t *testing.T) { bodyEnvelopePrefix := hexutility.MustDecodeHex("b9012b") var bodyEnvelope []byte bodyEnvelope = append(bodyEnvelope, bodyEnvelopePrefix...) - bodyEnvelope = append(bodyEnvelope, BlobTxType) + bodyEnvelope = append(bodyEnvelope, BlobTxnType) bodyEnvelope = append(bodyEnvelope, bodyRlp...) ctx := NewTxnParseContext(*uint256.NewInt(5)) ctx.withSender = false - var thinTx TxnSlot // only txn body, no blobs - txType, err := PeekTransactionType(bodyEnvelope) + var thinTxn TxnSlot // only txn body, no blobs + txnType, err := PeekTransactionType(bodyEnvelope) require.NoError(t, err) - assert.Equal(t, BlobTxType, txType) + assert.Equal(t, BlobTxnType, txnType) - p, err := ctx.ParseTransaction(bodyEnvelope, 0, &thinTx, nil, hasEnvelope, wrappedWithBlobs, nil) + p, err := ctx.ParseTransaction(bodyEnvelope, 0, &thinTxn, nil, hasEnvelope, wrappedWithBlobs, nil) require.NoError(t, err) assert.Equal(t, len(bodyEnvelope), p) - assert.Equal(t, len(bodyEnvelope)-len(bodyEnvelopePrefix), int(thinTx.Size)) - assert.Equal(t, bodyEnvelope[3:], thinTx.Rlp) - assert.Equal(t, BlobTxType, thinTx.Type) - assert.Equal(t, 2, len(thinTx.BlobHashes)) - assert.Equal(t, 0, len(thinTx.Blobs)) - assert.Equal(t, 0, len(thinTx.Commitments)) - assert.Equal(t, 0, len(thinTx.Proofs)) + assert.Equal(t, len(bodyEnvelope)-len(bodyEnvelopePrefix), int(thinTxn.Size)) + assert.Equal(t, bodyEnvelope[3:], thinTxn.Rlp) + assert.Equal(t, BlobTxnType, thinTxn.Type) + assert.Equal(t, 2, len(thinTxn.BlobHashes)) + assert.Equal(t, 0, len(thinTxn.Blobs)) + assert.Equal(t, 0, len(thinTxn.Commitments)) + assert.Equal(t, 0, len(thinTxn.Proofs)) // Now parse the same txn body, but wrapped with blobs/commitments/proofs wrappedWithBlobs = true @@ -256,44 +256,44 @@ func TestBlobTxParsing(t *testing.T) { wrapperRlp = append(wrapperRlp, 0xb0) wrapperRlp = append(wrapperRlp, proof1[:]...) - var fatTx TxnSlot // with blobs/commitments/proofs - txType, err = PeekTransactionType(wrapperRlp) + var fatTxn TxnSlot // with blobs/commitments/proofs + txnType, err = PeekTransactionType(wrapperRlp) require.NoError(t, err) - assert.Equal(t, BlobTxType, txType) + assert.Equal(t, BlobTxnType, txnType) - p, err = ctx.ParseTransaction(wrapperRlp, 0, &fatTx, nil, hasEnvelope, wrappedWithBlobs, nil) + p, err = ctx.ParseTransaction(wrapperRlp, 0, &fatTxn, nil, hasEnvelope, wrappedWithBlobs, nil) require.NoError(t, err) assert.Equal(t, len(wrapperRlp), p) - assert.Equal(t, len(wrapperRlp), int(fatTx.Size)) - assert.Equal(t, wrapperRlp, fatTx.Rlp) - assert.Equal(t, BlobTxType, fatTx.Type) - - assert.Equal(t, thinTx.Value, fatTx.Value) - assert.Equal(t, thinTx.Tip, fatTx.Tip) - assert.Equal(t, thinTx.FeeCap, fatTx.FeeCap) - assert.Equal(t, thinTx.Nonce, fatTx.Nonce) - assert.Equal(t, thinTx.DataLen, fatTx.DataLen) - assert.Equal(t, thinTx.DataNonZeroLen, fatTx.DataNonZeroLen) - assert.Equal(t, thinTx.AlAddrCount, fatTx.AlAddrCount) - assert.Equal(t, thinTx.AlStorCount, fatTx.AlStorCount) - assert.Equal(t, thinTx.Gas, fatTx.Gas) - assert.Equal(t, thinTx.IDHash, fatTx.IDHash) - assert.Equal(t, thinTx.Creation, fatTx.Creation) - assert.Equal(t, thinTx.BlobFeeCap, fatTx.BlobFeeCap) - assert.Equal(t, thinTx.BlobHashes, fatTx.BlobHashes) - - require.Equal(t, 2, len(fatTx.Blobs)) - require.Equal(t, 2, len(fatTx.Commitments)) - require.Equal(t, 2, len(fatTx.Proofs)) - assert.Equal(t, blob0, fatTx.Blobs[0]) - assert.Equal(t, blob1, fatTx.Blobs[1]) - assert.Equal(t, commitment0, fatTx.Commitments[0]) - assert.Equal(t, commitment1, fatTx.Commitments[1]) - assert.Equal(t, proof0, fatTx.Proofs[0]) - assert.Equal(t, proof1, fatTx.Proofs[1]) + assert.Equal(t, len(wrapperRlp), int(fatTxn.Size)) + assert.Equal(t, wrapperRlp, fatTxn.Rlp) + assert.Equal(t, BlobTxnType, fatTxn.Type) + + assert.Equal(t, thinTxn.Value, fatTxn.Value) + assert.Equal(t, thinTxn.Tip, fatTxn.Tip) + assert.Equal(t, thinTxn.FeeCap, fatTxn.FeeCap) + assert.Equal(t, thinTxn.Nonce, fatTxn.Nonce) + assert.Equal(t, thinTxn.DataLen, fatTxn.DataLen) + assert.Equal(t, thinTxn.DataNonZeroLen, fatTxn.DataNonZeroLen) + assert.Equal(t, thinTxn.AlAddrCount, fatTxn.AlAddrCount) + assert.Equal(t, thinTxn.AlStorCount, fatTxn.AlStorCount) + assert.Equal(t, thinTxn.Gas, fatTxn.Gas) + assert.Equal(t, thinTxn.IDHash, fatTxn.IDHash) + assert.Equal(t, thinTxn.Creation, fatTxn.Creation) + assert.Equal(t, thinTxn.BlobFeeCap, fatTxn.BlobFeeCap) + assert.Equal(t, thinTxn.BlobHashes, fatTxn.BlobHashes) + + require.Equal(t, 2, len(fatTxn.Blobs)) + require.Equal(t, 2, len(fatTxn.Commitments)) + require.Equal(t, 2, len(fatTxn.Proofs)) + assert.Equal(t, blob0, fatTxn.Blobs[0]) + assert.Equal(t, blob1, fatTxn.Blobs[1]) + assert.Equal(t, commitment0, fatTxn.Commitments[0]) + assert.Equal(t, commitment1, fatTxn.Commitments[1]) + assert.Equal(t, proof0, fatTxn.Proofs[0]) + assert.Equal(t, proof1, fatTxn.Proofs[1]) } -func TestSetCodeTxParsing(t *testing.T) { +func TestSetCodeTxnParsing(t *testing.T) { bodyRlxHex := "0x04f9041701880124ec419e9796da8868b499f209983df888bb35ca86e3d9ea47882486c24309101b0e94e4ec12c49d6bcf7cc1325aa50afff92a561229fe880c716dca0e3e3d28b902b6779e563691f1ca8a86a02efdd93db261215047dad430a475d0e191f66b580d6e759a7c7a739532455e65160acf92dc1e1cc11970e7851277278e9d5d2549e451de8c8dd98ebdd3c55e73cd0b465875b72ea6d54917474f7ddfbd1f66d1a929694becc69bc3064c79c32b2db2a094844b400133724e046d9a96f2b6c7888fe008e6a667a970068487ce9a8e6c1260973956b26c1b78235f3452e21c5ed6d47507023ec4072b9ebea8ea9bde77ea64352ef7a6a8efb2ca61fbd0cf7c31491a4c38e3081dfc7b5e8066fca60d8f57b641032f23119a67a37ad0514529df22ba73b4028dc4a6aef0b26161371d731a81d8ac20ea90515b924f2534e32c240d0b75b5d1683e1bc7ecf8b82b73fb4c40d7cfc38e8c32f2c4d3424a86ba8c6e867f13328be201dd8d5e8ee47e03c1d9096968b71228b068cc21514f6bab7867a0d0a2651f40e927079b008c3ef11d571eb5f71d729ee9cfb3d2a99d258c10371fa1df271f4588e031498b155244295490fd842b3055e240ea89843a188b7f15be53252367761b9a8d21818d2c756822c0383246e167dd645722aefe4ecc5e78608bcc851dc5a51255a3f91e908bb5fa53063596458f45c6e25a712de4b2a5b36eea57f5b772c84f1d0f2f2ae103445fb7f2d38493041ca452f1e846c34331bea7b5b350d02306fa3a15b50e978b4efebccce8a3479479d51c95a08e0cab0732fc4f8095337d7502c6a962199342ed127701a6f5b0e54cbdd88f23556aab406a3a7ef49f848c3efbf4cf62052999bde1940abf4944158aefc5472f4ec9e23308cfb63deedc79e9a4f39d8b353c7e6f15d36f4c63987ae6f32701c6579e68f05f9ae86b6fbbc8d57bc17e5c2f3e5389ea75d102017767205c10d6bf5cf6e33a94ad9e6cfac5accf56d61dcee39f2e954ea89b7241e480e6021fa099a81bc9d28d6ca58a11d36f406b212be70c721bd8a4d1d643fa2bf30ebd59a4f838f794fbba2afaae8cabd778b6e151b0431e3fef0a033ce1a07081820b2a08cc2ed4355811644547f23597f7ebe516538baac51d97cbccee97f8ccf201941d994a07f0b3e925d332d4eae10c9ba474da3d8a8806320d2ae09c60e880887dbf8422d2f6549088321947f20ebcbfeff20194327d773bdc6c27cd28a533e81074372dc33a8afd884ef63dce09c5e56c8088cb702ac89cff765f88d26fe11c3d471949f20194f61ffc773a97207c8124c29526a59e6fa0b34a52880e563a787da952ab808884f2a19b171abfb2882d473907f3ada086f20194c1d608bb39e078a99086e7564e89a7625ed86dca88e8a0ab45821912e88088df6c3d43080350518895a828c35680a0278088e2487fd89ca40b3488689accdbeb8d4d2e" bodyRlx := hexutility.MustDecodeHex(bodyRlxHex) @@ -301,15 +301,15 @@ func TestSetCodeTxParsing(t *testing.T) { ctx := NewTxnParseContext(*uint256.NewInt(1)) ctx.withSender = false - var tx TxnSlot - txType, err := PeekTransactionType(bodyRlx) + var txn TxnSlot + txnType, err := PeekTransactionType(bodyRlx) require.NoError(t, err) - assert.Equal(t, SetCodeTxType, txType) + assert.Equal(t, SetCodeTxnType, txnType) - _, err = ctx.ParseTransaction(bodyRlx, 0, &tx, nil, hasEnvelope, false, nil) + _, err = ctx.ParseTransaction(bodyRlx, 0, &txn, nil, hasEnvelope, false, nil) require.NoError(t, err) - assert.Equal(t, 4, len(tx.Authorizations)) - assert.Equal(t, SetCodeTxType, tx.Type) + assert.Equal(t, 4, len(txn.Authorizations)) + assert.Equal(t, SetCodeTxnType, txn.Type) // test empty authorizations bodyRlxHex = "0x04f903420188db1b29114eba96ab887145908699cc1f3488987b96c0c55fced7886b85e4937b481442949a60a150fda306891ad7aff6d47584c8a0e1571788c5f7682286d452e0b9021164b57ad1f652639f5d44536f1b868437787082df48b3e2a684742d0eafcfda5336e7a958afb22ae57aad8e9a271528f9aa1f4a34e29491a8929732e22c04a438578b2b8510862572dd36b5304a9c3b6668b7c8f818be8411c07866ccb1fbe34586f80a1ace62753b918139acefc71f92d0c4679c0a56bb6c8ae38bc37a7ee8f348255c8ada95e842b52d4bd2b2447789a8543beda9f3bc8e27f28d51373ef9b1494c3d21adc6b0416444088ed08834eb5736d48566da000356bbcd7d78b118c39d15a56874fd254dcfcc172cd7a82e36621b964ebc54fdaa64de9e381b1545cfc7c4ea1cfccff829f0dfa395ef5f750b79689e5c8e3f6c7de9afe34d05f599dac8e3ae999f7acb32f788991425a7d8b36bf92a7dc14d913c3cc5854e580f48d507bf06018f3d012155791e1930791afccefe46f268b59e023ddacaf1e8278026a4c962f9b968f065e7c33d98d2aea49e8885ac77bfcc952e322c5e414cb5b4e7477829c0a4b8b0964fc28d202bca1b3bedca34f3fe12d62629b30a4764121440d0ea0f50f26579c486070d00309a44c14f6c3347c5d14b520eca8a399a1cd3c421f28ae5485e96b4c500a411754a78f558701d1a9788d22e6d2f02fefd1c45c2d427b518adda66a34432c3f94b4b3811e2d063dca2917f403033b0400e4e9dc3fd327b10a43a15229332596671d0392e501c39f43b23f814e95b093e981418091f9e2a32013ab8fa7a409d5636b52fded6f8d5f794de688ae4be9a54b20eb5366903223863de2bc895e1a0f5ecb3956919b8e9e9956c20c89b523e71c5803592c99871b7d5ee025e402941f89b94ae16863cc3bf6e6946f186d0f63d77343f81363ef884a0b09afe54c0376e3e3091473edb4e2bf43f08530356a2c9236bf373869b79c8d0a0ec2c57ca577173865f340a7cd13cf0051e52229722e3a529f851d4b74e315c8ca00bbe5f1a1ef2e5830d0c5cb8e93a05d4d29b4d7bf244ceea432888c4fbd5d5d5a0823b7ceaeba3a4cd70572c2ccc560d588ffeed638aec7c0cc364afa7dbf1c51cc0018818848492f65ca7bd88ea2017dc526fff7f" @@ -318,65 +318,65 @@ func TestSetCodeTxParsing(t *testing.T) { ctx.withSender = false var tx2 TxnSlot - txType, err = PeekTransactionType(bodyRlx) + txnType, err = PeekTransactionType(bodyRlx) require.NoError(t, err) - assert.Equal(t, SetCodeTxType, txType) + assert.Equal(t, SetCodeTxnType, txnType) _, err = ctx.ParseTransaction(bodyRlx, 0, &tx2, nil, hasEnvelope, false, nil) require.NoError(t, err) assert.Equal(t, 0, len(tx2.Authorizations)) - assert.Equal(t, SetCodeTxType, tx2.Type) + assert.Equal(t, SetCodeTxnType, tx2.Type) // generated using this in core/types/encdec_test.go /* - func TestGenerateSetCodeTxRlp(t *testing.T) { + func TestGenerateSetCodeTxnRlp(t *testing.T) { tr := NewTRand() - var tx Transaction + var txn Transaction requiredAuthLen := 0 - for tx = tr.RandTransaction(); tx.Type() != types2.SetCodeTxType || len(tx.(*SetCodeTransaction).GetAuthorizations()) != requiredAuthLen; tx = tr.RandTransaction() { + for txn = tr.RandTransaction(); txn.Type() != types2.SetCodeTxnType || len(txn.(*SetCodeTransaction).GetAuthorizations()) != requiredAuthLen; txn = tr.RandTransaction() { } - v, _, _ := tx.RawSignatureValues() + v, _, _ := txn.RawSignatureValues() v.SetUint64(uint64(randIntInRange(0, 2))) - tx.GetChainID().SetUint64(1) + txn.GetChainID().SetUint64(1) - auths := tx.(*SetCodeTransaction).GetAuthorizations() + auths := txn.(*SetCodeTransaction).GetAuthorizations() for i := range auths { auths[i].ChainID.SetUint64(1) auths[i].V.SetUint64(uint64(randIntInRange(0, 2))) } w := bytes.NewBuffer(nil) - if err := tx.MarshalBinary(w); err != nil { + if err := txn.MarshalBinary(w); err != nil { t.Error(err) } hex := hexutility.Bytes(w.Bytes()).String() //hex := libcommon.BytesToHash().Hex() - authj, err := json.Marshal(tx.(*SetCodeTransaction).GetAuthorizations()) + authj, err := json.Marshal(txn.(*SetCodeTransaction).GetAuthorizations()) if err != nil { t.Error(err) } - fmt.Println("tx", hex, len(tx.(*SetCodeTransaction).GetAuthorizations()), string(authj)) + fmt.Println("txn", hex, len(txn.(*SetCodeTransaction).GetAuthorizations()), string(authj)) } */ } // See https://github.com/ethereum/EIPs/pull/8845 -func TestSetCodeTxParsingWithLargeAuthorizationValues(t *testing.T) { +func TestSetCodeTxnParsingWithLargeAuthorizationValues(t *testing.T) { // generated using this in core/types/encdec_test.go /* - func TestGenerateSetCodeTxRlpWithLargeAuthorizationValues(t *testing.T) { + func TestGenerateSetCodeTxnRlpWithLargeAuthorizationValues(t *testing.T) { tr := NewTRand() - var tx Transaction + var txn. Transaction requiredAuthLen := 1 - for tx = tr.RandTransaction(); tx.Type() != types2.SetCodeTxType || len(tx.(*SetCodeTransaction).GetAuthorizations()) != requiredAuthLen; tx = tr.RandTransaction() { + for txn. = tr.RandTransaction(); txn..Type() != types2.SetCodeTxnType || len(txn..(*SetCodeTransaction).GetAuthorizations()) != requiredAuthLen; txn. = tr.RandTransaction() { } - v, _, _ := tx.RawSignatureValues() + v, _, _ := txn..RawSignatureValues() v.SetUint64(uint64(randIntInRange(0, 2))) - tx.GetChainID().SetUint64(1) + txn..GetChainID().SetUint64(1) - auths := tx.(*SetCodeTransaction).GetAuthorizations() + auths := txn..(*SetCodeTransaction).GetAuthorizations() for i := range auths { auths[i].ChainID.SetAllOne() auths[i].Nonce = math.MaxUint64 @@ -385,12 +385,12 @@ func TestSetCodeTxParsingWithLargeAuthorizationValues(t *testing.T) { auths[i].S.SetAllOne() } w := bytes.NewBuffer(nil) - if err := tx.MarshalBinary(w); err != nil { + if err := txn..MarshalBinary(w); err != nil { t.Error(err) } hex := hexutility.Bytes(w.Bytes()).String() - fmt.Println("tx", hex) + fmt.Println("txn.", hex) } */ bodyRlxHex := "0x04f90546018820d75f30c9812472883efdaaf328683c8f88791ecd238942f142882f6a9ebaec6c1af49484d85e90da36f0392202193df1101863eb895d498883bf224e11f95355b902540e61088a043ef305b21d1bab6e4c14edeae66b3c0d6c183e423324c562b33b98ca2900d6a0adc2c13fdce4835debb623bf9f02860959bf589e88392a98a57db341a182e7d063945aaa4153010dd1d58d508d27ddd07e82b2f95af341b76b3acfbe00fde8d890867b6794ac95a4096dccbfaf9f92f446d6e4f3a718185f875ce49308ad24cf8b7316f1a73da7fb626e92e7d45d3b6ffeb2e3d153e92bc2499ccd8a43a6295db0be96dffcb857ed409b3e4f29a126e38982bf927efa9e637f670f631b36795dc158cb32069e846f28e4721b9d3004c6951075bf14f27e9f81dfa409e344e713143da8b8b35bd5ebfbc2b5c1e6909fadc7a5681ca63ecd387b745bbd3fff1169308a02e313671f2e5e5e914e8085236112fe12ae52403f54a95230c5807e5697b34bea0bf932a8cd45b6bf7ac1b318c594de85c523b1b82358ee8fce4f94d04bc30369c5a5482668a354bb36bb0f6e8943662be124cc3650f8e563a9c62808fb65444f425ff274974cd6cce771e67c2d45a95431a731ae0db60ef83793d9c257d48a24dae64e43870ecaf56a7f3e95415cdaacee3da94ad569e430ba4cdf5f0ac7cd8bd2e5507a1d0f16849e1d1823fcce1670c861b591051170c60883a32c23bc0a552415203baad7d1a6d44e3229956387ae014e944dbd7b918fa1c52fc7a4ee1ea813f1ba4a1bdedd7a23b4a93faca01eb1127d51953603eae70499d485dc3c8633b778dbae199158e03977b003a9da717ae8f31780949c53f82c5d09dd7428747426f77e39349dcd4fb8e3793d6a46cd4e9be6d6614b285d79e772bae41fb8a1625d23b38cef14911092e78c86f901f0f85994e805c10b96ec670ff8d6b684ed413eb71babf735f842a0e1b6f8621d3f4513ac7d491849fdcf3a8264e6cf4a1503357414a38682662555a027d3e5a0f5e7478629ef06e831162a8e99c4d9cd973919e21c162d29ac1410e6f87a94a5bfb70f5ffb19b2b2173e2d80a1bbfb6ff10dc4f863a0e129afdd8d7ac6e5c52708e658ded4859b06f1b483497e0474f6599b72dd2f75a0a7169872faa1fdfc3c2d80c207bc64ae817301b4087979563ef690b02b0d7964a0fe009fc656d1f0fcfc1c7c93b7ab67bdc9dd06f06a37fdaecbd43ed5d1423a11f87a94feae80b40ef29bdd926061a9000c1b0875cb0be3f863a0a5a381867886a9780e6f955d62cf73849e338918751dba1442d632fccb8d52a8a0ee8501f7bbc25d0dde1f60771167abc421be099cf0ec07636f4e5092f8f6b66ba0660a025a421dd73f4747e3a262a726ab8ff76b893c23e4d595ac50c86b9ae8c0f89b94d94f45974bbdb5d2e27419b5202fd2eec115fe26f884a04ee78854a71d2c0965a62080f2cff53b788a3dc0f8c6a55bf0535e0197a8ba77a08eb0010ea0fbe6e9251421dcbc26d83abe55bc24c6466b1833365dd87b253623a0040fa96b15c24f6a6e6dfd1e7be34b7fb58e8cfc26e4ed16b45d8eb567b60089a0cbfa955cc7c5435e0b6694e1a3d64d773a8baa3c4a85d6eddad407dbff5e645df8a4f8a2a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff942d9986714cb0a7f215d435013a08af34c42406be88ffffffffffffffffa0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01886417de6405dde7ee88813b5026c7af887a" @@ -399,35 +399,35 @@ func TestSetCodeTxParsingWithLargeAuthorizationValues(t *testing.T) { ctx := NewTxnParseContext(*uint256.NewInt(1)) ctx.withSender = false - var tx TxnSlot - txType, err := PeekTransactionType(bodyRlx) + var txn TxnSlot + txnType, err := PeekTransactionType(bodyRlx) require.NoError(t, err) - assert.Equal(t, SetCodeTxType, txType) + assert.Equal(t, SetCodeTxnType, txnType) - _, err = ctx.ParseTransaction(bodyRlx, 0, &tx, nil, false /* hasEnvelope */, false, nil) + _, err = ctx.ParseTransaction(bodyRlx, 0, &txn, nil, false /* hasEnvelope */, false, nil) assert.ErrorContains(t, err, "chainId is too big") } -var txParseCalaverasTests = []parseTxTest{ +var txnParseCalaverasTests = []parseTxnTest{ // Legacy protected (EIP-155) from calveras, with chainId 123 {PayloadStr: "f86d808459682f0082520894e80d2a018c813577f33f9e69387dc621206fb3a48856bc75e2d63100008082011aa04ae3cae463329a32573f4fbf1bd9b011f93aecf80e4185add4682a03ba4a4919a02b8f05f3f4858b0da24c93c2a65e51b2fbbecf5ffdf97c1f8cc1801f307dc107", IdHashStr: "f4a91979624effdb45d2ba012a7995c2652b62ebbeb08cdcab00f4923807aa8a", SignHashStr: "ff44cf01ee9b831f09910309a689e8da83d19aa60bad325ee9154b7c25cf4de8", Nonce: 0}, } -var txParseDevNetTests = []parseTxTest{ +var txnParseDevNetTests = []parseTxnTest{ {PayloadStr: "f8620101830186a09400000000000000000000000000000000000000006401820a96a04f353451b272c6b183cedf20787dab556db5afadf16733a3c6bffb0d2fcd2563a0773cd45f7cc62250f7ee715b9e19f0489176f8966f75c8eed2fbf1ac861cb50c", IdHashStr: "35767571787cd95dd71e2081ac4f667076f012b854fc314ed3b131e12623cbbd", SignHashStr: "a2719fbc84efd65eee79201e46f5110edc4731c90ffe1cebf8644c8ddd62528d", SenderStr: "67b1d87101671b127f5f8714789c7192f7ad340e", Nonce: 1}, } -var txRopstenTests = []parseTxTest{ +var txnRopstenTests = []parseTxnTest{ {PayloadStr: "f868188902000000000000000082520894000000000000000000000000000000000000004380801ba01d852f75e0bdbdf3c2b770be97eb3b74d9a3b2450fb58aa6cfbc9e9faa1c4b24a079aef959a5f032ed90b2e44b74a2e850043a3e0ab83f994ab0619638173fe035", Nonce: 24, SenderStr: "874b54a8bd152966d63f706bae1ffeb0411921e5", IdHashStr: "5928c90044b9d2add2fc7f580e0c6ea1b2dca2ea8c254dfa4092c251f895ed52"}, } -type parseTxTest struct { +type parseTxnTest struct { PayloadStr string SenderStr string IdHashStr string @@ -436,28 +436,28 @@ type parseTxTest struct { } var allNetsTestCases = []struct { - tests []parseTxTest + tests []parseTxnTest chainID uint256.Int }{ { chainID: *uint256.NewInt(1), - tests: TxParseMainnetTests, + tests: TxnParseMainnetTests, }, { chainID: *uint256.NewInt(123), - tests: txParseCalaverasTests, + tests: txnParseCalaverasTests, }, { chainID: *uint256.NewInt(1337), - tests: txParseDevNetTests, + tests: txnParseDevNetTests, }, { chainID: *uint256.NewInt(3), - tests: txRopstenTests, + tests: txnRopstenTests, }, } -var TxParseMainnetTests = []parseTxTest{ +var TxnParseMainnetTests = []parseTxnTest{ // Legacy unprotected {PayloadStr: "f86a808459682f0082520894fe3b557e8fb62b89f4916b721be55ceb828dbd73872386f26fc10000801ca0d22fc3eed9b9b9dbef9eec230aa3fb849eff60356c6b34e86155dca5c03554c7a05e3903d7375337f103cb9583d97a59dcca7472908c31614ae240c6a8311b02d6", SenderStr: "fe3b557e8fb62b89f4916b721be55ceb828dbd73", IdHashStr: "595e27a835cd79729ff1eeacec3120eeb6ed1464a04ec727aaca734ead961328", diff --git a/txnprovider/txpool/txn_types_fuzz_test.go b/txnprovider/txpool/pool_txn_types_fuzz_test.go similarity index 100% rename from txnprovider/txpool/txn_types_fuzz_test.go rename to txnprovider/txpool/pool_txn_types_fuzz_test.go diff --git a/txnprovider/txpool/send.go b/txnprovider/txpool/send.go index 029819d1890..f5e25f1c75c 100644 --- a/txnprovider/txpool/send.go +++ b/txnprovider/txpool/send.go @@ -67,40 +67,40 @@ func (f *Send) notifyTests() { } // Broadcast given RLPs to random peers -func (f *Send) BroadcastPooledTxs(rlps [][]byte, maxPeers uint64) (txSentTo []int) { +func (f *Send) BroadcastPooledTxns(rlps [][]byte, maxPeers uint64) (txnSentTo []int) { defer f.notifyTests() if len(rlps) == 0 { return } - txSentTo = make([]int, len(rlps)) + txnSentTo = make([]int, len(rlps)) var prev, size int for i, l := 0, len(rlps); i < len(rlps); i++ { size += len(rlps[i]) // Wait till the combined size of rlps so far is greater than a threshold and // send them all at once. Then wait till end of array or this threshold hits again if i == l-1 || size >= p2pTxPacketLimit { - txsData := EncodeTransactions(rlps[prev:i+1], nil) - var txs66 *sentryproto.SendMessageToRandomPeersRequest + txnsData := EncodeTransactions(rlps[prev:i+1], nil) + var txns66 *sentryproto.SendMessageToRandomPeersRequest for _, sentryClient := range f.sentryClients { if ready, ok := sentryClient.(interface{ Ready() bool }); ok && !ready.Ready() { continue } - if txs66 == nil { - txs66 = &sentryproto.SendMessageToRandomPeersRequest{ + if txns66 == nil { + txns66 = &sentryproto.SendMessageToRandomPeersRequest{ Data: &sentryproto.OutboundMessageData{ Id: sentryproto.MessageId_TRANSACTIONS_66, - Data: txsData, + Data: txnsData, }, MaxPeers: maxPeers, } } - peers, err := sentryClient.SendMessageToRandomPeers(f.ctx, txs66) + peers, err := sentryClient.SendMessageToRandomPeers(f.ctx, txns66) if err != nil { - f.logger.Debug("[txpool.send] BroadcastPooledTxs", "err", err) + f.logger.Debug("[txpool.send] BroadcastPooledTxns", "err", err) } if peers != nil { for j := prev; j <= i; j++ { - txSentTo[j] = len(peers.Peers) + txnSentTo[j] = len(peers.Peers) } } } @@ -111,7 +111,7 @@ func (f *Send) BroadcastPooledTxs(rlps [][]byte, maxPeers uint64) (txSentTo []in return } -func (f *Send) AnnouncePooledTxs(types []byte, sizes []uint32, hashes Hashes, maxPeers uint64) (hashSentTo []int) { +func (f *Send) AnnouncePooledTxns(types []byte, sizes []uint32, hashes Hashes, maxPeers uint64) (hashSentTo []int) { defer f.notifyTests() hashSentTo = make([]int, len(types)) if len(types) == 0 { @@ -168,7 +168,7 @@ func (f *Send) AnnouncePooledTxs(types []byte, sizes []uint32, hashes Hashes, ma } peers, err := sentryClient.SendMessageToRandomPeers(f.ctx, req) if err != nil { - f.logger.Debug("[txpool.send] AnnouncePooledTxs", "err", err) + f.logger.Debug("[txpool.send] AnnouncePooledTxns", "err", err) } if peers != nil { for k := prevI; k < i; k += 32 { @@ -187,7 +187,7 @@ func (f *Send) AnnouncePooledTxs(types []byte, sizes []uint32, hashes Hashes, ma } peers, err := sentryClient.SendMessageToRandomPeers(f.ctx, req) if err != nil { - f.logger.Debug("[txpool.send] AnnouncePooledTxs68", "err", err) + f.logger.Debug("[txpool.send] AnnouncePooledTxns68", "err", err) } if peers != nil { for k := prevJ; k < j; k++ { @@ -204,7 +204,7 @@ func (f *Send) AnnouncePooledTxs(types []byte, sizes []uint32, hashes Hashes, ma return } -func (f *Send) PropagatePooledTxsToPeersList(peers []PeerID, types []byte, sizes []uint32, hashes []byte) { +func (f *Send) PropagatePooledTxnsToPeersList(peers []PeerID, types []byte, sizes []uint32, hashes []byte) { defer f.notifyTests() if len(types) == 0 { @@ -253,7 +253,7 @@ func (f *Send) PropagatePooledTxsToPeersList(peers []PeerID, types []byte, sizes }, } if _, err := sentryClient.SendMessageById(f.ctx, req, &grpc.EmptyCallOption{}); err != nil { - f.logger.Debug("[txpool.send] PropagatePooledTxsToPeersList", "err", err) + f.logger.Debug("[txpool.send] PropagatePooledTxnsToPeersList", "err", err) } } case 68: @@ -267,7 +267,7 @@ func (f *Send) PropagatePooledTxsToPeersList(peers []PeerID, types []byte, sizes }, } if _, err := sentryClient.SendMessageById(f.ctx, req, &grpc.EmptyCallOption{}); err != nil { - f.logger.Debug("[txpool.send] PropagatePooledTxsToPeersList68", "err", err) + f.logger.Debug("[txpool.send] PropagatePooledTxnsToPeersList68", "err", err) } } diff --git a/txnprovider/txpool/senders.go b/txnprovider/txpool/senders.go index fe04dd8889f..6ee17d8e1ad 100644 --- a/txnprovider/txpool/senders.go +++ b/txnprovider/txpool/senders.go @@ -100,7 +100,7 @@ func (b *BySenderAndNonce) blobCount(senderID uint64) uint64 { return b.senderIDBlobCount[senderID] } -func (b *BySenderAndNonce) hasTxs(senderID uint64) bool { +func (b *BySenderAndNonce) hasTxns(senderID uint64) bool { has := false b.ascend(senderID, func(*metaTxn) bool { has = true @@ -138,7 +138,7 @@ func (b *BySenderAndNonce) delete(mt *metaTxn, reason txpoolcfg.DiscardReason, l delete(b.senderIDTxnCount, senderID) } - if mt.TxnSlot.Type == BlobTxType && mt.TxnSlot.Blobs != nil { + if mt.TxnSlot.Type == BlobTxnType && mt.TxnSlot.Blobs != nil { accBlobCount := b.senderIDBlobCount[senderID] txnBlobCount := len(mt.TxnSlot.Blobs) if txnBlobCount > 1 { @@ -165,7 +165,7 @@ func (b *BySenderAndNonce) replaceOrInsert(mt *metaTxn, logger log.Logger) *meta } b.senderIDTxnCount[mt.TxnSlot.SenderID]++ - if mt.TxnSlot.Type == BlobTxType && mt.TxnSlot.Blobs != nil { + if mt.TxnSlot.Type == BlobTxnType && mt.TxnSlot.Blobs != nil { b.senderIDBlobCount[mt.TxnSlot.SenderID] += uint64(len(mt.TxnSlot.Blobs)) } return nil @@ -242,26 +242,26 @@ func (sc *sendersBatch) info(cacheView kvcache.CacheView, id uint64) (nonce uint return nonce, balance, nil } -func (sc *sendersBatch) registerNewSenders(newTxs *TxnSlots, logger log.Logger) (err error) { - for i, txn := range newTxs.Txs { - txn.SenderID, txn.Traced = sc.getOrCreateID(newTxs.Senders.AddressAt(i), logger) +func (sc *sendersBatch) registerNewSenders(newTxns *TxnSlots, logger log.Logger) (err error) { + for i, txn := range newTxns.Txns { + txn.SenderID, txn.Traced = sc.getOrCreateID(newTxns.Senders.AddressAt(i), logger) } return nil } -func (sc *sendersBatch) onNewBlock(stateChanges *remote.StateChangeBatch, unwindTxs, minedTxs TxnSlots, logger log.Logger) error { +func (sc *sendersBatch) onNewBlock(stateChanges *remote.StateChangeBatch, unwindTxns, minedTxns TxnSlots, logger log.Logger) error { for _, diff := range stateChanges.ChangeBatch { for _, change := range diff.Changes { // merge state changes addrB := gointerfaces.ConvertH160toAddress(change.Address) sc.getOrCreateID(addrB, logger) } - for i, txn := range unwindTxs.Txs { - txn.SenderID, txn.Traced = sc.getOrCreateID(unwindTxs.Senders.AddressAt(i), logger) + for i, txn := range unwindTxns.Txns { + txn.SenderID, txn.Traced = sc.getOrCreateID(unwindTxns.Senders.AddressAt(i), logger) } - for i, txn := range minedTxs.Txs { - txn.SenderID, txn.Traced = sc.getOrCreateID(minedTxs.Senders.AddressAt(i), logger) + for i, txn := range minedTxns.Txns { + txn.SenderID, txn.Traced = sc.getOrCreateID(minedTxns.Senders.AddressAt(i), logger) } } return nil diff --git a/txnprovider/txpool/txpool_grpc_server.go b/txnprovider/txpool/txpool_grpc_server.go index 4c6c4f2352a..60b30755277 100644 --- a/txnprovider/txpool/txpool_grpc_server.go +++ b/txnprovider/txpool/txpool_grpc_server.go @@ -188,11 +188,11 @@ func (s *GrpcServer) Add(ctx context.Context, in *txpool_proto.AddRequest) (*txp reply := &txpool_proto.AddReply{Imported: make([]txpool_proto.ImportResult, len(in.RlpTxs)), Errors: make([]string, len(in.RlpTxs))} for i := 0; i < len(in.RlpTxs); i++ { - j := len(slots.Txs) // some incoming txs may be rejected, so - need second index + j := len(slots.Txns) // some incoming txns may be rejected, so - need second index slots.Resize(uint(j + 1)) - slots.Txs[j] = &TxnSlot{} + slots.Txns[j] = &TxnSlot{} slots.IsLocal[j] = true - if _, err := parseCtx.ParseTransaction(in.RlpTxs[i], 0, slots.Txs[j], slots.Senders.At(j), false /* hasEnvelope */, true /* wrappedWithBlobs */, func(hash []byte) error { + if _, err := parseCtx.ParseTransaction(in.RlpTxs[i], 0, slots.Txns[j], slots.Senders.At(j), false /* hasEnvelope */, true /* wrappedWithBlobs */, func(hash []byte) error { if known, _ := s.txPool.IdHashKnown(tx, hash); known { return ErrAlreadyKnown } @@ -251,7 +251,7 @@ func mapDiscardReasonToProto(reason txpoolcfg.DiscardReason) txpool_proto.Import } func (s *GrpcServer) OnAdd(req *txpool_proto.OnAddRequest, stream txpool_proto.Txpool_OnAddServer) error { - s.logger.Info("New txs subscriber joined") + s.logger.Info("New txns subscriber joined") //txpool.Loop does send messages to this streams remove := s.NewSlotsStreams.Add(stream) defer remove() diff --git a/txnprovider/txpool/txpoolcfg/txpoolcfg.go b/txnprovider/txpool/txpoolcfg/txpoolcfg.go index 2dd7cbafb25..27ef3a979b0 100644 --- a/txnprovider/txpool/txpoolcfg/txpoolcfg.go +++ b/txnprovider/txpool/txpoolcfg/txpoolcfg.go @@ -30,7 +30,7 @@ import ( "github.com/erigontech/erigon/core/types" ) -// BorDefaultTxPoolPriceLimit defines the minimum gas price limit for bor to enforce txs acceptance into the pool. +// BorDefaultTxPoolPriceLimit defines the minimum gas price limit for bor to enforce txns acceptance into the pool. const BorDefaultTxPoolPriceLimit = 25 * common.GWei type Config struct { @@ -41,17 +41,17 @@ type Config struct { QueuedSubPoolLimit int MinFeeCap uint64 AccountSlots uint64 // Number of executable transaction slots guaranteed per account - BlobSlots uint64 // Total number of blobs (not txs) allowed per account - TotalBlobPoolLimit uint64 // Total number of blobs (not txs) allowed within the txpool + BlobSlots uint64 // Total number of blobs (not txns) allowed per account + TotalBlobPoolLimit uint64 // Total number of blobs (not txns) allowed within the txpool PriceBump uint64 // Price bump percentage to replace an already existing transaction BlobPriceBump uint64 //Price bump percentage to replace an existing 4844 blob txn (type-3) OverridePragueTime *big.Int // regular batch tasks processing - SyncToNewPeersEvery time.Duration - ProcessRemoteTxsEvery time.Duration - CommitEvery time.Duration - LogEvery time.Duration + SyncToNewPeersEvery time.Duration + ProcessRemoteTxnsEvery time.Duration + CommitEvery time.Duration + LogEvery time.Duration //txpool db MdbxPageSize datasize.ByteSize @@ -59,14 +59,14 @@ type Config struct { MdbxGrowthStep datasize.ByteSize MdbxWriteMap bool - NoGossip bool // this mode doesn't broadcast any txs, and if receive remote-txn - skip it + NoGossip bool // this mode doesn't broadcast any txns, and if receive remote-txn - skip it } var DefaultConfig = Config{ - SyncToNewPeersEvery: 5 * time.Second, - ProcessRemoteTxsEvery: 100 * time.Millisecond, - CommitEvery: 15 * time.Second, - LogEvery: 30 * time.Second, + SyncToNewPeersEvery: 5 * time.Second, + ProcessRemoteTxnsEvery: 100 * time.Millisecond, + CommitEvery: 15 * time.Second, + LogEvery: 30 * time.Second, PendingSubPoolLimit: 10_000, BaseFeeSubPoolLimit: 10_000, @@ -74,7 +74,7 @@ var DefaultConfig = Config{ MinFeeCap: 1, AccountSlots: 16, //TODO: to choose right value (16 to be compatible with Geth) - BlobSlots: 48, // Default for a total of 8 txs for 6 blobs each - for hive tests + BlobSlots: 48, // Default for a total of 8 txns for 6 blobs each - for hive tests TotalBlobPoolLimit: 480, // Default for a total of 10 different accounts hitting the above limit PriceBump: 10, // Price bump percentage to replace an already existing transaction BlobPriceBump: 100, @@ -117,7 +117,7 @@ const ( BlobHashCheckFail DiscardReason = 28 // KZGcommitment's versioned hash has to be equal to blob_versioned_hash at the same index UnmatchedBlobTxExt DiscardReason = 29 // KZGcommitments must match the corresponding blobs and proofs BlobTxReplace DiscardReason = 30 // Cannot replace type-3 blob txn with another type of txn - BlobPoolOverflow DiscardReason = 31 // The total number of blobs (through blob txs) in the pool has reached its limit + BlobPoolOverflow DiscardReason = 31 // The total number of blobs (through blob txns) in the pool has reached its limit NoAuthorizations DiscardReason = 32 // EIP-7702 transactions with an empty authorization list are invalid ) diff --git a/txnprovider/txpool/txpoolutil/all_components.go b/txnprovider/txpool/txpoolutil/all_components.go index 662e53cb438..d8e09fe7805 100644 --- a/txnprovider/txpool/txpoolutil/all_components.go +++ b/txnprovider/txpool/txpoolutil/all_components.go @@ -99,7 +99,7 @@ func SaveChainConfigIfNeed(ctx context.Context, coreDB kv.RoDB, txPoolDB kv.RwDB return cc, blockNum, nil } -func AllComponents(ctx context.Context, cfg txpoolcfg.Config, cache kvcache.Cache, newTxs chan txpool.Announcements, chainDB kv.RoDB, +func AllComponents(ctx context.Context, cfg txpoolcfg.Config, cache kvcache.Cache, newTxns chan txpool.Announcements, chainDB kv.RoDB, sentryClients []sentryproto.SentryClient, stateChangesClient txpool.StateChangesClient, feeCalculator txpool.FeeCalculator, logger log.Logger) (kv.RwDB, *txpool.TxPool, *txpool.Fetch, *txpool.Send, *txpool.GrpcServer, error) { opts := mdbx.NewMDBX(logger).Label(kv.TxPoolDB).Path(cfg.DBDir). WithTableCfg(func(defaultBuckets kv.TableCfg) kv.TableCfg { return kv.TxpoolTablesCfg }). @@ -145,7 +145,7 @@ func AllComponents(ctx context.Context, cfg txpoolcfg.Config, cache kvcache.Cach pragueTime = cfg.OverridePragueTime } - txPool, err := txpool.New(newTxs, chainDB, cfg, cache, *chainID, shanghaiTime, agraBlock, cancunTime, pragueTime, + txPool, err := txpool.New(newTxns, chainDB, cfg, cache, *chainID, shanghaiTime, agraBlock, cancunTime, pragueTime, maxBlobsPerBlock, feeCalculator, logger) if err != nil { return nil, nil, nil, nil, nil, err