/
utils.go
232 lines (201 loc) · 6.32 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
package utils
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"time"
"github.com/33cn/chain33/common"
"github.com/33cn/chain33/common/address"
"github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/system/crypto/secp256k1"
"github.com/33cn/chain33/types"
chain33Types "github.com/33cn/chain33/types"
ebrelayerChain33 "github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/relayer/chain33"
ebTypes "github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/types"
evmAbi "github.com/33cn/plugin/plugin/dapp/evm/executor/abi"
evmtypes "github.com/33cn/plugin/plugin/dapp/evm/types"
"github.com/golang/protobuf/proto"
)
type TxCreateInfo struct {
PrivateKey string
Expire string
Note string
Fee int64
ParaName string
ChainID int32
}
type Chain33OfflineTx struct {
ContractAddr string
TxHash string
SignedRawTx string
OperationName string
Interval time.Duration
}
func CreateContractAndSign(txCreateInfo *TxCreateInfo, code, abi, parameter, contractName string) (string, []byte, error) {
var action evmtypes.EVMContractAction
bCode, err := common.FromHex(code)
exector := types.GetExecName("evm", txCreateInfo.ParaName)
to := address.ExecAddress(exector)
if err != nil {
return "", nil, errors.New(contractName + " parse evm code error " + err.Error())
}
action = evmtypes.EVMContractAction{Amount: 0, Code: bCode, GasLimit: 0, GasPrice: 0, Note: txCreateInfo.Note, Alias: contractName, ContractAddr: to}
if parameter != "" {
constructorPara := "constructor(" + parameter + ")"
packData, err := evmAbi.PackContructorPara(constructorPara, abi)
if err != nil {
return "", nil, errors.New(contractName + " " + constructorPara + " Pack Contructor Para error:" + err.Error())
}
action.Code = append(action.Code, packData...)
}
data, txHash, err := CreateAndSignEvmTx(txCreateInfo.ChainID, &action, exector, txCreateInfo.PrivateKey, txCreateInfo.Expire, txCreateInfo.Fee)
if err != nil {
return "", nil, errors.New(contractName + " create contract error:" + err.Error())
}
return data, txHash, nil
}
func CreateAndSignEvmTx(chainID int32, action proto.Message, execer, privateKeyStr, expire string, fee int64) (string, []byte, error) {
tx := &types.Transaction{Execer: []byte(execer), Payload: types.Encode(action), Fee: fee, To: address.ExecAddress(execer), ChainID: chainID}
expireInt64, err := types.ParseExpire(expire)
if nil != err {
return "", nil, err
}
if expireInt64 > types.ExpireBound {
if expireInt64 < int64(time.Second*120) {
expireInt64 = int64(time.Second * 120)
}
//用秒数来表示的时间
tx.Expire = types.Now().Unix() + expireInt64/int64(time.Second)
} else {
tx.Expire = expireInt64
}
tx.Fee = int64(1e7)
if tx.Fee < fee {
tx.Fee += fee
}
random := rand.New(rand.NewSource(time.Now().UnixNano()))
tx.Nonce = random.Int63()
tx.ChainID = chainID
var driver secp256k1.Driver
privateKeySli, err := common.FromHex(privateKeyStr)
if nil != err {
return "", nil, err
}
privateKey, err := driver.PrivKeyFromBytes(privateKeySli)
if nil != err {
return "", nil, err
}
tx.Sign(types.SECP256K1, privateKey)
txData := types.Encode(tx)
dataStr := common.ToHex(txData)
return dataStr, tx.Hash(), nil
}
func WriteContractFile(fileName string, content string) {
err := ioutil.WriteFile(fileName, []byte(content), 0666)
if err != nil {
fmt.Println("Failed to write to file:", fileName)
}
fmt.Println("tx is written to file: ", fileName)
}
func CallContractAndSign(txCreateInfo *TxCreateInfo, action *evmtypes.EVMContractAction, contractAddr string) (string, []byte, error) {
exector := types.GetExecName("evm", txCreateInfo.ParaName)
data, txHash, err := CreateAndSignEvmTx(txCreateInfo.ChainID, action, exector, txCreateInfo.PrivateKey, txCreateInfo.Expire, txCreateInfo.Fee)
if err != nil {
return "", nil, errors.New(contractAddr + " call contract error:" + err.Error())
}
return data, txHash, nil
}
func ParseFileInJson(file string, result interface{}) error {
_, err := os.Stat(file)
if err != nil {
fmt.Println(err.Error())
return err
}
f, err := os.Open(file)
if err != nil {
panic(err)
}
b, err := ioutil.ReadAll(f)
if err != nil {
panic(err)
}
return json.Unmarshal(b, result)
}
func WriteToFileInJson(fileName string, content interface{}) {
jbytes, err := json.MarshalIndent(content, "", "\t")
if err != nil {
panic(err)
}
err = ioutil.WriteFile(fileName, jbytes, 0666)
if err != nil {
fmt.Println("Failed to write to file:", fileName)
}
fmt.Println("Txs are written to file", fileName)
}
func SendSignTxs2Chain33(filePath, rpcUrl string) {
var rdata []*Chain33OfflineTx
var retData []*Chain33OfflineTx
err := ParseFileInJson(filePath, &rdata)
if err != nil {
fmt.Printf("parse file with error:%s, make sure file:%s exist \n", err.Error(), filePath)
return
}
for _, deployInfo := range rdata {
txhash, err := sendTransactionRpc(deployInfo.SignedRawTx, rpcUrl)
if nil != err {
fmt.Printf("Failed to send %s to chain33 due to error:%s \n", deployInfo.OperationName, err.Error())
return
}
if deployInfo.Interval != 0 {
time.Sleep(deployInfo.Interval)
}
countTime := 0
for {
result := ebrelayerChain33.GetTxStatusByHashesRpc(txhash, rpcUrl)
//等待交易执行
if ebTypes.Invalid_Chain33Tx_Status == result {
time.Sleep(time.Second)
countTime++
// 超过2分钟 超时退出
if countTime > 120 {
fmt.Println("time out txhash: ", txhash)
return
}
continue
}
if result != chain33Types.ExecOk {
fmt.Println("Failed to send txhash: ", txhash, "result: ", result)
return
} else {
break
}
}
retData = append(retData, &Chain33OfflineTx{TxHash: txhash, ContractAddr: deployInfo.ContractAddr, OperationName: deployInfo.OperationName})
}
data, err := json.MarshalIndent(retData, "", " ")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Println(string(data))
}
func sendTransactionRpc(data, rpcLaddr string) (string, error) {
params := rpctypes.RawParm{
Data: data,
}
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.SendTransaction", params, nil)
var txhex string
rpc, err := jsonclient.NewJSONClient(ctx.Addr)
if err != nil {
return "", err
}
err = rpc.Call(ctx.Method, ctx.Params, &txhex)
if err != nil {
return "", err
}
return txhex, nil
}