forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
1196 lines (1046 loc) · 38.8 KB
/
transaction.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
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 txnbuild implements transactions and operations on the AiBlocks network.
This library provides an interface to the AiBlocks transaction model. It supports the building of Go applications on
top of the AiBlocks network (https://www.aiblocks.io/). Transactions constructed by this library may be submitted
to any Millennium instance for processing onto the ledger, using any AiBlocks SDK client. The recommended client for Go
programmers is millenniumclient (https://github.com/aiblocks/go/tree/master/clients/millenniumclient). Together, these two
libraries provide a complete AiBlocks SDK.
For more information and further examples, see https://www.aiblocks.io/developers/go/reference/index.html.
*/
package txnbuild
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"math"
"math/bits"
"strings"
"time"
"github.com/aiblocks/go/keypair"
"github.com/aiblocks/go/network"
"github.com/aiblocks/go/strkey"
"github.com/aiblocks/go/support/errors"
"github.com/aiblocks/go/xdr"
)
// MinBaseFee is the minimum transaction fee for the AiBlocks network.
const MinBaseFee = 100
// Account represents the aspects of a AiBlocks account necessary to construct transactions. See
// https://www.aiblocks.io/developers/guides/concepts/accounts.html
type Account interface {
GetAccountID() string
IncrementSequenceNumber() (int64, error)
GetSequenceNumber() (int64, error)
}
func hashHex(e xdr.TransactionEnvelope, networkStr string) (string, error) {
h, err := network.HashTransactionInEnvelope(e, networkStr)
if err != nil {
return "", err
}
return hex.EncodeToString(h[:]), nil
}
func concatSignatures(
e xdr.TransactionEnvelope,
networkStr string,
signatures []xdr.DecoratedSignature,
kps ...*keypair.Full,
) ([]xdr.DecoratedSignature, error) {
// Hash the transaction
h, err := network.HashTransactionInEnvelope(e, networkStr)
if err != nil {
return nil, errors.Wrap(err, "failed to hash transaction")
}
extended := make(
[]xdr.DecoratedSignature,
len(signatures),
len(signatures)+len(kps),
)
copy(extended, signatures)
// Sign the hash
for _, kp := range kps {
sig, err := kp.SignDecorated(h[:])
if err != nil {
return nil, errors.Wrap(err, "failed to sign transaction")
}
extended = append(extended, sig)
}
return extended, nil
}
func concatSignatureBase64(e xdr.TransactionEnvelope, signatures []xdr.DecoratedSignature, networkStr, publicKey, signature string) ([]xdr.DecoratedSignature, error) {
if signature == "" {
return nil, errors.New("signature not presented")
}
kp, err := keypair.ParseAddress(publicKey)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse the public key %s", publicKey)
}
sigBytes, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return nil, errors.Wrapf(err, "failed to base64-decode the signature %s", signature)
}
h, err := network.HashTransactionInEnvelope(e, networkStr)
if err != nil {
return nil, errors.Wrap(err, "failed to hash transaction")
}
err = kp.Verify(h[:], sigBytes)
if err != nil {
return nil, errors.Wrap(err, "failed to verify the signature")
}
extended := make([]xdr.DecoratedSignature, len(signatures), len(signatures)+1)
copy(extended, signatures)
extended = append(extended, xdr.DecoratedSignature{
Hint: xdr.SignatureHint(kp.Hint()),
Signature: xdr.Signature(sigBytes),
})
return extended, nil
}
func stringsToKP(keys ...string) ([]*keypair.Full, error) {
var signers []*keypair.Full
for _, k := range keys {
kp, err := keypair.Parse(k)
if err != nil {
return nil, errors.Wrapf(err, "provided string %s is not a valid AiBlocks key", k)
}
kpf, ok := kp.(*keypair.Full)
if !ok {
return nil, errors.New("provided string %s is not a valid AiBlocks secret key")
}
signers = append(signers, kpf)
}
return signers, nil
}
func concatHashX(signatures []xdr.DecoratedSignature, preimage []byte) ([]xdr.DecoratedSignature, error) {
if maxSize := xdr.Signature(preimage).XDRMaxSize(); len(preimage) > maxSize {
return nil, errors.Errorf(
"preimage cannnot be more than %d bytes", maxSize,
)
}
extended := make(
[]xdr.DecoratedSignature,
len(signatures),
len(signatures)+1,
)
copy(extended, signatures)
preimageHash := sha256.Sum256(preimage)
var hint [4]byte
// copy the last 4-bytes of the signer public key to be used as hint
copy(hint[:], preimageHash[28:])
sig := xdr.DecoratedSignature{
Hint: xdr.SignatureHint(hint),
Signature: xdr.Signature(preimage),
}
return append(extended, sig), nil
}
func marshallBinary(e xdr.TransactionEnvelope, signatures []xdr.DecoratedSignature) ([]byte, error) {
switch e.Type {
case xdr.EnvelopeTypeEnvelopeTypeTx:
e.V1.Signatures = signatures
case xdr.EnvelopeTypeEnvelopeTypeTxV0:
e.V0.Signatures = signatures
case xdr.EnvelopeTypeEnvelopeTypeTxFeeBump:
e.FeeBump.Signatures = signatures
default:
panic("invalid transaction type: " + e.Type.String())
}
var txBytes bytes.Buffer
_, err := xdr.Marshal(&txBytes, e)
if err != nil {
return nil, err
}
return txBytes.Bytes(), nil
}
func marshallBase64(e xdr.TransactionEnvelope, signatures []xdr.DecoratedSignature) (string, error) {
binary, err := marshallBinary(e, signatures)
if err != nil {
return "", errors.Wrap(err, "failed to get XDR bytestring")
}
return base64.StdEncoding.EncodeToString(binary), nil
}
func cloneEnvelope(e xdr.TransactionEnvelope, signatures []xdr.DecoratedSignature) (xdr.TransactionEnvelope, error) {
var clone xdr.TransactionEnvelope
binary, err := marshallBinary(e, signatures)
if err != nil {
return clone, errors.Wrap(err, "could not marshall envelope")
}
if err = xdr.SafeUnmarshal(binary, &clone); err != nil {
return clone, errors.Wrap(err, "could not unmarshall envelope")
}
return clone, nil
}
// Transaction represents a AiBlocks transaction. See
// https://www.aiblocks.io/developers/guides/concepts/transactions.html
// A Transaction may be wrapped by a FeeBumpTransaction in which case
// the account authorizing the FeeBumpTransaction will pay for the transaction fees
// instead of the Transaction's source account.
type Transaction struct {
envelope xdr.TransactionEnvelope
baseFee int64
maxFee int64
sourceAccount SimpleAccount
operations []Operation
memo Memo
timebounds Timebounds
signatures []xdr.DecoratedSignature
}
// BaseFee returns the per operation fee for this transaction.
func (t *Transaction) BaseFee() int64 {
return t.baseFee
}
// MaxFee returns the total fees which can be spent to submit this transaction.
func (t *Transaction) MaxFee() int64 {
return t.maxFee
}
// SourceAccount returns the account which is originating this account.
func (t *Transaction) SourceAccount() SimpleAccount {
return t.sourceAccount
}
// Memo returns the memo configured for this transaction.
func (t *Transaction) Memo() Memo {
return t.memo
}
// Timebounds returns the Timebounds configured for this transaction.
func (t *Transaction) Timebounds() Timebounds {
return t.timebounds
}
// Operations returns the list of operations included in this transaction.
// The contents of the returned slice should not be modified.
func (t *Transaction) Operations() []Operation {
return t.operations
}
// Signatures returns the list of signatures attached to this transaction.
// The contents of the returned slice should not be modified.
func (t *Transaction) Signatures() []xdr.DecoratedSignature {
return t.signatures
}
// Hash returns the network specific hash of this transaction
// encoded as a byte array.
func (t *Transaction) Hash(networkStr string) ([32]byte, error) {
return network.HashTransactionInEnvelope(t.envelope, networkStr)
}
// HashHex returns the network specific hash of this transaction
// encoded as a hexadecimal string.
func (t *Transaction) HashHex(network string) (string, error) {
return hashHex(t.envelope, network)
}
// Sign returns a new Transaction instance which extends the current instance
// with additional signatures derived from the given list of keypair instances.
func (t *Transaction) Sign(network string, kps ...*keypair.Full) (*Transaction, error) {
extendedSignatures, err := concatSignatures(t.envelope, network, t.signatures, kps...)
if err != nil {
return nil, err
}
newTx := new(Transaction)
*newTx = *t
newTx.signatures = extendedSignatures
return newTx, nil
}
// SignWithKeyString returns a new Transaction instance which extends the current instance
// with additional signatures derived from the given list of private key strings.
func (t *Transaction) SignWithKeyString(network string, keys ...string) (*Transaction, error) {
kps, err := stringsToKP(keys...)
if err != nil {
return nil, err
}
return t.Sign(network, kps...)
}
// SignHashX returns a new Transaction instance which extends the current instance
// with HashX signature type.
// See description here: https://www.aiblocks.io/developers/guides/concepts/multi-sig.html#hashx.
func (t *Transaction) SignHashX(preimage []byte) (*Transaction, error) {
extendedSignatures, err := concatHashX(t.signatures, preimage)
if err != nil {
return nil, err
}
newTx := new(Transaction)
*newTx = *t
newTx.signatures = extendedSignatures
return newTx, nil
}
// AddSignatureBase64 returns a new Transaction instance which extends the current instance
// with an additional signature derived from the given base64-encoded signature.
func (t *Transaction) AddSignatureBase64(network, publicKey, signature string) (*Transaction, error) {
extendedSignatures, err := concatSignatureBase64(t.envelope, t.signatures, network, publicKey, signature)
if err != nil {
return nil, err
}
newTx := new(Transaction)
*newTx = *t
newTx.signatures = extendedSignatures
return newTx, nil
}
// TxEnvelope returns the a xdr.TransactionEnvelope instance which is
// equivalent to this transaction.
func (t *Transaction) TxEnvelope() (xdr.TransactionEnvelope, error) {
return cloneEnvelope(t.envelope, t.signatures)
}
// ToXDR is like TxEnvelope except that the transaction envelope returned by ToXDR
// should not be modified because any changes applied to the transaction envelope may
// affect the internals of the Transaction instance.
func (t *Transaction) ToXDR() xdr.TransactionEnvelope {
env := t.envelope
switch env.Type {
case xdr.EnvelopeTypeEnvelopeTypeTx:
env.V1.Signatures = t.signatures
case xdr.EnvelopeTypeEnvelopeTypeTxV0:
env.V0.Signatures = t.signatures
default:
panic("invalid transaction type: " + env.Type.String())
}
return env
}
// MarshalBinary returns the binary XDR representation of the transaction envelope.
func (t *Transaction) MarshalBinary() ([]byte, error) {
return marshallBinary(t.envelope, t.signatures)
}
// Base64 returns the base 64 XDR representation of the transaction envelope.
func (t *Transaction) Base64() (string, error) {
return marshallBase64(t.envelope, t.signatures)
}
// ClaimableBalanceID returns the claimable balance ID for the operation at the given index within the transaction.
// given index (which should be a `CreateClaimableBalance` operation).
func (t *Transaction) ClaimableBalanceID(operationIndex int) (string, error) {
if operationIndex < 0 || operationIndex >= len(t.operations) {
return "", errors.New("invalid operation index")
}
operation, ok := t.operations[operationIndex].(*CreateClaimableBalance)
if !ok {
return "", errors.New("operation is not CreateClaimableBalance")
}
// Use the operation's source account or the transaction's source if not.
var account Account = &t.sourceAccount
if operation.SourceAccount != nil {
account = operation.GetSourceAccount()
}
seq, err := account.GetSequenceNumber()
if err != nil {
return "", errors.Wrap(err, "failed to retrieve account sequence number")
}
// We mimic the relevant code from AiBlocks Core
// https://github.com/aiblocks/aiblocks-core/blob/9f3cc04e6ec02c38974c42545a86cdc79809252b/src/test/TestAccount.cpp#L285
operationId := xdr.OperationId{
Type: xdr.EnvelopeTypeEnvelopeTypeOpId,
Id: &xdr.OperationIdId{
SourceAccount: xdr.MustMuxedAddress(account.GetAccountID()),
SeqNum: xdr.SequenceNumber(seq),
OpNum: xdr.Uint32(operationIndex),
},
}
binaryDump, err := operationId.MarshalBinary()
if err != nil {
return "", errors.Wrap(err, "invalid claimable balance operation")
}
hash := sha256.Sum256(binaryDump)
balanceIdXdr, err := xdr.NewClaimableBalanceId(
// TODO: look into whether this be determined programmatically from the operation structure.
xdr.ClaimableBalanceIdTypeClaimableBalanceIdTypeV0,
xdr.Hash(hash))
if err != nil {
return "", errors.Wrap(err, "unable to parse balance ID as XDR")
}
balanceIdHex, err := xdr.MarshalHex(balanceIdXdr)
if err != nil {
return "", errors.Wrap(err, "unable to encode balance ID as hex")
}
return balanceIdHex, nil
}
// FeeBumpTransaction represents a CAP 15 fee bump transaction.
// Fee bump transactions allow an arbitrary account to pay the fee for a transaction.
type FeeBumpTransaction struct {
envelope xdr.TransactionEnvelope
baseFee int64
maxFee int64
feeAccount string
inner *Transaction
signatures []xdr.DecoratedSignature
}
// BaseFee returns the per operation fee for this transaction.
func (t *FeeBumpTransaction) BaseFee() int64 {
return t.baseFee
}
// MaxFee returns the total fees which can be spent to submit this transaction.
func (t *FeeBumpTransaction) MaxFee() int64 {
return t.maxFee
}
// FeeAccount returns the address of the account which will be paying for the inner transaction.
func (t *FeeBumpTransaction) FeeAccount() string {
return t.feeAccount
}
// Signatures returns the list of signatures attached to this transaction.
// The contents of the returned slice should not be modified.
func (t *FeeBumpTransaction) Signatures() []xdr.DecoratedSignature {
return t.signatures
}
// Hash returns the network specific hash of this transaction
// encoded as a byte array.
func (t *FeeBumpTransaction) Hash(networkStr string) ([32]byte, error) {
return network.HashTransactionInEnvelope(t.envelope, networkStr)
}
// Sign returns a new FeeBumpTransaction instance which extends the current instance
// with additional signatures derived from the given list of keypair instances.
func (t *FeeBumpTransaction) Sign(network string, kps ...*keypair.Full) (*FeeBumpTransaction, error) {
extendedSignatures, err := concatSignatures(t.envelope, network, t.signatures, kps...)
if err != nil {
return nil, err
}
newTx := new(FeeBumpTransaction)
*newTx = *t
newTx.signatures = extendedSignatures
return newTx, nil
}
// TxEnvelope returns the a xdr.TransactionEnvelope instance which is
// equivalent to this transaction.
func (t *FeeBumpTransaction) TxEnvelope() (xdr.TransactionEnvelope, error) {
return cloneEnvelope(t.envelope, t.signatures)
}
// ToXDR is like TxEnvelope except that the transaction envelope returned by ToXDR
// should not be modified because any changes applied to the transaction envelope may
// affect the internals of the FeeBumpTransaction instance.
func (t *FeeBumpTransaction) ToXDR() xdr.TransactionEnvelope {
env := t.envelope
switch env.Type {
case xdr.EnvelopeTypeEnvelopeTypeTxFeeBump:
env.FeeBump.Signatures = t.signatures
default:
panic("invalid transaction type: " + env.Type.String())
}
return env
}
// MarshalBinary returns the binary XDR representation of the transaction envelope.
func (t *FeeBumpTransaction) MarshalBinary() ([]byte, error) {
return marshallBinary(t.envelope, t.signatures)
}
// Base64 returns the base 64 XDR representation of the transaction envelope.
func (t *FeeBumpTransaction) Base64() (string, error) {
return marshallBase64(t.envelope, t.signatures)
}
// InnerTransaction returns the Transaction which is wrapped by
// this FeeBumpTransaction instance.
func (t *FeeBumpTransaction) InnerTransaction() *Transaction {
innerCopy := new(Transaction)
*innerCopy = *t.inner
return innerCopy
}
// GenericTransaction represents a parsed transaction envelope returned by TransactionFromXDR.
// A GenericTransaction can be either a Transaction or a FeeBumpTransaction.
type GenericTransaction struct {
simple *Transaction
feeBump *FeeBumpTransaction
}
// Transaction unpacks the GenericTransaction instance into a Transaction.
// The function also returns a boolean which is true if the GenericTransaction can be
// unpacked into a Transaction.
func (t GenericTransaction) Transaction() (*Transaction, bool) {
return t.simple, t.simple != nil
}
// FeeBump unpacks the GenericTransaction instance into a FeeBumpTransaction.
// The function also returns a boolean which is true if the GenericTransaction
// can be unpacked into a FeeBumpTransaction.
func (t GenericTransaction) FeeBump() (*FeeBumpTransaction, bool) {
return t.feeBump, t.feeBump != nil
}
// TransactionFromXDR parses the supplied transaction envelope in base64 XDR
// and returns a GenericTransaction instance.
func TransactionFromXDR(txeB64 string) (*GenericTransaction, error) {
var xdrEnv xdr.TransactionEnvelope
err := xdr.SafeUnmarshalBase64(txeB64, &xdrEnv)
if err != nil {
return nil, errors.Wrap(err, "unable to unmarshal transaction envelope")
}
return transactionFromParsedXDR(xdrEnv)
}
func transactionFromParsedXDR(xdrEnv xdr.TransactionEnvelope) (*GenericTransaction, error) {
var err error
newTx := &GenericTransaction{}
if xdrEnv.IsFeeBump() {
var innerTx *GenericTransaction
innerTx, err = transactionFromParsedXDR(xdr.TransactionEnvelope{
Type: xdr.EnvelopeTypeEnvelopeTypeTx,
V1: xdrEnv.FeeBump.Tx.InnerTx.V1,
})
if err != nil {
return newTx, errors.New("could not parse inner transaction")
}
feeBumpAccount := xdrEnv.FeeBumpAccount().ToAccountId()
newTx.feeBump = &FeeBumpTransaction{
envelope: xdrEnv,
// A fee-bump transaction has an effective number of operations equal to one plus the
// number of operations in the inner transaction. Correspondingly, the minimum fee for
// the fee-bump transaction is one base fee more than the minimum fee for the inner
// transaction.
baseFee: xdrEnv.FeeBumpFee() / int64(len(innerTx.simple.operations)+1),
maxFee: xdrEnv.FeeBumpFee(),
inner: innerTx.simple,
feeAccount: feeBumpAccount.Address(),
signatures: xdrEnv.FeeBumpSignatures(),
}
return newTx, nil
}
sourceAccount := xdrEnv.SourceAccount().ToAccountId()
totalFee := int64(xdrEnv.Fee())
baseFee := totalFee
if count := int64(len(xdrEnv.Operations())); count > 0 {
baseFee = baseFee / count
}
newTx.simple = &Transaction{
envelope: xdrEnv,
baseFee: baseFee,
maxFee: totalFee,
sourceAccount: SimpleAccount{
AccountID: sourceAccount.Address(),
Sequence: xdrEnv.SeqNum(),
},
operations: nil,
memo: nil,
timebounds: Timebounds{},
signatures: xdrEnv.Signatures(),
}
if timeBounds := xdrEnv.TimeBounds(); timeBounds != nil {
newTx.simple.timebounds = NewTimebounds(int64(timeBounds.MinTime), int64(timeBounds.MaxTime))
}
newTx.simple.memo, err = memoFromXDR(xdrEnv.Memo())
if err != nil {
return nil, errors.Wrap(err, "unable to parse memo")
}
operations := xdrEnv.Operations()
for _, op := range operations {
newOp, err := operationFromXDR(op)
if err != nil {
return nil, err
}
newTx.simple.operations = append(newTx.simple.operations, newOp)
}
return newTx, nil
}
// TransactionParams is a container for parameters
// which are used to construct new Transaction instances
type TransactionParams struct {
SourceAccount Account
IncrementSequenceNum bool
Operations []Operation
BaseFee int64
Memo Memo
Timebounds Timebounds
}
// NewTransaction returns a new Transaction instance
func NewTransaction(params TransactionParams) (*Transaction, error) {
var sequence int64
var err error
if params.SourceAccount == nil {
return nil, errors.New("transaction has no source account")
}
if params.IncrementSequenceNum {
sequence, err = params.SourceAccount.IncrementSequenceNumber()
} else {
sequence, err = params.SourceAccount.GetSequenceNumber()
}
if err != nil {
return nil, errors.Wrap(err, "could not obtain account sequence")
}
tx := &Transaction{
baseFee: params.BaseFee,
sourceAccount: SimpleAccount{
AccountID: params.SourceAccount.GetAccountID(),
Sequence: sequence,
},
operations: params.Operations,
memo: params.Memo,
timebounds: params.Timebounds,
signatures: nil,
}
accountID, err := xdr.AddressToAccountId(tx.sourceAccount.AccountID)
if err != nil {
return nil, errors.Wrap(err, "account id is not valid")
}
if tx.baseFee < MinBaseFee {
return nil, errors.Errorf(
"base fee cannot be lower than network minimum of %d", MinBaseFee,
)
}
if len(tx.operations) == 0 {
return nil, errors.New("transaction has no operations")
}
// check if maxFee fits in a uint32
// 64 bit fees are only available in fee bump transactions
// if maxFee is negative then there must have been an int overflow
hi, lo := bits.Mul64(uint64(params.BaseFee), uint64(len(params.Operations)))
if hi > 0 || lo > math.MaxUint32 {
return nil, errors.Errorf("base fee %d results in an overflow of max fee", params.BaseFee)
}
tx.maxFee = int64(lo)
// Check and set the timebounds
err = tx.timebounds.Validate()
if err != nil {
return nil, errors.Wrap(err, "invalid time bounds")
}
envelope := xdr.TransactionEnvelope{
Type: xdr.EnvelopeTypeEnvelopeTypeTx,
V1: &xdr.TransactionV1Envelope{
Tx: xdr.Transaction{
SourceAccount: accountID.ToMuxedAccount(),
Fee: xdr.Uint32(tx.maxFee),
SeqNum: xdr.SequenceNumber(sequence),
TimeBounds: &xdr.TimeBounds{
MinTime: xdr.TimePoint(tx.timebounds.MinTime),
MaxTime: xdr.TimePoint(tx.timebounds.MaxTime),
},
},
Signatures: nil,
},
}
// Handle the memo, if one is present
if tx.memo != nil {
xdrMemo, err := tx.memo.ToXDR()
if err != nil {
return nil, errors.Wrap(err, "couldn't build memo XDR")
}
envelope.V1.Tx.Memo = xdrMemo
}
for _, op := range tx.operations {
if verr := op.Validate(); verr != nil {
return nil, errors.Wrap(verr, fmt.Sprintf("validation failed for %T operation", op))
}
xdrOperation, err2 := op.BuildXDR()
if err2 != nil {
return nil, errors.Wrap(err2, fmt.Sprintf("failed to build operation %T", op))
}
envelope.V1.Tx.Operations = append(envelope.V1.Tx.Operations, xdrOperation)
}
tx.envelope = envelope
return tx, nil
}
// FeeBumpTransactionParams is a container for parameters
// which are used to construct new FeeBumpTransaction instances
type FeeBumpTransactionParams struct {
Inner *Transaction
FeeAccount string
BaseFee int64
}
func convertToV1(tx *Transaction) (*Transaction, error) {
sourceAccount := tx.SourceAccount()
signatures := tx.Signatures()
tx, err := NewTransaction(TransactionParams{
SourceAccount: &sourceAccount,
IncrementSequenceNum: false,
Operations: tx.Operations(),
BaseFee: tx.BaseFee(),
Memo: tx.Memo(),
Timebounds: tx.Timebounds(),
})
if err != nil {
return tx, err
}
tx.signatures = signatures
return tx, nil
}
// NewFeeBumpTransaction returns a new FeeBumpTransaction instance
func NewFeeBumpTransaction(params FeeBumpTransactionParams) (*FeeBumpTransaction, error) {
inner := params.Inner
if inner == nil {
return nil, errors.New("inner transaction is missing")
}
innerEnv, err := inner.TxEnvelope()
if err != nil {
return nil, errors.Wrap(err, "inner transaction envelope not found")
}
if innerEnv.Type == xdr.EnvelopeTypeEnvelopeTypeTxV0 {
inner, err = convertToV1(inner)
if err != nil {
return nil, errors.Wrap(err, "could not upgrade transaction from v0 to v1")
}
} else if innerEnv.Type != xdr.EnvelopeTypeEnvelopeTypeTx {
return nil, errors.Errorf("%v transactions cannot be fee bumped", innerEnv.Type.String())
}
tx := &FeeBumpTransaction{
baseFee: params.BaseFee,
// A fee-bump transaction has an effective number of operations equal to one plus the
// number of operations in the inner transaction. Correspondingly, the minimum fee for
// the fee-bump transaction is one base fee more than the minimum fee for the inner
// transaction.
maxFee: params.BaseFee * int64(len(inner.operations)+1),
feeAccount: params.FeeAccount,
inner: new(Transaction),
}
*tx.inner = *inner
hi, lo := bits.Mul64(uint64(params.BaseFee), uint64(len(inner.operations)+1))
if hi > 0 || lo > math.MaxInt64 {
return nil, errors.Errorf("base fee %d results in an overflow of max fee", params.BaseFee)
}
tx.maxFee = int64(lo)
if tx.baseFee < tx.inner.baseFee {
return tx, errors.New("base fee cannot be lower than provided inner transaction fee")
}
if tx.baseFee < MinBaseFee {
return tx, errors.Errorf(
"base fee cannot be lower than network minimum of %d", MinBaseFee,
)
}
accountID, err := xdr.AddressToAccountId(tx.feeAccount)
if err != nil {
return tx, errors.Wrap(err, "fee account is not a valid address")
}
tx.envelope = xdr.TransactionEnvelope{
Type: xdr.EnvelopeTypeEnvelopeTypeTxFeeBump,
FeeBump: &xdr.FeeBumpTransactionEnvelope{
Tx: xdr.FeeBumpTransaction{
FeeSource: accountID.ToMuxedAccount(),
Fee: xdr.Int64(tx.maxFee),
InnerTx: xdr.FeeBumpTransactionInnerTx{
Type: xdr.EnvelopeTypeEnvelopeTypeTx,
V1: innerEnv.V1,
},
},
},
}
return tx, nil
}
// BuildChallengeTx is a factory method that creates a valid SEP 10 challenge, for use in web authentication.
// "timebound" is the time duration the transaction should be valid for, and must be greater than 1s (300s is recommended).
// More details on SEP 10: https://github.com/aiblocks/aiblocks-protocol/blob/master/ecosystem/sep-0010.md
func BuildChallengeTx(serverSignerSecret, clientAccountID, homeDomain, network string, timebound time.Duration) (*Transaction, error) {
if timebound < time.Second {
return nil, errors.New("provided timebound must be at least 1s (300s is recommended)")
}
serverKP, err := keypair.Parse(serverSignerSecret)
if err != nil {
return nil, err
}
// SEP10 spec requires 48 byte cryptographic-quality random string
randomNonce, err := generateRandomNonce(48)
if err != nil {
return nil, err
}
// Encode 48-byte nonce to base64 for a total of 64-bytes
randomNonceToString := base64.StdEncoding.EncodeToString(randomNonce)
if len(randomNonceToString) != 64 {
return nil, errors.New("64 byte long random nonce required")
}
if _, err = xdr.AddressToAccountId(clientAccountID); err != nil {
return nil, errors.Wrapf(err, "%s is not a valid account id", clientAccountID)
}
// represent server signing account as SimpleAccount
sa := SimpleAccount{
AccountID: serverKP.Address(),
Sequence: 0,
}
// represent client account as SimpleAccount
ca := SimpleAccount{
AccountID: clientAccountID,
}
currentTime := time.Now().UTC()
maxTime := currentTime.Add(timebound)
// Create a SEP 10 compatible response. See
// https://github.com/aiblocks/aiblocks-protocol/blob/master/ecosystem/sep-0010.md#response
tx, err := NewTransaction(
TransactionParams{
SourceAccount: &sa,
IncrementSequenceNum: false,
Operations: []Operation{
&ManageData{
SourceAccount: &ca,
Name: homeDomain + " auth",
Value: []byte(randomNonceToString),
},
},
BaseFee: MinBaseFee,
Memo: nil,
Timebounds: NewTimebounds(currentTime.Unix(), maxTime.Unix()),
},
)
if err != nil {
return nil, err
}
tx, err = tx.Sign(network, serverKP.(*keypair.Full))
if err != nil {
return nil, err
}
return tx, nil
}
// generateRandomNonce creates a cryptographically secure random slice of `n` bytes.
func generateRandomNonce(n int) ([]byte, error) {
binary := make([]byte, n)
_, err := rand.Read(binary)
if err != nil {
return []byte{}, err
}
return binary, err
}
// ReadChallengeTx reads a SEP 10 challenge transaction and returns the decoded
// transaction and client account ID contained within.
//
// Before calling this function, retrieve the SIGNING_KEY included in the TOML file
// hosted on the service's homeDomain and ensure it matches the serverAccountID you
// intend to pass.
//
// This function verifies the serverAccountID signed the challenge. If the
// serverAccountID also matches the SIGNING_KEY included in the TOML file hosted the
// service's homeDomain passed, malicious web services will not be able to use the
// challenge transaction POSTed back to the authentication endpoint.
//
// The homeDomain field is reserved for future use and not used.
//
// It does not verify that the transaction has been signed by the client or
// that any signatures other than the servers on the transaction are valid. Use
// one of the following functions to completely verify the transaction:
// - VerifyChallengeTxThreshold
// - VerifyChallengeTxSigners
func ReadChallengeTx(challengeTx, serverAccountID, network, homeDomain string) (tx *Transaction, clientAccountID string, err error) {
parsed, err := TransactionFromXDR(challengeTx)
if err != nil {
return tx, clientAccountID, errors.Wrap(err, "could not parse challenge")
}
var isSimple bool
tx, isSimple = parsed.Transaction()
if !isSimple {
return tx, clientAccountID, errors.New("challenge cannot be a fee bump transaction")
}
// Enforce no muxed accounts (at least until we understand their impact)
if tx.envelope.SourceAccount().Type == xdr.CryptoKeyTypeKeyTypeMuxedEd25519 {
err = errors.New("invalid source account: only valid Ed25519 accounts are allowed in challenge transactions")
return tx, clientAccountID, err
}
// verify transaction source
if tx.SourceAccount().AccountID != serverAccountID {
return tx, clientAccountID, errors.New("transaction source account is not equal to server's account")
}
// verify sequence number
if tx.SourceAccount().Sequence != 0 {
return tx, clientAccountID, errors.New("transaction sequence number must be 0")
}
// verify timebounds
if tx.Timebounds().MaxTime == TimeoutInfinite {
return tx, clientAccountID, errors.New("transaction requires non-infinite timebounds")
}
currentTime := time.Now().UTC().Unix()
if currentTime < tx.Timebounds().MinTime || currentTime > tx.Timebounds().MaxTime {
return tx, clientAccountID, errors.Errorf("transaction is not within range of the specified timebounds (currentTime=%d, MinTime=%d, MaxTime=%d)",
currentTime, tx.Timebounds().MinTime, tx.Timebounds().MaxTime)
}
// verify operation
operations := tx.Operations()
if len(operations) < 1 {
return tx, clientAccountID, errors.New("transaction requires at least one manage_data operation")
}
op, ok := operations[0].(*ManageData)
if !ok {
return tx, clientAccountID, errors.New("operation type should be manage_data")
}
if op.SourceAccount == nil {
return tx, clientAccountID, errors.New("operation should have a source account")
}
clientAccountID = op.SourceAccount.GetAccountID()
rawOperations := tx.envelope.Operations()
if len(rawOperations) > 0 && rawOperations[0].SourceAccount.Type == xdr.CryptoKeyTypeKeyTypeMuxedEd25519 {
err = errors.New("invalid operation source account: only valid Ed25519 accounts are allowed in challenge transactions")
return tx, clientAccountID, err
}
// verify manage data value
nonceB64 := string(op.Value)
if len(nonceB64) != 64 {
return tx, clientAccountID, errors.New("random nonce encoded as base64 should be 64 bytes long")
}
nonceBytes, err := base64.StdEncoding.DecodeString(nonceB64)
if err != nil {
return tx, clientAccountID, errors.Wrap(err, "failed to decode random nonce provided in manage_data operation")
}
if len(nonceBytes) != 48 {
return tx, clientAccountID, errors.New("random nonce before encoding as base64 should be 48 bytes long")
}
// verify subsequent operations are manage data ops with source account set to server account
for _, op := range operations[1:] {
op, ok := op.(*ManageData)
if !ok {
return tx, clientAccountID, errors.New("operation type should be manage_data")
}
if op.SourceAccount == nil {
return tx, clientAccountID, errors.New("operation should have a source account")
}
if op.SourceAccount.GetAccountID() != serverAccountID {
return tx, clientAccountID, errors.New("subsequent operations are unrecognized")
}
}
err = verifyTxSignature(tx, network, serverAccountID)
if err != nil {
return tx, clientAccountID, err
}
return tx, clientAccountID, nil
}
// VerifyChallengeTxThreshold verifies that for a SEP 10 challenge transaction