This repository has been archived by the owner on Dec 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 535
/
Copy pathaccount.go
386 lines (305 loc) · 8.75 KB
/
account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package txpool
import (
"sync"
"sync/atomic"
"github.com/0xPolygon/polygon-edge/types"
)
// Thread safe map of all accounts registered by the pool.
// Each account (value) is bound to one address (key).
type accountsMap struct {
sync.Map
count uint64
maxEnqueuedLimit uint64
}
// Initializes an account for the given address.
func (m *accountsMap) initOnce(addr types.Address, nonce uint64) *account {
a, loaded := m.LoadOrStore(addr, &account{
enqueued: newAccountQueue(),
promoted: newAccountQueue(),
nonceToTx: newNonceToTxLookup(),
maxEnqueued: m.maxEnqueuedLimit,
nextNonce: nonce,
})
newAccount := a.(*account) //nolint:forcetypeassert
if !loaded {
// update global count if it was a store
atomic.AddUint64(&m.count, 1)
}
return newAccount
}
// exists checks if an account exists within the map.
func (m *accountsMap) exists(addr types.Address) bool {
_, ok := m.Load(addr)
return ok
}
// getPrimaries collects the heads (first-in-line transaction)
// from each of the promoted queues.
func (m *accountsMap) getPrimaries() (primaries []*types.Transaction) {
m.Range(func(key, value interface{}) bool {
addressKey, ok := key.(types.Address)
if !ok {
return false
}
account := m.get(addressKey)
account.promoted.lock(false)
defer account.promoted.unlock()
// add head of the queue
if tx := account.promoted.peek(); tx != nil {
primaries = append(primaries, tx)
}
return true
})
return primaries
}
// get returns the account associated with the given address.
func (m *accountsMap) get(addr types.Address) *account {
a, ok := m.Load(addr)
if !ok {
return nil
}
fetchedAccount, ok := a.(*account)
if !ok {
return nil
}
return fetchedAccount
}
// promoted returns the number of all promoted transactons.
func (m *accountsMap) promoted() (total uint64) {
m.Range(func(key, value interface{}) bool {
accountKey, ok := key.(types.Address)
if !ok {
return false
}
account := m.get(accountKey)
account.promoted.lock(false)
defer account.promoted.unlock()
total += account.promoted.length()
return true
})
return
}
// allTxs returns all promoted and all enqueued transactions, depending on the flag.
func (m *accountsMap) allTxs(includeEnqueued bool) (
allPromoted, allEnqueued map[types.Address][]*types.Transaction,
) {
allPromoted = make(map[types.Address][]*types.Transaction)
allEnqueued = make(map[types.Address][]*types.Transaction)
m.Range(func(key, value interface{}) bool {
addr, _ := key.(types.Address)
account := m.get(addr)
account.promoted.lock(false)
defer account.promoted.unlock()
if account.promoted.length() != 0 {
allPromoted[addr] = account.promoted.queue
}
if includeEnqueued {
account.enqueued.lock(false)
defer account.enqueued.unlock()
if account.enqueued.length() != 0 {
allEnqueued[addr] = account.enqueued.queue
}
}
return true
})
return
}
type nonceToTxLookup struct {
mapping map[uint64]*types.Transaction
mutex sync.Mutex
}
func newNonceToTxLookup() *nonceToTxLookup {
return &nonceToTxLookup{
mapping: make(map[uint64]*types.Transaction),
}
}
func (m *nonceToTxLookup) lock() {
m.mutex.Lock()
}
func (m *nonceToTxLookup) unlock() {
m.mutex.Unlock()
}
func (m *nonceToTxLookup) get(nonce uint64) *types.Transaction {
return m.mapping[nonce]
}
func (m *nonceToTxLookup) set(tx *types.Transaction) {
m.mapping[tx.Nonce] = tx
}
func (m *nonceToTxLookup) reset() {
m.mapping = make(map[uint64]*types.Transaction)
}
func (m *nonceToTxLookup) remove(txs ...*types.Transaction) {
for _, tx := range txs {
delete(m.mapping, tx.Nonce)
}
}
// An account is the core structure for processing
// transactions from a specific address. The nextNonce
// field is what separates the enqueued from promoted transactions:
//
// 1. enqueued - transactions higher than the nextNonce
// 2. promoted - transactions lower than the nextNonce
//
// If an enqueued transaction matches the nextNonce,
// a promoteRequest is signaled for this account
// indicating the account's enqueued transaction(s)
// are ready to be moved to the promoted queue.
// lock order is important! promoted.lock(true), enqueued.lock(true), nonceToTx.lock()
type account struct {
enqueued, promoted *accountQueue
nonceToTx *nonceToTxLookup
nextNonce uint64
demotions uint64
// the number of consecutive blocks that don't contain account's transaction
skips uint64
// maximum number of enqueued transactions
maxEnqueued uint64
}
// getNonce returns the next expected nonce for this account.
func (a *account) getNonce() uint64 {
return atomic.LoadUint64(&a.nextNonce)
}
// setNonce sets the next expected nonce for this account.
func (a *account) setNonce(nonce uint64) {
atomic.StoreUint64(&a.nextNonce, nonce)
}
// Demotions returns the current value of demotions
func (a *account) Demotions() uint64 {
return a.demotions
}
// resetDemotions sets 0 to demotions to clear count
func (a *account) resetDemotions() {
a.demotions = 0
}
// incrementDemotions increments demotions
func (a *account) incrementDemotions() {
a.demotions++
}
// reset aligns the account with the new nonce
// by pruning all transactions with nonce lesser than new.
// After pruning, a promotion may be signaled if the first
// enqueued transaction matches the new nonce.
func (a *account) reset(nonce uint64, promoteCh chan<- promoteRequest) (
prunedPromoted,
prunedEnqueued []*types.Transaction,
) {
a.promoted.lock(true)
a.enqueued.lock(true)
a.nonceToTx.lock()
defer func() {
a.nonceToTx.unlock()
a.enqueued.unlock()
a.promoted.unlock()
}()
// prune the promoted txs
prunedPromoted = a.promoted.prune(nonce)
a.nonceToTx.remove(prunedPromoted...)
if nonce <= a.getNonce() {
// only the promoted queue needed pruning
return
}
// prune the enqueued txs
prunedEnqueued = a.enqueued.prune(nonce)
a.nonceToTx.remove(prunedEnqueued...)
// update nonce expected for this account
a.setNonce(nonce)
// it is important to signal promotion while
// the locks are held to ensure no other
// handler will mutate the account
if first := a.enqueued.peek(); first != nil && first.Nonce == nonce {
// first enqueued tx is expected -> signal promotion
promoteCh <- promoteRequest{account: first.From}
}
return
}
// enqueue push the transaction onto the enqueued queue or replace it
func (a *account) enqueue(tx *types.Transaction, replace bool) {
replaceInQueue := func(queue minNonceQueue) bool {
for i, x := range queue {
if x.Nonce == tx.Nonce {
queue[i] = tx // replace
return true
}
}
return false
}
a.nonceToTx.set(tx)
if !replace {
a.enqueued.push(tx)
} else {
// first -> try to replace in enqueued
if !replaceInQueue(a.enqueued.queue) {
// .. then try to replace in promoted
replaceInQueue(a.promoted.queue)
}
}
}
// Promote moves eligible transactions from enqueued to promoted.
//
// Eligible transactions are all sequential in order of nonce
// and the first one has to have nonce less (or equal) to the account's
// nextNonce.
func (a *account) promote() (promoted []*types.Transaction, pruned []*types.Transaction) {
a.promoted.lock(true)
a.enqueued.lock(true)
defer func() {
a.enqueued.unlock()
a.promoted.unlock()
}()
// sanity check
currentNonce := a.getNonce()
if a.enqueued.length() == 0 || a.enqueued.peek().Nonce > currentNonce {
// nothing to promote
return
}
nextNonce := a.enqueued.peek().Nonce
// move all promotable txs (enqueued txs that are sequential in nonce)
// to the account's promoted queue
for {
tx := a.enqueued.peek()
if tx == nil || tx.Nonce != nextNonce {
break
}
// pop from enqueued
tx = a.enqueued.pop()
// push to promoted
a.promoted.push(tx)
// update counters
nextNonce = tx.Nonce + 1
// prune the transactions with lower nonce
pruned = append(pruned, a.enqueued.prune(nextNonce)...)
// update return result
promoted = append(promoted, tx)
}
// only update the nonce map if the new nonce
// is higher than the one previously stored.
if nextNonce > currentNonce {
a.setNonce(nextNonce)
}
a.nonceToTx.lock()
a.nonceToTx.remove(pruned...)
a.nonceToTx.unlock()
return
}
// resetSkips sets 0 to skips
func (a *account) resetSkips() {
atomic.StoreUint64(&a.skips, 0)
}
// incrementSkips increments skips
func (a *account) incrementSkips() uint64 {
return atomic.AddUint64(&a.skips, 1)
}
// getLowestTx returns the transaction with lowest nonce, which might be popped next
// this method don't pop a transaction from both queues
func (a *account) getLowestTx() *types.Transaction {
a.promoted.lock(true)
defer a.promoted.unlock()
if firstPromoted := a.promoted.peek(); firstPromoted != nil {
return firstPromoted
}
a.enqueued.lock(true)
defer a.enqueued.unlock()
if firstEnqueued := a.enqueued.peek(); firstEnqueued != nil {
return firstEnqueued
}
return nil
}