-
Notifications
You must be signed in to change notification settings - Fork 861
Expand file tree
/
Copy pathmempool.go
More file actions
309 lines (276 loc) · 9.4 KB
/
Copy pathmempool.go
File metadata and controls
309 lines (276 loc) · 9.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package txpool
import (
"errors"
"fmt"
"github.com/ava-labs/libevm/log"
"github.com/holiman/uint256"
"github.com/prometheus/client_golang/prometheus"
"github.com/ava-labs/avalanchego/graft/coreth/plugin/evm/atomic"
"github.com/ava-labs/avalanchego/graft/coreth/plugin/evm/config"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/network/p2p/gossip"
"github.com/ava-labs/avalanchego/utils/bloom"
)
var (
_ gossip.HandlerSet[*atomic.Tx] = (*Mempool)(nil)
_ gossip.PullGossiperSet[*atomic.Tx] = (*Mempool)(nil)
_ gossip.PushGossiperSet = (*Mempool)(nil)
ErrAlreadyKnown = errors.New("already known")
ErrConflict = errors.New("conflict present")
ErrInsufficientFee = errors.New("insufficient fee")
ErrMempoolFull = errors.New("mempool full")
// If the transaction is already in the mempool, marking it as Discarded,
// could unexpectedly cause the transaction to have multiple statuses.
//
// If the mempool is full, that is not the transaction's fault, so we should
// not prevent adding the transaction to the mempool later.
errsNotToDiscard = []error{
ErrAlreadyKnown,
ErrMempoolFull,
}
)
// Mempool is a simple mempool for atomic transactions
type Mempool struct {
*Txs
// bloom is a bloom filter containing the txs in the mempool
bloom *gossip.BloomFilter
verify func(tx *atomic.Tx) error
}
func NewMempool(
txs *Txs,
registerer prometheus.Registerer,
verify func(tx *atomic.Tx) error,
) (*Mempool, error) {
bloom, err := gossip.NewBloomFilter(registerer, "atomic_mempool_bloom_filter",
config.TxGossipBloomMinTargetElements,
config.TxGossipBloomTargetFalsePositiveRate,
config.TxGossipBloomResetFalsePositiveRate,
)
if err != nil {
return nil, fmt.Errorf("failed to initialize bloom filter: %w", err)
}
return &Mempool{
Txs: txs,
bloom: bloom,
verify: verify,
}, nil
}
// Add attempts to add tx to the mempool as a Remote transaction. It is assumed
// the snow context lock is not held.
func (m *Mempool) Add(tx *atomic.Tx) error {
m.ctx.Lock.RLock()
defer m.ctx.Lock.RUnlock()
return m.AddRemoteTx(tx)
}
// AddRemoteTx attempts to add tx to the mempool as a Remote transaction.
//
// Remote transactions are checked for recent verification failures prior to
// performing verification. If a Remote transaction failed verification recently
// it will not be added to the mempool.
func (m *Mempool) AddRemoteTx(tx *atomic.Tx) error {
m.lock.Lock()
defer m.lock.Unlock()
err := m.addTx(tx, false, false)
if err == nil {
return nil
}
for _, errNotToDiscard := range errsNotToDiscard {
if errors.Is(err, errNotToDiscard) {
return err
}
}
// Unlike local txs, invalid remote txs are recorded as discarded so that
// they won't be requested again
txID := tx.ID()
m.discardedTxs.Put(txID, tx)
log.Debug("failed to issue remote tx to mempool",
"txID", txID,
"err", err,
)
return err
}
// AddLocalTx attempts to add tx to the mempool as a Local transaction.
//
// Local transactions are not checked for recent verification failures prior to
// performing verification. Even if a Local transaction failed verification
// recently, the mempool will attempt to re-verify it.
func (m *Mempool) AddLocalTx(tx *atomic.Tx) error {
m.lock.Lock()
defer m.lock.Unlock()
return m.addTx(tx, true, false)
}
// ForceAddTx forcibly adds a tx to the mempool and bypasses all verification.
func (m *Mempool) ForceAddTx(tx *atomic.Tx) error {
m.lock.Lock()
defer m.lock.Unlock()
return m.addTx(tx, true, true)
}
// checkConflictTx checks for any transactions in the mempool that spend the
// same input UTXOs as the provided transaction. If any conflicts are present,
// it returns the highest gas price of any conflicting transaction, the ID of
// the corresponding tx and the full list of conflicting transactions.
func (m *Mempool) checkConflictTx(tx *atomic.Tx) (uint256.Int, ids.ID, []*atomic.Tx, error) {
utxoSet := tx.InputUTXOs()
var ( //nolint:prealloc
highestGasPrice uint256.Int
highestGasPriceConflictTxID ids.ID
// We don't know the length ahead of time (# of conflicts), so we don't want to preallocate
conflictingTxs []*atomic.Tx
)
for utxoID := range utxoSet {
// Get current gas price of the existing tx in the mempool
conflictTx, ok := m.utxoSpenders[utxoID]
if !ok {
continue
}
conflictTxGasPrice, err := atomic.EffectiveGasPrice(conflictTx, m.ctx.AVAXAssetID, true)
// Should never error to calculate the gas price of a transaction
// already in the mempool
if err != nil {
return uint256.Int{}, ids.ID{}, conflictingTxs, fmt.Errorf("failed to re-calculate gas price for conflict tx due to: %w", err)
}
if highestGasPrice.Lt(&conflictTxGasPrice) {
highestGasPrice = conflictTxGasPrice
highestGasPriceConflictTxID = conflictTx.ID()
}
conflictingTxs = append(conflictingTxs, conflictTx)
}
return highestGasPrice, highestGasPriceConflictTxID, conflictingTxs, nil
}
// Assumes the lock is held.
func (m *Mempool) length() int {
return m.pendingTxs.Len() + len(m.currentTxs) + len(m.issuedTxs)
}
// addTx attempts to add tx to the mempool.
//
// Unless local, discarded transactions can not be added.
// If force, conflict checks are skipped.
//
// Assumes lock is held.
func (m *Mempool) addTx(tx *atomic.Tx, local bool, force bool) error {
// If the tx has already been included in the mempool, there's no need to
// add it again.
txID := tx.ID()
if _, exists := m.issuedTxs[txID]; exists {
return fmt.Errorf("%w: tx %s was issued previously", ErrAlreadyKnown, txID)
}
if _, exists := m.currentTxs[txID]; exists {
return fmt.Errorf("%w: tx %s is being built into a block", ErrAlreadyKnown, txID)
}
if _, exists := m.pendingTxs.Get(txID); exists {
return fmt.Errorf("%w: tx %s is pending", ErrAlreadyKnown, txID)
}
if !local {
if _, exists := m.discardedTxs.Get(txID); exists {
return fmt.Errorf("%w: tx %s was discarded", ErrAlreadyKnown, txID)
}
}
if !force && m.verify != nil {
if err := m.verify(tx); err != nil {
return err
}
}
gasPrice, err := atomic.EffectiveGasPrice(tx, m.ctx.AVAXAssetID, true)
if err != nil {
return err
}
highestGasPrice, highestGasPriceConflictTxID, conflictingTxs, err := m.checkConflictTx(tx)
if err != nil {
return err
}
if len(conflictingTxs) != 0 && !force {
// If the transaction does not have a higher fee than all of its
// conflicts, we refuse to add it to the mempool. (Prefer items already
// in the mempool).
if !gasPrice.Gt(&highestGasPrice) {
return fmt.Errorf(
"%w: issued tx (%s) gas price %d <= conflict tx (%s) gas price %d (%d total conflicts in mempool)",
ErrConflict,
txID,
gasPrice,
highestGasPriceConflictTxID,
highestGasPrice,
len(conflictingTxs),
)
}
// Remove all conflicting transactions from the mempool.
for _, conflictTx := range conflictingTxs {
m.removeTx(conflictTx, true)
}
}
// If adding this transaction would exceed the mempool's size, check if
// there is a lower priced transaction that can be evicted from the mempool.
//
// Recall that the size of the mempool is denominated in transactions, so to
// add a new transaction we only need to evict at most one other
// transaction.
if m.length() >= m.maxSize {
if m.pendingTxs.Len() == 0 {
// This could occur if we have used our entire size allowance on
// transactions that are either Current or Issued.
return ErrMempoolFull
}
// Get the transaction with the lowest gasPrice
minTx, minGasPrice := m.pendingTxs.PeekMin()
// If the new tx doesn't have a higher fee than the transaction it
// would replace, discard new transaction. (Prefer items already
// in the mempool).
if !gasPrice.Gt(&minGasPrice) {
return fmt.Errorf(
"%w currentMin=%d provided=%d",
ErrInsufficientFee,
minGasPrice,
gasPrice,
)
}
m.removeTx(minTx, true)
}
// If the transaction was recently discarded, log the event and evict from
// discarded transactions so it's not in two places within the mempool.
// We allow the transaction to be re-issued since it may have been invalid
// due to an atomic UTXO not being present yet.
if _, has := m.discardedTxs.Get(txID); has {
log.Debug("Adding recently discarded transaction back to the mempool",
"txID", txID,
)
m.discardedTxs.Evict(txID)
}
// Mark the transaction as Pending.
m.pendingTxs.Push(tx, gasPrice)
m.metrics.addedTxs.Inc(1)
m.metrics.pendingTxs.Update(int64(m.pendingTxs.Len()))
for utxoID := range tx.InputUTXOs() {
m.utxoSpenders[utxoID] = tx
}
m.bloom.Add(tx)
reset, err := gossip.ResetBloomFilterIfNeeded(m.bloom, m.length()*config.TxGossipBloomChurnMultiplier)
if err != nil {
return err
}
if reset {
log.Debug("resetting bloom filter", "reason", "reached max filled ratio")
for _, pendingTx := range m.pendingTxs.minHeap.items {
m.bloom.Add(pendingTx.tx)
}
// Current transactions must be added to the bloom filter as well
// because they could be added back into the pending set without going
// through addTx again.
for _, currentTx := range m.currentTxs {
m.bloom.Add(currentTx)
}
}
// When adding a transaction to the mempool, we make sure that there is an
// item in Pending to signal the VM to produce a block.
select {
case m.pending <- struct{}{}:
default:
}
return nil
}
func (m *Mempool) BloomFilter() (*bloom.Filter, ids.ID) {
m.lock.RLock()
defer m.lock.RUnlock()
return m.bloom.BloomFilter()
}