-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbatch_tx_pool.go
More file actions
277 lines (242 loc) · 7.4 KB
/
Copy pathbatch_tx_pool.go
File metadata and controls
277 lines (242 loc) · 7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package requester
import (
"context"
"encoding/hex"
"sort"
"sync"
"time"
gethCommon "github.com/ethereum/go-ethereum/common"
gethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/hashicorp/golang-lru/v2/expirable"
"github.com/onflow/cadence"
"github.com/onflow/flow-go-sdk"
"github.com/rs/zerolog"
"github.com/onflow/flow-evm-gateway/config"
"github.com/onflow/flow-evm-gateway/metrics"
"github.com/onflow/flow-evm-gateway/models"
"github.com/onflow/flow-evm-gateway/services/requester/keystore"
)
const eoaActivityCacheSize = 10_000
type pooledEvmTx struct {
txPayload cadence.String
nonce uint64
}
// BatchTxPool is a `TxPool` implementation that collects and groups
// transactions based on their EOA signer, and submits them for execution
// using a batch.
//
// The underlying Cadence EVM API used, is `EVM.batchRun`, instead of the
// `EVM.run` used in `SingleTxPool`.
//
// The main advantage of this implementation over the `SingleTxPool`, is the
// guarantee that transactions originated from the same EOA address, which
// arrive in a short time interval (about the same as Flow's block production rate),
// will be executed in the same order their arrived.
// This helps to reduce the nonce mismatch errors which mainly occur from the
// re-ordering of Cadence transactions that happens from Collection nodes.
type BatchTxPool struct {
*SingleTxPool
pooledTxs map[gethCommon.Address][]pooledEvmTx
txMux sync.Mutex
eoaActivity *expirable.LRU[gethCommon.Address, time.Time]
}
var _ TxPool = &BatchTxPool{}
func NewBatchTxPool(
ctx context.Context,
client *CrossSporkClient,
transactionsPublisher *models.Publisher[*gethTypes.Transaction],
logger zerolog.Logger,
config config.Config,
collector metrics.Collector,
keystore *keystore.KeyStore,
) *BatchTxPool {
// initialize the available keys metric since it is only updated when sending a tx
collector.AvailableSigningKeys(keystore.AvailableKeys())
singleTxPool := NewSingleTxPool(
client,
transactionsPublisher,
logger,
config,
collector,
keystore,
)
eoaActivity := expirable.NewLRU[gethCommon.Address, time.Time](
eoaActivityCacheSize,
nil,
config.EOAActivityCacheTTL,
)
batchPool := &BatchTxPool{
SingleTxPool: singleTxPool,
pooledTxs: make(map[gethCommon.Address][]pooledEvmTx),
txMux: sync.Mutex{},
eoaActivity: eoaActivity,
}
go batchPool.processPooledTransactions(ctx)
return batchPool
}
// Add adds the EVM transaction to the tx pool, grouped with the rest of the
// transactions from the same EOA signer.
// After the configured `TxBatchInterval`, the collected transations
// are batched and sent to the Flow network using `EVM.batchRun`, for execution.
func (t *BatchTxPool) Add(
ctx context.Context,
tx *gethTypes.Transaction,
) error {
t.txPublisher.Publish(tx) // publish pending transaction event
// tx adding should be blocking, so we don't have races when
// pooled transactions are being processed in the background.
t.txMux.Lock()
defer t.txMux.Unlock()
from, err := models.DeriveTxSender(tx)
if err != nil {
return err
}
txData, err := tx.MarshalBinary()
if err != nil {
return err
}
hexEncodedTx, err := cadence.NewString(hex.EncodeToString(txData))
if err != nil {
return err
}
// Scenarios
// 1. EOA activity not found:
// => We send the transaction individually, without adding it
// to the batch pool.
//
// 2. EOA activity found AND it was more than [X] seconds ago:
// => We send the transaction individually, without adding it
// to the batch pool.
//
// 3. EOA activity found AND it was less than [X] seconds ago:
// => We add the transaction to the batch pool, so that it gets
// processed and submitted according to the configured
// `TxBatchInterval`.
//
// For all 3 cases, we record the activity time for the next
// transactions that might come from the same EOA.
// [X] is equal to the configured `TxBatchInterval` duration.
lastActivityTime, found := t.eoaActivity.Get(from)
if !found {
// Case 1. EOA activity not found:
err = t.submitSingleTransaction(ctx, hexEncodedTx)
} else if time.Since(lastActivityTime) > t.config.TxBatchInterval {
// Case 2. EOA activity found AND it was more than [X] seconds ago:
err = t.submitSingleTransaction(ctx, hexEncodedTx)
} else {
// Case 3. EOA activity found AND it was less than [X] seconds ago:
userTx := pooledEvmTx{txPayload: hexEncodedTx, nonce: tx.Nonce()}
t.pooledTxs[from] = append(t.pooledTxs[from], userTx)
}
t.eoaActivity.Add(from, time.Now())
return err
}
func (t *BatchTxPool) processPooledTransactions(ctx context.Context) {
ticker := time.NewTicker(t.config.TxBatchInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
latestBlock, account, err := t.fetchFlowLatestBlockAndCOA(ctx)
if err != nil {
t.logger.Error().Err(err).Msg(
"failed to get COA / latest Flow block on batch tx submission",
)
continue
}
// Take a copy here to allow `Add()` to continue accept
// incoming EVM transactions, without blocking until the
// batch transactions are submitted.
t.txMux.Lock()
txsGroupedByAddress := t.pooledTxs
t.pooledTxs = make(map[gethCommon.Address][]pooledEvmTx)
t.txMux.Unlock()
for address, pooledTxs := range txsGroupedByAddress {
err := t.batchSubmitTransactionsForSameAddress(
ctx,
latestBlock,
account,
pooledTxs,
)
if err != nil {
t.logger.Error().Err(err).Msgf(
"failed to submit Flow transaction from BatchTxPool for EOA: %s",
address.Hex(),
)
continue
}
}
}
}
}
func (t *BatchTxPool) batchSubmitTransactionsForSameAddress(
ctx context.Context,
latestBlock *flow.Block,
account *flow.Account,
pooledTxs []pooledEvmTx,
) error {
// Sort the transactions based on their nonce, to make sure
// that no re-ordering has happened due to races etc.
sort.Slice(pooledTxs, func(i, j int) bool {
return pooledTxs[i].nonce < pooledTxs[j].nonce
})
hexEncodedTxs := make([]cadence.Value, len(pooledTxs))
for i, txPayload := range pooledTxs {
hexEncodedTxs[i] = txPayload.txPayload
}
coinbaseAddress, err := cadence.NewString(t.config.Coinbase.Hex())
if err != nil {
return err
}
script := replaceAddresses(runTxScript, t.config.FlowNetworkID)
flowTx, err := t.buildTransaction(
latestBlock,
account,
script,
cadence.NewArray(hexEncodedTxs),
coinbaseAddress,
)
if err != nil {
// If there was any error during the transaction build
// process, we record all transactions as dropped.
t.collector.TransactionsDropped(len(hexEncodedTxs))
return err
}
if err := t.client.SendTransaction(ctx, *flowTx); err != nil {
return err
}
return nil
}
func (t *BatchTxPool) submitSingleTransaction(
ctx context.Context,
hexEncodedTx cadence.String,
) error {
latestBlock, account, err := t.fetchFlowLatestBlockAndCOA(ctx)
if err != nil {
return err
}
coinbaseAddress, err := cadence.NewString(t.config.Coinbase.Hex())
if err != nil {
return err
}
script := replaceAddresses(runTxScript, t.config.FlowNetworkID)
flowTx, err := t.buildTransaction(
latestBlock,
account,
script,
cadence.NewArray([]cadence.Value{hexEncodedTx}),
coinbaseAddress,
)
if err != nil {
// If there was any error during the transaction build
// process, we record it as a dropped transaction.
t.collector.TransactionsDropped(1)
return err
}
if err := t.client.SendTransaction(ctx, *flowTx); err != nil {
return err
}
return nil
}