-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
tx_multisign.go
420 lines (351 loc) · 11.3 KB
/
tx_multisign.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
package cli
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/protobuf/types/known/anypb"
errorsmod "cosmossdk.io/errors"
txsigning "cosmossdk.io/x/tx/signing"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig"
"github.com/cosmos/cosmos-sdk/crypto/types/multisig"
sdk "github.com/cosmos/cosmos-sdk/types"
signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing"
"github.com/cosmos/cosmos-sdk/version"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
"github.com/cosmos/cosmos-sdk/x/auth/signing"
)
// GetMultiSignCommand returns the multi-sign command
func GetMultiSignCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "multi-sign [file] [name] [[signature]...]",
Aliases: []string{"multisign"},
Short: "Generate multisig signatures for transactions generated offline",
Long: strings.TrimSpace(
fmt.Sprintf(`Sign transactions created with the --generate-only flag that require multisig signatures.
Read one or more signatures from one or more [signature] file, generate a multisig signature compliant to the
multisig key [name], and attach the key name to the transaction read from [file].
Example:
$ %s tx multisign transaction.json k1k2k3 k1sig.json k2sig.json k3sig.json
If --signature-only flag is on, output a JSON representation
of only the generated signature.
If the --offline flag is on, the client will not reach out to an external node.
Account number or sequence number lookups are not performed so you must
set these parameters manually.
The current multisig implementation defaults to amino-json sign mode.
The SIGN_MODE_DIRECT sign mode is not supported.'
`,
version.AppName,
),
),
RunE: makeMultiSignCmd(),
Args: cobra.MinimumNArgs(3),
}
cmd.Flags().Bool(flagSigOnly, false, "Print only the generated signature, then exit")
cmd.Flags().String(flags.FlagOutputDocument, "", "The document is written to the given file instead of STDOUT")
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func makeMultiSignCmd() func(cmd *cobra.Command, args []string) (err error) {
return func(cmd *cobra.Command, args []string) (err error) {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
parsedTx, err := authclient.ReadTxFromFile(clientCtx, args[0])
if err != nil {
return err
}
txFactory, err := tx.NewFactoryCLI(clientCtx, cmd.Flags())
if err != nil {
return err
}
if txFactory.SignMode() == signingtypes.SignMode_SIGN_MODE_UNSPECIFIED {
txFactory = txFactory.WithSignMode(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON)
}
txCfg := clientCtx.TxConfig
txBuilder, err := txCfg.WrapTxBuilder(parsedTx)
if err != nil {
return err
}
k, err := getMultisigRecord(clientCtx, args[1])
if err != nil {
return err
}
pubKey, err := k.GetPubKey()
if err != nil {
return err
}
addr, err := k.GetAddress()
if err != nil {
return err
}
multisigPub := pubKey.(*kmultisig.LegacyAminoPubKey)
multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys))
if !clientCtx.Offline {
accnum, seq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr)
if err != nil {
return err
}
txFactory = txFactory.WithAccountNumber(accnum).WithSequence(seq)
}
// read each signature and add it to the multisig if valid
for i := 2; i < len(args); i++ {
sigs, err := unmarshalSignatureJSON(clientCtx, args[i])
if err != nil {
return err
}
if txFactory.ChainID() == "" {
return fmt.Errorf("set the chain id with either the --chain-id flag or config file")
}
for _, sig := range sigs {
anyPk, err := codectypes.NewAnyWithValue(sig.PubKey)
if err != nil {
return err
}
txSignerData := txsigning.SignerData{
ChainID: txFactory.ChainID(),
AccountNumber: txFactory.AccountNumber(),
Sequence: txFactory.Sequence(),
Address: sdk.AccAddress(sig.PubKey.Address()).String(),
PubKey: &anypb.Any{
TypeUrl: anyPk.TypeUrl,
Value: anyPk.Value,
},
}
builtTx := txBuilder.GetTx()
adaptableTx, ok := builtTx.(signing.V2AdaptableTx)
if !ok {
return fmt.Errorf("expected Tx to be signing.V2AdaptableTx, got %T", builtTx)
}
txData := adaptableTx.GetSigningTxData()
err = signing.VerifySignature(cmd.Context(), sig.PubKey, txSignerData, sig.Data,
txCfg.SignModeHandler(), txData)
if err != nil {
addr, _ := sdk.AccAddressFromHexUnsafe(sig.PubKey.Address().String())
return fmt.Errorf("couldn't verify signature for address %s", addr)
}
if err := multisig.AddSignatureV2(multisigSig, sig, multisigPub.GetPubKeys()); err != nil {
return err
}
}
}
sigV2 := signingtypes.SignatureV2{
PubKey: multisigPub,
Data: multisigSig,
Sequence: txFactory.Sequence(),
}
err = txBuilder.SetSignatures(sigV2)
if err != nil {
return err
}
sigOnly, _ := cmd.Flags().GetBool(flagSigOnly)
var json []byte
json, err = marshalSignatureJSON(txCfg, txBuilder, sigOnly)
if err != nil {
return err
}
outputDoc, _ := cmd.Flags().GetString(flags.FlagOutputDocument)
if outputDoc == "" {
cmd.Printf("%s\n", json)
return nil
}
fp, err := os.OpenFile(outputDoc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
defer func() {
err2 := fp.Close()
if err == nil {
err = err2
}
}()
err = clientCtx.PrintBytes(json)
return err
}
}
func GetMultiSignBatchCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "multisign-batch [file] [name] [[signature-file]...]",
Aliases: []string{"multi-sign-batch"},
Short: "Assemble multisig transactions in batch from batch signatures",
Long: strings.TrimSpace(
fmt.Sprintf(`Assemble a batch of multisig transactions generated by batch sign command.
Read one or more signatures from one or more [signature] file, generate a multisig signature compliant to the
multisig key [name], and attach the key name to the transaction read from [file].
Example:
$ %s tx multisign-batch transactions.json multisigk1k2k3 k1sigs.json k2sigs.json k3sig.json
The current multisig implementation defaults to amino-json sign mode.
The SIGN_MODE_DIRECT sign mode is not supported.'
`, version.AppName,
),
),
PreRun: preSignCmd,
RunE: makeBatchMultisignCmd(),
Args: cobra.MinimumNArgs(3),
}
cmd.Flags().Bool(flagNoAutoIncrement, false, "disable sequence auto increment")
cmd.Flags().String(
flagMultisig, "",
"Address of the multisig account that the transaction signs on behalf of",
)
cmd.Flags().String(flags.FlagOutputDocument, "", "The document is written to the given file instead of STDOUT")
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func makeBatchMultisignCmd() func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) (err error) {
var clientCtx client.Context
clientCtx, err = client.GetClientTxContext(cmd)
if err != nil {
return err
}
txCfg := clientCtx.TxConfig
txFactory, err := tx.NewFactoryCLI(clientCtx, cmd.Flags())
if err != nil {
return err
}
if txFactory.SignMode() == signingtypes.SignMode_SIGN_MODE_UNSPECIFIED {
txFactory = txFactory.WithSignMode(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON)
}
// reads tx from args[0]
scanner, err := authclient.ReadTxsFromInput(txCfg, args[0])
if err != nil {
return err
}
k, err := getMultisigRecord(clientCtx, args[1])
if err != nil {
return err
}
var signatureBatch [][]signingtypes.SignatureV2
for i := 2; i < len(args); i++ {
sigs, err := readSignaturesFromFile(clientCtx, args[i])
if err != nil {
return err
}
signatureBatch = append(signatureBatch, sigs)
}
addr, err := k.GetAddress()
if err != nil {
return err
}
if !clientCtx.Offline {
accnum, seq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr)
if err != nil {
return err
}
txFactory = txFactory.WithAccountNumber(accnum).WithSequence(seq)
}
// prepare output document
closeFunc, err := setOutputFile(cmd)
if err != nil {
return err
}
defer closeFunc()
clientCtx.WithOutput(cmd.OutOrStdout())
for i := 0; scanner.Scan(); i++ {
txBldr, err := txCfg.WrapTxBuilder(scanner.Tx())
if err != nil {
return err
}
pubKey, err := k.GetPubKey()
if err != nil {
return err
}
multisigPub := pubKey.(*kmultisig.LegacyAminoPubKey)
multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys))
anyPk, err := codectypes.NewAnyWithValue(multisigPub)
if err != nil {
return err
}
txSignerData := txsigning.SignerData{
ChainID: txFactory.ChainID(),
AccountNumber: txFactory.AccountNumber(),
Sequence: txFactory.Sequence(),
Address: sdk.AccAddress(pubKey.Address()).String(),
PubKey: &anypb.Any{
TypeUrl: anyPk.TypeUrl,
Value: anyPk.Value,
},
}
builtTx := txBldr.GetTx()
adaptableTx, ok := builtTx.(signing.V2AdaptableTx)
if !ok {
return fmt.Errorf("expected Tx to be signing.V2AdaptableTx, got %T", builtTx)
}
txData := adaptableTx.GetSigningTxData()
for _, sig := range signatureBatch {
err = signing.VerifySignature(cmd.Context(), sig[i].PubKey, txSignerData, sig[i].Data,
txCfg.SignModeHandler(), txData)
if err != nil {
return fmt.Errorf("couldn't verify signature: %w %v", err, sig)
}
if err := multisig.AddSignatureV2(multisigSig, sig[i], multisigPub.GetPubKeys()); err != nil {
return err
}
}
sigV2 := signingtypes.SignatureV2{
PubKey: multisigPub,
Data: multisigSig,
Sequence: txFactory.Sequence(),
}
err = txBldr.SetSignatures(sigV2)
if err != nil {
return err
}
sigOnly, _ := cmd.Flags().GetBool(flagSigOnly)
var json []byte
json, err = marshalSignatureJSON(txCfg, txBldr, sigOnly)
if err != nil {
return err
}
err = clientCtx.PrintString(fmt.Sprintf("%s\n", json))
if err != nil {
return err
}
if viper.GetBool(flagNoAutoIncrement) {
continue
}
sequence := txFactory.Sequence() + 1
txFactory = txFactory.WithSequence(sequence)
}
return scanner.UnmarshalErr()
}
}
func unmarshalSignatureJSON(clientCtx client.Context, filename string) (sigs []signingtypes.SignatureV2, err error) {
var bytes []byte
if bytes, err = os.ReadFile(filename); err != nil {
return
}
return clientCtx.TxConfig.UnmarshalSignatureJSON(bytes)
}
func readSignaturesFromFile(ctx client.Context, filename string) (sigs []signingtypes.SignatureV2, err error) {
bz, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
newString := strings.TrimSuffix(string(bz), "\n")
lines := strings.Split(newString, "\n")
for _, bz := range lines {
sig, err := ctx.TxConfig.UnmarshalSignatureJSON([]byte(bz))
if err != nil {
return nil, err
}
sigs = append(sigs, sig...)
}
return sigs, nil
}
func getMultisigRecord(clientCtx client.Context, name string) (*keyring.Record, error) {
kb := clientCtx.Keyring
multisigRecord, err := kb.Key(name)
if err != nil {
return nil, errorsmod.Wrap(err, "error getting keybase multisig account")
}
return multisigRecord, nil
}