forked from blocktree/quorum-adapter
/
manager.go
705 lines (621 loc) · 18.6 KB
/
manager.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/*
* Copyright 2018 The openwallet Authors
* This file is part of the openwallet library.
*
* The openwallet library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The openwallet library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package quorum
import (
"encoding/json"
"fmt"
"reflect"
"github.com/assetsadapterstore/klaytn-adapter/quorum_addrdec"
"github.com/assetsadapterstore/klaytn-adapter/quorum_rpc"
"github.com/blocktree/go-owcrypt"
"github.com/blocktree/openwallet/v2/common"
"github.com/blocktree/openwallet/v2/log"
"github.com/blocktree/openwallet/v2/openwallet"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
ethcom "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
// "log"
"math/big"
"strings"
)
type WalletManager struct {
openwallet.AssetsAdapterBase
RawClient *ethclient.Client //原生ETH客户端
WalletClient *quorum_rpc.Client // 节点客户端
BroadcastClient *quorum_rpc.Client // 节点客户端
Config *WalletConfig //钱包管理配置
Blockscanner openwallet.BlockScanner //区块扫描器
Decoder openwallet.AddressDecoderV2 //地址编码器
TxDecoder openwallet.TransactionDecoder //交易单编码器
ContractDecoder openwallet.SmartContractDecoder //智能合约解释器
Log *log.OWLogger //日志工具
CustomAddressEncodeFunc func(address string) string //自定义地址转换算法
CustomAddressDecodeFunc func(address string) string //自定义地址转换算法
}
func NewWalletManager() *WalletManager {
wm := WalletManager{}
wm.Config = NewConfig(Symbol)
wm.Blockscanner = NewBlockScanner(&wm)
wm.Decoder = &quorum_addrdec.Default
wm.TxDecoder = NewTransactionDecoder(&wm)
wm.ContractDecoder = &EthContractDecoder{wm: &wm}
wm.Log = log.NewOWLogger(wm.Symbol())
wm.CustomAddressEncodeFunc = CustomAddressEncode
wm.CustomAddressDecodeFunc = CustomAddressDecode
return &wm
}
func (wm *WalletManager) GetTransactionCount(addr string) (uint64, error) {
addr = wm.CustomAddressDecodeFunc(addr)
params := []interface{}{
AppendOxToAddress(addr),
"latest",
}
if wm.WalletClient == nil {
return 0, fmt.Errorf("wallet client is not initialized")
}
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_getTransactionCount", params)
if err != nil {
return 0, err
}
nonceStr := result.String()
return hexutil.DecodeUint64(nonceStr)
}
func (wm *WalletManager) GetTransactionReceipt(transactionId string) (*TransactionReceipt, error) {
params := []interface{}{
transactionId,
}
var ethReceipt *types.Receipt
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_getTransactionReceipt", params)
if err != nil {
return nil, err
}
ethReceipt, err = UnmarshalReceiptJSON([]byte(result.Raw))
if err != nil {
return nil, err
}
txReceipt := &TransactionReceipt{ETHReceipt: ethReceipt, Raw: result.Raw}
return txReceipt, nil
}
func (wm *WalletManager) GetTransactionByHash(txid string) (*BlockTransaction, error) {
params := []interface{}{
AppendOxToAddress(txid),
}
var tx BlockTransaction
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_getTransactionByHash", params)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(result.Raw), &tx)
if err != nil {
return nil, err
}
blockHeight, err := hexutil.DecodeUint64(tx.BlockNumber)
if err != nil {
blockHeight = 0
}
tx.BlockHeight = blockHeight
tx.From = wm.CustomAddressEncodeFunc(tx.From)
tx.To = wm.CustomAddressEncodeFunc(tx.To)
return &tx, nil
}
func (wm *WalletManager) GetBlockByNum(blockNum uint64, showTransactionSpec bool) (*EthBlock, error) {
params := []interface{}{
hexutil.EncodeUint64(blockNum),
showTransactionSpec,
}
var ethBlock EthBlock
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_getBlockByNumber", params)
if err != nil {
return nil, err
}
if showTransactionSpec {
err = json.Unmarshal([]byte(result.Raw), ðBlock)
} else {
err = json.Unmarshal([]byte(result.Raw), ðBlock.BlockHeader)
}
if err != nil {
return nil, err
}
ethBlock.BlockHeight, err = hexutil.DecodeUint64(ethBlock.BlockNumber)
if err != nil {
return nil, err
}
return ðBlock, nil
}
func (wm *WalletManager) RecoverUnscannedTransactions(unscannedTxs []*openwallet.UnscanRecord) ([]*BlockTransaction, error) {
allTxs := make([]*BlockTransaction, 0, len(unscannedTxs))
for _, unscanned := range unscannedTxs {
tx, err := wm.GetTransactionByHash(unscanned.TxID)
if err != nil {
return nil, err
}
allTxs = append(allTxs, tx)
}
return allTxs, nil
}
// ERC20GetAddressBalance
func (wm *WalletManager) ERC20GetAddressBalance(address string, contractAddr string) (*big.Int, error) {
address = wm.CustomAddressDecodeFunc(address)
contractAddr = wm.CustomAddressDecodeFunc(contractAddr)
address = AppendOxToAddress(address)
contractAddr = AppendOxToAddress(contractAddr)
//abi编码
data, err := wm.EncodeABIParam(ERC20_ABI, "balanceOf", address)
if err != nil {
return nil, err
}
//toAddr := ethcom.HexToAddress(contractAddr)
callMsg := CallMsg{
From: ethcom.HexToAddress(address),
To: ethcom.HexToAddress(contractAddr),
Data: data,
Value: big.NewInt(0),
}
result, err := wm.EthCall(callMsg, "latest")
if err != nil {
return nil, err
}
rMap, _, err := wm.DecodeABIResult(ERC20_ABI, "balanceOf", result)
if err != nil {
return nil, err
}
balance, ok := rMap[""].(*big.Int)
if !ok {
return big.NewInt(0), fmt.Errorf("balance type is not big.Int ")
}
return balance, nil
}
// GetAddrBalance
func (wm *WalletManager) GetAddrBalance(address string, sign string) (*big.Int, error) {
address = wm.CustomAddressDecodeFunc(address)
params := []interface{}{
AppendOxToAddress(address),
sign,
}
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_getBalance", params)
if err != nil {
return big.NewInt(0), err
}
balance, err := hexutil.DecodeBig(result.String())
if err != nil {
return big.NewInt(0), err
}
return balance, nil
}
// GetBlockNumber
func (wm *WalletManager) GetBlockNumber() (uint64, error) {
param := make([]interface{}, 0)
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_blockNumber", param)
if err != nil {
return 0, err
}
return hexutil.DecodeUint64(result.String())
}
func (wm *WalletManager) GetTransactionFeeEstimated(from string, to string, value *big.Int, data []byte) (*txFeeInfo, error) {
var (
gasLimit *big.Int
gasPrice *big.Int
err error
)
if wm.Config.FixGasLimit.Cmp(big.NewInt(0)) > 0 {
//配置设置固定gasLimit
gasLimit = wm.Config.FixGasLimit
} else {
//动态计算gas消耗
gasLimit, err = wm.GetGasEstimated(from, to, value, data)
if err != nil {
return nil, err
}
}
if wm.Config.FixGasPrice.Cmp(big.NewInt(0)) > 0 {
//配置设置固定gasLimit
gasPrice = wm.Config.FixGasPrice
} else {
//动态计算gasPrice
gasPrice, err = wm.GetGasPrice()
if err != nil {
return nil, err
}
gasPrice.Add(gasPrice, wm.Config.OffsetsGasPrice)
}
// fee := new(big.Int)
// fee.Mul(gasLimit, gasPrice)
feeInfo := &txFeeInfo{
GasLimit: gasLimit,
GasPrice: gasPrice,
// Fee: fee,
}
feeInfo.CalcFee()
return feeInfo, nil
}
// GetGasEstimated
func (wm *WalletManager) GetGasEstimated(from string, to string, value *big.Int, data []byte) (*big.Int, error) {
//toAddr := ethcom.HexToAddress(to)
callMsg := map[string]interface{}{
"from": wm.CustomAddressDecodeFunc(from),
"to": wm.CustomAddressDecodeFunc(to),
"data": hexutil.Encode(data),
}
if value != nil {
callMsg["value"] = hexutil.EncodeBig(value)
}
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_estimateGas", []interface{}{callMsg})
if err != nil {
return big.NewInt(0), err
}
gasLimit, err := common.StringValueToBigInt(result.String(), 16)
if err != nil {
return big.NewInt(0), fmt.Errorf("convert estimated gas[%v] format to bigint failed, err = %v\n", result.String(), err)
}
if data != nil {
//当data有值时,代表交易是调用合约, gasLimit = gasLimit * 1.1,确保gas足够
gasLimit = gasLimit.Mul(gasLimit, big.NewInt(110))
gasLimit = gasLimit.Div(gasLimit, big.NewInt(100))
}
return gasLimit, nil
}
func (wm *WalletManager) GetGasPrice() (*big.Int, error) {
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_gasPrice", []interface{}{})
if err != nil {
return big.NewInt(0), err
}
gasLimit, err := common.StringValueToBigInt(result.String(), 16)
if err != nil {
return big.NewInt(0), fmt.Errorf("convert estimated gas[%v] format to bigint failed, err = %v\n", result.String(), err)
}
return gasLimit, nil
}
func (wm *WalletManager) SetNetworkChainID() (uint64, error) {
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_chainId", nil)
if err != nil {
return 0, err
}
id, err := hexutil.DecodeUint64(result.String())
if err != nil {
return 0, err
}
wm.Config.ChainID = id
//wm.Log.Debugf("Network chainID: %d", wm.Config.ChainID)
return id, nil
}
// EncodeABIParam 编码API调用参数
func (wm *WalletManager) EncodeABIParam(abiInstance abi.ABI, abiParam ...string) ([]byte, error) {
var (
args = make([]interface{}, 0)
)
if len(abiParam) == 0 {
return nil, fmt.Errorf("abi param length is empty")
}
method := abiParam[0]
//转化string参数为abi调用参数
abiMethod, ok := abiInstance.Methods[method]
if !ok {
return nil, fmt.Errorf("abi method can not found")
}
abiArgs := abiParam[1:]
if len(abiMethod.Inputs) != len(abiArgs) {
return nil, fmt.Errorf("abi input arguments is: %d, except is : %d", len(abiArgs), len(abiMethod.Inputs))
}
for i, input := range abiMethod.Inputs {
//var a interface{}
a, err := convertStringParamToABIParam(input.Type, abiArgs[i])
if err != nil {
return nil, err
}
args = append(args, a)
}
return abiInstance.Pack(method, args...)
}
// DecodeABIResult 解码ABI结果
func (wm *WalletManager) DecodeABIResult(abiInstance abi.ABI, method string, dataHex string) (map[string]interface{}, string, error) {
var (
err error
resultJSON []byte
result = make(CallResult)
)
data, _ := hexutil.Decode(dataHex)
if len(data) == 0 {
return result, "", nil
}
err = abiInstance.UnpackIntoMap(result, method, data)
if err != nil {
return result, string(resultJSON), err
}
resultJSON, err = result.MarshalJSON()
return result, string(resultJSON), err
}
// DecodeReceiptLogResult 解码回执日志结果
func (wm *WalletManager) DecodeReceiptLogResult(abiInstance abi.ABI, log types.Log) (map[string]interface{}, string, string, error) {
var (
err error
resultJSON []byte
result = make(CallResult)
event *abi.Event
)
bc := bind.NewBoundContract(ethcom.HexToAddress("0x0"), abiInstance, nil, nil, nil)
//wm.Log.Debugf("log.txid: %s", log.TxHash.String())
//wm.Log.Debugf("log.Topics[0]: %s", log.Topics[0].Hex())
//for _, e := range abiInstance.Events {
// wm.Log.Debugf("event: %s, ID: %s", e.Name, e.ID().Hex())
//}
event, err = abiInstance.EventByID(log.Topics[0])
if err != nil {
return result, "", "", err
}
err = bc.UnpackLogIntoMap(result, event.Name, log)
if err != nil {
return result, "", "", err
}
resultJSON, err = result.MarshalJSON()
return result, event.Name, string(resultJSON), err
}
func (wm *WalletManager) EthCall(callMsg CallMsg, sign string) (string, error) {
param := map[string]interface{}{
"from": callMsg.From.String(),
"to": callMsg.To.String(),
"value": hexutil.EncodeBig(callMsg.Value),
"data": hexutil.Encode(callMsg.Data),
}
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_call", []interface{}{param, sign})
if err != nil {
return "", err
}
return result.String(), nil
}
// SendRawTransaction
func (wm *WalletManager) SendRawTransaction(signedTx string) (string, error) {
params := []interface{}{
signedTx,
}
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_sendRawTransaction", params)
if err != nil {
return "", err
}
return result.String(), nil
}
// IsContract 是否合约
func (wm *WalletManager) IsContract(address string) (bool, error) {
params := []interface{}{
wm.CustomAddressDecodeFunc(address),
"latest",
}
result, err := wm.WalletClient.Call(strings.ToLower(wm.Config.Symbol)+"_getCode", params)
if err != nil {
return false, err
}
if result.String() == "0x" {
return false, nil
} else {
return true, nil
}
}
// GetAddressNonce
func (wm *WalletManager) GetAddressNonce(wrapper openwallet.WalletDAI, address string) uint64 {
var (
key = wm.Symbol() + "-nonce"
nonce uint64
nonce_db interface{}
nonce_onchain uint64
err error
)
//NonceComputeMode = 0时,使用外部系统的自增值
if wm.Config.NonceComputeMode == 0 {
//获取db记录的nonce并确认nonce值
nonce_db, _ = wrapper.GetAddressExtParam(address, key)
//判断nonce_db是否为空,为空则说明当前nonce是0
if nonce_db == nil {
nonce = 0
} else {
nonce = common.NewString(nonce_db).UInt64()
}
}
nonce_onchain, err = wm.GetTransactionCount(address)
if err != nil {
return nonce
}
//如果本地nonce_db > 链上nonce,采用本地nonce,否则采用链上nonce
if nonce > nonce_onchain {
//wm.Log.Debugf("%s nonce_db=%v > nonce_chain=%v,Use nonce_db...", address, nonce_db, nonce_onchain)
} else {
nonce = nonce_onchain
//wm.Log.Debugf("%s nonce_db=%v <= nonce_chain=%v,Use nonce_chain...", address, nonce_db, nonce_onchain)
}
//wm.Log.Debugf("nonce: %v", nonce)
return nonce
}
// UpdateAddressNonce
func (wm *WalletManager) UpdateAddressNonce(wrapper openwallet.WalletDAI, address string, nonce uint64) {
key := wm.Symbol() + "-nonce"
err := wrapper.SetAddressExtParam(address, key, nonce)
if err != nil {
wm.Log.Errorf("WalletDAI SetAddressExtParam failed, err: %v", err)
}
}
func AppendOxToAddress(addr string) string {
if strings.Index(addr, "0x") == -1 {
return "0x" + addr
}
return addr
}
func removeOxFromHex(value string) string {
result := value
if strings.Index(value, "0x") != -1 {
result = common.Substr(value, 2, len(value))
}
return result
}
// convertStringParamToABIParam string参数转为ABI参数
func convertStringParamToABIParam(inputType abi.Type, abiArg string) (interface{}, error) {
var (
err error
a interface{}
)
switch inputType.T {
case abi.BoolTy:
a = common.NewString(abiArg).Bool()
case abi.UintTy, abi.IntTy:
a, err = convertParamToNum(abiArg, inputType)
case abi.AddressTy:
a = ethcom.HexToAddress(AppendOxToAddress(abiArg))
case abi.FixedBytesTy, abi.BytesTy, abi.HashTy:
slice, decodeErr := hexutil.Decode(AppendOxToAddress(abiArg))
if decodeErr != nil {
slice = owcrypt.Hash([]byte(abiArg), 0, owcrypt.HASH_ALG_KECCAK256)
//return nil, fmt.Errorf("abi input hex string can not convert byte, err: %v", decodeErr)
}
var fixBytes [32]byte
copy(fixBytes[:], slice)
a = fixBytes
case abi.StringTy:
a = abiArg
case abi.ArrayTy, abi.SliceTy:
subArgs := strings.Split(abiArg, ",")
a, err = convertArrayParamToABIParam(*inputType.Elem, subArgs)
}
if err != nil {
return nil, err
}
return a, nil
}
//convertArrayParamToABIParam 数组参数转化
func convertArrayParamToABIParam(inputType abi.Type, subArgs []string) (interface{}, error) {
var (
err error
a interface{}
)
switch inputType.T {
case abi.BoolTy:
arr := make([]bool, 0)
for _, subArg := range subArgs {
elem, subErr := convertStringParamToABIParam(inputType, subArg)
if subErr != nil {
err = subErr
break
}
arr = append(arr, elem.(bool))
}
a = arr
case abi.UintTy:
arr := make([]uint, 0)
for _, subArg := range subArgs {
elem, subErr := convertStringParamToABIParam(inputType, subArg)
if subErr != nil {
err = subErr
break
}
arr = append(arr, elem.(uint))
}
a = arr
case abi.IntTy:
arr := make([]int, 0)
for _, subArg := range subArgs {
elem, subErr := convertStringParamToABIParam(inputType, subArg)
if subErr != nil {
err = subErr
break
}
arr = append(arr, elem.(int))
}
a = arr
case abi.AddressTy:
arr := make([]ethcom.Address, 0)
for _, subArg := range subArgs {
elem, subErr := convertStringParamToABIParam(inputType, subArg)
if subErr != nil {
err = subErr
break
}
arr = append(arr, elem.(ethcom.Address))
}
a = arr
case abi.FixedBytesTy, abi.BytesTy, abi.HashTy:
arr := make([][32]byte, 0)
for _, subArg := range subArgs {
elem, subErr := convertStringParamToABIParam(inputType, subArg)
if subErr != nil {
err = subErr
break
}
arr = append(arr, elem.([32]byte))
}
a = arr
case abi.StringTy:
arr := make([]string, 0)
for _, subArg := range subArgs {
elem, subErr := convertStringParamToABIParam(inputType, subArg)
if subErr != nil {
err = subErr
break
}
arr = append(arr, elem.(string))
}
a = arr
}
if err != nil {
return nil, err
}
return a, nil
}
func convertParamToNum(param string, abiType abi.Type) (interface{}, error) {
var (
base int
bInt *big.Int
err error
)
if strings.HasPrefix(param, "0x") {
base = 16
} else {
base = 10
}
bInt, err = common.StringValueToBigInt(param, base)
if err != nil {
return nil, err
}
switch abiType.Kind {
case reflect.Uint:
return uint(bInt.Uint64()), nil
case reflect.Uint8:
return uint8(bInt.Uint64()), nil
case reflect.Uint16:
return uint16(bInt.Uint64()), nil
case reflect.Uint32:
return uint32(bInt.Uint64()), nil
case reflect.Uint64:
return uint64(bInt.Uint64()), nil
case reflect.Int:
return int(bInt.Int64()), nil
case reflect.Int8:
return int8(bInt.Int64()), nil
case reflect.Int16:
return int16(bInt.Int64()), nil
case reflect.Int32:
return int32(bInt.Int64()), nil
case reflect.Int64:
return int64(bInt.Int64()), nil
case reflect.Ptr:
return bInt, nil
default:
return nil, fmt.Errorf("abi input arguments: %v is invaild integer type", param)
}
}
func CustomAddressEncode(address string) string {
return address
}
func CustomAddressDecode(address string) string {
return address
}