-
Notifications
You must be signed in to change notification settings - Fork 12
/
tx.go
409 lines (380 loc) · 13.4 KB
/
tx.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
package cli
import (
"crypto/ecdsa"
"encoding/hex"
"fmt"
"os"
"strconv"
"strings"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/ethereum/go-ethereum/accounts/keystore"
gethcommon "github.com/ethereum/go-ethereum/common"
ethCrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/functionx/fx-core/v2/x/gravity/types"
)
const (
flagEthKeyType = "eth-key-type"
flagEthKeystore = "eth-keystore"
flagEthPassword = "eth-password"
)
func GetTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: "Gravity transaction subcommands",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand([]*cobra.Command{
// set delegate address
CmdSetOrchestratorAddress(),
// send to eth
CmdSendToEth(),
CmdCancelSendToEth(),
CmdRequestBatch(),
// validator consensus confirm
CmdValidatorSetConfirm(),
CmdRequestBatchConfirm(),
}...)
return cmd
}
func CmdSetOrchestratorAddress() *cobra.Command {
cmd := &cobra.Command{
Use: "set-orchestrator-address [validator-address] [orchestrator-address] [eth-address]",
Short: "Allows validators to delegate their voting responsibilities to a given key.",
Example: "fxcored tx gravity set-orchestrator-address fxvaloper1zgpzdf2uqla7hkx85wnn4p2r3duwqzd8wpk9j2 " +
"fx1zgpzdf2uqla7hkx85wnn4p2r3duwqzd8xst6v2 0xb86d4DC8e2C57190c1cfb834fE69A7a65E2756C2",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
validatorAddress, err := sdk.ValAddressFromBech32(args[0])
if err != nil {
return err
}
orchestratorAddress, err := sdk.AccAddressFromBech32(args[1])
if err != nil {
return err
}
ethAddress := args[2]
if !gethcommon.IsHexAddress(ethAddress) {
return fmt.Errorf("invalid eth address:%v", ethAddress)
}
msg := types.MsgSetOrchestratorAddress{
Validator: validatorAddress.String(),
Orchestrator: orchestratorAddress.String(),
EthAddress: ethAddress,
}
return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func CmdSendToEth() *cobra.Command {
cmd := &cobra.Command{
Use: "send-to-eth [eth-dest] [amount] [bridge-fee]",
Short: "Adds a new entry to the transaction pool to withdraw an amount from the Ethereum bridge contract",
Example: "fxcored tx gravity send-to-eth 0xb86d4DC8e2C57190c1cfb834fE69A7a65E2756C2 1000FX 20FX",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
sender := cliCtx.GetFromAddress()
if !gethcommon.IsHexAddress(args[0]) {
return sdkerrors.Wrap(fmt.Errorf("invalid bsd-dest address:%v", args[0]), "eth-dest")
}
amount, err := sdk.ParseCoinsNormalized(args[1])
if err != nil {
return sdkerrors.Wrap(err, "amount")
}
bridgeFee, err := sdk.ParseCoinsNormalized(args[2])
if err != nil {
return sdkerrors.Wrap(err, "bridge fee")
}
if len(amount) > 1 || len(bridgeFee) > 1 {
return fmt.Errorf("coin amounts too long, expecting just 1 coin amount for both amount and bridgeFee")
}
// Make the message
msg := types.MsgSendToEth{
Sender: sender.String(),
EthDest: args[0],
Amount: amount[0],
BridgeFee: bridgeFee[0],
}
return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func CmdCancelSendToEth() *cobra.Command {
cmd := &cobra.Command{
Use: "cancel-send-to-eth [txID]",
Short: "Cancel transaction send to eth",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
senderAddr := cliCtx.GetFromAddress()
txId, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
msg := types.NewMsgCancelSendToEth(senderAddr, txId)
return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func CmdRequestBatch() *cobra.Command {
cmd := &cobra.Command{
Use: "build-batch [token_contract] [minimum_fee] [eth_fee_receive]",
Short: "Build a new batch on the fxcore side for pooled withdrawal transactions",
Example: "fxcored tx gravity build-batch 0xb86d4DC8e2C57190c1cfb834fE69A7a65E2756C2 1 0xb86d4DC8e2C57190c1cfb834fE69A7a65E2756C2",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
fromAddress := cliCtx.GetFromAddress()
minimumFee, ok := sdk.NewIntFromString(args[1])
if !ok || minimumFee.IsNegative() {
return fmt.Errorf("miniumu fee is valid!!!fee:%v\n", args[1])
}
ethFeeReceive := args[2]
if !gethcommon.IsHexAddress(ethFeeReceive) {
return fmt.Errorf("invalid ethFeeReceive address:%v", args[2])
}
baseFee := sdk.ZeroInt()
baseFeeStr, err := cmd.Flags().GetString("base-fee")
if err == nil {
baseFeeStr = strings.TrimSpace(baseFeeStr)
if len(baseFeeStr) > 0 {
baseFee, ok = sdk.NewIntFromString(baseFeeStr)
if !ok {
return fmt.Errorf("invalid baseFee:%v", baseFeeStr)
}
}
}
msg := types.NewMsgRequestBatch(fromAddress, args[0], minimumFee, ethFeeReceive, baseFee)
return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg)
},
}
cmd.Flags().String("base-fee", "", "requestBatch baseFee, is empty is sdk.ZeroInt")
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func CmdRequestBatchConfirm() *cobra.Command {
cmd := &cobra.Command{
Use: "request-batch-confirm [contractAddress] [nonce] [...hexEthPrivate]",
Short: "Send valset confirm msg",
Example: fmt.Sprintf("1. fxcored tx gravity valset-confirm 0x30dA8589BFa1E509A319489E014d384b87815D89 1 hexEthPrivateKey --eth-key-type=hex\n" +
"2. fxcored tx gravity valset-confirm 0x30dA8589BFa1E509A319489E014d384b87815D89 1 --eth-key-type=keystore --eth-keystore=./key --eth-password=./password"),
Args: cobra.RangeArgs(2, 3),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
fromAddress := clientCtx.GetFromAddress()
contractAddress := args[0]
if !gethcommon.IsHexAddress(contractAddress) {
return fmt.Errorf("invalid contract address:%v", contractAddress)
}
nonce, err := strconv.ParseUint(args[1], 10, 64)
if err != nil {
return err
}
ethKeyType, err := cmd.Flags().GetString(flagEthKeyType)
if err != nil {
return err
}
var ethPrivateKey *ecdsa.PrivateKey
switch ethKeyType {
case "hex":
if len(args) < 3 {
return fmt.Errorf("eth-key-type=hex must input hexEthPrivateKey")
}
ethPrivateKey, err = recoveryPrivateKeyHexPrivateKey(args[2])
if err != nil {
return err
}
case "keystore":
keystoreFile, err := cmd.Flags().GetString(flagEthKeystore)
if err != nil {
return err
}
passwordFile, err := cmd.Flags().GetString(flagEthPassword)
if err != nil {
return err
}
ethPrivateKey, err = recoveryPrivateKeyByKeystore(keystoreFile, passwordFile)
if err != nil {
return err
}
default:
return fmt.Errorf("unknown eth-key-type flag:%v, support:(keystore|hex)", ethKeyType)
}
ethAddress := ethCrypto.PubkeyToAddress(ethPrivateKey.PublicKey)
queryClient := types.NewQueryClient(clientCtx)
batchRequestByNonceResp, err := queryClient.BatchRequestByNonce(cmd.Context(), &types.QueryBatchRequestByNonceRequest{
Nonce: nonce,
TokenContract: contractAddress,
})
if err != nil {
return err
}
if batchRequestByNonceResp.Batch == nil {
return fmt.Errorf("not found batch request by nonce!!!contractAddress:[%v], nonce:[%v]", contractAddress, nonce)
}
// Determine whether it has been confirmed
batchConfirmResp, err := queryClient.BatchConfirm(cmd.Context(), &types.QueryBatchConfirmRequest{
Nonce: nonce,
TokenContract: contractAddress,
Address: fromAddress.String(),
})
if err != nil {
return err
}
if batchConfirmResp.GetConfirm() != nil {
confirm := batchConfirmResp.GetConfirm()
return clientCtx.PrintString(fmt.Sprintf("already confirm requestBatch!!!\n\tnonce:[%v]\n\ttokenContract:[%v]\n\torchestrator:[%v]\n\tethAddress:[%v]\n\tsignature:[%v]\n",
confirm.Nonce, confirm.TokenContract, confirm.Orchestrator, confirm.EthSigner, confirm.Signature))
}
paramsResp, err := queryClient.Params(cmd.Context(), &types.QueryParamsRequest{})
if err != nil {
return err
}
checkpoint, err := batchRequestByNonceResp.GetBatch().GetCheckpoint(paramsResp.Params.GetGravityId())
if err != nil {
return err
}
signature, err := types.NewEthereumSignature(checkpoint, ethPrivateKey)
if err != nil {
return err
}
msg := types.NewMsgConfirmBatch(nonce, contractAddress, ethAddress.String(), hex.EncodeToString(signature), fromAddress)
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
}}
cmd.Flags().String(flagEthKeyType, "keystore", "eth private key type(keystore|hex), default:keystore")
cmd.Flags().String(flagEthKeystore, "", "eth keystore file")
cmd.Flags().String(flagEthPassword, "", "eth keystore password file")
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func CmdValidatorSetConfirm() *cobra.Command {
cmd := &cobra.Command{
Use: "valset-confirm [nonce] [...hexEthPrivate]",
Short: "Send valset confirm msg",
Example: fmt.Sprintf("1. fxcored tx gravity valset-confirm 1 hexEthPrivateKey --eth-key-type=hex\n" +
"2. fxcored tx gravity valset-confirm 1 --eth-key-type=keystore --eth-keystore=./key --eth-password=./password"),
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
fromAddress := clientCtx.GetFromAddress()
nonce, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
ethKeyType, err := cmd.Flags().GetString(flagEthKeyType)
if err != nil {
return err
}
var ethPrivateKey *ecdsa.PrivateKey
switch ethKeyType {
case "hex":
if len(args) < 2 {
return fmt.Errorf("eth-key-type=hex must input hexEthPrivateKey")
}
ethPrivateKey, err = recoveryPrivateKeyHexPrivateKey(args[1])
if err != nil {
return errors.WithStack(err)
}
case "keystore":
keystoreFile, err := cmd.Flags().GetString(flagEthKeystore)
if err != nil {
return err
}
passwordFile, err := cmd.Flags().GetString(flagEthPassword)
if err != nil {
return err
}
ethPrivateKey, err = recoveryPrivateKeyByKeystore(keystoreFile, passwordFile)
if err != nil {
return err
}
default:
return fmt.Errorf("unknown eth-key-type flag:%v, support:(keystore|hex)", ethKeyType)
}
ethAddress := ethCrypto.PubkeyToAddress(ethPrivateKey.PublicKey)
queryClient := types.NewQueryClient(clientCtx)
valsetRequestResp, err := queryClient.ValsetRequest(cmd.Context(), &types.QueryValsetRequestRequest{Nonce: nonce})
if err != nil {
return err
}
// Determine whether it has been confirmed
valsetConfirmResp, err := queryClient.ValsetConfirm(cmd.Context(), &types.QueryValsetConfirmRequest{
Nonce: nonce,
Address: fromAddress.String(),
})
if err != nil {
return err
}
if valsetConfirmResp.GetConfirm() != nil {
confirm := valsetConfirmResp.GetConfirm()
return fmt.Errorf("already confirm valset!!!\n\tnonce:[%v]\n\torchestrator:[%v]\n\tethAddress:[%v]\n\tsignature:[%v]\n", confirm.Nonce, confirm.Orchestrator, confirm.EthAddress, confirm.Signature)
}
paramsResp, err := queryClient.Params(cmd.Context(), &types.QueryParamsRequest{})
if err != nil {
return err
}
checkpoint := valsetRequestResp.GetValset().GetCheckpoint(paramsResp.Params.GetGravityId())
signature, err := types.NewEthereumSignature(checkpoint, ethPrivateKey)
if err != nil {
return err
}
msg := types.NewMsgValsetConfirm(nonce, ethAddress.String(), fromAddress, hex.EncodeToString(signature))
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
}}
cmd.Flags().String(flagEthKeyType, "keystore", "eth private key type(keystore|hex), default:keystore")
cmd.Flags().String(flagEthKeystore, "", "eth keystore file")
cmd.Flags().String(flagEthPassword, "", "eth keystore password file")
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func recoveryPrivateKeyByKeystore(keystoreFile, passwordFile string) (*ecdsa.PrivateKey, error) {
keystoreData, err := os.ReadFile(keystoreFile)
if err != nil {
return nil, errors.WithMessagef(err, "keystoreFile:[%s]", keystoreFile)
}
passwordData, err := os.ReadFile(passwordFile)
if err != nil {
return nil, errors.WithMessagef(err, "passwordFile:[%s]", keystoreFile)
}
decryptKey, err := keystore.DecryptKey(keystoreData, string(passwordData))
if err != nil {
return nil, errors.WithMessagef(err, "decryptKey err")
}
return decryptKey.PrivateKey, nil
}
func recoveryPrivateKeyHexPrivateKey(hexPrivateKey string) (*ecdsa.PrivateKey, error) {
return ethCrypto.HexToECDSA(hexPrivateKey)
}