-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfulfillment_handler.go
1518 lines (1245 loc) · 60.5 KB
/
fulfillment_handler.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 async_sequencer
import (
"context"
"encoding/hex"
"errors"
"math"
"sync"
"time"
commonpb "github.com/code-payments/code-protobuf-api/generated/go/common/v1"
commitment_worker "github.com/code-payments/code-server/pkg/code/async/commitment"
"github.com/code-payments/code-server/pkg/code/common"
code_data "github.com/code-payments/code-server/pkg/code/data"
"github.com/code-payments/code-server/pkg/code/data/commitment"
"github.com/code-payments/code-server/pkg/code/data/fulfillment"
"github.com/code-payments/code-server/pkg/code/data/timelock"
"github.com/code-payments/code-server/pkg/code/data/transaction"
"github.com/code-payments/code-server/pkg/code/data/treasury"
transaction_util "github.com/code-payments/code-server/pkg/code/transaction"
"github.com/code-payments/code-server/pkg/solana"
timelock_token "github.com/code-payments/code-server/pkg/solana/timelock/v1"
"github.com/code-payments/code-server/pkg/solana/token"
)
var (
// Global treasury pool lock
//
// todo: Use a distributed lock
treasuryPoolLock sync.Mutex
)
type FulfillmentHandler interface {
// CanSubmitToBlockchain determines whether the given fulfillment can be
// scheduled for submission to the blockchain.
//
// Implementations must consider global, account, intent, action and local
// state relevant to the type of fulfillment being handled to determine if
// it's safe to schedule.
//
// Implementations do not need to validate basic preconditions or basic
// circuit breaking checks, which is performed by the contextual scheduler.
CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error)
// SupportsOnDemandTransactions returns whether a fulfillment type supports
// on demand transaction creation
SupportsOnDemandTransactions() bool
// MakeOnDemandTransaction constructs a transaction at the time of submission
// to the blockchain. This is an optimization for the nonce pool. Implementations
// should not modify the provided fulfillment record or selected nonce, but rather
// use relevant fields to make the corresponding transaction.
MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error)
// OnSuccess is a callback function executed on a finalized transaction.
OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error
// OnFailure is a callback function executed upon detecting a failed
// transaction.
//
// In general, for automated and manual recovery, the steps should be
// 1. Ensure the assigned nonce is transitioned back to available
// state with the correct blockhash.
// 2. Update the fulfillment record with a new transaction, plus relevant
// metadata (eg. nonce, signature, etc), that does the exact same operation
// The fulfillment's state should be pending, so the fulfillment worker can
// begin submitting it immediately. The worker does this when recovered = true.
OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error)
// IsRevoked checks whether a fulfillment in the unknown state is revoked.
// It also provides a hint as to whether the nonce was used or not. When in
// doubt, say no or error out and let a human decide.
IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error)
}
type InitializeLockedTimelockAccountFulfillmentHandler struct {
data code_data.Provider
}
func NewInitializeLockedTimelockAccountFulfillmentHandler(data code_data.Provider) FulfillmentHandler {
return &InitializeLockedTimelockAccountFulfillmentHandler{
data: data,
}
}
func (h *InitializeLockedTimelockAccountFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.InitializeLockedTimelockAccount {
return false, errors.New("invalid fulfillment type")
}
accountInfoRecord, err := h.data.GetAccountInfoByTokenAddress(ctx, fulfillmentRecord.Source)
if err != nil {
return false, err
}
// New primary accounts are scheduled immediately, so the user can receive deposits
if accountInfoRecord.AccountType == commonpb.AccountType_PRIMARY {
return true, nil
}
// Every other account type needs to be used in a transfer of funds to be opened
nextScheduledFulfillment, err := h.data.GetNextSchedulableFulfillmentByAddress(ctx, fulfillmentRecord.Source, fulfillmentRecord.IntentOrderingIndex, fulfillmentRecord.ActionId, fulfillmentRecord.FulfillmentOrderingIndex)
if err != nil {
return false, err
}
switch nextScheduledFulfillment.FulfillmentType {
case fulfillment.NoPrivacyTransferWithAuthority, fulfillment.NoPrivacyWithdraw, fulfillment.TransferWithCommitment:
// The account must be the receiver of funds. Obviously it cannot be
// sending funds if it hasn't been opened yet.
if nextScheduledFulfillment.Source == fulfillmentRecord.Source || *nextScheduledFulfillment.Destination != fulfillmentRecord.Source {
return false, errors.New("account being opened is used in an unexpected way")
}
return true, nil
case fulfillment.CloseDormantTimelockAccount, fulfillment.CloseEmptyTimelockAccount:
// Technically valid, but we won't open for these cases
return false, nil
default:
// Any other type of fulfillment indicates we're using this account in
// an unexpected way.
return false, errors.New("account being opened is used in an unexpected way")
}
}
func (h *InitializeLockedTimelockAccountFulfillmentHandler) SupportsOnDemandTransactions() bool {
return true
}
func (h *InitializeLockedTimelockAccountFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
if fulfillmentRecord.FulfillmentType != fulfillment.InitializeLockedTimelockAccount {
return nil, errors.New("invalid fulfillment type")
}
timelockRecord, err := h.data.GetTimelockByVault(ctx, fulfillmentRecord.Source)
if err != nil {
return nil, err
}
authorityAccount, err := common.NewAccountFromPublicKeyString(timelockRecord.VaultOwner)
if err != nil {
return nil, err
}
// todo: a single function utility in the common package to do exactly how we're getting timelockAccounts
timelockAccounts, err := authorityAccount.GetTimelockAccounts(timelock_token.DataVersion1, common.KinMintAccount)
if err != nil {
return nil, err
}
txn, err := transaction_util.MakeOpenAccountTransaction(selectedNonce.Account, selectedNonce.Blockhash, timelockAccounts)
if err != nil {
return nil, err
}
err = txn.Sign(common.GetSubsidizer().PrivateKey().ToBytes())
if err != nil {
return nil, err
}
return &txn, nil
}
func (h *InitializeLockedTimelockAccountFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.InitializeLockedTimelockAccount {
return errors.New("invalid fulfillment type")
}
return markTimelockLocked(ctx, h.data, fulfillmentRecord.Source, txnRecord.Slot)
}
func (h *InitializeLockedTimelockAccountFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.InitializeLockedTimelockAccount {
return false, errors.New("invalid fulfillment type")
}
// Fulfillment record needs to be scheduled with a new transaction.
//
// todo: Implement auto-recovery
return false, nil
}
func (h *InitializeLockedTimelockAccountFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.InitializeLockedTimelockAccount {
return false, false, errors.New("invalid fulfillment type")
}
return false, false, nil
}
type NoPrivacyTransferWithAuthorityFulfillmentHandler struct {
data code_data.Provider
}
func NewNoPrivacyTransferWithAuthorityFulfillmentHandler(data code_data.Provider) FulfillmentHandler {
return &NoPrivacyTransferWithAuthorityFulfillmentHandler{
data: data,
}
}
func (h *NoPrivacyTransferWithAuthorityFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyTransferWithAuthority {
return false, errors.New("invalid fulfillment type")
}
// The source user account is a Code account, so we must validate it exists on
// the blockchain prior to sending funds from it.
isSourceAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, fulfillmentRecord.Source)
if err != nil {
return false, err
} else if !isSourceAccountCreated {
return false, nil
}
// The destination user account might be a Code account or external wallet, so we
// must validate it exists on the blockchain prior to send funds to it.
isDestinationAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, *fulfillmentRecord.Destination)
if err != nil {
return false, err
} else if !isDestinationAccountCreated {
return false, nil
}
// Check whether there's an earlier fulfillment that should be scheduled first
// where the source user account is the destination. This fulfillment might depend
// on the receipt of some funds.
earliestFulfillmentForSourceAsDestination, err := h.data.GetFirstSchedulableFulfillmentByAddressAsDestination(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillmentForSourceAsDestination != nil && earliestFulfillmentForSourceAsDestination.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
return true, nil
}
func (h *NoPrivacyTransferWithAuthorityFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyTransferWithAuthority {
return errors.New("invalid fulfillment type")
}
return savePaymentRecord(ctx, h.data, fulfillmentRecord, txnRecord)
}
func (h *NoPrivacyTransferWithAuthorityFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyTransferWithAuthority {
return false, errors.New("invalid fulfillment type")
}
// This is bad, we need to make the user whole
return false, nil
}
func (h *NoPrivacyTransferWithAuthorityFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyTransferWithAuthority {
return false, false, errors.New("invalid fulfillment type")
}
return false, false, nil
}
func (h *NoPrivacyTransferWithAuthorityFulfillmentHandler) SupportsOnDemandTransactions() bool {
return false
}
func (h *NoPrivacyTransferWithAuthorityFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
return nil, errors.New("not supported")
}
type NoPrivacyWithdrawFulfillmentHandler struct {
data code_data.Provider
}
func NewNoPrivacyWithdrawFulfillmentHandler(data code_data.Provider) FulfillmentHandler {
return &NoPrivacyWithdrawFulfillmentHandler{
data: data,
}
}
func (h *NoPrivacyWithdrawFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyWithdraw {
return false, errors.New("invalid fulfillment type")
}
// The source user account is a Code account, so we must validate it exists on
// the blockchain prior to sending funds from it.
isSourceAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, fulfillmentRecord.Source)
if err != nil {
return false, err
} else if !isSourceAccountCreated {
return false, nil
}
// The destination user account might be a Code account or external wallet, so we
// must validate it exists on the blockchain prior to send funds to it.
isDestinationAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, *fulfillmentRecord.Destination)
if err != nil {
return false, err
} else if !isDestinationAccountCreated {
return false, nil
}
// todo: We can have single "AsSourceOrDestination" query
// Check whether there's an earlier fulfillment that should be scheduled first
// where the source user account is the source. The account will be closed, so
// any prior transfers must be completed.
earliestFulfillment, err := h.data.GetFirstSchedulableFulfillmentByAddressAsSource(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillment != nil && earliestFulfillment.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
// Check whether there's an earlier fulfillment that should be scheduled first
// where the source user account is the destination. This fulfillment might depend
// on the receipt of some funds.
earliestFulfillment, err = h.data.GetFirstSchedulableFulfillmentByAddressAsDestination(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillment != nil && earliestFulfillment.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
return true, nil
}
func (h *NoPrivacyWithdrawFulfillmentHandler) SupportsOnDemandTransactions() bool {
return false
}
func (h *NoPrivacyWithdrawFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
return nil, errors.New("not supported")
}
func (h *NoPrivacyWithdrawFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyWithdraw {
return errors.New("invalid fulfillment type")
}
err := savePaymentRecord(ctx, h.data, fulfillmentRecord, txnRecord)
if err != nil {
return err
}
return onTokenAccountClosed(ctx, h.data, fulfillmentRecord, txnRecord)
}
func (h *NoPrivacyWithdrawFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyWithdraw {
return false, errors.New("invalid fulfillment type")
}
// This is bad, we need to make the user whole
return false, nil
}
func (h *NoPrivacyWithdrawFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.NoPrivacyWithdraw {
return false, false, errors.New("invalid fulfillment type")
}
return false, false, nil
}
type TemporaryPrivacyTransferWithAuthorityFulfillmentHandler struct {
conf *conf
data code_data.Provider
}
func NewTemporaryPrivacyTransferWithAuthorityFulfillmentHandler(data code_data.Provider, configProvider ConfigProvider) FulfillmentHandler {
return &TemporaryPrivacyTransferWithAuthorityFulfillmentHandler{
conf: configProvider(),
data: data,
}
}
func (h *TemporaryPrivacyTransferWithAuthorityFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.TemporaryPrivacyTransferWithAuthority {
return false, errors.New("invalid fulfillment type")
}
commitmentRecord, err := h.data.GetCommitmentByAction(ctx, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
if err != nil {
return false, err
}
// Sanity check that we haven't upgraded this private transfer
if commitmentRecord.RepaymentDivertedTo != nil {
return false, nil
}
// The commitment vault must be opened before we can send funds to it
if commitmentRecord.State != commitment.StateOpen {
return false, nil
}
// Check the privacy upgrade deadline, which is one of many factors as to
// why we may have opened the commitment vault. We need to ensure the
// deadline is hit before proceeding.
privacyUpgradeDeadline, err := commitment_worker.GetDeadlineToUpgradePrivacy(ctx, h.data, commitmentRecord)
if err == commitment_worker.ErrNoPrivacyUpgradeDeadline {
return false, nil
} else if err != nil {
return false, err
}
// The deadline to upgrade privacy hasn't been met, so don't schedule it
if privacyUpgradeDeadline.After(time.Now()) {
return false, nil
}
// The source user account is a Code account, so we must validate it exists on
// the blockchain prior to sending funds from it.
isSourceAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, fulfillmentRecord.Source)
if err != nil {
return false, err
} else if !isSourceAccountCreated {
return false, nil
}
// Check whether there's an earlier fulfillment that should be scheduled first
// where the source user account is the destination. This fulfillment might depend
// on the receipt of some funds.
earliestFulfillmentForSourceAsDestination, err := h.data.GetFirstSchedulableFulfillmentByAddressAsDestination(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillmentForSourceAsDestination != nil && earliestFulfillmentForSourceAsDestination.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
recordTemporaryPrivateTransferScheduledEvent(ctx, fulfillmentRecord)
return true, nil
}
func (h *TemporaryPrivacyTransferWithAuthorityFulfillmentHandler) SupportsOnDemandTransactions() bool {
return false
}
func (h *TemporaryPrivacyTransferWithAuthorityFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
return nil, errors.New("not supported")
}
func (h *TemporaryPrivacyTransferWithAuthorityFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.TemporaryPrivacyTransferWithAuthority {
return errors.New("invalid fulfillment type")
}
return savePaymentRecord(ctx, h.data, fulfillmentRecord, txnRecord)
}
func (h *TemporaryPrivacyTransferWithAuthorityFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.TemporaryPrivacyTransferWithAuthority {
return false, errors.New("invalid fulfillment type")
}
// This is bad. The treasury pool cannot be refunded
return false, nil
}
func (h *TemporaryPrivacyTransferWithAuthorityFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.TemporaryPrivacyTransferWithAuthority {
return false, false, errors.New("invalid fulfillment type")
}
count, err := h.data.GetFulfillmentCountByTypeActionAndState(
ctx,
fulfillmentRecord.Intent,
fulfillmentRecord.ActionId,
fulfillment.PermanentPrivacyTransferWithAuthority,
fulfillment.StateConfirmed,
)
if err != nil {
return false, false, err
}
// Temporary private transfer is revoked when the corresponding permanent
// private transfer in the same action is confirmed.
if count == 0 {
return false, false, nil
}
nonceRecord, err := h.data.GetNonce(ctx, *fulfillmentRecord.Nonce)
if err != nil {
return false, false, err
}
// Sanity check because this is dangerous since the blockhash would never be
// progressed and we'd be using a stale one on the next transaction. In an
// ideal world, this points to the upgraded fulfillment or nothing at all.
if nonceRecord.Signature == *fulfillmentRecord.Signature {
return false, false, errors.New("too dangerous to revoke fulfillment")
}
return true, true, nil
}
type PermanentPrivacyTransferWithAuthorityFulfillmentHandler struct {
conf *conf
data code_data.Provider
}
func NewPermanentPrivacyTransferWithAuthorityFulfillmentHandler(data code_data.Provider, configProvider ConfigProvider) FulfillmentHandler {
return &PermanentPrivacyTransferWithAuthorityFulfillmentHandler{
conf: configProvider(),
data: data,
}
}
func (h *PermanentPrivacyTransferWithAuthorityFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.PermanentPrivacyTransferWithAuthority {
return false, errors.New("invalid fulfillment type")
}
oldCommitmentRecord, err := h.data.GetCommitmentByAction(ctx, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
if err != nil {
return false, err
}
// The old commitment record must be marked as diverting funds to the new
// intended commitment vault before proceeding.
if oldCommitmentRecord.RepaymentDivertedTo == nil || *oldCommitmentRecord.RepaymentDivertedTo != *fulfillmentRecord.Destination {
return false, nil
}
newCommitmentRecord, err := h.data.GetCommitmentByVault(ctx, *fulfillmentRecord.Destination)
if err != nil {
return false, err
}
// The commitment vault must be opened before we can send funds to it
if newCommitmentRecord.State != commitment.StateOpen {
return false, nil
}
// The source user account is a Code account, so we must validate it exists on
// the blockchain prior to sending funds from it.
isSourceAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, fulfillmentRecord.Source)
if err != nil {
return false, err
} else if !isSourceAccountCreated {
return false, nil
}
// Check whether there's an earlier fulfillment that should be scheduled first
// where the source user account is the destination. This fulfillment might depend
// on the receipt of some funds.
earliestFulfillmentForSourceAsDestination, err := h.data.GetFirstSchedulableFulfillmentByAddressAsDestination(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillmentForSourceAsDestination != nil && earliestFulfillmentForSourceAsDestination.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
return true, nil
}
func (h *PermanentPrivacyTransferWithAuthorityFulfillmentHandler) SupportsOnDemandTransactions() bool {
return false
}
func (h *PermanentPrivacyTransferWithAuthorityFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
return nil, errors.New("not supported")
}
func (h *PermanentPrivacyTransferWithAuthorityFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.PermanentPrivacyTransferWithAuthority {
return errors.New("invalid fulfillment type")
}
err := savePaymentRecord(ctx, h.data, fulfillmentRecord, txnRecord)
if err != nil {
return err
}
// Wake up the temporary privacy transaction so we can process it to a revoked state
temporaryTransferFulfillment, err := h.data.GetAllFulfillmentsByTypeAndAction(ctx, fulfillment.TemporaryPrivacyTransferWithAuthority, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return err
} else if err == nil {
return markFulfillmentAsActivelyScheduled(ctx, h.data, temporaryTransferFulfillment[0])
}
return nil
}
func (h *PermanentPrivacyTransferWithAuthorityFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.PermanentPrivacyTransferWithAuthority {
return false, errors.New("invalid fulfillment type")
}
// This is bad. The treasury pool cannot be refunded
return false, nil
}
func (h *PermanentPrivacyTransferWithAuthorityFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.PermanentPrivacyTransferWithAuthority {
return false, false, errors.New("invalid fulfillment type")
}
return false, false, nil
}
type TransferWithCommitmentFulfillmentHandler struct {
data code_data.Provider
}
func NewTransferWithCommitmentFulfillmentHandler(data code_data.Provider) FulfillmentHandler {
return &TransferWithCommitmentFulfillmentHandler{
data: data,
}
}
func (h *TransferWithCommitmentFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.TransferWithCommitment {
return false, errors.New("invalid fulfillment type")
}
// Ensure the commitment record exists and it's in a valid initial state.
commitmentRecord, err := h.data.GetCommitmentByAction(ctx, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
if err != nil {
return false, err
} else if commitmentRecord.State != commitment.StateUnknown && commitmentRecord.State != commitment.StatePayingDestination {
return false, errors.New("commitment in unexpected state")
}
// The destination account is a Code account, so we must validate it exists
// on the blockchain prior to sending funds to it.
isDestinationAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, *fulfillmentRecord.Destination)
if err != nil {
return false, err
} else if !isDestinationAccountCreated {
return false, nil
}
// If our funds aren't already reserved for use with the treasury pool, then we
// need to check if there's sufficient funding to pay the destination.
if commitmentRecord.State != commitment.StatePayingDestination {
// No need to include the state transition in the lock yet, since we transition
// the commitment account to a state where the funds will be reserved. If the DB
// has a failure, we'll just retry scheduling and it will go through the next
// time.
treasuryPoolLock.Lock()
defer treasuryPoolLock.Unlock()
poolRecord, err := h.data.GetTreasuryPoolByAddress(ctx, commitmentRecord.Pool)
if err != nil {
return false, err
}
totalAvailableTreasuryPoolFunds, usedTreasuryPoolFunds, err := estimateTreasuryPoolFundingLevels(ctx, h.data, poolRecord)
if err != nil {
return false, err
}
// The treasury pool's funds are used entirely
if usedTreasuryPoolFunds >= totalAvailableTreasuryPoolFunds {
return false, nil
}
// The treasury pool doesn't have sufficient funds to transfer to the destination
// account.
remainingTreasuryPoolFunds := totalAvailableTreasuryPoolFunds - usedTreasuryPoolFunds
if remainingTreasuryPoolFunds < commitmentRecord.Amount {
return false, nil
}
// Mark the commitment as paying the destination, so we can track the funds we're
// going to be using from the treasury pool.
err = markCommitmentPayingDestination(ctx, h.data, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
if err != nil {
return false, err
}
}
return true, nil
}
func (h *TransferWithCommitmentFulfillmentHandler) SupportsOnDemandTransactions() bool {
return true
}
func (h *TransferWithCommitmentFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
commitmentRecord, err := h.data.GetCommitmentByAction(ctx, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
if err != nil {
return nil, err
}
if commitmentRecord.State != commitment.StatePayingDestination {
return nil, errors.New("commitment in unexpected state")
}
treasuryPool, err := common.NewAccountFromPublicKeyString(commitmentRecord.Pool)
if err != nil {
return nil, err
}
treasuryPoolVault, err := common.NewAccountFromPublicKeyString(fulfillmentRecord.Source)
if err != nil {
return nil, err
}
destination, err := common.NewAccountFromPublicKeyString(commitmentRecord.Destination)
if err != nil {
return nil, err
}
commitment, err := common.NewAccountFromPublicKeyString(commitmentRecord.Address)
if err != nil {
return nil, err
}
transcript, err := hex.DecodeString(commitmentRecord.Transcript)
if err != nil {
return nil, err
}
recentRoot, err := hex.DecodeString(commitmentRecord.RecentRoot)
if err != nil {
return nil, err
}
txn, err := transaction_util.MakeTreasuryAdvanceTransaction(
selectedNonce.Account,
selectedNonce.Blockhash,
treasuryPool,
treasuryPoolVault,
destination,
commitment,
commitmentRecord.PoolBump,
commitmentRecord.Amount,
transcript,
recentRoot,
)
if err != nil {
return nil, err
}
err = txn.Sign(common.GetSubsidizer().PrivateKey().ToBytes())
if err != nil {
return nil, err
}
return &txn, nil
}
func (h *TransferWithCommitmentFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.TransferWithCommitment {
return errors.New("invalid fulfillment type")
}
err := savePaymentRecord(ctx, h.data, fulfillmentRecord, txnRecord)
if err != nil {
return err
}
return markCommitmentReadyToOpen(ctx, h.data, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
}
func (h *TransferWithCommitmentFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.TransferWithCommitment {
return false, errors.New("invalid fulfillment type")
}
// Fulfillment record needs to be scheduled with a new transaction
//
// todo: Implement auto-recovery
return false, nil
}
func (h *TransferWithCommitmentFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.TransferWithCommitment {
return false, false, errors.New("invalid fulfillment type")
}
return false, false, nil
}
type CloseEmptyTimelockAccountFulfillmentHandler struct {
data code_data.Provider
}
func NewCloseEmptyTimelockAccountFulfillmentHandler(data code_data.Provider) FulfillmentHandler {
return &CloseEmptyTimelockAccountFulfillmentHandler{
data: data,
}
}
func (h *CloseEmptyTimelockAccountFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseEmptyTimelockAccount {
return false, errors.New("invalid fulfillment type")
}
// todo: We can have single "AsSourceOrDestination" query
// The source account is a user account, so check that there are no other
// fulfillments where it's used as a source account.
earliestFulfillment, err := h.data.GetFirstSchedulableFulfillmentByAddressAsSource(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillment != nil && earliestFulfillment.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
// The source account is a user account, so check that there are no other
// fulfillments where it's used as a destination account.
earliestFulfillment, err = h.data.GetFirstSchedulableFulfillmentByAddressAsDestination(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillment != nil && earliestFulfillment.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
return true, nil
}
func (h *CloseEmptyTimelockAccountFulfillmentHandler) SupportsOnDemandTransactions() bool {
return false
}
func (h *CloseEmptyTimelockAccountFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
return nil, errors.New("not supported")
}
func (h *CloseEmptyTimelockAccountFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseEmptyTimelockAccount {
return errors.New("invalid fulfillment type")
}
return onTokenAccountClosed(ctx, h.data, fulfillmentRecord, txnRecord)
}
func (h *CloseEmptyTimelockAccountFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseEmptyTimelockAccount {
return false, errors.New("invalid fulfillment type")
}
// Fulfillment record needs to be scheduled with a new transaction, which may
// or may not need to be signed by the client. It all depends on whether there
// is dust in the account.
//
// todo: Implement auto-recovery when we know the account is empty
// todo: Do "something" to indicate the client needs to resign a new transaction
return false, nil
}
func (h *CloseEmptyTimelockAccountFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseEmptyTimelockAccount {
return false, false, errors.New("invalid fulfillment type")
}
return false, false, nil
}
type CloseDormantTimelockAccountFulfillmentHandler struct {
data code_data.Provider
}
func NewCloseDormantTimelockAccountFulfillmentHandler(data code_data.Provider) FulfillmentHandler {
return &CloseDormantTimelockAccountFulfillmentHandler{
data: data,
}
}
func (h *CloseDormantTimelockAccountFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseDormantTimelockAccount {
return false, errors.New("invalid fulfillment type")
}
// For now, we only ever save fulfillment records for gift cards, so the below
// check isn't necessary yet. However, if this is no longer the case, the code
// below should be uncommented, unless other flows warrant it.
/*
accountInfoRecord, err := h.data.GetAccountInfoByTokenAddress(ctx, fulfillmentRecord.Source)
if err != nil {
return false, err
}
// Sanity check that could avoid a distastrous scenario if we accidentally
// schedule something that's not a gift card
if accountInfoRecord.AccountType != commonpb.AccountType_REMOTE_SEND_GIFT_CARD {
return false, errors.New("source must be a remote send gift card")
}
*/
// The source account is a Code account, so we must validate it exists on
// the blockchain prior to sending funds from it.
isSourceAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, fulfillmentRecord.Source)
if err != nil {
return false, err
} else if !isSourceAccountCreated {
return false, nil
}
// The destination account might is a Code account, so we must validate it
// exists on the blockchain prior to send funds to it.
isDestinationAccountCreated, err := isTokenAccountOnBlockchain(ctx, h.data, *fulfillmentRecord.Destination)
if err != nil {
return false, err
} else if !isDestinationAccountCreated {
return false, nil
}
// todo: We can have single "AsSourceOrDestination" query
// The source account is a user account, so check that there are no other
// fulfillments where it's used as a source account before closing it.
earliestFulfillment, err := h.data.GetFirstSchedulableFulfillmentByAddressAsSource(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillment != nil && earliestFulfillment.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
// The source account is a user account, so check that there are no other
// fulfillments where it's used as a destination before closing it.
earliestFulfillment, err = h.data.GetFirstSchedulableFulfillmentByAddressAsDestination(ctx, fulfillmentRecord.Source)
if err != nil && err != fulfillment.ErrFulfillmentNotFound {
return false, err
}
if earliestFulfillment != nil && earliestFulfillment.ScheduledBefore(fulfillmentRecord) {
return false, nil
}
return true, nil
}
func (h *CloseDormantTimelockAccountFulfillmentHandler) SupportsOnDemandTransactions() bool {
return false
}
func (h *CloseDormantTimelockAccountFulfillmentHandler) MakeOnDemandTransaction(ctx context.Context, fulfillmentRecord *fulfillment.Record, selectedNonce *transaction_util.SelectedNonce) (*solana.Transaction, error) {
return nil, errors.New("not supported")
}
func (h *CloseDormantTimelockAccountFulfillmentHandler) OnSuccess(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) error {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseDormantTimelockAccount {
return errors.New("invalid fulfillment type")
}
return onTokenAccountClosed(ctx, h.data, fulfillmentRecord, txnRecord)
}
func (h *CloseDormantTimelockAccountFulfillmentHandler) OnFailure(ctx context.Context, fulfillmentRecord *fulfillment.Record, txnRecord *transaction.Record) (recovered bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseDormantTimelockAccount {
return false, errors.New("invalid fulfillment type")
}
return false, nil
}
func (h *CloseDormantTimelockAccountFulfillmentHandler) IsRevoked(ctx context.Context, fulfillmentRecord *fulfillment.Record) (revoked bool, nonceUsed bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.CloseDormantTimelockAccount {
return false, false, errors.New("invalid fulfillment type")
}
// Replace above logic with commented code if we decide to use CloseDormantAccount actions
timelockRecord, err := h.data.GetTimelockByVault(ctx, fulfillmentRecord.Source)
if err != nil {
return false, false, err
}
if timelockRecord.IsClosed() {
err = markActionRevoked(ctx, h.data, fulfillmentRecord.Intent, fulfillmentRecord.ActionId)
if err != nil {
return false, false, err
}
return true, false, nil
}
return false, false, nil
}
type SaveRecentRootFulfillmentHandler struct {
data code_data.Provider
}
func NewSaveRecentRootFulfillmentHandler(data code_data.Provider) FulfillmentHandler {
return &SaveRecentRootFulfillmentHandler{
data: data,
}
}
// Assumption: Saving a recent root is pre-sorted to the back of the line
func (h *SaveRecentRootFulfillmentHandler) CanSubmitToBlockchain(ctx context.Context, fulfillmentRecord *fulfillment.Record) (scheduled bool, err error) {
if fulfillmentRecord.FulfillmentType != fulfillment.SaveRecentRoot {
return false, errors.New("invalid fulfillment type")
}
// Ensure that any prior TransferWithCommitment fulfillments are played out