/
models_chain_links.go
561 lines (460 loc) · 15.7 KB
/
models_chain_links.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
package types
import (
"bytes"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
"github.com/tendermint/tendermint/crypto/tmhash"
"github.com/btcsuite/btcd/btcec"
"github.com/ethereum/go-ethereum/crypto"
"github.com/gogo/protobuf/proto"
"github.com/mr-tron/base58"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/crypto/types/multisig"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// NewChainConfig allows to build a new ChainConfig instance
func NewChainConfig(name string) ChainConfig {
return ChainConfig{
Name: name,
}
}
// Validate checks the validity of the ChainConfig
func (c ChainConfig) Validate() error {
if strings.TrimSpace(c.Name) == "" {
return fmt.Errorf("chain name cannot be empty or blank")
}
if c.Name != strings.ToLower(c.Name) {
return fmt.Errorf("chain name must be lowercase")
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
// NewProof is a constructor function for Proof
// nolint:interfacer
func NewProof(pubKey cryptotypes.PubKey, signature SignatureData, plainText string) Proof {
pubKeyAny, err := codectypes.NewAnyWithValue(pubKey)
if err != nil {
panic("failed to pack public key to any type")
}
signatureAny, err := codectypes.NewAnyWithValue(signature)
if err != nil {
panic("failed to pack signature data to any type")
}
return Proof{
PubKey: pubKeyAny,
Signature: signatureAny,
PlainText: plainText,
}
}
// Validate checks the validity of the Proof
func (p Proof) Validate() error {
if p.PubKey == nil {
return fmt.Errorf("public key field cannot be nil")
}
if p.Signature == nil {
return fmt.Errorf("signature field cannot be nil")
}
if strings.TrimSpace(p.PlainText) == "" {
return fmt.Errorf("plain text cannot be empty or blank")
}
_, err := hex.DecodeString(p.PlainText)
if err != nil {
return fmt.Errorf("invalid hex-encoded plain text")
}
return nil
}
// Verify verifies the signature using the given plain text and public key.
// It returns and error if something is invalid.
func (p Proof) Verify(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, owner string, address AddressData) error {
value, err := hex.DecodeString(p.PlainText)
if err != nil {
return fmt.Errorf("error while decoding proof text: %s", err)
}
// Make sure the signed value is valid, if it's a transaction
isValidTextSig := IsValidTextSig(value, owner)
isValidDirectTxSig := IsValidDirectTxSig(value, owner, cdc)
isValidAminoTxSig := IsValidAminoTxSig(value, owner, legacyAmino)
if !isValidTextSig && !isValidDirectTxSig && !isValidAminoTxSig {
return fmt.Errorf("proof signed value must either be the user address or a transaction containing it as the memo")
}
var sigData SignatureData
err = cdc.UnpackAny(p.Signature, &sigData)
if err != nil {
return fmt.Errorf("failed to unpack the signature")
}
// Convert the signature data to the Cosmos type
cosmosSigData, err := SignatureDataToCosmosSignatureData(cdc, sigData)
if err != nil {
return err
}
// Verify the signature
var pubkey cryptotypes.PubKey
switch sigData := cosmosSigData.(type) {
case *signing.SingleSignatureData:
err = cdc.UnpackAny(p.PubKey, &pubkey)
if err != nil {
return fmt.Errorf("failed to unpack the public key")
}
if !pubkey.VerifySignature(value, sigData.Signature) {
return fmt.Errorf("failed to verify the signature")
}
case *signing.MultiSignatureData:
var multiPubkey multisig.PubKey
err = cdc.UnpackAny(p.PubKey, &multiPubkey)
if err != nil {
return fmt.Errorf("failed to unpack the public key")
}
err = multiPubkey.VerifyMultisignature(
func(mode signing.SignMode) ([]byte, error) {
return value, nil
},
sigData,
)
if err != nil {
return err
}
pubkey = multiPubkey
}
// Verify the public key
valid, err := address.VerifyPubKey(pubkey)
if err != nil {
return err
}
if !valid {
return fmt.Errorf("invalid address and public key combination provided")
}
return nil
}
// IsValidTextSig tells whether the given value has been generated using SIGN_MODE_TEXTUAL
// and signing the given expected value
func IsValidTextSig(value []byte, expectedValue string) bool {
return string(value) == expectedValue
}
// IsValidDirectTxSig tells whether the given value has been generated using SIGN_MODE_DIRECT and signing
// a transaction that contains a memo field equals to the given expected value
func IsValidDirectTxSig(value []byte, expectedMemo string, cdc codec.BinaryCodec) bool {
// Unmarshal the SignDoc
var signDoc tx.SignDoc
err := cdc.Unmarshal(value, &signDoc)
if err != nil {
return false
}
// Check to make sure the value was a SignDoc. If that's not the case, the two arrays will not match
if !bytes.Equal(value, cdc.MustMarshal(&signDoc)) {
return false
}
// Get the TxBody
var txBody tx.TxBody
err = cdc.Unmarshal(signDoc.BodyBytes, &txBody)
if err != nil {
return false
}
// Check memo
return txBody.Memo == expectedMemo
}
// IsValidAminoTxSig tells whether the given value has been generated using SIGN_MODE_AMINO_JSON and signing
// a transaction that contains a memo field equals to the given expected value
func IsValidAminoTxSig(value []byte, expectedMemo string, cdc *codec.LegacyAmino) bool {
// Unmarshal the StdSignDoc
var signDoc legacytx.StdSignDoc
err := cdc.UnmarshalJSON(value, &signDoc)
if err != nil {
return false
}
// Check the memo field
return signDoc.Memo == expectedMemo
}
// UnpackInterfaces implements codectypes.UnpackInterfacesMessage
func (p *Proof) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
var pubKey cryptotypes.PubKey
err := unpacker.UnpackAny(p.PubKey, &pubKey)
if err != nil {
return err
}
var signatureData SignatureData
return unpacker.UnpackAny(p.Signature, &signatureData)
}
// --------------------------------------------------------------------------------------------------------------------
// SignatureData represents a generic single- or multi- signature data
type SignatureData interface {
proto.Message
isSignatureData()
}
// SignatureDataToCosmosSignatureData allows to convert the given SignatureData to a Cosmos SignatureData instance
// unpacking the proto.Any instance using the given unpacker.
func SignatureDataToCosmosSignatureData(unpacker codectypes.AnyUnpacker, s SignatureData) (signing.SignatureData, error) {
switch data := s.(type) {
case *SingleSignatureData:
return &signing.SingleSignatureData{
Signature: data.Signature,
SignMode: data.Mode,
}, nil
case *MultiSignatureData:
sigs, err := unpackSignatures(unpacker, data.Signatures)
if err != nil {
return nil, err
}
return &signing.MultiSignatureData{
BitArray: data.BitArray,
Signatures: sigs,
}, nil
}
return nil, fmt.Errorf("signature type not supported: %T", s)
}
// SignatureDataFromCosmosSignatureData allows to create a SignatureData instance from the given Cosmos SignatureData
func SignatureDataFromCosmosSignatureData(data signing.SignatureData) (SignatureData, error) {
switch data := data.(type) {
case *signing.SingleSignatureData:
return &SingleSignatureData{
Mode: data.SignMode,
Signature: data.Signature,
}, nil
case *signing.MultiSignatureData:
sigAnys := make([]*codectypes.Any, len(data.Signatures))
for i, data := range data.Signatures {
sigData, err := SignatureDataFromCosmosSignatureData(data)
if err != nil {
return nil, err
}
sigAny, err := codectypes.NewAnyWithValue(sigData)
if err != nil {
return nil, err
}
sigAnys[i] = sigAny
}
return &MultiSignatureData{
BitArray: data.BitArray,
Signatures: sigAnys,
}, nil
default:
return nil, fmt.Errorf("unexpected case %+v", data)
}
}
// unpackSignatures unpacks the given signatures using the provided unpacker
func unpackSignatures(unpacker codectypes.AnyUnpacker, sigs []*codectypes.Any) ([]signing.SignatureData, error) {
var signatures = make([]signing.SignatureData, len(sigs))
for i, sig := range sigs {
var signatureData SignatureData
if err := unpacker.UnpackAny(sig, &signatureData); err != nil {
return nil, err
}
cosmosSigData, err := SignatureDataToCosmosSignatureData(unpacker, signatureData)
if err != nil {
return nil, err
}
signatures[i] = cosmosSigData
}
return signatures, nil
}
// --------------------------------------------------------------------------------------------------------------------
var _ SignatureData = &SingleSignatureData{}
// isSignatureData implements SignatureData
func (s *SingleSignatureData) isSignatureData() {}
// --------------------------------------------------------------------------------------------------------------------
var _ SignatureData = &MultiSignatureData{}
// isSignatureData implements SignatureData
func (s *MultiSignatureData) isSignatureData() {}
// UnpackInterfaces implements codectypes.UnpackInterfacesMessage
func (s *MultiSignatureData) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
for _, signature := range s.Signatures {
var signatureData SignatureData
err := unpacker.UnpackAny(signature, &signatureData)
if err != nil {
return err
}
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
// AddressData is an interface representing a generic external chain address
type AddressData interface {
proto.Message
// Validate checks the validity of the AddressData
Validate() error
// GetValue returns the address value
GetValue() string
// VerifyPubKey verifies that the given public key is associated with this address data
VerifyPubKey(key cryptotypes.PubKey) (bool, error)
}
// --------------------------------------------------------------------------------------------------------------------
var _ AddressData = &Bech32Address{}
// NewBech32Address returns a new Bech32Address instance
func NewBech32Address(value, prefix string) *Bech32Address {
return &Bech32Address{Value: value, Prefix: prefix}
}
// Validate implements AddressData
func (b Bech32Address) Validate() error {
if strings.TrimSpace(b.Value) == "" {
return fmt.Errorf("value cannot be empty or blank")
}
if strings.TrimSpace(b.Prefix) == "" {
return fmt.Errorf("prefix cannot be empty or blank")
}
_, err := sdk.GetFromBech32(b.Value, b.Prefix)
if err != nil {
return fmt.Errorf("invalid Bech32 value or wrong prefix")
}
return nil
}
// GetValue implements AddressData
func (b Bech32Address) GetValue() string {
return b.Value
}
// VerifyPubKey implements AddressData
func (b Bech32Address) VerifyPubKey(key cryptotypes.PubKey) (bool, error) {
_, bz, err := bech32.DecodeAndConvert(b.Value)
if err != nil {
return false, err
}
return bytes.Equal(bz, key.Address().Bytes()), nil
}
// --------------------------------------------------------------------------------------------------------------------
var _ AddressData = &Base58Address{}
// NewBase58Address returns a new Base58Address instance
func NewBase58Address(value string) *Base58Address {
return &Base58Address{Value: value}
}
// Validate implements AddressData
func (b Base58Address) Validate() error {
if strings.TrimSpace(b.Value) == "" {
return fmt.Errorf("address cannot be empty or blank")
}
if _, err := base58.Decode(b.Value); err != nil {
return fmt.Errorf("invalid Base58 address")
}
return nil
}
// GetValue implements AddressData
func (b Base58Address) GetValue() string {
return b.Value
}
// VerifyPubKey implements AddressData
func (b Base58Address) VerifyPubKey(key cryptotypes.PubKey) (bool, error) {
bz, err := base58.Decode(b.Value)
return bytes.Equal(tmhash.SumTruncated(bz), key.Address().Bytes()), err
}
// --------------------------------------------------------------------------------------------------------------------
var _ AddressData = &HexAddress{}
// NewHexAddress returns a new HexAddress instance
func NewHexAddress(value, prefix string) *HexAddress {
return &HexAddress{Value: value, Prefix: prefix}
}
// Validate implements AddressData
func (h HexAddress) Validate() error {
if strings.TrimSpace(h.Value) == "" {
return fmt.Errorf("value cannot be empty or blank")
}
if len(h.Value) <= len(h.Prefix) {
return fmt.Errorf("address cannot be smaller than prefix")
}
prefix, addrWithoutPrefix := h.Value[:len(h.Prefix)], h.Value[len(h.Prefix):]
if prefix != h.Prefix {
return fmt.Errorf("prefix does not match")
}
if _, err := hex.DecodeString(addrWithoutPrefix); err != nil {
return fmt.Errorf("invalid hex address")
}
return nil
}
// GetValue implements AddressData
func (h HexAddress) GetValue() string {
return h.Value
}
// VerifyPubKey implements AddressData
func (h HexAddress) VerifyPubKey(key cryptotypes.PubKey) (bool, error) {
addr := h.Value[len(h.Prefix):]
bz, err := hex.DecodeString(addr)
if err != nil {
return false, err
}
pubKey, err := btcec.ParsePubKey(key.Bytes(), btcec.S256())
if err != nil {
return false, err
}
uncompressedPubKey := pubKey.SerializeUncompressed()
return bytes.Equal(crypto.Keccak256(uncompressedPubKey[1:])[12:], bz), err
}
// --------------------------------------------------------------------------------------------------------------------
// UnpackAddressData deserializes the given any type value as an address data using the provided unpacker
func UnpackAddressData(unpacker codectypes.AnyUnpacker, addressAny *codectypes.Any) (AddressData, error) {
var address AddressData
if err := unpacker.UnpackAny(addressAny, &address); err != nil {
return nil, err
}
return address, nil
}
// --------------------------------------------------------------------------------------------------------------------
// NewChainLink returns a new ChainLink instance
// nolint:interfacer
func NewChainLink(user string, address AddressData, proof Proof, chainConfig ChainConfig, creationTime time.Time) ChainLink {
addressAny, err := codectypes.NewAnyWithValue(address)
if err != nil {
panic("failed to pack address data to any type")
}
return ChainLink{
User: user,
Address: addressAny,
Proof: proof,
ChainConfig: chainConfig,
CreationTime: creationTime,
}
}
// GetAddressData returns the AddressData associated with this chain link
func (link ChainLink) GetAddressData() AddressData {
return link.Address.GetCachedValue().(AddressData)
}
// Validate checks the validity of the ChainLink
func (link ChainLink) Validate() error {
if _, err := sdk.AccAddressFromBech32(link.User); err != nil {
return fmt.Errorf("invalid creator address: %s", link.User)
}
if link.Address == nil {
return fmt.Errorf("address cannot be nil")
}
err := link.Proof.Validate()
if err != nil {
return err
}
err = link.ChainConfig.Validate()
if err != nil {
return err
}
if link.CreationTime.IsZero() {
return fmt.Errorf("creation time cannot be zero")
}
return nil
}
// UnpackInterfaces implements codectypes.UnpackInterfacesMessage
func (link *ChainLink) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
if link.Address != nil {
var address AddressData
err := unpacker.UnpackAny(link.Address, &address)
if err != nil {
return err
}
}
err := link.Proof.UnpackInterfaces(unpacker)
if err != nil {
return err
}
return nil
}
// MustMarshalChainLink serializes the given chain link using the provided BinaryCodec
func MustMarshalChainLink(cdc codec.BinaryCodec, link ChainLink) []byte {
return cdc.MustMarshal(&link)
}
// MustUnmarshalChainLink deserializes the given byte array as a chain link using
// the provided BinaryCodec
func MustUnmarshalChainLink(codec codec.BinaryCodec, bz []byte) ChainLink {
var link ChainLink
codec.MustUnmarshal(bz, &link)
return link
}