-
Notifications
You must be signed in to change notification settings - Fork 168
/
backend.go
223 lines (189 loc) · 5.87 KB
/
backend.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
package eth
import (
"context"
"errors"
"fmt"
"math/big"
"strings"
"sync"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/params"
"github.com/golang/glog"
"github.com/livepeer/go-livepeer/eth/contracts"
)
var abis = []string{
contracts.BondingManagerABI,
contracts.ControllerABI,
contracts.LivepeerTokenABI,
contracts.LivepeerTokenFaucetABI,
contracts.MinterABI,
contracts.RoundsManagerABI,
contracts.ServiceRegistryABI,
contracts.TicketBrokerABI,
contracts.PollABI,
}
var abiMap = makeABIMap()
type Backend interface {
ethereum.ChainStateReader
ethereum.TransactionReader
ethereum.TransactionSender
ethereum.ContractCaller
ethereum.PendingContractCaller
ethereum.PendingStateReader
ethereum.GasEstimator
ethereum.GasPricer
ethereum.LogFilterer
ethereum.ChainReader
ChainID(ctx context.Context) (*big.Int, error)
GasPriceMonitor() *GasPriceMonitor
SuggestGasTipCap(context.Context) (*big.Int, error)
}
type backend struct {
*ethclient.Client
nonceManager *NonceManager
signer types.Signer
gpm *GasPriceMonitor
tm *TransactionManager
sync.RWMutex
}
func NewBackend(client *ethclient.Client, signer types.Signer, gpm *GasPriceMonitor, tm *TransactionManager) Backend {
return &backend{
Client: client,
nonceManager: NewNonceManager(client),
signer: signer,
gpm: gpm,
tm: tm,
}
}
func (b *backend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
b.nonceManager.Lock(account)
defer b.nonceManager.Unlock(account)
return b.nonceManager.Next(account)
}
func (b *backend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
// Use the transaction manager instead of the ethereum client
if err := b.tm.SendTransaction(ctx, tx); err != nil {
return err
}
sender, err := types.Sender(b.signer, tx)
if err != nil {
return err
}
// update local nonce
b.nonceManager.Lock(sender)
b.nonceManager.Update(sender, tx.Nonce())
b.nonceManager.Unlock(sender)
return nil
}
func (b *backend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
// Use the gas price monitor instead of the ethereum client to suggest a gas price
gp := b.gpm.GasPrice()
maxGp := b.gpm.MaxGasPrice()
if maxGp != nil && gp.Cmp(maxGp) > 0 {
return nil, fmt.Errorf("current gas price exceeds maximum gas price max=%v GWei current=%v GWei",
FromWei(maxGp, params.GWei),
FromWei(gp, params.GWei),
)
}
return gp, nil
}
func (b *backend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
// This runs the max gas price check against the value returned by eth_gasPrice which should be priority fee + base fee.
// We may use the returned value later on to derive the priority fee if the eth_maxPriorityFeePerGas method is not supported.
gasPrice, err := b.SuggestGasPrice(ctx)
if err != nil {
return nil, err
}
tip, err := b.Client.SuggestGasTipCap(ctx)
if err != nil {
// SuggestGasTipCap() uses the eth_maxPriorityFeePerGas RPC call under the hood which
// is not a part of the ETH JSON-RPC spec.
// In the future, eth_maxPriorityFeePerGas can be replaced with an eth_feeHistory based algorithm (see https://github.com/ethereum/go-ethereum/issues/23479).
// For now, if the provider does not support eth_maxPriorityFeePerGas (i.e. not geth), then we calculate the priority fee as
// eth_gasPrice - baseFee.
head, err := b.HeaderByNumber(ctx, nil)
if err != nil {
return nil, err
}
if head.BaseFee == nil {
return nil, errors.New("missing base fee")
}
tip = new(big.Int).Sub(gasPrice, head.BaseFee)
}
return tip, nil
}
func (b *backend) GasPriceMonitor() *GasPriceMonitor {
return b.gpm
}
type txLog struct {
method string
inputs string
}
func (b *backend) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
return b.retryRemoteCall(func() ([]byte, error) {
return b.Client.CallContract(ctx, msg, blockNumber)
})
}
func (b *backend) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) {
return b.retryRemoteCall(func() ([]byte, error) {
return b.Client.PendingCallContract(ctx, msg)
})
}
func (b *backend) retryRemoteCall(remoteCall func() ([]byte, error)) (out []byte, err error) {
count := 3 // consider making this a package-level global constant
retry := true // consider making this a package-level global constant
for i := 0; i < count && retry; i++ {
out, err = remoteCall()
if err != nil && (err.Error() == "EOF" || err.Error() == "tls: use of closed connection") {
glog.V(4).Infof("Retrying call to remote ethereum node")
} else {
retry = false
}
}
return out, err
}
func makeABIMap() map[string]*abi.ABI {
abiMap := make(map[string]*abi.ABI)
for _, ABI := range abis {
parsedAbi, err := abi.JSON(strings.NewReader(ABI))
if err != nil {
glog.Errorf("Error creating ABI map err=%v", err)
return map[string]*abi.ABI{}
}
for _, m := range parsedAbi.Methods {
abiMap[string(m.ID)] = &parsedAbi
}
}
return abiMap
}
func newTxLog(tx *types.Transaction) (txLog, error) {
var txParamsString string
data := tx.Data()
if len(data) < 4 {
return txLog{}, errors.New("no method signature")
}
methodSig := data[:4]
abi, ok := abiMap[string(methodSig)]
if !ok {
return txLog{}, errors.New("unknown ABI")
}
method, err := abi.MethodById(methodSig)
if err != nil {
return txLog{}, err
}
txParams := make(map[string]interface{})
if err := decodeTxParams(abiMap[string(methodSig)], txParams, data); err != nil {
return txLog{}, err
}
for _, arg := range method.Inputs {
txParamsString += fmt.Sprintf("%v: %v ", arg.Name, txParams[arg.Name])
}
return txLog{
method: method.Name,
inputs: strings.TrimSpace(txParamsString),
}, nil
}