-
Notifications
You must be signed in to change notification settings - Fork 4
/
construction.go
671 lines (602 loc) · 18.5 KB
/
construction.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
// Copyright (c) 2020 IoTeX Foundation
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package services
import (
"context"
"encoding/hex"
"math/big"
"github.com/btcsuite/btcd/btcec"
"github.com/coinbase/rosetta-sdk-go/server"
"github.com/coinbase/rosetta-sdk-go/types"
"github.com/golang/protobuf/proto"
"github.com/spf13/cast"
"github.com/iotexproject/go-pkgs/crypto"
"github.com/iotexproject/go-pkgs/hash"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-proto/golang/iotextypes"
ic "github.com/iotexproject/iotex-core-rosetta-gateway/iotex-client"
)
const (
// TODO config these
CurveType = "secp256k1"
SignatureType = "ecdsa_recovery"
)
type constructionAPIService struct {
client ic.IoTexClient
}
// NewConstructionAPIService creates a new instance of an ConstructionAPIService.
func NewConstructionAPIService(client ic.IoTexClient) server.ConstructionAPIServicer {
return &constructionAPIService{
client: client,
}
}
// ConstructionCombine implements the /construction/combine endpoint.
func (s *constructionAPIService) ConstructionCombine(
ctx context.Context,
request *types.ConstructionCombineRequest,
) (*types.ConstructionCombineResponse, *types.Error) {
if terr := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier); terr != nil {
return nil, terr
}
tran, err := hex.DecodeString(request.UnsignedTransaction)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += err.Error()
return nil, terr
}
act := &iotextypes.Action{}
if err := proto.Unmarshal(tran, act); err != nil {
return nil, ErrUnmarshal
}
if len(request.Signatures) != 1 {
terr := ErrInvalidInputParam
terr.Message += "need exact 1 signature"
return nil, terr
}
rawPub := request.Signatures[0].PublicKey.Bytes
if btcec.IsCompressedPubKey(rawPub) {
pubk, err := btcec.ParsePubKey(rawPub, btcec.S256())
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "invalid pubkey: " + err.Error()
return nil, terr
}
rawPub = pubk.SerializeUncompressed()
}
// NOTE set right sender pubkey here
act.SenderPubKey = rawPub
rawSig := request.Signatures[0].Bytes
if len(rawSig) != 65 {
terr := ErrInvalidInputParam
terr.Message += "invalid signature length"
return nil, terr
}
act.Signature = rawSig
msg, err := proto.Marshal(act)
if err != nil {
terr := ErrServiceInternal
terr.Message += err.Error()
return nil, terr
}
return &types.ConstructionCombineResponse{
SignedTransaction: hex.EncodeToString(msg),
}, nil
}
// ConstructionDerive implements the /construction/derive endpoint.
func (s *constructionAPIService) ConstructionDerive(
ctx context.Context,
request *types.ConstructionDeriveRequest,
) (*types.ConstructionDeriveResponse, *types.Error) {
if terr := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier); terr != nil {
return nil, terr
}
if len(request.PublicKey.Bytes) == 0 || request.PublicKey.CurveType != CurveType {
terr := ErrInvalidInputParam
terr.Message += "unsupported public key type"
return nil, terr
}
rawPub := request.PublicKey.Bytes
if btcec.IsCompressedPubKey(rawPub) {
pubk, err := btcec.ParsePubKey(rawPub, btcec.S256())
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "invalid public key: " + err.Error()
return nil, terr
}
rawPub = pubk.SerializeUncompressed()
}
pub, err := crypto.BytesToPublicKey(rawPub)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "invalid public key: " + err.Error()
return nil, terr
}
addr, err := address.FromBytes(pub.Hash())
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "invalid public key: " + err.Error()
return nil, terr
}
return &types.ConstructionDeriveResponse{
AccountIdentifier: &types.AccountIdentifier{
Address: addr.String(),
},
}, nil
}
// ConstructionHash implements the /construction/hash endpoint.
func (s *constructionAPIService) ConstructionHash(
ctx context.Context,
request *types.ConstructionHashRequest,
) (*types.TransactionIdentifierResponse, *types.Error) {
if terr := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier); terr != nil {
return nil, terr
}
tran, err := hex.DecodeString(request.SignedTransaction)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "invalid signed transaction format: " + err.Error()
return nil, terr
}
h := hash.Hash256b(tran)
return &types.TransactionIdentifierResponse{
TransactionIdentifier: &types.TransactionIdentifier{
hex.EncodeToString(h[:]),
},
}, nil
}
type metadataInputOptions struct {
senderAddress string
gasLimit *uint64
gasPrice *uint64
maxFee *big.Int
feeMultiplier *float64
typ iotextypes.TransactionLogType
}
func parseMetadataInputOptions(options map[string]interface{}) (*metadataInputOptions, *types.Error) {
opts := &metadataInputOptions{}
idRaw, ok := options["sender"]
if !ok {
terr := ErrInvalidInputParam
terr.Message += "empty sender address"
return nil, terr
}
var err error
opts.senderAddress, err = cast.ToStringE(idRaw)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += err.Error()
return nil, terr
}
if _, ok := options["type"]; !ok {
terr := ErrInvalidInputParam
terr.Message += "empty operation type"
return nil, terr
}
typ, err := cast.ToStringE(options["type"])
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "failed to parse type: " + err.Error()
return nil, terr
}
if !IsSupportedConstructionType(typ) {
terr := ErrInvalidInputParam
terr.Message += "unsupported type"
return nil, terr
}
opts.typ = iotextypes.TransactionLogType(iotextypes.TransactionLogType_value[typ])
if rawgl, ok := options["gasLimit"]; ok {
gasLimit, err := cast.ToUint64E(rawgl)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "failed to parse gasLimit: " + err.Error()
return nil, terr
}
opts.gasLimit = &gasLimit
}
if rawgp, ok := options["gasPrice"]; ok {
gasPrice, err := cast.ToUint64E(rawgp)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "failed to parse gasPrice: " + err.Error()
return nil, terr
}
opts.gasPrice = &gasPrice
}
if rawmp, ok := options["feeMultiplier"]; ok {
feeMultiplier, err := cast.ToFloat64E(rawmp)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "failed to parse fee multiplier: " + err.Error()
return nil, terr
}
opts.feeMultiplier = &feeMultiplier
}
if rawmf, ok := options["maxFee"]; ok {
maxFeeStr, err := cast.ToStringE(rawmf)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += "failed to parse max fee: " + err.Error()
return nil, terr
}
maxFee, ok := new(big.Int).SetString(maxFeeStr, 10)
if !ok {
terr := ErrInvalidInputParam
terr.Message += "failed to parse max fee"
return nil, terr
}
opts.maxFee = maxFee
}
return opts, nil
}
func estimateGasAction(opts *metadataInputOptions) (*iotextypes.Action, *types.Error) {
// need a valid pubkey to estimate, just use one
rawPrivKey, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
terr := ErrServiceInternal
terr.Message += err.Error()
return nil, terr
}
rawPubKey := rawPrivKey.PubKey()
act := &iotextypes.Action{
SenderPubKey: rawPubKey.SerializeUncompressed(),
Signature: action.ValidSig,
}
switch opts.typ {
// XXX once support send out payload, need to pass payload here to get right gaslimit
case iotextypes.TransactionLogType_NATIVE_TRANSFER:
act.Core = &iotextypes.ActionCore{
Action: &iotextypes.ActionCore_Transfer{
Transfer: &iotextypes.Transfer{},
},
}
}
return act, nil
}
// ConstructionMetadata implements the /construction/metadata endpoint.
func (s *constructionAPIService) ConstructionMetadata(
ctx context.Context,
request *types.ConstructionMetadataRequest,
) (*types.ConstructionMetadataResponse, *types.Error) {
if terr := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier); terr != nil {
return nil, terr
}
opts, terr := parseMetadataInputOptions(request.Options)
if terr != nil {
return nil, terr
}
account, err := s.client.GetAccount(ctx, 0, opts.senderAddress)
if err != nil {
terr := ErrUnableToGetAccount
terr.Message += err.Error()
return nil, terr
}
meta := account.Metadata
var gasLimit, gasPrice uint64
if opts.gasLimit == nil {
estAct, terr := estimateGasAction(opts)
if terr != nil {
return nil, terr
}
gasLimit, err = s.client.EstimateGasForAction(ctx, estAct)
if err != nil {
terr := ErrUnableToEstimateGas
terr.Message += err.Error()
return nil, terr
}
} else {
gasLimit = *opts.gasLimit
}
if opts.gasPrice == nil {
gasPrice, err = s.client.SuggestGasPrice(ctx)
if err != nil {
terr := ErrUnableToGetSuggestGas
terr.Message += err.Error()
return nil, terr
}
} else {
gasPrice = *opts.gasPrice
}
// apply fee multiplier
if opts.feeMultiplier != nil {
base := new(big.Float).SetUint64(gasPrice)
multiplier := new(big.Float).SetFloat64(*opts.feeMultiplier)
gasPrice, _ = new(big.Float).Mul(base, multiplier).Uint64()
}
meta["gasLimit"] = gasLimit
meta["gasPrice"] = gasPrice
suggestedFee := new(big.Int).Mul(
new(big.Int).SetUint64(gasPrice),
new(big.Int).SetUint64(gasLimit))
// check if maxFee >= fee
if opts.maxFee != nil {
if opts.maxFee.Cmp(suggestedFee) < 0 {
return nil, ErrExceededFee
}
}
return &types.ConstructionMetadataResponse{
Metadata: meta,
SuggestedFee: []*types.Amount{
&types.Amount{
Value: suggestedFee.String(),
Currency: &types.Currency{
Symbol: s.client.GetConfig().Currency.Symbol,
Decimals: s.client.GetConfig().Currency.Decimals,
},
},
},
}, nil
}
// ConstructionParse implements the /construction/parse endpoint.
func (s *constructionAPIService) ConstructionParse(
ctx context.Context,
request *types.ConstructionParseRequest,
) (*types.ConstructionParseResponse, *types.Error) {
if terr := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier); terr != nil {
return nil, terr
}
tran, err := hex.DecodeString(request.Transaction)
if err != nil {
return nil, ErrUnableToParseTx
}
act := &iotextypes.Action{}
if err := proto.Unmarshal(tran, act); err != nil {
return nil, ErrUnableToParseTx
}
sender, terr := s.checkIoAction(act, request.Signed)
if terr != nil {
return nil, terr
}
ops, meta := s.ioActionToOps(sender, act)
resp := &types.ConstructionParseResponse{
Operations: ops,
Metadata: meta,
}
if request.Signed {
resp.AccountIdentifierSigners = []*types.AccountIdentifier{
&types.AccountIdentifier{
Address: sender,
},
}
}
return resp, nil
}
// ConstructionPayloads implements the /construction/payloads endpoint.
func (s *constructionAPIService) ConstructionPayloads(
ctx context.Context,
request *types.ConstructionPayloadsRequest,
) (*types.ConstructionPayloadsResponse, *types.Error) {
if err := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier); err != nil {
return nil, err
}
if err := s.checkOperationAndMeta(request.Operations, request.Metadata, true); err != nil {
return nil, err
}
act := s.opsToIoAction(request.Operations, request.Metadata)
msg, err := proto.Marshal(act)
if err != nil {
terr := ErrServiceInternal
terr.Message += err.Error()
return nil, terr
}
unsignedTx := hex.EncodeToString(msg)
core, err := proto.Marshal(act.GetCore())
if err != nil {
terr := ErrServiceInternal
terr.Message += err.Error()
return nil, terr
}
h := hash.Hash256b(core)
return &types.ConstructionPayloadsResponse{
UnsignedTransaction: unsignedTx,
Payloads: []*types.SigningPayload{
{
AccountIdentifier: &types.AccountIdentifier{
Address: request.Operations[0].Account.Address,
},
Bytes: h[:],
SignatureType: SignatureType,
},
},
}, nil
}
// ConstructionPreprocess implements the /construction/preprocess endpoint.
func (s *constructionAPIService) ConstructionPreprocess(
ctx context.Context,
request *types.ConstructionPreprocessRequest,
) (*types.ConstructionPreprocessResponse, *types.Error) {
if err := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier); err != nil {
return nil, err
}
if err := s.checkOperationAndMeta(request.Operations, request.Metadata, false); err != nil {
return nil, err
}
options := make(map[string]interface{})
options["sender"] = request.Operations[0].Account.Address
options["type"] = request.Operations[0].Type
options["amount"] = request.Operations[1].Amount.Value
options["symbol"] = request.Operations[1].Amount.Currency.Symbol
options["decimals"] = request.Operations[1].Amount.Currency.Decimals
options["recipient"] = request.Operations[1].Account.Address
// XXX it is unclear where these meta data should be
if request.Metadata["gasLimit"] != nil {
options["gasLimit"] = request.Metadata["gasLimit"]
}
if request.Metadata["gasPrice"] != nil {
options["gasPrice"] = request.Metadata["gasPrice"]
}
// check and set max fee and fee multiplier
if len(request.MaxFee) != 0 {
maxFee := request.MaxFee[0]
if maxFee.Currency.Symbol != s.client.GetConfig().Currency.Symbol ||
maxFee.Currency.Decimals != s.client.GetConfig().Currency.Decimals {
terr := ErrConstructionCheck
terr.Message += "invalid currency"
return nil, terr
}
options["maxFee"] = maxFee.Value
}
if request.SuggestedFeeMultiplier != nil {
options["feeMultiplier"] = *request.SuggestedFeeMultiplier
}
return &types.ConstructionPreprocessResponse{
Options: options,
}, nil
}
// ConstructionSubmit implements the /construction/submit endpoint.
func (s *constructionAPIService) ConstructionSubmit(
ctx context.Context,
request *types.ConstructionSubmitRequest,
) (*types.TransactionIdentifierResponse, *types.Error) {
terr := ValidateNetworkIdentifier(ctx, s.client, request.NetworkIdentifier)
if terr != nil {
return nil, terr
}
tran, err := hex.DecodeString(request.SignedTransaction)
if err != nil {
terr := ErrInvalidInputParam
terr.Message += err.Error()
return nil, terr
}
act := &iotextypes.Action{}
if err := proto.Unmarshal(tran, act); err != nil {
terr := ErrInvalidInputParam
terr.Message += err.Error()
return nil, terr
}
txID, err := s.client.SubmitTx(ctx, act)
if err != nil {
terr := ErrUnableToSubmitTx
terr.Message += err.Error()
return nil, terr
}
return &types.TransactionIdentifierResponse{
TransactionIdentifier: &types.TransactionIdentifier{
Hash: txID,
},
}, nil
}
func (s *constructionAPIService) opsToIoAction(ops []*types.Operation, meta map[string]interface{}) *iotextypes.Action {
act := &iotextypes.Action{
Core: &iotextypes.ActionCore{
GasLimit: cast.ToUint64(meta["gasLimit"]),
GasPrice: new(big.Int).SetUint64(cast.ToUint64(meta["gasPrice"])).String(),
Nonce: cast.ToUint64(meta["nonce"]),
},
// NOTE use SenderPubKey field to temporary pass sender address,
// since rosetta-cli need to verify sender address in operations.
SenderPubKey: []byte(ops[0].Account.Address),
}
switch iotextypes.TransactionLogType(iotextypes.TransactionLogType_value[ops[0].Type]) {
case iotextypes.TransactionLogType_NATIVE_TRANSFER:
act.Core.Action = &iotextypes.ActionCore_Transfer{Transfer: opsToIoTransfer(ops)}
}
return act
}
func (s *constructionAPIService) ioActionToOps(sender string, act *iotextypes.Action) ([]*types.Operation, map[string]interface{}) {
meta := make(map[string]interface{})
meta["nonce"] = act.GetCore().GetNonce()
meta["gasLimit"] = act.GetCore().GetGasLimit()
gasPrice, _ := new(big.Int).SetString(act.GetCore().GetGasPrice(), 10)
meta["gasPrice"] = gasPrice.Uint64()
actCore := act.GetCore()
var ops []*types.Operation
switch {
case actCore.GetTransfer() != nil:
ops = ioTransferToOps(sender, actCore.GetTransfer(), &types.Currency{
Symbol: s.client.GetConfig().Currency.Symbol,
Decimals: s.client.GetConfig().Currency.Decimals,
})
}
return ops, meta
}
func (s *constructionAPIService) checkOperationAndMeta(ops []*types.Operation, meta map[string]interface{}, mustMeta bool) *types.Error {
terr := ErrConstructionCheck
if len(ops) == 0 {
terr.Message += "operation numbers are no expected"
return terr
}
typ := ops[0].Type
if !IsSupportedConstructionType(typ) {
terr.Message += "unsupported construction type"
return terr
}
switch iotextypes.TransactionLogType(iotextypes.TransactionLogType_value[typ]) {
case iotextypes.TransactionLogType_NATIVE_TRANSFER:
if terr := checkTransferOps(ops, &types.Currency{
Symbol: s.client.GetConfig().Currency.Symbol,
Decimals: s.client.GetConfig().Currency.Decimals,
}); terr != nil {
return terr
}
}
// check metadata exists
if mustMeta {
if meta["gasLimit"] == nil || meta["gasPrice"] == nil || meta["nonce"] == nil {
terr.Message += "metadata not complete"
return terr
}
}
// check gas
if meta["gasLimit"] != nil {
if _, err := cast.ToUint64E(meta["gasLimit"]); err != nil {
terr.Message += "invalid gas limit"
return terr
}
}
if meta["gasPrice"] != nil {
if _, err := cast.ToUint64E(meta["gasPrice"]); err != nil {
terr.Message += "invalid gas price"
return terr
}
}
if meta["nonce"] != nil {
if _, err := cast.ToUint64E(meta["nonce"]); err != nil {
terr.Message += "invalid nonce"
return terr
}
}
return nil
}
func (s *constructionAPIService) checkIoAction(act *iotextypes.Action, signed bool) (sender string, terr *types.Error) {
terr = ErrConstructionCheck
if _, ok := new(big.Int).SetString(act.GetCore().GetGasPrice(), 10); !ok {
terr.Message += "invalid gas price"
return "", terr
}
if !signed {
// NOTE use SenderPubKey to pass sender address
return string(act.GetSenderPubKey()), nil
}
// check pubkey and address
if len(act.GetSenderPubKey()) == 0 {
terr.Message += "invalid pub key"
return "", terr
}
pub, err := crypto.BytesToPublicKey(act.GetSenderPubKey())
if err != nil {
terr.Message += "invalid pub key"
return "", terr
}
senderAddr, err := address.FromBytes(pub.Hash())
if err != nil {
terr.Message += "invalid io address"
return "", terr
}
sender = senderAddr.String()
core, err := proto.Marshal(act.GetCore())
if err != nil {
terr = ErrServiceInternal
terr.Message += err.Error()
return "", terr
}
h := hash.Hash256b(core)
if !pub.Verify(h[:], act.GetSignature()) {
terr.Message += "invalid signature"
return "", terr
}
return sender, nil
}