-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
stellar.go
2151 lines (1929 loc) · 70.4 KB
/
stellar.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 stellar
import (
"context"
"encoding/hex"
"errors"
"fmt"
"sort"
"strings"
"unicode/utf8"
"github.com/keybase/client/go/engine"
"github.com/keybase/client/go/externals"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/client/go/protocol/stellar1"
"github.com/keybase/client/go/stellar/bundle"
"github.com/keybase/client/go/stellar/relays"
"github.com/keybase/client/go/stellar/remote"
"github.com/keybase/client/go/stellar/stellarcommon"
"github.com/keybase/stellarnet"
stellarAddress "github.com/stellar/go/address"
"github.com/stellar/go/build"
federationProto "github.com/stellar/go/protocols/federation"
)
const AccountNameMaxRunes = 24
// CreateWallet creates and posts an initial stellar bundle for a user.
// Only succeeds if they do not already have one.
// Safe (but wasteful) to call even if the user has a bundle already.
func CreateWallet(mctx libkb.MetaContext) (created bool, err error) {
defer mctx.Trace("Stellar.CreateWallet", &err)()
loggedInUsername := mctx.ActiveDevice().Username(mctx)
if !loggedInUsername.IsValid() {
return false, fmt.Errorf("could not get logged-in username")
}
perUserKeyUpgradeSoft(mctx, "create-wallet")
clearBundle, err := bundle.NewInitial(fmt.Sprintf("%v's account", loggedInUsername))
if err != nil {
return false, err
}
meUV, err := mctx.G().GetMeUV(mctx.Ctx())
if err != nil {
return false, err
}
err = remote.PostWithChainlink(mctx, *clearBundle)
switch e := err.(type) {
case nil:
// ok
case libkb.AppStatusError:
if keybase1.StatusCode(e.Code) == keybase1.StatusCode_SCStellarWrongRevision {
// Assume this happened because a bundle already existed.
// And suppress the error.
mctx.Debug("suppressing error: %v", err)
return false, nil
}
return false, err
default:
return false, err
}
getGlobal(mctx.G()).InformHasWallet(mctx.Ctx(), meUV)
go getGlobal(mctx.G()).KickAutoClaimRunner(mctx.BackgroundWithLogTags(), gregor1.MsgID{})
return true, nil
}
type CreateWalletGatedResult struct {
JustCreated bool // whether the user's wallet was created by this call
HasWallet bool // whether the user now has a wallet
AcceptedDisclaimer bool // whether the user has accepted the disclaimer
ErrorCreating error // error encountered while attempting to create the wallet
}
// CreateWalletGated may create a wallet for the user.
// Taking into account settings from the server.
// It should be speedy to call repeatedly _if_ the user gets a wallet.
func CreateWalletGated(mctx libkb.MetaContext) (res CreateWalletGatedResult, err error) {
defer mctx.Trace("Stellar.CreateWalletGated", &err)()
defer func() {
mctx.Debug("CreateWalletGated: (res:%+v, err:%v)", res, err != nil)
}()
res, err = createWalletGatedHelper(mctx)
if err == nil && res.ErrorCreating != nil {
// An error was encountered while creating the wallet.
// This could have been the result of losing a race against other threads.
// When multiple threads create a wallet only one will succeed.
// In that case we _do_ have a wallet now even though this thread failed,
// so run again for an accurate reply.
return createWalletGatedHelper(mctx)
}
return res, err
}
func createWalletGatedHelper(mctx libkb.MetaContext) (res CreateWalletGatedResult, err error) {
defer mctx.Trace("Stellar.createWalletGatedHelper", &err)()
defer func() {
mctx.Debug("createWalletGatedHelper: (res:%+v, err:%v)", res, err != nil)
}()
meUV, err := mctx.G().GetMeUV(mctx.Ctx())
if err != nil {
return res, err
}
if getGlobal(mctx.G()).CachedHasWallet(mctx.Ctx(), meUV) {
mctx.Debug("createWalletGatedHelper: local cache says we already have a wallet")
return CreateWalletGatedResult{
JustCreated: false,
HasWallet: true,
AcceptedDisclaimer: true, // because it should be impossible to have created a wallet without accepting.
}, nil
}
scr, err := remote.ShouldCreate(mctx.Ctx(), mctx.G())
if err != nil {
return res, err
}
res.HasWallet = scr.HasWallet
res.AcceptedDisclaimer = scr.AcceptedDisclaimer
if scr.HasWallet {
mctx.Debug("createWalletGatedHelper: server says we already have a wallet")
getGlobal(mctx.G()).InformHasWallet(mctx.Ctx(), meUV)
return res, nil
}
if !scr.ShouldCreate {
mctx.Debug("createWalletGatedHelper: server did not recommend wallet creation")
return res, nil
}
justCreated, err := CreateWallet(mctx)
if err != nil {
mctx.Debug("createWalletGatedHelper: error creating wallet: %v", err)
res.ErrorCreating = err
return res, nil
}
res.JustCreated = justCreated
if justCreated {
res.HasWallet = true
}
return res, nil
}
// CreateWalletSoft creates a user's initial wallet if they don't already have one.
// Does not get in the way of intentional user actions.
func CreateWalletSoft(mctx libkb.MetaContext) {
var err error
defer mctx.Trace("CreateWalletSoft", &err)()
if !mctx.G().LocalSigchainGuard().IsAvailable(mctx.Ctx(), "CreateWalletSoft") {
err = fmt.Errorf("yielding to guard")
return
}
_, err = CreateWalletGated(mctx)
}
func pushSimpleUpdateForAccount(mctx libkb.MetaContext, accountID stellar1.AccountID) (err error) {
defer mctx.Trace("Stellar.Upkeep pushSimpleUpdateForAccount", &err)()
prevBundle, err := remote.FetchAccountBundle(mctx, accountID)
if err != nil {
return err
}
nextBundle := bundle.AdvanceAccounts(*prevBundle, []stellar1.AccountID{accountID})
return remote.Post(mctx, nextBundle)
}
// Upkeep makes sure the bundle is encrypted for the user's latest PUK.
func Upkeep(mctx libkb.MetaContext) (err error) {
defer mctx.Trace("Stellar.Upkeep", &err)()
_, _, prevAccountPukGens, err := remote.FetchBundleWithGens(mctx)
if err != nil {
return err
}
pukring, err := mctx.G().GetPerUserKeyring(mctx.Ctx())
if err != nil {
return err
}
err = pukring.Sync(mctx)
if err != nil {
return err
}
currentPukGen := pukring.CurrentGeneration()
var madeAnyChanges bool
for accountID, accountPukGen := range prevAccountPukGens {
if accountPukGen < currentPukGen {
madeAnyChanges = true
mctx.Debug("Stellar.Upkeep: reencrypting %s... for gen %v from gen %v", accountID[:5], currentPukGen, accountPukGen)
if err = pushSimpleUpdateForAccount(mctx, accountID); err != nil {
mctx.Debug("Stellar.Upkeep: error reencrypting %v: %v", accountID[:5], err)
return err
}
}
}
if !madeAnyChanges {
mctx.Debug("Stellar.Upkeep: no need to reencrypt. Everything is at gen %v", currentPukGen)
}
return nil
}
func ImportSecretKey(mctx libkb.MetaContext, secretKey stellar1.SecretKey, makePrimary bool, accountName string) (err error) {
prevBundle, err := remote.FetchSecretlessBundle(mctx)
if err != nil {
return err
}
nextBundle := bundle.AdvanceBundle(*prevBundle)
err = bundle.AddAccount(&nextBundle, secretKey, accountName, makePrimary)
if err != nil {
return err
}
if makePrimary {
// primary account changes need sigchain link
// (so other users can find user's primary account id)
err = remote.PostWithChainlink(mctx, nextBundle)
} else {
err = remote.Post(mctx, nextBundle)
}
if err != nil {
return err
}
// inform the global stellar object that there is a new bundle.
mctx.G().GetStellar().InformBundle(mctx, nextBundle.Revision, nextBundle.Accounts)
// after import, mark all the transactions in this account as "read"
// any errors in this process are not fatal, since the important task
// has been accomplished.
_, accountID, _, err := libkb.ParseStellarSecretKey(string(secretKey))
if err != nil {
mctx.Debug("ImportSecretKey, failed to parse secret key after import: %s", err)
return nil
}
arg := remote.RecentPaymentsArg{
AccountID: accountID,
SkipPending: true,
IncludeAdvanced: true,
}
page, err := remote.RecentPayments(mctx.Ctx(), mctx.G(), arg)
if err != nil {
mctx.Debug("ImportSecretKey, RecentPayments error: %s", err)
return nil
}
if len(page.Payments) == 0 {
return nil
}
mostRecentID, err := page.Payments[0].TransactionID()
if err != nil {
mctx.Debug("ImportSecretKey, tx id from most recent payment error: %s", err)
return nil
}
if err = remote.MarkAsRead(mctx.Ctx(), mctx.G(), accountID, mostRecentID); err != nil {
mctx.Debug("ImportSecretKey, markAsRead error: %s", err)
return nil
}
return nil
}
func ExportSecretKey(mctx libkb.MetaContext, accountID stellar1.AccountID) (res stellar1.SecretKey, err error) {
prevBundle, err := remote.FetchAccountBundle(mctx, accountID)
if err != nil {
return res, err
}
for _, account := range prevBundle.Accounts {
if account.AccountID.Eq(accountID) {
signers := prevBundle.AccountBundles[account.AccountID].Signers
if len(signers) == 0 {
return res, fmt.Errorf("no secret keys found for account")
}
if len(signers) != 1 {
return res, fmt.Errorf("expected 1 secret key but found %v", len(signers))
}
return signers[0], nil
}
}
_, _, _, parseSecErr := libkb.ParseStellarSecretKey(accountID.String())
if parseSecErr == nil {
// Just in case a secret key worked its way in here
return res, fmt.Errorf("account not found: unexpected secret key")
}
return res, fmt.Errorf("account not found: %v", accountID)
}
func OwnAccount(mctx libkb.MetaContext, accountID stellar1.AccountID) (own, isPrimary bool, err error) {
own, isPrimary, _, err = OwnAccountPlusName(mctx, accountID)
return own, isPrimary, err
}
func OwnAccountPlusName(mctx libkb.MetaContext, accountID stellar1.AccountID) (own, isPrimary bool, accountName string, err error) {
bundle, err := remote.FetchSecretlessBundle(mctx)
if err != nil {
return false, false, "", err
}
for _, account := range bundle.Accounts {
if account.AccountID.Eq(accountID) {
return true, account.IsPrimary, account.Name, nil
}
}
return false, false, "", nil
}
func OwnAccountCached(mctx libkb.MetaContext, accountID stellar1.AccountID) (own, isPrimary bool, err error) {
return getGlobal(mctx.G()).OwnAccountCached(mctx, accountID)
}
func OwnAccountPlusNameCached(mctx libkb.MetaContext, accountID stellar1.AccountID) (own, isPrimary bool, accountName string, err error) {
return getGlobal(mctx.G()).OwnAccountPlusNameCached(mctx, accountID)
}
func lookupSenderEntry(mctx libkb.MetaContext, accountID stellar1.AccountID) (stellar1.BundleEntry, stellar1.AccountBundle, error) {
if accountID == "" {
bundle, err := remote.FetchSecretlessBundle(mctx)
if err != nil {
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, err
}
entry, err := bundle.PrimaryAccount()
if err != nil {
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, err
}
accountID = entry.AccountID
}
bundle, err := remote.FetchAccountBundle(mctx, accountID)
switch err := err.(type) {
case nil:
// ok
case libkb.AppStatusError:
if libkb.IsAppStatusCode(err, keybase1.StatusCode_SCStellarMissingAccount) {
mctx.Debug("suppressing error: %v", err)
err = err.WithDesc("Sender account not found")
}
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, err
default:
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, err
}
for _, entry := range bundle.Accounts {
if entry.AccountID.Eq(accountID) {
return entry, bundle.AccountBundles[entry.AccountID], nil
}
}
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, libkb.NotFoundError{Msg: "Sender account not found"}
}
func LookupSenderPrimary(mctx libkb.MetaContext) (stellar1.BundleEntry, stellar1.AccountBundle, error) {
return LookupSender(mctx, "" /* empty account id returns primary */)
}
func LookupSender(mctx libkb.MetaContext, accountID stellar1.AccountID) (stellar1.BundleEntry, stellar1.AccountBundle, error) {
entry, ab, err := lookupSenderEntry(mctx, accountID)
if err != nil {
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, err
}
if len(ab.Signers) == 0 {
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, errors.New("no signer for bundle")
}
if len(ab.Signers) > 1 {
return stellar1.BundleEntry{}, stellar1.AccountBundle{}, errors.New("only single signer supported")
}
return entry, ab, nil
}
// Wrapper around LookupByAddress that acts likes Context is plumbed through.
// After context is canceled, any return from LookupByAddress is ignored.
func federationLookupByAddressCtx(mctx libkb.MetaContext, addy string) (*federationProto.NameResponse, error) {
fedCli := getGlobal(mctx.G()).federationClient
type packT struct {
res *federationProto.NameResponse
err error
}
ch := make(chan packT, 1)
go func() {
var pack packT
pack.res, pack.err = fedCli.LookupByAddress(addy)
ch <- pack
}()
select {
case <-mctx.Ctx().Done():
return nil, mctx.Ctx().Err()
case pack := <-ch:
return pack.res, pack.err
}
}
// LookupRecipient finds a recipient.
// `to` can be a username, social assertion, account ID, or federation address.
func LookupRecipient(m libkb.MetaContext, to stellarcommon.RecipientInput, isCLI bool) (res stellarcommon.Recipient, err error) {
defer m.Trace("Stellar.LookupRecipient", &err)()
res = stellarcommon.Recipient{
Input: to,
}
if len(to) == 0 {
return res, fmt.Errorf("empty recipient parameter")
}
storeAddress := func(address string) error {
_, err := libkb.ParseStellarAccountID(address)
if err != nil {
if verr, ok := err.(libkb.VerboseError); ok {
m.Debug(verr.Verbose())
}
return err
}
accountID, err := stellarnet.NewAddressStr(address)
if err != nil {
return err
}
res.AccountID = &accountID
return nil
}
// Federation address
if strings.Contains(string(to), stellarAddress.Separator) {
name, domain, err := stellarAddress.Split(string(to))
if err != nil {
return res, err
}
if domain == "keybase.io" {
// Keybase.io federation address. Fall through to identify
// path.
m.Debug("Got federation address %q but it's under keybase.io domain!", to)
m.Debug("Instead going to lookup Keybase assertion: %q", name)
to = stellarcommon.RecipientInput(name)
} else {
// Actual federation address that is not under keybase.io
// domain. Use federation client.
nameResponse, err := federationLookupByAddressCtx(m, string(to))
if err != nil {
errStr := err.Error()
m.Debug("federation.LookupByAddress returned error: %s", errStr)
if strings.Contains(errStr, "lookup federation server failed") {
return res, fmt.Errorf("Server at url %q does not respond to federation requests", domain)
} else if strings.Contains(errStr, "get federation failed") {
return res, fmt.Errorf("Federation server %q did not find record %q", domain, name)
}
return res, err
}
// We got an address! Fall through to the "Stellar
// address" path.
m.Debug("federation.LookupByAddress returned: %+v", nameResponse)
to = stellarcommon.RecipientInput(nameResponse.AccountID)
// if there is a memo, include it in the result
if nameResponse.Memo.Value != "" {
res.PublicMemo = &nameResponse.Memo.Value
if nameResponse.MemoType == "" {
return res, fmt.Errorf("Federation server %q returned invalid memo", domain)
}
res.PublicMemoType = &nameResponse.MemoType
}
}
}
// Stellar account ID
if to[0] == 'G' && len(to) > 16 {
err := storeAddress(string(to))
return res, err
}
maybeUsername, err := lookupRecipientAssertion(m, string(to), isCLI)
if err != nil {
return res, err
}
if maybeUsername == "" {
expr, err := externals.AssertionParse(m, string(to))
if err != nil {
m.Debug("error parsing assertion: %s", err)
return res, fmt.Errorf("invalid recipient %q: %s", to, err)
}
// valid assertion, but not a user yet
m.Debug("assertion %s (%s) is valid, but not a user yet", to, expr)
social, err := expr.ToSocialAssertion()
if err != nil {
m.Debug("not a social assertion: %s (%s)", to, expr)
if _, ok := expr.(libkb.AssertionKeybase); ok {
return res, libkb.NotFoundError{Msg: fmt.Sprintf("user not found: %q", to)}
}
return res, fmt.Errorf("invalid recipient %q: %s", to, err)
}
res.Assertion = &social
return res, nil
}
// load the user to get their wallet
user, err := libkb.LoadUser(
libkb.NewLoadUserByNameArg(m.G(), maybeUsername).
WithNetContext(m.Ctx()).
WithPublicKeyOptional())
if err != nil {
return res, err
}
res.User = &stellarcommon.User{
UV: user.ToUserVersion(),
Username: user.GetNormalizedName(),
}
accountID := user.StellarAccountID()
if accountID == nil {
return res, nil
}
err = storeAddress(accountID.String())
return res, err
}
type DisplayBalance struct {
Amount string
Currency string
}
func getTimeboundsForSending(m libkb.MetaContext, walletState *WalletState) (*build.Timebounds, error) {
// Timeout added as Timebounds.MaxTime to Stellar transactions that client
// creates, effectively adding a "deadline" to the transaction. We can
// safely assume that a transaction will never end up in a ledger if it's
// not included before the deadline.
// We ask server for timebounds because local clock might not be accurate,
// and typically we will be setting timeout as 30 seconds.
start := m.G().Clock().Now()
serverTimes, err := walletState.ServerTimeboundsRecommendation(m.Ctx())
if err != nil {
return nil, err
}
took := m.G().Clock().Since(start)
m.Debug("Server timebounds recommendation is: %+v. Request took %fs", serverTimes, took.Seconds())
if serverTimes.TimeNow == 0 {
return nil, fmt.Errorf("Invalid server response for transaction timebounds")
}
if serverTimes.Timeout == 0 {
m.Debug("Returning nil timebounds")
return nil, nil
}
// Offset server time by our latency to the server. We are making two
// requests to submit a transaction: one here to get the server time, and
// another one to send the signed transaction. Assuming server roundtrip
// time will be the same for both requests, we can offset timebounds here
// by entire roundtrip time and then we will have MaxTime set as 30 seconds
// counting from when the server gets our signed tx.
deadline := serverTimes.TimeNow.Time().Add(took).Unix() + serverTimes.Timeout
tb := build.Timebounds{
MaxTime: uint64(deadline),
}
m.Debug("Returning timebounds for tx: %+v", tb)
return &tb, nil
}
type SendPaymentArg struct {
From stellar1.AccountID // Optional. Defaults to primary account.
To stellarcommon.RecipientInput
Amount string // Amount of XLM to send.
DisplayBalance DisplayBalance
SecretNote string // Optional.
PublicMemo *stellarnet.Memo // Optional.
ForceRelay bool
QuickReturn bool
}
type SendPaymentResult struct {
KbTxID stellar1.KeybaseTransactionID
// Direct: tx ID of the payment tx
// Relay : tx ID of the funding payment tx
TxID stellar1.TransactionID
Pending bool
// Implicit team that the relay secret is encrypted for.
// Present if this was a relay transfer.
RelayTeamID *keybase1.TeamID
JumpToChat string
}
// SendPaymentCLI sends XLM from CLI.
func SendPaymentCLI(m libkb.MetaContext, walletState *WalletState, sendArg SendPaymentArg) (res SendPaymentResult, err error) {
return sendPayment(m, walletState, sendArg, true)
}
// SendPaymentGUI sends XLM from GUI.
func SendPaymentGUI(m libkb.MetaContext, walletState *WalletState, sendArg SendPaymentArg) (res SendPaymentResult, err error) {
return sendPayment(m, walletState, sendArg, false)
}
// sendPayment sends XLM.
// Recipient:
// Stellar address : Standard payment
// User with wallet ready : Standard payment
// User without a wallet : Relay payment
// Unresolved assertion : Relay payment
func sendPayment(mctx libkb.MetaContext, walletState *WalletState, sendArg SendPaymentArg, isCLI bool) (res SendPaymentResult, err error) {
defer mctx.Trace("Stellar.SendPayment", &err)()
// look up sender account
senderEntry, senderAccountBundle, err := LookupSender(mctx, sendArg.From)
if err != nil {
return res, err
}
senderSeed := senderAccountBundle.Signers[0]
senderAccountID := senderEntry.AccountID
// look up recipient
recipient, err := LookupRecipient(mctx, sendArg.To, isCLI)
if err != nil {
return res, err
}
mctx.Debug("using stellar network passphrase: %q", stellarnet.Network().Passphrase)
baseFee := walletState.BaseFee(mctx)
if recipient.AccountID == nil || sendArg.ForceRelay {
return sendRelayPayment(mctx, walletState,
senderSeed, recipient, sendArg.Amount, sendArg.DisplayBalance,
sendArg.SecretNote, sendArg.PublicMemo, sendArg.QuickReturn, senderEntry.IsPrimary, baseFee)
}
ownRecipient, _, err := OwnAccount(mctx, stellar1.AccountID(recipient.AccountID.String()))
if err != nil {
mctx.Debug("error determining if user own's recipient: %v", err)
return res, err
}
if ownRecipient {
// When sending to an account that we own, act as though sending to a user as opposed to just an account ID.
uv, un := mctx.G().ActiveDevice.GetUsernameAndUserVersionIfValid(mctx)
if uv.IsNil() || un.IsNil() {
mctx.Debug("error finding self: uv:%v un:%v", uv, un)
return res, fmt.Errorf("error getting logged-in user")
}
recipient.User = &stellarcommon.User{
UV: uv,
Username: un,
}
}
senderSeed2, err := stellarnet.NewSeedStr(senderSeed.SecureNoLogString())
if err != nil {
return res, err
}
post := stellar1.PaymentDirectPost{
FromDeviceID: mctx.G().ActiveDevice.DeviceID(),
DisplayAmount: sendArg.DisplayBalance.Amount,
DisplayCurrency: sendArg.DisplayBalance.Currency,
QuickReturn: sendArg.QuickReturn,
}
if recipient.User != nil {
post.To = &recipient.User.UV
}
// check if recipient account exists
funded, err := isAccountFunded(mctx.Ctx(), walletState, stellar1.AccountID(recipient.AccountID.String()))
if err != nil {
return res, fmt.Errorf("error checking destination account balance: %v", err)
}
if !funded && isAmountLessThanMin(sendArg.Amount, minAmountCreateAccountXLM) {
return res, fmt.Errorf("you must send at least %s XLM to fund the account for %s", minAmountCreateAccountXLM, sendArg.To)
}
sp, unlock := NewSeqnoProvider(mctx, walletState)
defer unlock()
tb, err := getTimeboundsForSending(mctx, walletState)
if err != nil {
return res, err
}
if recipient.HasMemo() {
if sendArg.PublicMemo != nil {
return res, fmt.Errorf("federation recipient included its own memo, but send called with a memo")
}
sendArg.PublicMemo, err = recipient.Memo()
if err != nil {
return res, err
}
}
var txID string
var seqno uint64
if !funded {
// if no balance, create_account operation
sig, err := stellarnet.CreateAccountXLMTransactionWithMemo(senderSeed2, *recipient.AccountID, sendArg.Amount, sendArg.PublicMemo, sp, tb, baseFee)
if err != nil {
return res, err
}
post.SignedTransaction = sig.Signed
txID = sig.TxHash
seqno = sig.Seqno
} else {
// if balance, payment operation
sig, err := stellarnet.PaymentXLMTransactionWithMemo(senderSeed2, *recipient.AccountID, sendArg.Amount, sendArg.PublicMemo, sp, tb, baseFee)
if err != nil {
return res, err
}
post.SignedTransaction = sig.Signed
txID = sig.TxHash
seqno = sig.Seqno
}
if err := walletState.AddPendingTx(mctx.Ctx(), senderAccountID, stellar1.TransactionID(txID), seqno); err != nil {
mctx.Debug("error calling AddPendingTx: %s", err)
}
if len(sendArg.SecretNote) > 0 {
noteClear := stellar1.NoteContents{
Note: sendArg.SecretNote,
StellarID: stellar1.TransactionID(txID),
}
var recipientUv *keybase1.UserVersion
if recipient.User != nil {
recipientUv = &recipient.User.UV
}
post.NoteB64, err = NoteEncryptB64(mctx, noteClear, recipientUv)
if err != nil {
return res, fmt.Errorf("error encrypting note: %v", err)
}
}
// submit the transaction
rres, err := walletState.SubmitPayment(mctx.Ctx(), post)
if err != nil {
mctx.Debug("SEQNO SubmitPayment error seqno: %d txID: %s, err: %s", seqno, rres.StellarID, err)
if rerr := walletState.RemovePendingTx(mctx.Ctx(), senderAccountID, stellar1.TransactionID(txID)); rerr != nil {
mctx.Debug("error calling RemovePendingTx: %s", rerr)
}
return res, err
}
mctx.Debug("sent payment (direct) kbTxID:%v txID:%v pending:%v", seqno, rres.KeybaseID, rres.StellarID, rres.Pending)
mctx.Debug("SEQNO SubmitPayment success seqno: %d txID: %s", seqno, rres.StellarID)
if !rres.Pending {
mctx.Debug("SubmitPayment result wasn't pending, removing from wallet state: %s/%s", senderAccountID, txID)
err = walletState.RemovePendingTx(mctx.Ctx(), senderAccountID, stellar1.TransactionID(txID))
if err != nil {
mctx.Debug("SubmitPayment ws.RemovePendingTx error: %s", err)
}
}
err = walletState.Refresh(mctx, senderEntry.AccountID, "SubmitPayment")
if err != nil {
mctx.Debug("SubmitPayment ws.Refresh error: %s", err)
}
var chatRecipient string
if senderEntry.IsPrimary {
chatRecipient = chatRecipientStr(mctx, recipient)
sendChat := func(mctx libkb.MetaContext) {
chatSendPaymentMessageSoft(mctx, chatRecipient, rres.StellarID, "SendPayment")
}
if sendArg.QuickReturn {
go sendChat(mctx.WithCtx(context.Background()))
} else {
sendChat(mctx)
}
} else {
mctx.Debug("not sending chat message: sending from non-primary account")
}
return SendPaymentResult{
KbTxID: rres.KeybaseID,
TxID: rres.StellarID,
Pending: rres.Pending,
JumpToChat: chatRecipient,
}, nil
}
type SendPathPaymentArg struct {
From stellar1.AccountID
To stellarcommon.RecipientInput
Path stellar1.PaymentPath
SecretNote string
PublicMemo *stellarnet.Memo
QuickReturn bool
}
// SendPathPaymentCLI sends a path payment from CLI.
func SendPathPaymentCLI(mctx libkb.MetaContext, walletState *WalletState, sendArg SendPathPaymentArg) (res SendPaymentResult, err error) {
return sendPathPayment(mctx, walletState, sendArg)
}
// SendPathPaymentGUI sends a path payment from GUI.
func SendPathPaymentGUI(mctx libkb.MetaContext, walletState *WalletState, sendArg SendPathPaymentArg) (res SendPaymentResult, err error) {
return sendPathPayment(mctx, walletState, sendArg)
}
// PathPaymentTx reutrns a signed path payment tx.
func PathPaymentTx(mctx libkb.MetaContext, walletState *WalletState, sendArg SendPathPaymentArg) (*stellarnet.SignResult, *stellar1.BundleEntry, *stellarcommon.Recipient, error) {
senderEntry, senderAccountBundle, err := LookupSender(mctx, sendArg.From)
if err != nil {
return nil, nil, nil, err
}
senderSeed, err := stellarnet.NewSeedStr(senderAccountBundle.Signers[0].SecureNoLogString())
if err != nil {
return nil, nil, nil, err
}
recipient, err := LookupRecipient(mctx, sendArg.To, false)
if err != nil {
return nil, nil, nil, err
}
if recipient.AccountID == nil {
return nil, nil, nil, errors.New("cannot send a path payment to a user without a stellar account")
}
if recipient.HasMemo() {
if sendArg.PublicMemo != nil {
return nil, nil, nil, fmt.Errorf("federation recipient included its own memo, but send called with a memo")
}
sendArg.PublicMemo, err = recipient.Memo()
if err != nil {
return nil, nil, nil, err
}
}
baseFee := walletState.BaseFee(mctx)
to, err := stellarnet.NewAddressStr(recipient.AccountID.String())
if err != nil {
return nil, nil, nil, err
}
sp, unlock := NewSeqnoProvider(mctx, walletState)
defer unlock()
sig, err := stellarnet.PathPaymentTransactionWithMemo(senderSeed, to, sendArg.Path.SourceAsset, sendArg.Path.SourceAmountMax, sendArg.Path.DestinationAsset, sendArg.Path.DestinationAmount, AssetSliceToAssetBase(sendArg.Path.Path), sendArg.PublicMemo, sp, nil, baseFee)
if err != nil {
return nil, nil, nil, err
}
return &sig, &senderEntry, &recipient, nil
}
func sendPathPayment(mctx libkb.MetaContext, walletState *WalletState, sendArg SendPathPaymentArg) (res SendPaymentResult, err error) {
sig, senderEntry, recipient, err := PathPaymentTx(mctx, walletState, sendArg)
if err != nil {
return res, err
}
senderAccountID := senderEntry.AccountID
post := stellar1.PathPaymentPost{
FromDeviceID: mctx.G().ActiveDevice.DeviceID(),
QuickReturn: sendArg.QuickReturn,
SignedTransaction: sig.Signed,
}
if recipient.User != nil {
post.To = &recipient.User.UV
}
if err := walletState.AddPendingTx(mctx.Ctx(), senderEntry.AccountID, stellar1.TransactionID(sig.TxHash), sig.Seqno); err != nil {
mctx.Debug("error calling AddPendingTx: %s", err)
}
if len(sendArg.SecretNote) > 0 {
noteClear := stellar1.NoteContents{
Note: sendArg.SecretNote,
StellarID: stellar1.TransactionID(sig.TxHash),
}
var recipientUv *keybase1.UserVersion
if recipient.User != nil {
recipientUv = &recipient.User.UV
}
post.NoteB64, err = NoteEncryptB64(mctx, noteClear, recipientUv)
if err != nil {
return res, fmt.Errorf("error encrypting note: %v", err)
}
}
rres, err := walletState.SubmitPathPayment(mctx, post)
if err != nil {
mctx.Debug("SEQNO SubmitPathPayment error seqno: %d txID: %s, err: %s", sig.Seqno, rres.StellarID, err)
if rerr := walletState.RemovePendingTx(mctx.Ctx(), senderEntry.AccountID, stellar1.TransactionID(sig.TxHash)); rerr != nil {
mctx.Debug("error calling RemovePendingTx: %s", rerr)
}
return res, err
}
mctx.Debug("sent path payment (direct) kbTxID:%v txID:%v pending:%v", sig.Seqno, rres.KeybaseID, rres.StellarID, rres.Pending)
mctx.Debug("SEQNO SubmitPathPayment success seqno: %d txID: %s", sig.Seqno, rres.StellarID)
if !rres.Pending {
mctx.Debug("SubmitPathPayment result wasn't pending, removing from wallet state: %s/%s", senderAccountID, sig.TxHash)
err = walletState.RemovePendingTx(mctx.Ctx(), senderEntry.AccountID, stellar1.TransactionID(sig.TxHash))
if err != nil {
mctx.Debug("SubmitPathPayment ws.RemovePendingTx error: %s", err)
}
}
err = walletState.Refresh(mctx, senderEntry.AccountID, "SubmitPathPayment")
if err != nil {
mctx.Debug("SubmitPathPayment ws.Refresh error: %s", err)
}
var chatRecipient string
if senderEntry.IsPrimary {
chatRecipient = chatRecipientStr(mctx, *recipient)
sendChat := func(mctx libkb.MetaContext) {
chatSendPaymentMessageSoft(mctx, chatRecipient, rres.StellarID, "SendPathPayment")
}
if sendArg.QuickReturn {
go sendChat(mctx.WithCtx(context.Background()))
} else {
sendChat(mctx)
}
} else {
mctx.Debug("not sending chat message: sending from non-primary account")
}
return SendPaymentResult{
KbTxID: rres.KeybaseID,
TxID: rres.StellarID,
Pending: rres.Pending,
JumpToChat: chatRecipient,
}, nil
}
type indexedSpec struct {
spec libkb.MiniChatPaymentSpec
index int
xlmAmountNumeric int64
}
// SpecMiniChatPayments returns a summary of the payment amounts for each recipient
// and a total.
func SpecMiniChatPayments(mctx libkb.MetaContext, walletState *WalletState, payments []libkb.MiniChatPayment) (*libkb.MiniChatPaymentSummary, error) {
// look up sender account
_, senderAccountBundle, err := LookupSenderPrimary(mctx)
if err != nil {
return nil, err
}
senderAccountID := senderAccountBundle.AccountID
senderCurrency, err := GetCurrencySetting(mctx, senderAccountID)
if err != nil {
return nil, err
}
senderRate, err := walletState.ExchangeRate(mctx.Ctx(), string(senderCurrency.Code))
if err != nil {
return nil, err
}
var summary libkb.MiniChatPaymentSummary
var xlmTotal int64
if len(payments) > 0 {
ch := make(chan indexedSpec)
for i, payment := range payments {
go func(payment libkb.MiniChatPayment, index int) {
spec, xlmAmountNumeric := specMiniChatPayment(mctx, walletState, payment)
ch <- indexedSpec{spec: spec, index: index, xlmAmountNumeric: xlmAmountNumeric}
}(payment, i)
}
summary.Specs = make([]libkb.MiniChatPaymentSpec, len(payments))
for i := 0; i < len(payments); i++ {
ispec := <-ch
summary.Specs[ispec.index] = ispec.spec
xlmTotal += ispec.xlmAmountNumeric
}
}
summary.XLMTotal = stellarnet.StringFromStellarAmount(xlmTotal)
if senderRate.Currency != "" && senderRate.Currency != "XLM" {
outsideAmount, err := stellarnet.ConvertXLMToOutside(summary.XLMTotal, senderRate.Rate)
if err != nil {
return nil, err
}
summary.DisplayTotal, err = FormatCurrencyWithCodeSuffix(mctx, outsideAmount, senderRate.Currency, stellarnet.Round)
if err != nil {
return nil, err
}
}
summary.XLMTotal, err = FormatAmountDescriptionXLM(mctx, summary.XLMTotal)
if err != nil {
return nil, err
}
return &summary, nil
}
func specMiniChatPayment(mctx libkb.MetaContext, walletState *WalletState, payment libkb.MiniChatPayment) (libkb.MiniChatPaymentSpec, int64) {
spec := libkb.MiniChatPaymentSpec{Username: payment.Username}
xlmAmount := payment.Amount
if payment.Currency != "" && payment.Currency != "XLM" {
exchangeRate, err := walletState.ExchangeRate(mctx.Ctx(), payment.Currency)
if err != nil {
spec.Error = err
return spec, 0
}
spec.DisplayAmount, err = FormatCurrencyWithCodeSuffix(mctx, payment.Amount, exchangeRate.Currency, stellarnet.Round)
if err != nil {
spec.Error = err
return spec, 0
}
xlmAmount, err = stellarnet.ConvertOutsideToXLM(payment.Amount, exchangeRate.Rate)
if err != nil {
spec.Error = err
return spec, 0
}
}
xlmAmountNumeric, err := stellarnet.ParseStellarAmount(xlmAmount)
if err != nil {
spec.Error = err
return spec, 0
}