-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathintent_handler.go
513 lines (437 loc) · 15.2 KB
/
intent_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
package async_sequencer
import (
"context"
"errors"
code_data "github.com/code-payments/code-server/pkg/code/data"
"github.com/code-payments/code-server/pkg/code/data/action"
"github.com/code-payments/code-server/pkg/code/data/fulfillment"
"github.com/code-payments/code-server/pkg/code/data/intent"
)
var (
ErrInvalidIntentStateTransition = errors.New("invalid intent state transition")
)
type IntentHandler interface {
// Note: As of right now, we're restricted to checking actions, whose state is
// guaranteed to be updated by the time this is called. As a result, the
// intent handler should just get the records as needed since they need
// a global view anyways.
OnActionUpdated(ctx context.Context, intentId string) error
}
type OpenAccountsIntentHandler struct {
data code_data.Provider
}
func NewOpenAccountsIntentHandler(data code_data.Provider) IntentHandler {
return &OpenAccountsIntentHandler{
data: data,
}
}
func (h *OpenAccountsIntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecords, err := h.data.GetAllActionsByIntent(ctx, intentId)
if err != nil {
return err
}
for _, actionRecord := range actionRecords {
if actionRecord.ActionType != action.OpenAccount {
continue
}
// Intent is failed if at least one OpenAccount action fails
if actionRecord.State == action.StateFailed {
return markIntentFailed(ctx, h.data, intentId)
}
if actionRecord.State != action.StateConfirmed {
return nil
}
}
// Intent is confirmed when all OpenAccount actions are confirmed
return markIntentConfirmed(ctx, h.data, intentId)
}
type SendPrivatePaymentIntentHandler struct {
data code_data.Provider
}
func NewSendPrivatePaymentIntentHandler(data code_data.Provider) IntentHandler {
return &SendPrivatePaymentIntentHandler{
data: data,
}
}
func (h *SendPrivatePaymentIntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecords, err := h.data.GetAllActionsByIntent(ctx, intentId)
if err != nil {
return err
}
canMarkConfirmed := true
for _, actionRecord := range actionRecords {
switch actionRecord.ActionType {
case action.PrivateTransfer, action.NoPrivacyTransfer, action.NoPrivacyWithdraw:
default:
continue
}
// Intent is failed if at least one money movement action fails
if actionRecord.State == action.StateFailed {
return markIntentFailed(ctx, h.data, intentId)
}
if actionRecord.State != action.StateConfirmed {
canMarkConfirmed = false
}
}
// Intent is confirmed when all money movement actions are confirmed
if canMarkConfirmed {
return markIntentConfirmed(ctx, h.data, intentId)
}
return h.maybeMarkTempOutgoingAccountActionsAsActivelyScheduled(ctx, intentId, actionRecords)
}
func (h *SendPrivatePaymentIntentHandler) maybeMarkTempOutgoingAccountActionsAsActivelyScheduled(ctx context.Context, intentId string, actionsRecords []*action.Record) error {
intentRecord, err := h.data.GetIntent(ctx, intentId)
if err != nil {
return err
}
// Find relevant actions that have fulfillments using the temp outgoing account
// where active scheduling is disabled because of treasury advance dependencies.
//
// Note: SubmitIntent validation guarantees there's a single NoPrivacyWithdraw
// and NoPrivacyTransfer action that maps to the payment to the destianattion
// account and optional fee to Code, respectively, all coming from the temp
// outgoing account.
var paymentToDestinationAction *action.Record
var feePaymentAction *action.Record
for _, actionRecord := range actionsRecords {
switch actionRecord.ActionType {
case action.NoPrivacyWithdraw:
paymentToDestinationAction = actionRecord
case action.NoPrivacyTransfer:
feePaymentAction = actionRecord
}
}
if paymentToDestinationAction == nil {
return errors.New("payment to destination action not found")
}
if feePaymentAction == nil && intentRecord.SendPrivatePaymentMetadata.IsMicroPayment {
return errors.New("fee payment action not found")
}
// Extract the corresponding fulfillment records that have active scheduling
// disabled.
var paymentToDestinationFulfillment *fulfillment.Record
fulfillmentRecords, err := h.data.GetAllFulfillmentsByTypeAndAction(
ctx,
fulfillment.NoPrivacyWithdraw,
intentId,
paymentToDestinationAction.ActionId,
)
if err != nil {
return err
} else if err == nil && fulfillmentRecords[0].DisableActiveScheduling {
paymentToDestinationFulfillment = fulfillmentRecords[0]
}
var feePaymentFulfillment *fulfillment.Record
if feePaymentAction != nil {
fulfillmentRecords, err := h.data.GetAllFulfillmentsByTypeAndAction(
ctx,
fulfillment.NoPrivacyTransferWithAuthority,
intentId,
feePaymentAction.ActionId,
)
if err != nil {
return err
} else if err == nil && fulfillmentRecords[0].DisableActiveScheduling {
feePaymentFulfillment = fulfillmentRecords[0]
}
}
// Short circuit if there's nothing to update to avoid redundant intent
// state checks spanning all actions.
if paymentToDestinationFulfillment == nil && feePaymentFulfillment == nil {
return nil
}
// Do some sanity checks to determine whether active scheduling can be enabled.
tempOutgoingAccount := paymentToDestinationAction.Source
for _, actionRecord := range actionsRecords {
if actionRecord.ActionType != action.PrivateTransfer {
continue
}
if *actionRecord.Destination != tempOutgoingAccount {
continue
}
// Is there a treasury advance that's sending funds to the temp outgoing
// account that's not pending or completed? If so, wait for all advances
// to be scheduled or completed. We need to rely on fulfillments because
// private transfer action states operate on the entire lifecycle, and we
// only care about the treasury advances.
transferWithCommitmentFulfillment, err := h.data.GetAllFulfillmentsByTypeAndAction(
ctx,
fulfillment.TransferWithCommitment,
intentId,
actionRecord.ActionId,
)
if err != nil {
return err
}
// Note: Due to how the generic fulfillment worker logic functions, it's
// likely that at least one fulfillment is in an in flux state from pending
// to confirmed. This is by design to allow the worker to retry, but makes
// this logic imperfect by just checking for all confirmed. That's why it
// differs from other intent handlers that can operate on actions, since
// that flow has these guarantees. Regardless, dependency logic still saves
// us and we're only making the fulfillment available for active polling.
if transferWithCommitmentFulfillment[0].State != fulfillment.StatePending && transferWithCommitmentFulfillment[0].State != fulfillment.StateConfirmed {
return nil
}
}
// Mark fulfillments as actively scheduled when at least all treasury payments
// to the temp outgoing account are in flight.
if feePaymentFulfillment != nil {
err = markFulfillmentAsActivelyScheduled(ctx, h.data, feePaymentFulfillment)
if err != nil {
return err
}
}
if paymentToDestinationFulfillment != nil {
err = markFulfillmentAsActivelyScheduled(ctx, h.data, paymentToDestinationFulfillment)
if err != nil {
return err
}
}
return nil
}
type ReceivePaymentsPrivatelyIntentHandler struct {
data code_data.Provider
}
func NewReceivePaymentsPrivatelyIntentHandler(data code_data.Provider) IntentHandler {
return &ReceivePaymentsPrivatelyIntentHandler{
data: data,
}
}
func (h *ReceivePaymentsPrivatelyIntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecords, err := h.data.GetAllActionsByIntent(ctx, intentId)
if err != nil {
return err
}
canMarkConfirmed := true
for _, actionRecord := range actionRecords {
switch actionRecord.ActionType {
case action.PrivateTransfer, action.CloseEmptyAccount:
default:
continue
}
// Intent is failed if at least one PrivateTransfer action fails
if actionRecord.State == action.StateFailed {
return markIntentFailed(ctx, h.data, intentId)
}
if actionRecord.State != action.StateConfirmed {
canMarkConfirmed = false
}
}
// Intent is confirmed when all PrivateTransfer and CloseEmptyAccount (there should only
// be one when receiving from temp incoming) actions are confirmed
if canMarkConfirmed {
return markIntentConfirmed(ctx, h.data, intentId)
}
return h.maybeMarkCloseEmptyAccountActionAsActivelyScheduled(ctx, intentId, actionRecords)
}
func (h *ReceivePaymentsPrivatelyIntentHandler) maybeMarkCloseEmptyAccountActionAsActivelyScheduled(ctx context.Context, intentId string, actionsRecords []*action.Record) error {
intentRecord, err := h.data.GetIntent(ctx, intentId)
if err != nil {
return err
}
// Deposits don't have a CloseEmptyAccount action because they receive from a
// persistent primary account
if intentRecord.ReceivePaymentsPrivatelyMetadata.IsDeposit {
return nil
}
var closeEmptyAccountAction *action.Record
for _, actionRecord := range actionsRecords {
if actionRecord.ActionType == action.CloseEmptyAccount {
closeEmptyAccountAction = actionRecord
break
}
}
if closeEmptyAccountAction == nil {
return errors.New("close empty account action not found")
}
tempIncomingAccount := closeEmptyAccountAction.Source
// Is there an unconfirmed private transfer that's dependent on the account
// being closed as a source of funds? If so, wait for it to complete to drain
// the balance.
for _, actionRecord := range actionsRecords {
if actionRecord.ActionType != action.PrivateTransfer {
continue
}
if actionRecord.Source != tempIncomingAccount {
continue
}
if actionRecord.State != action.StateConfirmed {
return nil
}
}
// All private transfers from the temp incoming account are confirmed. There
// should be no funds (except possibly some dust), so w can actively schedule
// to close fulfillment.
// There should only be one per intent validation in SubmitIntent
closeEmptyAccountFulfillment, err := h.data.GetAllFulfillmentsByTypeAndAction(
ctx,
fulfillment.CloseEmptyTimelockAccount,
closeEmptyAccountAction.Intent,
closeEmptyAccountAction.ActionId,
)
if err != nil {
return err
}
return markFulfillmentAsActivelyScheduled(ctx, h.data, closeEmptyAccountFulfillment[0])
}
type SaveRecentRootIntentHandler struct {
data code_data.Provider
}
func NewSaveRecentRootIntentHandler(data code_data.Provider) IntentHandler {
return &SaveRecentRootIntentHandler{
data: data,
}
}
func (h *SaveRecentRootIntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecord, err := h.data.GetActionById(ctx, intentId, 0)
if err != nil {
return err
}
// Intent is confirmed/failed based on the state the single action
switch actionRecord.State {
case action.StateConfirmed:
return markIntentConfirmed(ctx, h.data, intentId)
case action.StateFailed:
return markIntentFailed(ctx, h.data, intentId)
}
return nil
}
type MigrateToPrivacy2022IntentHandler struct {
data code_data.Provider
}
func NewMigrateToPrivacy2022IntentHandler(data code_data.Provider) IntentHandler {
return &MigrateToPrivacy2022IntentHandler{
data: data,
}
}
func (h *MigrateToPrivacy2022IntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecord, err := h.data.GetActionById(ctx, intentId, 0)
if err != nil {
return err
}
// Intent is confirmed/failed based on the state the single action
switch actionRecord.State {
case action.StateConfirmed:
return markIntentConfirmed(ctx, h.data, intentId)
case action.StateFailed:
return markIntentFailed(ctx, h.data, intentId)
}
return nil
}
type SendPublicPaymentIntentHandler struct {
data code_data.Provider
}
func NewSendPublicPaymentIntentHandler(data code_data.Provider) IntentHandler {
return &MigrateToPrivacy2022IntentHandler{
data: data,
}
}
func (h *SendPublicPaymentIntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecord, err := h.data.GetActionById(ctx, intentId, 0)
if err != nil {
return err
}
// Intent is confirmed/failed based on the state the single action
switch actionRecord.State {
case action.StateConfirmed:
return markIntentConfirmed(ctx, h.data, intentId)
case action.StateFailed:
return markIntentFailed(ctx, h.data, intentId)
}
return nil
}
type ReceivePaymentsPubliclyIntentHandler struct {
data code_data.Provider
}
func NewReceivePaymentsPubliclyIntentHandler(data code_data.Provider) IntentHandler {
return &ReceivePaymentsPubliclyIntentHandler{
data: data,
}
}
func (h *ReceivePaymentsPubliclyIntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecord, err := h.data.GetActionById(ctx, intentId, 0)
if err != nil {
return err
}
// Intent is confirmed/failed based on the state the single action
switch actionRecord.State {
case action.StateConfirmed:
return markIntentConfirmed(ctx, h.data, intentId)
case action.StateFailed:
return markIntentFailed(ctx, h.data, intentId)
}
return nil
}
type EstablishRelationshipIntentHandler struct {
data code_data.Provider
}
func NewEstablishRelationshipIntentHandler(data code_data.Provider) IntentHandler {
return &EstablishRelationshipIntentHandler{
data: data,
}
}
func (h *EstablishRelationshipIntentHandler) OnActionUpdated(ctx context.Context, intentId string) error {
actionRecord, err := h.data.GetActionById(ctx, intentId, 0)
if err != nil {
return err
}
// Intent is confirmed/failed based on the state the single action
switch actionRecord.State {
case action.StateConfirmed:
return markIntentConfirmed(ctx, h.data, intentId)
case action.StateFailed:
return markIntentFailed(ctx, h.data, intentId)
}
return nil
}
func validateIntentState(record *intent.Record, states ...intent.State) error {
for _, validState := range states {
if record.State == validState {
return nil
}
}
return ErrInvalidIntentStateTransition
}
func markIntentConfirmed(ctx context.Context, data code_data.Provider, intentId string) error {
record, err := data.GetIntent(ctx, intentId)
if err != nil {
return err
}
if record.State == intent.StateConfirmed {
return nil
}
err = validateIntentState(record, intent.StatePending)
if err != nil {
return err
}
record.State = intent.StateConfirmed
return data.SaveIntent(ctx, record)
}
func markIntentFailed(ctx context.Context, data code_data.Provider, intentId string) error {
record, err := data.GetIntent(ctx, intentId)
if err != nil {
return err
}
if record.State == intent.StateFailed {
return nil
}
err = validateIntentState(record, intent.StatePending)
if err != nil {
return err
}
record.State = intent.StateFailed
return data.SaveIntent(ctx, record)
}
func getIntentHandlers(data code_data.Provider) map[intent.Type]IntentHandler {
handlersByType := make(map[intent.Type]IntentHandler)
handlersByType[intent.OpenAccounts] = NewOpenAccountsIntentHandler(data)
handlersByType[intent.SendPrivatePayment] = NewSendPrivatePaymentIntentHandler(data)
handlersByType[intent.ReceivePaymentsPrivately] = NewReceivePaymentsPrivatelyIntentHandler(data)
handlersByType[intent.SaveRecentRoot] = NewSaveRecentRootIntentHandler(data)
handlersByType[intent.MigrateToPrivacy2022] = NewMigrateToPrivacy2022IntentHandler(data)
handlersByType[intent.SendPublicPayment] = NewSendPublicPaymentIntentHandler(data)
handlersByType[intent.ReceivePaymentsPublicly] = NewReceivePaymentsPubliclyIntentHandler(data)
handlersByType[intent.EstablishRelationship] = NewEstablishRelationshipIntentHandler(data)
return handlersByType
}