forked from cosmos/rosetta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.go
791 lines (678 loc) · 26.9 KB
/
converter.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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
package rosetta
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
signingv1beta1 "cosmossdk.io/api/cosmos/tx/signing/v1beta1"
rosettatypes "github.com/coinbase/rosetta-sdk-go/types"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/crypto"
tmcoretypes "github.com/cometbft/cometbft/rpc/core/types"
cmttypes "github.com/cometbft/cometbft/types"
secp "github.com/decred/dcrd/dcrec/secp256k1/v4"
sdkmath "cosmossdk.io/math"
sdkclient "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
crgerrs "github.com/cosmos/rosetta/lib/errors"
crgtypes "github.com/cosmos/rosetta/lib/types"
)
// Converter is a utility that can be used to convert
// back and forth from rosetta to sdk and CometBFT types
// IMPORTANT NOTES:
// - IT SHOULD BE USED ONLY TO DEAL WITH THINGS
// IN A STATELESS WAY! IT SHOULD NEVER INTERACT DIRECTLY
// WITH COMETBFT RPC AND COSMOS GRPC
//
// - IT SHOULD RETURN cosmos rosetta gateway error types!
type Converter interface {
// ToSDK exposes the methods that convert
// rosetta types to cosmos sdk and CometBFT types
ToSDK() ToSDKConverter
// ToRosetta exposes the methods that convert
// sdk and CometBFT types to rosetta types
ToRosetta() ToRosettaConverter
}
// ToRosettaConverter is an interface that exposes
// all the functions used to convert sdk and
// CometBFT types to rosetta known types
type ToRosettaConverter interface {
// BlockResponse returns a block response given a result block
BlockResponse(block *tmcoretypes.ResultBlock) crgtypes.BlockResponse
// BeginBlockToTx converts the given begin block hash to rosetta transaction hash
BeginBlockTxHash(blockHash []byte) string
// EndBlockTxHash converts the given endblock hash to rosetta transaction hash
EndBlockTxHash(blockHash []byte) string
// Amounts converts sdk.Coins to rosetta.Amounts
Amounts(ownedCoins []sdk.Coin, availableCoins sdk.Coins) []*rosettatypes.Amount
// Ops converts an sdk.Msg to rosetta operations
Ops(status string, msg sdk.Msg) ([]*rosettatypes.Operation, error)
// OpsAndSigners takes raw transaction bytes and returns rosetta operations and the expected signers
OpsAndSigners(txBytes []byte) (ops []*rosettatypes.Operation, signers []*rosettatypes.AccountIdentifier, err error)
// Meta converts an sdk.Msg to rosetta metadata
Meta(msg sdk.Msg) (meta map[string]interface{}, err error)
// SignerData returns account signing data from a queried any account
SignerData(anyAccount *codectypes.Any) (*SignerData, error)
// SigningComponents returns rosetta's components required to build a signable transaction
SigningComponents(tx authsigning.Tx, metadata *ConstructionMetadata, rosPubKeys []*rosettatypes.PublicKey) (txBytes []byte, payloadsToSign []*rosettatypes.SigningPayload, err error)
// Tx converts a CometBFT transaction and tx result if provided to a rosetta tx
Tx(rawTx cmttypes.Tx, txResult *abci.ExecTxResult) (*rosettatypes.Transaction, error)
// TxIdentifiers converts a CometBFT tx to transaction identifiers
TxIdentifiers(txs []cmttypes.Tx) []*rosettatypes.TransactionIdentifier
// BalanceOps converts events to balance operations
BalanceOps(status string, events []abci.Event) []*rosettatypes.Operation
// SyncStatus converts a CometBFT status to sync status
SyncStatus(status *tmcoretypes.ResultStatus) *rosettatypes.SyncStatus
// Peers converts CometBFT peers to rosetta
Peers(peers []tmcoretypes.Peer) []*rosettatypes.Peer
}
// ToSDKConverter is an interface that exposes
// all the functions used to convert rosetta types
// to CometBFT and sdk types
type ToSDKConverter interface {
// UnsignedTx converts rosetta operations to an unsigned cosmos sdk transactions
UnsignedTx(ops []*rosettatypes.Operation) (tx authsigning.Tx, err error)
// SignedTx adds the provided signatures after decoding the unsigned transaction raw bytes
// and returns the signed tx bytes
SignedTx(txBytes []byte, signatures []*rosettatypes.Signature) (signedTxBytes []byte, err error)
// Msg converts metadata to an sdk message
Msg(meta map[string]interface{}, msg sdk.Msg) (err error)
// HashToTxType returns the transaction type (end block, begin block or deliver tx)
// and the real hash to query in order to get information
HashToTxType(hashBytes []byte) (txType TransactionType, realHash []byte)
// PubKey attempts to convert a rosetta public key to cosmos sdk one
PubKey(pk *rosettatypes.PublicKey) (cryptotypes.PubKey, error)
}
type converter struct {
newTxBuilder func() sdkclient.TxBuilder
txBuilderFromTx func(tx sdk.Tx) (sdkclient.TxBuilder, error)
txDecode sdk.TxDecoder
txEncode sdk.TxEncoder
bytesToSign func(tx authsigning.Tx, signerData authsigning.SignerData) (b []byte, err error)
ir codectypes.InterfaceRegistry
cdc *codec.ProtoCodec
}
func NewConverter(cdc *codec.ProtoCodec, ir codectypes.InterfaceRegistry, cfg sdkclient.TxConfig) Converter {
return converter{
newTxBuilder: cfg.NewTxBuilder,
txBuilderFromTx: cfg.WrapTxBuilder,
txDecode: cfg.TxDecoder(),
txEncode: cfg.TxEncoder(),
bytesToSign: func(tx authsigning.Tx, signerData authsigning.SignerData) (b []byte, err error) {
parsedSignerData := parseSignerData(signerData)
txData, err := parseTxData(tx, parsedSignerData)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while getting tx data %s", err.Error()))
}
bytesToSign, err := cfg.SignModeHandler().GetSignBytes(context.TODO(), signingv1beta1.SignMode(signing.SignMode_SIGN_MODE_DIRECT), parsedSignerData, *txData)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while getting bytes to sign %s", err.Error()))
}
return crypto.Sha256(bytesToSign), nil
},
ir: ir,
cdc: cdc,
}
}
func (c converter) ToSDK() ToSDKConverter {
return c
}
func (c converter) ToRosetta() ToRosettaConverter {
return c
}
// OpsToUnsignedTx returns all the sdk.Msgs given the operations
func (c converter) UnsignedTx(ops []*rosettatypes.Operation) (tx authsigning.Tx, err error) {
builder := c.newTxBuilder()
var msgs []sdk.Msg
for i := 0; i < len(ops); i++ {
op := ops[i]
msg, err := c.ir.Resolve(op.Type)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrBadArgument, "operation not found: "+op.Type)
}
err = c.Msg(op.Metadata, msg)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrCodec, err.Error())
}
signers, _, err := c.cdc.GetMsgV1Signers(msg)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while getting msg signers %s", err.Error()))
}
// check if there are enough signers
if len(signers) == 0 {
return nil, crgerrs.WrapError(crgerrs.ErrBadArgument, fmt.Sprintf("operation at index %d got no signers", op.OperationIdentifier.Index))
}
// append the msg
msgs = append(msgs, msg)
// if there's only one signer then simply continue
if len(signers) == 1 {
continue
}
// after we have got the msg, we need to verify if the message has multiple signers
// if it has got multiple signers, then we need to fetch all the related operations
// which involve the other signers of the msg, we expect to find them in order
// so if the msg is named "v1.test.Send" and it expects 3 signers, the next 3 operations
// must be with the same name "v1.test.Send" and contain the other signers
// then we can just skip their processing
for j := 0; j < len(signers)-1; j++ {
skipOp := ops[i+j] // get the next index
// verify that the operation is equal to the new one
if skipOp.Type != op.Type {
return nil, crgerrs.WrapError(
crgerrs.ErrBadArgument,
fmt.Sprintf("operation at index %d should have had type %s got: %s", i+j, op.Type, skipOp.Type),
)
}
if !reflect.DeepEqual(op.Metadata, skipOp.Metadata) {
return nil, crgerrs.WrapError(
crgerrs.ErrBadArgument,
fmt.Sprintf("operation at index %d should have had metadata equal to %#v, got: %#v", i+j, op.Metadata, skipOp.Metadata))
}
i++ // increase so we skip it
}
}
if err := builder.SetMsgs(msgs...); err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrBadArgument, err.Error())
}
return builder.GetTx(), nil
}
// Msg unmarshals the rosetta metadata to the given sdk.Msg
func (c converter) Msg(meta map[string]interface{}, msg sdk.Msg) error {
metaBytes, err := json.Marshal(meta)
if err != nil {
return crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while marshaling meta to json %s", err.Error()))
}
return c.cdc.UnmarshalJSON(metaBytes, msg)
}
func (c converter) Meta(msg sdk.Msg) (meta map[string]interface{}, err error) {
b, err := c.cdc.MarshalJSON(msg)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrCodec, err.Error())
}
err = json.Unmarshal(b, &meta)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrCodec, err.Error())
}
return
}
// Ops will create an operation for each msg signer
// with the message proto name as type, and the raw fields
// as metadata
func (c converter) Ops(status string, msg sdk.Msg) ([]*rosettatypes.Operation, error) {
meta, err := c.Meta(msg)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while getting meta from message %s", err.Error()))
}
signers, _, err := c.cdc.GetMsgV1Signers(msg)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while getting msg signers in Ops %s", err.Error()))
}
ops := make([]*rosettatypes.Operation, len(signers))
for i, signer := range signers {
addr, err := c.ir.SigningContext().AddressCodec().BytesToString(signer)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while getting address from signer %s", err.Error()))
}
op := &rosettatypes.Operation{
Type: sdk.MsgTypeURL(msg),
Status: &status,
Account: &rosettatypes.AccountIdentifier{Address: addr},
Metadata: meta,
}
ops[i] = op
}
return ops, nil
}
// Tx converts a CometBFT raw transaction and its result (if provided) to a rosetta transaction
func (c converter) Tx(rawTx cmttypes.Tx, txResult *abci.ExecTxResult) (*rosettatypes.Transaction, error) {
// decode tx
tx, err := c.txDecode(rawTx)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrCodec, err.Error())
}
// get initial status, as per sdk design, if one msg fails
// the whole TX will be considered failing, so we can't have
// 1 msg being success and 1 msg being reverted
status := StatusTxSuccess
switch txResult {
// if nil, we're probably checking an unconfirmed tx
// or trying to build a new transaction, so status
// is not put inside
case nil:
status = ""
// set the status
default:
if txResult.Code != abci.CodeTypeOK {
status = StatusTxReverted
}
}
// get operations from msgs
msgs := tx.GetMsgs()
var rawTxOps []*rosettatypes.Operation
for _, msg := range msgs {
ops, err := c.Ops(status, msg)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while getting operations from status and msg %s", err.Error()))
}
rawTxOps = append(rawTxOps, ops...)
}
// now get balance events from response deliver tx
var balanceOps []*rosettatypes.Operation
// tx result might be nil, in case we're querying an unconfirmed tx from the mempool
if txResult != nil {
balanceOps = c.BalanceOps(StatusTxSuccess, txResult.Events) // force set to success because no events for failed tx
}
// now normalize indexes
totalOps := AddOperationIndexes(rawTxOps, balanceOps)
return &rosettatypes.Transaction{
TransactionIdentifier: &rosettatypes.TransactionIdentifier{Hash: fmt.Sprintf("%X", rawTx.Hash())},
Operations: totalOps,
}, nil
}
func (c converter) BalanceOps(status string, events []abci.Event) []*rosettatypes.Operation {
var ops []*rosettatypes.Operation
for _, e := range events {
balanceOps, ok := sdkEventToBalanceOperations(status, e)
if !ok {
continue
}
ops = append(ops, balanceOps...)
}
return ops
}
// sdkEventToBalanceOperations converts an event to a rosetta balance operation
// it will panic if the event is malformed because it might mean the sdk spec
// has changed and rosetta needs to reflect those changes too.
// The balance operations are multiple, one for each denom.
func sdkEventToBalanceOperations(status string, event abci.Event) (operations []*rosettatypes.Operation, isBalanceEvent bool) {
var (
accountIdentifier string
coinChange sdk.Coins
isSub bool
)
switch event.Type {
default:
return nil, false
case banktypes.EventTypeCoinSpent:
spender := sdk.MustAccAddressFromBech32(event.Attributes[0].Value)
coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value)
if err != nil {
panic(err)
}
isSub = true
coinChange = coins
accountIdentifier = spender.String()
case banktypes.EventTypeCoinReceived:
receiver := sdk.MustAccAddressFromBech32(event.Attributes[0].Value)
coins, err := sdk.ParseCoinsNormalized(event.Attributes[1].Value)
if err != nil {
panic(err)
}
isSub = false
coinChange = coins
accountIdentifier = receiver.String()
// rosetta does not have the concept of burning coins, so we need to mock
// the burn as a send to an address that cannot be resolved to anything
case banktypes.EventTypeCoinBurn:
coin, err := base64.StdEncoding.DecodeString(event.Attributes[1].Value)
if err != nil {
panic(err)
}
coins, err := sdk.ParseCoinsNormalized(string(coin))
if err != nil {
panic(err)
}
coinChange = coins
accountIdentifier = BurnerAddressIdentifier
}
operations = make([]*rosettatypes.Operation, len(coinChange))
for i, coin := range coinChange {
value := coin.Amount.String()
// in case the event is a subtract balance one the rewrite value with
// the negative coin identifier
if isSub {
value = "-" + value
}
op := &rosettatypes.Operation{
Type: event.Type,
Status: &status,
Account: &rosettatypes.AccountIdentifier{Address: accountIdentifier},
Amount: &rosettatypes.Amount{
Value: value,
Currency: &rosettatypes.Currency{
Symbol: coin.Denom,
Decimals: 0,
},
},
}
operations[i] = op
}
return operations, true
}
// Amounts converts []sdk.Coin to rosetta amounts
func (c converter) Amounts(ownedCoins []sdk.Coin, availableCoins sdk.Coins) []*rosettatypes.Amount {
amounts := make([]*rosettatypes.Amount, len(availableCoins))
ownedCoinsMap := make(map[string]sdkmath.Int, len(availableCoins))
for _, ownedCoin := range ownedCoins {
ownedCoinsMap[ownedCoin.Denom] = ownedCoin.Amount
}
for i, coin := range availableCoins {
value, owned := ownedCoinsMap[coin.Denom]
if !owned {
amounts[i] = &rosettatypes.Amount{
Value: sdkmath.NewInt(0).String(),
Currency: &rosettatypes.Currency{
Symbol: coin.Denom,
},
}
continue
}
amounts[i] = &rosettatypes.Amount{
Value: value.String(),
Currency: &rosettatypes.Currency{
Symbol: coin.Denom,
},
}
}
return amounts
}
// AddOperationIndexes adds the indexes to operations adhering to specific rules:
// operations related to messages will be always before than the balance ones
func AddOperationIndexes(msgOps, balanceOps []*rosettatypes.Operation) (finalOps []*rosettatypes.Operation) {
lenMsgOps := len(msgOps)
lenBalanceOps := len(balanceOps)
finalOps = make([]*rosettatypes.Operation, 0, lenMsgOps+lenBalanceOps)
var currentIndex int64
// add indexes to msg ops
for _, op := range msgOps {
op.OperationIdentifier = &rosettatypes.OperationIdentifier{
Index: currentIndex,
}
finalOps = append(finalOps, op)
currentIndex++
}
// add indexes to balance ops
for _, op := range balanceOps {
op.OperationIdentifier = &rosettatypes.OperationIdentifier{
Index: currentIndex,
}
finalOps = append(finalOps, op)
currentIndex++
}
return finalOps
}
// EndBlockTxHash produces a mock endblock hash that rosetta can query
// for endblock operations, it also serves the purpose of representing
// part of the state changes happening at endblock level (balance ones)
func (c converter) EndBlockTxHash(hash []byte) string {
final := append([]byte{EndBlockHashStart}, hash...)
return fmt.Sprintf("%X", final)
}
// BeginBlockTxHash produces a mock beginblock hash that rosetta can query
// for beginblock operations, it also serves the purpose of representing
// part of the state changes happening at beginblock level (balance ones)
func (c converter) BeginBlockTxHash(hash []byte) string {
final := append([]byte{BeginBlockHashStart}, hash...)
return fmt.Sprintf("%X", final)
}
// HashToTxType takes the provided hash bytes from rosetta and discerns if they are
// a deliver tx type or endblock/begin block hash, returning the real hash afterwards
func (c converter) HashToTxType(hashBytes []byte) (txType TransactionType, realHash []byte) {
switch len(hashBytes) {
case DeliverTxSize:
return DeliverTxTx, hashBytes
case BeginEndBlockTxSize:
switch hashBytes[0] {
case BeginBlockHashStart:
return BeginBlockTx, hashBytes[1:]
case EndBlockHashStart:
return EndBlockTx, hashBytes[1:]
default:
return UnrecognizedTx, nil
}
default:
return UnrecognizedTx, nil
}
}
// StatusToSyncStatus converts a CometBFT status to rosetta sync status
func (c converter) SyncStatus(status *tmcoretypes.ResultStatus) *rosettatypes.SyncStatus {
// determine sync status
stage := StatusPeerSynced
if status.SyncInfo.CatchingUp {
stage = StatusPeerSyncing
}
return &rosettatypes.SyncStatus{
CurrentIndex: &status.SyncInfo.LatestBlockHeight,
TargetIndex: nil, // sync info does not allow us to get target height
Stage: &stage,
}
}
// TxIdentifiers converts a CometBFT raw transactions into an array of rosetta tx identifiers
func (c converter) TxIdentifiers(txs []cmttypes.Tx) []*rosettatypes.TransactionIdentifier {
converted := make([]*rosettatypes.TransactionIdentifier, len(txs))
for i, tx := range txs {
converted[i] = &rosettatypes.TransactionIdentifier{Hash: fmt.Sprintf("%X", tx.Hash())}
}
return converted
}
// tmResultBlockToRosettaBlockResponse converts a CometBFT result block to block response
func (c converter) BlockResponse(block *tmcoretypes.ResultBlock) crgtypes.BlockResponse {
var parentBlock *rosettatypes.BlockIdentifier
switch block.Block.Height {
case 1:
parentBlock = &rosettatypes.BlockIdentifier{
Index: 1,
Hash: fmt.Sprintf("%X", block.BlockID.Hash.Bytes()),
}
default:
parentBlock = &rosettatypes.BlockIdentifier{
Index: block.Block.Height - 1,
Hash: fmt.Sprintf("%X", block.Block.LastBlockID.Hash.Bytes()),
}
}
return crgtypes.BlockResponse{
Block: &rosettatypes.BlockIdentifier{
Index: block.Block.Height,
Hash: block.Block.Hash().String(),
},
ParentBlock: parentBlock,
MillisecondTimestamp: timeToMilliseconds(block.Block.Time),
TxCount: int64(len(block.Block.Txs)),
}
}
// Peers converts tm peers to rosetta peers
func (c converter) Peers(peers []tmcoretypes.Peer) []*rosettatypes.Peer {
converted := make([]*rosettatypes.Peer, len(peers))
for i, peer := range peers {
converted[i] = &rosettatypes.Peer{
PeerID: peer.NodeInfo.Moniker,
Metadata: map[string]interface{}{
"addr": peer.NodeInfo.ListenAddr,
},
}
}
return converted
}
// OpsAndSigners takes transactions bytes and returns the operation, is signed is true it will return
// the account identifiers which have signed the transaction
func (c converter) OpsAndSigners(txBytes []byte) (ops []*rosettatypes.Operation, signers []*rosettatypes.AccountIdentifier, err error) {
rosTx, err := c.ToRosetta().Tx(txBytes, nil)
if err != nil {
return nil, nil, err
}
ops = rosTx.Operations
// get the signers
sdkTx, err := c.txDecode(txBytes)
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting tx encoder %s", err.Error()))
}
txBuilder, err := c.txBuilderFromTx(sdkTx)
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting tx builder %s", err.Error()))
}
txSigners, err := txBuilder.GetTx().GetSigners()
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting tx signers %s", err.Error()))
}
for _, signer := range txSigners {
signers = append(signers, &rosettatypes.AccountIdentifier{
Address: string(signer),
})
}
return
}
func (c converter) SignedTx(txBytes []byte, signatures []*rosettatypes.Signature) (signedTxBytes []byte, err error) {
rawTx, err := c.txDecode(txBytes)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while decoding tx from bytes %s", err.Error()))
}
txBuilder, err := c.txBuilderFromTx(rawTx)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting tx bytes from tx %s", err.Error()))
}
notSignedSigs, err := txBuilder.GetTx().GetSignaturesV2() //
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting signatures from tx %s", err.Error()))
}
if len(notSignedSigs) != len(signatures) {
return nil, crgerrs.WrapError(
crgerrs.ErrInvalidTransaction,
fmt.Sprintf("expected transaction to have signers data matching the provided signatures: %d <-> %d", len(notSignedSigs), len(signatures)))
}
signedSigs := make([]signing.SignatureV2, len(notSignedSigs))
for i, signature := range signatures {
// TODO(fdymylja): here we should check that the public key matches...
signedSigs[i] = signing.SignatureV2{
PubKey: notSignedSigs[i].PubKey,
Data: &signing.SingleSignatureData{
SignMode: signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON,
Signature: signature.Bytes,
},
Sequence: notSignedSigs[i].Sequence,
}
}
if err = txBuilder.SetSignatures(signedSigs...); err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while setting signatures %s", err.Error()))
}
txBytes, err = c.txEncode(txBuilder.GetTx())
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting bytes from tx %s", err.Error()))
}
return txBytes, nil
}
func (c converter) PubKey(pubKey *rosettatypes.PublicKey) (cryptotypes.PubKey, error) {
if pubKey.CurveType != "secp256k1" {
return nil, crgerrs.WrapError(crgerrs.ErrUnsupportedCurve, "only secp256k1 supported")
}
cmp, err := secp.ParsePubKey(pubKey.Bytes)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrBadArgument, err.Error())
}
compressedPublicKey := make([]byte, secp256k1.PubKeySize)
copy(compressedPublicKey, cmp.SerializeCompressed())
pk := &secp256k1.PubKey{Key: compressedPublicKey}
return pk, nil
}
// SigningComponents takes a sdk tx and construction metadata and returns signable components
func (c converter) SigningComponents(tx authsigning.Tx, metadata *ConstructionMetadata, rosPubKeys []*rosettatypes.PublicKey) (txBytes []byte, payloadsToSign []*rosettatypes.SigningPayload, err error) {
// verify metadata correctness
feeAmount, err := sdk.ParseCoinsNormalized(metadata.GasPrice)
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting signers v2 from tx %s", err.Error()))
}
signers, err := tx.GetSignaturesV2()
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting signers v2 from tx %s", err.Error()))
}
// assert the signers data provided in options are the same as the expected signing accounts
// and that the number of rosetta provided public keys equals the one of the signers
if len(metadata.SignersData) != len(signers) || len(signers) != len(rosPubKeys) {
return nil, nil, crgerrs.WrapError(crgerrs.ErrBadArgument, "signers data and account identifiers mismatch")
}
// add transaction metadata
builder, err := c.txBuilderFromTx(tx)
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("getting tx builder %s", err.Error()))
}
builder.SetFeeAmount(feeAmount)
builder.SetGasLimit(metadata.GasLimit)
builder.SetMemo(metadata.Memo)
// build signatures
partialSignatures := make([]signing.SignatureV2, len(signers))
payloadsToSign = make([]*rosettatypes.SigningPayload, len(signers))
// pub key ordering matters, in a future release this check might be relaxed
for i, signer := range signers {
// assert that the provided public keys are correctly ordered
// by checking if the signer at index i matches the pubkey at index
pubKey, err := c.ToSDK().PubKey(rosPubKeys[0])
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while setting signatures %s", err.Error()))
}
if !bytes.Equal(pubKey.Address().Bytes(), signer.PubKey.Address()) {
return nil, nil, crgerrs.WrapError(
crgerrs.ErrBadArgument,
fmt.Sprintf("public key at index %d does not match the expected transaction signer: %X <-> %X", i, rosPubKeys[i].Bytes, signer),
)
}
// set the signer data
signerData := authsigning.SignerData{
Address: string(signer.PubKey.Address()),
ChainID: metadata.ChainID,
AccountNumber: metadata.SignersData[i].AccountNumber,
Sequence: metadata.SignersData[i].Sequence,
PubKey: pubKey,
}
// get signature bytes
signBytes, err := c.bytesToSign(tx, signerData)
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrUnknown, fmt.Sprintf("unable to sign tx: %s", err.Error()))
}
// set payload
signerAddress := sdk.AccAddress(signer.PubKey.Address()).String()
payloadsToSign[i] = &rosettatypes.SigningPayload{
AccountIdentifier: &rosettatypes.AccountIdentifier{Address: signerAddress},
Bytes: signBytes,
SignatureType: rosettatypes.Ecdsa,
}
// set partial signature
partialSignatures[i] = signing.SignatureV2{
PubKey: pubKey,
Data: &signing.SingleSignatureData{}, // needs to be set to empty otherwise the codec will cry
Sequence: metadata.SignersData[i].Sequence,
}
}
// now we set the partial signatures in the tx
// because we will need to decode the sequence
// information of each account in a stateless way
err = builder.SetSignatures(partialSignatures...)
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while setting signatures %s", err.Error()))
}
// finally encode the tx
txBytes, err = c.txEncode(builder.GetTx())
if err != nil {
return nil, nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while encoding tx %s", err.Error()))
}
return txBytes, payloadsToSign, nil
}
// SignerData converts the given any account to signer data
func (c converter) SignerData(anyAccount *codectypes.Any) (*SignerData, error) {
var acc sdkclient.Account
err := c.ir.UnpackAny(anyAccount, &acc)
if err != nil {
return nil, crgerrs.WrapError(crgerrs.ErrConverter, fmt.Sprintf("while unpacking an account %s", err.Error()))
}
return &SignerData{
AccountNumber: acc.GetAccountNumber(),
Sequence: acc.GetSequence(),
}, nil
}