-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconstruction_service.go
More file actions
1514 lines (1495 loc) · 40.7 KB
/
Copy pathconstruction_service.go
File metadata and controls
1514 lines (1495 loc) · 40.7 KB
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package api
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"strconv"
"strings"
"github.com/coinbase/rosetta-sdk-go/parser"
"github.com/coinbase/rosetta-sdk-go/types"
legacyProto "github.com/golang/protobuf/proto"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/onflow/flow/protobuf/go/flow/entities"
"github.com/onflow/rosetta/access"
"github.com/onflow/rosetta/crypto"
"github.com/onflow/rosetta/fees"
"github.com/onflow/rosetta/log"
"github.com/onflow/rosetta/model"
"github.com/onflow/rosetta/trace"
"golang.org/x/crypto/sha3"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
const (
txnTypeFlow = 1
txnTypeInner = 2
)
// ConstructionCombine implements the /construction/combine endpoint.
func (s *Server) ConstructionCombine(ctx context.Context, r *types.ConstructionCombineRequest) (*types.ConstructionCombineResponse, *types.Error) {
if len(r.Signatures) != 1 || r.Signatures[0] == nil {
return nil, errInvalidSignature
}
constructOpts := ""
split := strings.Split(r.UnsignedTransaction, ":")
if len(split) == 2 {
constructOpts = split[1]
}
txn, inner, xerr := s.decodeTransaction(r.UnsignedTransaction, false)
if xerr != nil {
return nil, xerr
}
// NOTE(tav): We truncate the signature passed in by the caller, in case
// they accidentally send us signatures in the ecdsa_recovery format.
sig := r.Signatures[0].Bytes[:64]
if txn != nil {
txn.EnvelopeSignatures = []*entities.Transaction_Signature{{
Address: txn.Payer,
KeyId: txn.ProposalKey.KeyId,
Signature: sig,
}}
enc, err := proto.Marshal(legacyProto.MessageV2(txn))
if err != nil {
return nil, wrapErr(errProtobuf, err)
}
enc = append([]byte{txnTypeFlow}, enc...)
return &types.ConstructionCombineResponse{
SignedTransaction: hex.EncodeToString(enc) + ":" + constructOpts,
}, nil
}
enc := append(inner.raw, sig...)
return &types.ConstructionCombineResponse{
SignedTransaction: hex.EncodeToString(enc),
}, nil
}
// ConstructionDerive implements the /construction/derive endpoint.
func (s *Server) ConstructionDerive(ctx context.Context, r *types.ConstructionDeriveRequest) (*types.ConstructionDeriveResponse, *types.Error) {
return &types.ConstructionDeriveResponse{}, nil
}
// ConstructionHash implements the /construction/hash endpoint.
func (s *Server) ConstructionHash(ctx context.Context, r *types.ConstructionHashRequest) (*types.TransactionIdentifierResponse, *types.Error) {
txn, inner, xerr := s.decodeTransaction(r.SignedTransaction, true)
if xerr != nil {
return nil, xerr
}
if txn != nil {
hash, err := model.TransactionHash(txn)
if err != nil {
return nil, wrapErr(errInternal, err)
}
return &types.TransactionIdentifierResponse{
TransactionIdentifier: &types.TransactionIdentifier{
Hash: hex.EncodeToString(hash),
},
}, nil
}
// NOTE(tav): For inner transactions, we generate a synthetic transaction
// hash.
hasher := sha3.New256()
_, _ = hasher.Write([]byte("inner-transaction-tag"))
_, _ = hasher.Write(inner.raw)
return &types.TransactionIdentifierResponse{
TransactionIdentifier: &types.TransactionIdentifier{
Hash: hex.EncodeToString(hasher.Sum(nil)),
},
}, nil
}
// ConstructionMetadata implements the /construction/metadata endpoint.
func (s *Server) ConstructionMetadata(ctx context.Context, r *types.ConstructionMetadataRequest) (*types.ConstructionMetadataResponse, *types.Error) {
if s.Offline {
return nil, errOfflineMode
}
_, opts, xerr := s.getConstructOpts(r.Options)
if xerr != nil {
return nil, xerr
}
height := uint64(0)
client := s.ConstructionAccessNodes.Client()
hdr, err := client.LatestBlockHeader(ctx)
if err != nil {
return nil, wrapErr(errInternal, err)
}
if opts.Inner {
if opts.SequenceNumber == -1 {
resp, err := client.Execute(
ctx, hdr.Id, s.scriptGetProxyNonce,
[]cadence.Value{cadence.BytesToAddress(opts.Payer)},
)
if err != nil {
return nil, wrapErrorf(
errFailedAccessAPICall,
"failed to execute get_proxy_nonce: %s", err,
)
}
nonce, ok := resp.(cadence.Int64)
if !ok {
return nil, wrapErrorf(
errInternal,
"expected type cadence.Int64 for nonce, got %T", resp,
)
}
opts.SequenceNumber = int64(nonce)
}
} else {
latest := s.Index.Latest()
if hdr.Height > latest.Height {
height = hdr.Height
opts.BlockHash = hdr.Id
opts.BlockHashFromRemote = true
opts.BlockHashRemoteServer = client.ServerAddress()
} else {
height = latest.Height
opts.BlockHash = latest.Hash
}
resp, err := client.Execute(
ctx, hdr.Id, s.scriptComputeFees,
[]cadence.Value{
cadence.UFix64(opts.InclusionEffort),
cadence.UFix64(opts.ExecutionEffort),
},
)
if err != nil {
return nil, wrapErrorf(
errFailedAccessAPICall,
"failed to execute compute_fees: %s", err,
)
}
cost, ok := resp.(cadence.UFix64)
if !ok {
return nil, wrapErrorf(
errInternal,
"expected type cadence.UFix64 for cost, got %T", resp,
)
}
opts.Fees = uint64(cost) + (opts.NewAccounts * fees.MinimumAccountBalance)
trace.SetAttributes(
ctx,
trace.String("access_api_server", client.ServerAddress()),
trace.Int64("latest_height_local", int64(latest.Height)),
trace.Int64("latest_height_remote", int64(hdr.Height)),
)
acct, err := client.AccountAtHeight(ctx, opts.Payer, height)
if err != nil {
return nil, wrapErr(errInternal, err)
}
count := 0
if opts.SequenceNumber == -1 {
found := false
for _, key := range acct.Keys {
if key.Index == opts.KeyId {
if key.Revoked {
return nil, wrapErrorf(
errInvalidKeyID,
"key %d has been revoked",
opts.KeyId,
)
}
opts.SequenceNumber = int64(key.SequenceNumber)
count++
found = true
} else if !key.Revoked {
count++
}
}
if !found {
return nil, wrapErrorf(
errInvalidKeyID,
"could not find key ID %d out of %d keys",
opts.KeyId, len(acct.Keys),
)
}
} else {
for _, key := range acct.Keys {
if !key.Revoked {
count++
}
}
}
if count != 1 {
return nil, wrapErrorf(
errInvalidNumberOfAccountKeys,
"found %d valid keys out of total %d keys",
count, len(acct.Keys),
)
}
}
data, err := proto.Marshal(opts)
if err != nil {
return nil, wrapErr(errProtobuf, err)
}
return &types.ConstructionMetadataResponse{
Metadata: map[string]interface{}{
"height": strconv.FormatUint(height, 10),
"protobuf": hex.EncodeToString(data),
},
SuggestedFee: []*types.Amount{
{Currency: flowCurrency, Value: strconv.FormatUint(opts.Fees, 10)},
},
}, nil
}
// ConstructionParse implements the /construction/parse endpoint.
func (s *Server) ConstructionParse(ctx context.Context, r *types.ConstructionParseRequest) (*types.ConstructionParseResponse, *types.Error) {
txn, inner, xerr := s.decodeTransaction(r.Transaction, r.Signed)
if xerr != nil {
return nil, xerr
}
if txn != nil {
if bytes.Equal(txn.Script, s.scriptBasicTransfer) {
return decodeTransferOps(txn, false, r.Signed)
}
if bytes.Equal(txn.Script, s.scriptProxyTransfer) {
return decodeTransferOps(txn, true, r.Signed)
}
if bytes.Equal(txn.Script, s.scriptCreateAccount) {
return decodeCreateAccountOps(txn, false, r.Signed)
}
if bytes.Equal(txn.Script, s.scriptCreateProxyAccount) {
return decodeCreateAccountOps(txn, true, r.Signed)
}
if bytes.Equal(txn.Script, s.scriptSetContract) {
return decodeContractOps(txn, r.Signed)
}
return nil, errInvalidTransactionPayload
}
ops := []*types.Operation{
{
Account: &types.AccountIdentifier{
Address: "0x" + hex.EncodeToString(inner.sender),
},
Amount: &types.Amount{
Currency: flowCurrency,
Value: "-" + strconv.FormatUint(inner.amount, 10),
},
OperationIdentifier: &types.OperationIdentifier{
Index: 0,
},
Type: opProxyTransferInner,
},
{
Account: &types.AccountIdentifier{
Address: "0x" + hex.EncodeToString(inner.receiver),
},
Amount: &types.Amount{
Currency: flowCurrency,
Value: strconv.FormatUint(inner.amount, 10),
},
OperationIdentifier: &types.OperationIdentifier{
Index: 1,
},
RelatedOperations: []*types.OperationIdentifier{{
Index: 0,
}},
Type: opProxyTransferInner,
},
}
txn = &entities.Transaction{
Payer: inner.sender,
}
return txnOps(txn, ops, r.Signed)
}
// ConstructionPayloads implements the /construction/payloads endpoint.
func (s *Server) ConstructionPayloads(ctx context.Context, r *types.ConstructionPayloadsRequest) (*types.ConstructionPayloadsResponse, *types.Error) {
rawOpts, opts, xerr := s.getConstructOpts(r.Metadata)
if xerr != nil {
return nil, xerr
}
payer := opts.Payer
intent, xerr := s.parseIntent(r.Operations)
if xerr != nil {
return nil, xerr
}
var (
args [][]byte
script []byte
)
if opts.SequenceNumber < 0 {
return nil, wrapErrorf(
errInvalidConstructOptions,
"invalid sequence_number from construct options: %d",
opts.SequenceNumber,
)
}
if intent.inner {
enc := make([]byte, 33)
enc[0] = txnTypeInner
binary.BigEndian.PutUint64(enc[1:], intent.amount)
binary.BigEndian.PutUint64(enc[9:], uint64(opts.SequenceNumber))
copy(enc[17:], intent.receiver)
copy(enc[25:], intent.sender)
hasher := sha3.New256()
_, _ = hasher.Write(userTag)
_, _ = hasher.Write(intent.receiver)
_, _ = hasher.Write(enc[1:17])
return &types.ConstructionPayloadsResponse{
Payloads: []*types.SigningPayload{{
AccountIdentifier: &types.AccountIdentifier{
Address: "0x" + hex.EncodeToString(intent.sender),
},
Bytes: hasher.Sum(nil),
SignatureType: types.Ecdsa,
}},
UnsignedTransaction: hex.EncodeToString(enc),
}, nil
}
if len(intent.keys) > 0 {
if intent.proxy {
script = s.scriptCreateProxyAccount
arg, err := jsoncdc.Encode(cadence.String(intent.keys[0]))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode public key: %s", err,
)
}
args = append(args, arg)
} else {
script = s.scriptCreateAccount
ckeys := make([]cadence.Value, len(intent.keys))
for i, key := range intent.keys {
ckeys[i] = cadence.String(key)
}
keys := cadence.NewArray(ckeys)
arg, err := jsoncdc.Encode(keys)
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode public keys: %s", err,
)
}
args = append(args, arg)
}
} else if intent.contractCode != "" {
script = s.scriptSetContract
arg, err := jsoncdc.Encode(cadence.Bool(intent.contractUpdate))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent,
"unable to JSON encode contract deploy/update flag: %s",
err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.String(intent.contractName))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode contract name: %s", err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.String(intent.contractCode))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode contract code: %s", err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.NewInt(int(intent.prevKeyIndex)))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode prev key index: %s", err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.String(intent.newKey))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode new key: %s", err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.String(intent.keyMessage))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode key message: %s", err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.String(intent.keySignature))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode key signature: %s", err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.String(intent.keyMetadata))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode key metadata: %s", err,
)
}
args = append(args, arg)
} else {
if intent.proxy {
script = s.scriptProxyTransfer
arg, err := jsoncdc.Encode(cadence.BytesToAddress(intent.sender))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode sender: %s", err,
)
}
args = append(args, arg)
} else {
script = s.scriptBasicTransfer
}
arg, err := jsoncdc.Encode(cadence.BytesToAddress(intent.receiver))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode receiver: %s", err,
)
}
args = append(args, arg)
arg, err = jsoncdc.Encode(cadence.UFix64(intent.amount))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode amount: %s", err,
)
}
args = append(args, arg)
if intent.proxy {
if len(opts.ProxyTransferPayload) == 0 {
return nil, wrapErrorf(
errInvalidConstructOptions,
"proxy_transfer_payload was not specified in the /construction/preprocess metadata",
)
}
_, inner, xerr := s.decodeTransaction(opts.ProxyTransferPayload, true)
if xerr != nil {
return nil, xerr
}
arg, err = jsoncdc.Encode(cadence.Int64(inner.nonce))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode nonce: %s", err,
)
}
args = append(args, arg)
sig := hex.EncodeToString(inner.raw[33:])
arg, err = jsoncdc.Encode(cadence.String(sig))
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent, "unable to JSON encode signature: %s", err,
)
}
args = append(args, arg)
}
}
txn := &entities.Transaction{
Arguments: args,
Authorizers: [][]byte{payer},
GasLimit: 9999,
Payer: payer,
ProposalKey: &entities.Transaction_ProposalKey{
Address: payer,
KeyId: opts.KeyId,
SequenceNumber: uint64(opts.SequenceNumber),
},
ReferenceBlockId: opts.BlockHash,
Script: script,
}
hash, err := model.TransactionEnvelopeHash(txn)
if err != nil {
return nil, wrapErr(errInternal, err)
}
enc, err := proto.Marshal(legacyProto.MessageV2(txn))
if err != nil {
return nil, wrapErr(errProtobuf, err)
}
enc = append([]byte{txnTypeFlow}, enc...)
return &types.ConstructionPayloadsResponse{
Payloads: []*types.SigningPayload{{
AccountIdentifier: &types.AccountIdentifier{
Address: "0x" + hex.EncodeToString(payer),
},
Bytes: hash,
SignatureType: types.Ecdsa,
}},
UnsignedTransaction: hex.EncodeToString(enc) + ":" + rawOpts,
}, nil
}
// ConstructionPreprocess implements the /construction/preprocess endpoint.
func (s *Server) ConstructionPreprocess(ctx context.Context, r *types.ConstructionPreprocessRequest) (*types.ConstructionPreprocessResponse, *types.Error) {
intent, xerr := s.parseIntent(r.Operations)
if xerr != nil {
return nil, xerr
}
// NOTE(tav): We explicitly error on transfers to a fee address so as to
// simplify our event processing logic.
feeAddrs := s.feeAddrs
if latest := s.Index.Latest(); latest != nil {
feeAddrs = s.currentFeeAddrs(latest.Height)
}
if feeAddrs[string(intent.receiver)] {
return nil, wrapErrorf(
errInvalidOpsIntent,
"cannot make transfers to the fee address: 0x%x",
intent.receiver,
)
}
opts := &model.ConstructOpts{
InclusionEffort: fees.InclusionEffort,
Inner: intent.inner,
NewAccounts: uint64(len(intent.keys)),
SequenceNumber: -1,
}
if intent.proxy && len(intent.keys) == 0 {
val, ok := r.Metadata["proxy_transfer_payload"]
if !ok {
return nil, wrapErrorf(
errInvalidMetadataField,
"proxy_transfer_payload metadata field is missing",
)
}
raw, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidMetadataField,
"proxy_transfer_payload metadata field is not a string: %v", val,
)
}
opts.ProxyTransferPayload = raw
}
if intent.contractCode != "" {
opts.KeyId = intent.prevKeyIndex
if intent.contractUpdate {
opts.ExecutionEffort = fees.UpdateContractEffort
} else {
opts.ExecutionEffort = fees.DeployContractEffort
}
} else if len(intent.keys) > 0 {
if intent.proxy {
opts.ExecutionEffort = fees.CreateProxyAccountEffort
} else {
opts.ExecutionEffort = uint64(fees.CreateAccountEffort * len(intent.keys))
}
} else {
if intent.proxy {
opts.ExecutionEffort = fees.FlowTransferEffort
} else {
opts.ExecutionEffort = fees.ProxyTransferEffort
}
}
if val, ok := r.Metadata["sequence_number"]; ok {
raw, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidMetadataField,
"sequence_number metadata field is not a string: %v", val,
)
}
seq, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return nil, wrapErrorf(
errInvalidMetadataField,
"invalid sequence_number value: %q: %s", val, err,
)
}
if seq < 0 {
return nil, wrapErrorf(
errInvalidMetadataField,
"invalid sequence_number value: %d", seq,
)
}
opts.SequenceNumber = seq
}
// NOTE(tav): We override the metadata.payer with the sender account
// address, if it is a proxy_transfer_inner operation.
if opts.Inner {
opts.Payer = intent.sender
} else {
val, ok := r.Metadata["payer"]
if !ok {
return nil, wrapErrorf(
errInvalidMetadataField,
"payer metadata field is missing",
)
}
raw, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidMetadataField,
"payer metadata field is not a string: %v", val,
)
}
payer, xerr := s.getAccount(raw)
if xerr != nil {
return nil, wrapErrorf(
errInvalidMetadataField,
"invalid payer value: %s", formatErr(xerr),
)
}
opts.Payer = payer
}
data, err := proto.Marshal(opts)
if err != nil {
return nil, wrapErr(errProtobuf, err)
}
return &types.ConstructionPreprocessResponse{
Options: map[string]interface{}{
"protobuf": hex.EncodeToString(data),
},
}, nil
}
// ConstructionSubmit implements the /construction/submit endpoint.
func (s *Server) ConstructionSubmit(ctx context.Context, r *types.ConstructionSubmitRequest) (*types.TransactionIdentifierResponse, *types.Error) {
if s.Offline {
return nil, errOfflineMode
}
txn, inner, xerr := s.decodeTransaction(r.SignedTransaction, true)
if xerr != nil {
return nil, xerr
}
if inner != nil {
return nil, wrapErrorf(
errInvalidTransactionPayload,
"inner transactions cannot be submitted",
)
}
client := s.ConstructionAccessNodes.Client()
err := client.Ping(ctx)
if err != nil {
return nil, wrapErr(errAccessNodeInaccessible, err)
}
hash, err := client.SendTransaction(ctx, txn)
if err != nil {
txnHash := ""
hash, herr := model.TransactionHash(txn)
if herr == nil {
txnHash = hex.EncodeToString(hash)
} else {
log.Errorf("Unable to derive transaction hash: %s", herr)
}
if access.IsRateLimited(err) {
return nil, wrapErrorf(
errRateLimited,
"failed to submit txn %s: %s",
txnHash, err,
)
}
switch status.Code(err) {
case codes.InvalidArgument:
// NOTE(tav): The substring match below needs to be kept in sync
// with upstream responses.
if strings.Contains(err.Error(), "transaction is expired") {
opts := decodeOptsFromTransaction(r.SignedTransaction)
if opts != nil {
src := "locally indexed data"
if opts.BlockHashFromRemote {
src = fmt.Sprintf("remote server %q", opts.BlockHashRemoteServer)
}
return nil, wrapErrorf(
errTransactionExpired,
"expired transaction %s: %s: reference block hash used from %s",
txnHash, err, src,
)
}
return nil, wrapErrorf(
errTransactionExpired,
"expired transaction %s: %s",
txnHash, err,
)
}
}
// TODO(tav): Distinguish between other non-fatal and fatal errors.
return nil, wrapErrorf(
errBroadcastFailed,
"failed to submit transaction %s: %s",
txnHash, err,
)
}
return &types.TransactionIdentifierResponse{
TransactionIdentifier: &types.TransactionIdentifier{
Hash: hex.EncodeToString(hash),
},
}, nil
}
func (s *Server) decodeTransaction(src string, signed bool) (*entities.Transaction, *innerTxn, *types.Error) {
split := strings.Split(src, ":")
if len(split) == 2 {
src = split[0]
}
raw, err := hex.DecodeString(src)
if err != nil {
return nil, nil, wrapErr(errInvalidTransactionPayload, err)
}
if len(raw) == 0 {
return nil, nil, wrapErrorf(errInvalidTransactionPayload, "missing transaction data")
}
switch raw[0] {
case txnTypeFlow:
txn := &entities.Transaction{}
if err := proto.Unmarshal(raw[1:], legacyProto.MessageV2(txn)); err != nil {
return nil, nil, wrapErr(errProtobuf, err)
}
if signed {
if len(txn.EnvelopeSignatures) != 1 {
return nil, nil, wrapErrorf(
errInvalidTransactionPayload,
"invalid number of envelope signatures for signed transaction: %d",
len(txn.EnvelopeSignatures),
)
}
if txn.EnvelopeSignatures[0] == nil {
return nil, nil, wrapErrorf(
errInvalidTransactionPayload,
"transaction missing envelope signature",
)
}
}
return txn, nil, nil
case txnTypeInner:
txn := &innerTxn{
raw: raw,
}
if signed {
if len(raw) != 97 {
return nil, nil, wrapErrorf(
errInvalidTransactionPayload,
"unexpected length for signed transaction payload: expected 97, got %d",
len(raw),
)
}
} else {
if len(raw) != 33 {
return nil, nil, wrapErrorf(
errInvalidTransactionPayload,
"unexpected length for transaction payload: expected 33, got %d",
len(raw),
)
}
}
txn.amount = binary.BigEndian.Uint64(raw[1:])
txn.nonce = binary.BigEndian.Uint64(raw[9:])
txn.receiver = raw[17:25]
txn.sender = raw[25:33]
return nil, txn, nil
default:
return nil, nil, wrapErrorf(
errInvalidTransactionPayload, "unknown transaction type: %d", raw[0],
)
}
}
func (s *Server) getConstructOpts(md map[string]interface{}) (string, *model.ConstructOpts, *types.Error) {
val, ok := md["protobuf"]
if !ok {
return "", nil, wrapErrorf(
errInvalidConstructOptions,
"missing protobuf options field",
)
}
raw, ok := val.(string)
if !ok {
return "", nil, wrapErrorf(
errInvalidConstructOptions,
"protobuf options field is not a string: %v", val,
)
}
enc, err := hex.DecodeString(raw)
if err != nil {
return "", nil, wrapErrorf(
errInvalidConstructOptions,
"protobuf options field is not a string: %v", val,
)
}
opts := &model.ConstructOpts{}
err = proto.Unmarshal(enc, opts)
if err != nil {
return "", nil, wrapErr(errProtobuf, err)
}
return raw, opts, nil
}
func (s *Server) parseIntent(ops []*types.Operation) (*txnIntent, *types.Error) {
if len(ops) == 0 {
return nil, wrapErrorf(errInvalidOpsIntent, "missing operations")
}
if ops[0] == nil {
return nil, wrapErrorf(errInvalidOpsIntent, "null operation value encountered")
}
typ := ops[0].Type
for _, op := range ops {
if op == nil {
return nil, wrapErrorf(errInvalidOpsIntent, "null operation value encountered")
}
if op.Type != typ {
return nil, wrapErrorf(
errInvalidOpsIntent,
"mismatching operation types encountered: %q and %q",
typ,
op.Type,
)
}
}
intent := &txnIntent{}
switch typ {
case opCreateAccount, opCreateProxyAccount:
for _, op := range ops {
val, ok := op.Metadata["public_key"]
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent, "public_key metadata field missing on operation",
)
}
raw, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent,
"public_key metadata field on operation is not a string: %v",
val,
)
}
compressed, err := hex.DecodeString(raw)
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent,
"invalid public_key metadata field on operation: %s",
err,
)
}
pub, err := crypto.ConvertRosettaPublicKey(compressed)
if err != nil {
return nil, wrapErr(errInvalidOpsIntent, err)
}
intent.keys = append(intent.keys, hex.EncodeToString(pub))
}
if typ == opCreateProxyAccount {
if len(ops) > 1 {
return nil, wrapErrorf(
errInvalidOpsIntent,
"multiple (%d) %s operations found",
len(ops), typ,
)
}
intent.proxy = true
}
case opDeployContract, opUpdateContract:
if len(ops) > 1 {
return nil, wrapErrorf(
errInvalidOpsIntent,
"multiple (%d) %s operations found",
len(ops), typ,
)
}
op := ops[0]
val, ok := op.Metadata["contract_name"]
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent, "contract_name metadata field missing on operation",
)
}
name, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent,
"contract_name metadata field on operation is not a string: %v",
val,
)
}
if len(name) == 0 {
return nil, wrapErrorf(
errInvalidOpsIntent,
"contract_name metadata field on operation is empty",
)
}
val, ok = op.Metadata["contract_code"]
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent, "contract_code metadata field missing on operation",
)
}
code, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent,
"contract_code metadata field on operation is not a string: %v",
val,
)
}
_, err := hex.DecodeString(code)
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent,
"failed to hex-decode contract_code metadata field on operation: %s",
err,
)
}
if len(code) == 0 {
return nil, wrapErrorf(
errInvalidOpsIntent,
"contract_code metadata field on operation is empty",
)
}
val, ok = op.Metadata["prev_key_index"]
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent, "prev_key_index metadata field missing on operation",
)
}
prevKeyIndex, ok := val.(float64)
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent,
"prev_key_index metadata field on operation is not a number: %v",
val,
)
}
val, ok = op.Metadata["new_key"]
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent, "new_key metadata field missing on operation",
)
}
rawKey, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent,
"new_key metadata field on operation is not a string: %v",
val,
)
}
srcKey, err := hex.DecodeString(rawKey)
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent,
"failed to hex-decode new_key metadata field on operation: %s",
err,
)
}
if len(srcKey) == 0 {
return nil, wrapErrorf(
errInvalidOpsIntent,
"new_key metadata field on operation is empty",
)
}
newKey, err := crypto.ConvertRosettaPublicKey(srcKey)
if err != nil {
return nil, wrapErrorf(
errInvalidOpsIntent,
"could not convert new_key value from operation: %s",
err,
)
}
val, ok = op.Metadata["key_message"]
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent, "key_message metadata field missing on operation",
)
}
keyMessage, ok := val.(string)
if !ok {
return nil, wrapErrorf(
errInvalidOpsIntent,
"key_message metadata field on operation is not a string: %v",
val,
)
}
if len(keyMessage) == 0 {
return nil, wrapErrorf(