-
Notifications
You must be signed in to change notification settings - Fork 19
/
transaction_send.go
296 lines (249 loc) · 9.87 KB
/
transaction_send.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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"code.vegaprotocol.io/vega/cmd/vegawallet/commands/cli"
"code.vegaprotocol.io/vega/cmd/vegawallet/commands/flags"
"code.vegaprotocol.io/vega/cmd/vegawallet/commands/printer"
vgzap "code.vegaprotocol.io/vega/libs/zap"
"code.vegaprotocol.io/vega/paths"
coreversion "code.vegaprotocol.io/vega/version"
"code.vegaprotocol.io/vega/wallet/api"
walletnode "code.vegaprotocol.io/vega/wallet/api/node"
networkStore "code.vegaprotocol.io/vega/wallet/network/store/v1"
"code.vegaprotocol.io/vega/wallet/version"
"code.vegaprotocol.io/vega/wallet/wallets"
"github.com/spf13/cobra"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
sendTransactionLong = cli.LongDesc(`
Send a transaction to a Vega node via the gRPC API. The transaction can be sent to
any node of a registered network or to a specific node address.
The transaction should be a Vega transaction formatted as a JSON payload, as follows:
'{"commandName": {"someProperty": "someValue"} }'
For vote submission, it will look like this:
'{"voteSubmission": {"proposalId": "some-id", "value": "VALUE_YES"}}'
`)
sendTransactionExample = cli.Examples(`
# Send a transaction to a registered network
{{.Software}} transaction send --network NETWORK --wallet WALLET --pubkey PUBKEY TRANSACTION
# Send a transaction to a specific Vega node address
{{.Software}} transaction send --node-address ADDRESS --wallet WALLET --pubkey PUBKEY TRANSACTION
# Send a transaction with a log level set to debug
{{.Software}} transaction send --network NETWORK --wallet WALLET --pubkey PUBKEY --level debug TRANSACTION
# Send a transaction with a maximum of 10 retries
{{.Software}} transaction send --network NETWORK --wallet WALLET --pubkey PUBKEY --retries 10 TRANSACTION
# Send a transaction with a maximum request duration of 10 seconds
{{.Software}} transaction send --network NETWORK --wallet WALLET --pubkey PUBKEY --max-request-duration "10s" TRANSACTION
# Send a transaction to a registered network without verifying network version compatibility
{{.Software}} transaction send --network NETWORK --wallet WALLET --pubkey PUBKEY --no-version-check TRANSACTION
`)
)
type SendTransactionHandler func(api.AdminSendTransactionParams, string, *zap.Logger) (api.AdminSendTransactionResult, error)
func NewCmdSendTransaction(w io.Writer, rf *RootFlags) *cobra.Command {
handler := func(params api.AdminSendTransactionParams, passphrase string, log *zap.Logger) (api.AdminSendTransactionResult, error) {
ctx := context.Background()
vegaPaths := paths.New(rf.Home)
walletStore, err := wallets.InitialiseStore(rf.Home, false)
if err != nil {
return api.AdminSendTransactionResult{}, fmt.Errorf("couldn't initialise wallets store: %w", err)
}
defer walletStore.Close()
ns, err := networkStore.InitialiseStore(vegaPaths)
if err != nil {
return api.AdminSendTransactionResult{}, fmt.Errorf("couldn't initialise network store: %w", err)
}
if _, errDetails := api.NewAdminUnlockWallet(walletStore).Handle(ctx, api.AdminUnlockWalletParams{
Wallet: params.Wallet,
Passphrase: passphrase,
}); errDetails != nil {
return api.AdminSendTransactionResult{}, errors.New(errDetails.Data)
}
sendTx := api.NewAdminSendTransaction(walletStore, ns, func(hosts []string, retries uint64, requestTTL time.Duration) (walletnode.Selector, error) {
return walletnode.BuildRoundRobinSelectorWithRetryingNodes(log, hosts, retries, requestTTL)
})
rawResult, errDetails := sendTx.Handle(ctx, params)
if errDetails != nil {
return api.AdminSendTransactionResult{}, errors.New(errDetails.Data)
}
return rawResult.(api.AdminSendTransactionResult), nil
}
return BuildCmdSendTransaction(w, handler, rf)
}
func BuildCmdSendTransaction(w io.Writer, handler SendTransactionHandler, rf *RootFlags) *cobra.Command {
f := &SendTransactionFlags{}
cmd := &cobra.Command{
Use: "send",
Short: "Send a transaction to a Vega node",
Long: sendTransactionLong,
Example: sendTransactionExample,
RunE: func(_ *cobra.Command, args []string) error {
if aLen := len(args); aLen == 0 {
return flags.ArgMustBeSpecifiedError("transaction")
} else if aLen > 1 {
return flags.TooManyArgsError("transaction")
}
f.RawTransaction = args[0]
req, pass, err := f.Validate()
if err != nil {
return err
}
log, err := buildCmdLogger(rf.Output, f.LogLevel)
if err != nil {
return fmt.Errorf("failed to build a logger: %w", err)
}
resp, err := handler(req, pass, log)
if err != nil {
return err
}
switch rf.Output {
case flags.InteractiveOutput:
PrintSendTransactionResponse(w, resp, rf)
case flags.JSONOutput:
return printer.FprintJSON(w, resp)
}
return nil
},
}
cmd.Flags().StringVarP(&f.Network,
"network", "n",
"",
"Network to which the transaction is sent",
)
cmd.Flags().StringVar(&f.NodeAddress,
"node-address",
"",
"Vega node address to which the transaction is sent",
)
cmd.Flags().StringVarP(&f.Wallet,
"wallet", "w",
"",
"Wallet holding the public key",
)
cmd.Flags().StringVarP(&f.PubKey,
"pubkey", "k",
"",
"Public key of the key pair to use for signing (hex-encoded)",
)
cmd.Flags().StringVarP(&f.PassphraseFile,
"passphrase-file", "p",
"",
"Path to the file containing the wallet's passphrase",
)
cmd.Flags().StringVar(&f.LogLevel,
"level",
zapcore.InfoLevel.String(),
fmt.Sprintf("Set the log level: %v", vgzap.SupportedLogLevels),
)
cmd.Flags().Uint64Var(&f.Retries,
"retries",
defaultRequestRetryCount,
"Number of retries when contacting the Vega node",
)
cmd.Flags().DurationVar(&f.MaximumRequestDuration,
"max-request-duration",
defaultMaxRequestDuration,
"Maximum duration the wallet will wait for a node to respond. Supported format: <number>+<time unit>. Valid time units are `s` and `m`.",
)
cmd.Flags().BoolVar(&f.NoVersionCheck,
"no-version-check",
false,
"Do not check for network version compatibility",
)
autoCompleteNetwork(cmd, rf.Home)
autoCompleteWallet(cmd, rf.Home, "wallet")
autoCompleteLogLevel(cmd)
return cmd
}
type SendTransactionFlags struct {
Network string
NodeAddress string
Wallet string
PubKey string
PassphraseFile string
Retries uint64
LogLevel string
RawTransaction string
NoVersionCheck bool
MaximumRequestDuration time.Duration
}
func (f *SendTransactionFlags) Validate() (api.AdminSendTransactionParams, string, error) {
if len(f.Wallet) == 0 {
return api.AdminSendTransactionParams{}, "", flags.MustBeSpecifiedError("wallet")
}
if len(f.LogLevel) == 0 {
return api.AdminSendTransactionParams{}, "", flags.MustBeSpecifiedError("level")
}
if err := vgzap.EnsureIsSupportedLogLevel(f.LogLevel); err != nil {
return api.AdminSendTransactionParams{}, "", err
}
if len(f.NodeAddress) == 0 && len(f.Network) == 0 {
return api.AdminSendTransactionParams{}, "", flags.OneOfFlagsMustBeSpecifiedError("network", "node-address")
}
if len(f.NodeAddress) != 0 && len(f.Network) != 0 {
return api.AdminSendTransactionParams{}, "", flags.MutuallyExclusiveError("network", "node-address")
}
if len(f.PubKey) == 0 {
return api.AdminSendTransactionParams{}, "", flags.MustBeSpecifiedError("pubkey")
}
if len(f.RawTransaction) == 0 {
return api.AdminSendTransactionParams{}, "", flags.ArgMustBeSpecifiedError("transaction")
}
passphrase, err := flags.GetPassphrase(f.PassphraseFile)
if err != nil {
return api.AdminSendTransactionParams{}, "", err
}
// Encode transaction into a nested structure; this is a bit nasty but mirroring what happens
// when our json-rpc library parses a request. There's an issue (6983#) to make the use
// json.RawMessage instead.
transaction := make(map[string]any)
if err := json.Unmarshal([]byte(f.RawTransaction), &transaction); err != nil {
return api.AdminSendTransactionParams{}, "", fmt.Errorf("couldn't unmarshal transaction: %w", err)
}
params := api.AdminSendTransactionParams{
Wallet: f.Wallet,
PublicKey: f.PubKey,
Network: f.Network,
NodeAddress: f.NodeAddress,
Retries: f.Retries,
Transaction: transaction,
SendingMode: "TYPE_ASYNC",
MaximumRequestDuration: f.MaximumRequestDuration,
}
return params, passphrase, nil
}
func PrintSendTransactionResponse(w io.Writer, res api.AdminSendTransactionResult, rf *RootFlags) {
p := printer.NewInteractivePrinter(w)
if rf.Output == flags.InteractiveOutput && version.IsUnreleased() {
str := p.String()
str.CrossMark().DangerText("You are running an unreleased version of the Vega wallet (").DangerText(coreversion.Get()).DangerText(").").NextLine()
str.Pad().DangerText("Use it at your own risk!").NextSection()
p.Print(str)
}
str := p.String()
defer p.Print(str)
str.CheckMark().SuccessText("Transaction sending successful").NextSection()
str.Text("Transaction Hash:").NextLine().WarningText(res.TransactionHash).NextSection()
str.Text("Sent at:").NextLine().WarningText(res.SentAt.Format(time.ANSIC)).NextSection()
str.Text("Selected node:").NextLine().WarningText(res.Node.Host).NextLine()
}