-
Notifications
You must be signed in to change notification settings - Fork 246
/
nonce.go
67 lines (56 loc) · 1.55 KB
/
nonce.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
package transactions
import (
"context"
"sync"
"github.com/ethereum/go-ethereum/common"
"github.com/status-im/status-go/eth-node/types"
)
type Nonce struct {
addrLock *AddrLocker
localNonce map[uint64]*sync.Map
}
func NewNonce() *Nonce {
return &Nonce{
addrLock: &AddrLocker{},
localNonce: make(map[uint64]*sync.Map),
}
}
func (n *Nonce) Next(rpcWrapper *rpcWrapper, from types.Address) (uint64, func(inc bool, nonce uint64), error) {
n.addrLock.LockAddr(from)
current, err := n.GetCurrent(rpcWrapper, from)
unlock := func(inc bool, nonce uint64) {
if inc {
if _, ok := n.localNonce[rpcWrapper.chainID]; !ok {
n.localNonce[rpcWrapper.chainID] = &sync.Map{}
}
n.localNonce[rpcWrapper.chainID].Store(from, nonce+1)
}
n.addrLock.UnlockAddr(from)
}
return current, unlock, err
}
func (n *Nonce) GetCurrent(rpcWrapper *rpcWrapper, from types.Address) (uint64, error) {
var (
localNonce uint64
remoteNonce uint64
)
if _, ok := n.localNonce[rpcWrapper.chainID]; !ok {
n.localNonce[rpcWrapper.chainID] = &sync.Map{}
}
// get the local nonce
if val, ok := n.localNonce[rpcWrapper.chainID].Load(from); ok {
localNonce = val.(uint64)
}
// get the remote nonce
ctx := context.Background()
remoteNonce, err := rpcWrapper.PendingNonceAt(ctx, common.Address(from))
if err != nil {
return 0, err
}
// if upstream node returned nonce higher than ours we will use it, as it probably means
// that another client was used for sending transactions
if remoteNonce > localNonce {
return remoteNonce, nil
}
return localNonce, nil
}