/
utils.go
314 lines (273 loc) · 9.39 KB
/
utils.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
package ethtxs
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"math/big"
"sync"
"time"
"github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethinterface"
"github.com/33cn/plugin/plugin/dapp/x2ethereum/ebrelayer/ethtxs"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
//EthTxStatus ...
type EthTxStatus int32
type NonceMutex struct {
Nonce int64
RWLock *sync.RWMutex
}
var (
addr2Nonce = make(map[common.Address]NonceMutex)
ErrGetSuggestGasPrice = errors.New("ErrGetSuggestGasPrice")
ErrNodeNetwork = errors.New("ErrNodeNetwork")
)
//String ...
func (ethTxStatus EthTxStatus) String() string {
return [...]string{"Fail", "Success", "Pending"}[ethTxStatus]
}
//const
const (
PendingDuration4TxExeuction = 300
EthTxPending = EthTxStatus(2)
)
// fromChain 是否从链上获取
func getNonce4MultiEth(sender common.Address, client ethinterface.EthClientSpec, addr2TxNonce map[common.Address]*NonceMutex, fromChain bool) (*big.Int, error) {
if fromChain == false {
if nonceMutex, exist := addr2TxNonce[sender]; exist {
nonceMutex.RWLock.Lock()
defer nonceMutex.RWLock.Unlock()
nonceMutex.Nonce++
addr2TxNonce[sender] = nonceMutex
txslog.Debug("getNonce from cache", "address", sender.String(), "nonce", nonceMutex.Nonce)
return big.NewInt(nonceMutex.Nonce), nil
}
}
nonce, err := client.PendingNonceAt(context.Background(), sender)
if nil != err {
return nil, err
}
txslog.Debug("getNonce", "address", sender.String(), "nonce", nonce, "fromChain", fromChain)
n := new(NonceMutex)
n.Nonce = int64(nonce)
n.RWLock = new(sync.RWMutex)
addr2TxNonce[sender] = n
return big.NewInt(int64(nonce)), nil
}
func revokeNonce4MultiEth(sender common.Address, addr2TxNonce map[common.Address]*NonceMutex) (*big.Int, error) {
if nonceMutex, exist := addr2TxNonce[sender]; exist {
nonceMutex.RWLock.Lock()
defer nonceMutex.RWLock.Unlock()
nonceMutex.Nonce--
addr2TxNonce[sender] = nonceMutex
txslog.Debug("revokeNonce", "address", sender.String(), "nonce", nonceMutex.Nonce)
return big.NewInt(nonceMutex.Nonce), nil
}
return nil, errors.New("address doesn't exist tx")
}
func getNonce(sender common.Address, client ethinterface.EthClientSpec) (*big.Int, error) {
if nonceMutex, exist := addr2Nonce[sender]; exist {
nonceMutex.RWLock.Lock()
defer nonceMutex.RWLock.Unlock()
nonceMutex.Nonce++
addr2Nonce[sender] = nonceMutex
txslog.Debug("getNonce from cache", "address", sender.String(), "nonce", nonceMutex.Nonce)
return big.NewInt(nonceMutex.Nonce), nil
}
nonce, err := client.PendingNonceAt(context.Background(), sender)
if nil != err {
return nil, err
}
txslog.Debug("getNonce", "address", sender.String(), "nonce", nonce)
n := new(NonceMutex)
n.Nonce = int64(nonce)
n.RWLock = new(sync.RWMutex)
addr2Nonce[sender] = *n
return big.NewInt(int64(nonce)), nil
}
func revokeNonce(sender common.Address) (*big.Int, error) {
if nonceMutex, exist := addr2Nonce[sender]; exist {
nonceMutex.RWLock.Lock()
defer nonceMutex.RWLock.Unlock()
nonceMutex.Nonce--
addr2Nonce[sender] = nonceMutex
txslog.Debug("revokeNonce", "address", sender.String(), "nonce", nonceMutex.Nonce)
return big.NewInt(nonceMutex.Nonce), nil
}
return nil, errors.New("address doesn't exist tx")
}
//PrepareAuth ...
func PrepareAuth(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, transactor common.Address) (*bind.TransactOpts, error) {
if nil == privateKey || nil == client {
txslog.Error("PrepareAuth", "nil input parameter", "client", client, "privateKey", privateKey)
return nil, errors.New("nil input parameter")
}
ctx := context.Background()
gasPrice, err := client.SuggestGasPrice(ctx)
if err != nil {
txslog.Error("PrepareAuth", "Failed to SuggestGasPrice due to:", err.Error())
return nil, errors.New("failed to get suggest gas price " + err.Error())
}
chainID, err := client.NetworkID(ctx)
if err != nil {
txslog.Error("PrepareAuth NetworkID", "err", err)
return nil, err
}
_, isSim := client.(*ethinterface.SimExtend)
if isSim {
chainID = big.NewInt(1337)
}
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
txslog.Error("PrepareAuth NewKeyedTransactorWithChainID", "err", err, "chainID", chainID)
return nil, err
}
auth.Value = big.NewInt(0) // in wei
auth.GasLimit = GasLimit4Deploy
auth.GasPrice = gasPrice
if auth.Nonce, err = getNonce(transactor, client); err != nil {
return nil, err
}
return auth, nil
}
func PrepareAuth4MultiEthereum(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, transactor common.Address, addr2TxNonce map[common.Address]*NonceMutex) (*bind.TransactOpts, error) {
if nil == privateKey || nil == client {
txslog.Error("PrepareAuth", "nil input parameter", "client", client, "privateKey", privateKey)
return nil, errors.New("nil input parameter")
}
ctx := context.Background()
gasPrice, err := client.SuggestGasPrice(ctx)
if err != nil {
txslog.Error("PrepareAuth", "Failed to SuggestGasPrice due to:", err.Error())
return nil, errors.New("failed to get suggest gas price " + err.Error())
}
chainID, err := client.NetworkID(ctx)
if err != nil {
txslog.Error("PrepareAuth NetworkID", "err", err)
return nil, err
}
_, isSim := client.(*ethinterface.SimExtend)
if isSim {
chainID = big.NewInt(1337)
}
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
txslog.Error("PrepareAuth NewKeyedTransactorWithChainID", "err", err, "chainID", chainID)
return nil, err
}
auth.Value = big.NewInt(0) // in wei
auth.GasLimit = GasLimit4Deploy
auth.GasPrice = gasPrice
if auth.Nonce, err = getNonce4MultiEth(transactor, client, addr2TxNonce, false); err != nil {
return nil, err
}
return auth, nil
}
func PrepareAuth4MultiEthereumOpt(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, transactor common.Address, addr2TxNonce map[common.Address]*NonceMutex, chainID *big.Int) (*bind.TransactOpts, error) {
if nil == privateKey || nil == client {
txslog.Error("PrepareAuth", "nil input parameter", "client", client, "privateKey", privateKey)
return nil, errors.New("nil input parameter")
}
ctx := context.Background()
gasPrice, err := client.SuggestGasPrice(ctx)
if err != nil {
txslog.Error("PrepareAuth", "Failed to SuggestGasPrice due to:", err.Error())
return nil, ErrGetSuggestGasPrice
}
auth, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
if err != nil {
txslog.Error("PrepareAuth NewKeyedTransactorWithChainID", "err", err, "chainID", chainID)
return nil, err
}
auth.Value = big.NewInt(0) // in wei
auth.GasLimit = GasLimit4Deploy
auth.GasPrice = gasPrice
if auth.Nonce, err = getNonce4MultiEth(transactor, client, addr2TxNonce, false); err != nil {
return nil, err
}
return auth, nil
}
func waitEthTxFinished(client ethinterface.EthClientSpec, txhash common.Hash, txName, providerHttp string) error {
sim, isSim := client.(*ethinterface.SimExtend)
if isSim {
fmt.Println("in waitEthTxFinished Use the simulator")
sim.Commit()
return nil
}
txslog.Info(txName, "Wait for tx to be finished executing with hash", txhash.String())
timeout := time.NewTimer(PendingDuration4TxExeuction * time.Second)
oneSecondtimeout := time.NewTicker(5 * time.Second)
count := 0
for {
select {
case <-timeout.C:
txslog.Info(txName, "tx", "eth tx timeout")
return errors.New("eth tx timeout")
case <-oneSecondtimeout.C:
_, err := client.TransactionReceipt(context.Background(), txhash)
if err == ethereum.NotFound {
continue
} else if err != nil {
if count < 5 {
count++
client, err = ethtxs.SetupWebsocketEthClient(providerHttp)
if err != nil {
txslog.Error("waitEthTxFinished", "Failed to SetupWebsocketEthClient due to:", err.Error(), "count", count)
continue
}
}
return err
}
txslog.Info(txName, "Finished executing for tx", txhash.String())
return nil
}
}
}
//GetEthTxStatus ...
func GetEthTxStatus(client ethinterface.EthClientSpec, txhash common.Hash) string {
receipt, err := client.TransactionReceipt(context.Background(), txhash)
if nil != err {
return EthTxPending.String()
}
status := EthTxStatus(receipt.Status).String()
if status != EthTxPending.String() {
txslog.Info("GetEthTxStatus", "Eth tx hash", txhash.String(), "status", status, "BlockNum", receipt.BlockNumber.Int64())
}
return status
}
func NewTransferTx(clientSpec ethinterface.EthClientSpec, from, to common.Address, input []byte, value *big.Int, addr2TxNonce map[common.Address]*NonceMutex, fromChain bool) (*types.Transaction, error) {
price, err := clientSpec.SuggestGasPrice(context.Background())
if err != nil {
return nil, err
}
nonce, err := getNonce4MultiEth(from, clientSpec, addr2TxNonce, fromChain)
if err != nil {
return nil, err
}
var gas uint64 = 21000
if input != nil {
//var msg ethereum.CallMsg
//msg.To = &to
//msg.Data = input
//gas, err = clientSpec.EstimateGas(context.Background(), msg)
//if err != nil {
// //return nil,err
// txslog.Error("handleLogWithdraw", "EstimateGas err", err)
// gas = 80000
//}
//实际测试"cumulativeGasUsed": "0xdc82",
gas = uint64(80000)
}
ntx := types.NewTx(&types.LegacyTx{
Nonce: nonce.Uint64(),
GasPrice: price,
To: &to,
Data: input,
Value: value,
Gas: gas,
})
return ntx, nil
}