forked from StellarGateLabs/StellarGate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.rs
More file actions
2025 lines (1849 loc) · 73.1 KB
/
Copy pathdb.rs
File metadata and controls
2025 lines (1849 loc) · 73.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::Result;
use sqlx::{Pool, Row, Sqlite};
pub type Db = Pool<Sqlite>;
/// Normalize a raw SQLite timestamp to strict RFC 3339 UTC with a Z suffix.
///
/// Handles both legacy rows (`"2026-04-29 15:00:00"` / `"2026-04-29T15:00:00"`)
/// and already-correct rows (`"2026-04-29T15:00:00Z"`). Any value that doesn't
/// look like a 19-character datetime is returned unchanged so we never silently
/// corrupt unexpected data.
fn normalize_ts(raw: &str) -> String {
let s = raw.trim();
// Already has an explicit offset/Z — nothing to do.
if s.ends_with('Z') || s.contains('+') {
return s.to_string();
}
// Replace the space separator with T if present, then append Z.
if s.len() == 19 {
let with_t = s.replacen(' ', "T", 1);
return format!("{with_t}Z");
}
s.to_string()
}
pub async fn migrate(pool: &Db) -> Result<()> {
sqlx::query(
"CREATE TABLE IF NOT EXISTS payments (
id TEXT PRIMARY KEY,
merchant_id TEXT NOT NULL DEFAULT 'anonymous',
destination_address TEXT NOT NULL,
memo TEXT NOT NULL UNIQUE,
amount TEXT NOT NULL,
asset TEXT NOT NULL DEFAULT 'XLM',
asset_issuer TEXT,
status TEXT NOT NULL DEFAULT 'pending',
webhook_url TEXT,
tx_hash TEXT,
paid_amount TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
expires_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now','+1 hour'))
)",
)
.execute(pool)
.await?;
/* Bring pre-existing payment tables up to schema. New databases already have
`expires_at` from the CREATE TABLE above; older ones need it added in
place. SQLite rejects a non-constant DEFAULT on ALTER ... ADD COLUMN, so we
add it nullable and backfill below. */
let has_expires_at: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('payments') WHERE name = 'expires_at'",
)
.fetch_one(pool)
.await?;
if has_expires_at == 0 {
sqlx::query("ALTER TABLE payments ADD COLUMN expires_at TEXT")
.execute(pool)
.await?;
}
/* Backfill any row without an expiry (legacy rows, or rows inserted in the
brief window before the column existed). `created_at + 1h` mirrors the
default TTL; SQLite's date functions accept the stored RFC 3339 `Z` form. */
sqlx::query(
"UPDATE payments
SET expires_at = strftime('%Y-%m-%dT%H:%M:%SZ', created_at, '+1 hour')
WHERE expires_at IS NULL",
)
.execute(pool)
.await?;
/* `asset_issuer` completes the asset identity of an intent. Only the code
used to be stored, so which USDC (say) a historical row referred to lived in
process configuration and changed whenever `ACCEPTED_ASSETS` was edited
(issue #223). Existing databases get the column added in place; it is
nullable by design — NULL means the native asset, which has no issuer.
Rows created before this migration are backfilled, best-effort, from the
configured allow-list by [`backfill_asset_issuers`]. */
let has_asset_issuer: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('payments') WHERE name = 'asset_issuer'",
)
.fetch_one(&mut *tx)
.await?;
if has_asset_issuer == 0 {
sqlx::query("ALTER TABLE payments ADD COLUMN asset_issuer TEXT")
.execute(&mut *tx)
.await?;
}
sqlx::query("CREATE INDEX IF NOT EXISTS idx_payments_memo ON payments(memo)")
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_payments_status ON payments(status)")
.execute(pool)
.await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_payments_created_id ON payments(created_at DESC, id DESC)",
)
.execute(pool)
.await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS webhook_deliveries (
id TEXT PRIMARY KEY,
payment_id TEXT NOT NULL,
url TEXT NOT NULL,
payload TEXT NOT NULL,
event_type TEXT,
status TEXT NOT NULL DEFAULT 'pending',
attempts INTEGER NOT NULL DEFAULT 0,
last_attempt TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
)",
)
.execute(pool)
.await?;
/* Bring pre-existing delivery tables up to schema. `event_type` records
which event the payload represents so a redelivery can echo the original
`X-StellarGate-Event` header instead of guessing. Rows written before this
column existed stay NULL; readers fall back to the `event` field inside the
stored payload. */
let has_event_type: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('webhook_deliveries') WHERE name = 'event_type'",
)
.fetch_one(pool)
.await?;
if has_event_type == 0 {
sqlx::query("ALTER TABLE webhook_deliveries ADD COLUMN event_type TEXT")
.execute(&mut *tx)
.await?;
}
/* Back-fill `event_type` for legacy rows whose column is NULL but whose
stored payload carries an `event` field (issue #237). This makes the
FALLBACK_EVENT path in `WebhookDelivery::event` genuinely unreachable for
rows this gateway wrote — the fallback is only needed for payloads that
could not be parsed at all (corruption, manual edits), which should never
happen for rows we inserted ourselves.
The JSON path expression `json_extract(payload, '$.event')` returns NULL
when the field is absent, keeping those rows NULL (they remain for the
fallback). This is a no-op for rows that already have event_type set. */
sqlx::query(
"UPDATE webhook_deliveries
SET event_type = json_extract(payload, '$.event')
WHERE event_type IS NULL
AND json_extract(payload, '$.event') IS NOT NULL",
)
.execute(&mut *tx)
.await?;
/* `acknowledged_at` records that somebody has seen a terminal failure and
acted on it — set by the bulk requeue/acknowledge endpoint. It exists so
retention can distinguish "this failure was dealt with" from "nobody has
looked at this yet", and refuse to delete the latter (issue #319). Rows
that predate the column are NULL, i.e. unacknowledged, which is the safe
reading: we do not know that anyone saw them. */
let has_acknowledged_at: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('webhook_deliveries') WHERE name = 'acknowledged_at'",
)
.fetch_one(&mut *tx)
.await?;
if has_acknowledged_at == 0 {
sqlx::query("ALTER TABLE webhook_deliveries ADD COLUMN acknowledged_at TEXT")
.execute(&mut *tx)
.await?;
}
/* Durable key/value state — used by the Horizon poller to persist its
paging cursor so it resumes exactly where it left off across restarts. */
sqlx::query(
"CREATE TABLE IF NOT EXISTS kv_state (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
)",
)
.execute(pool)
.await?;
/* Merchants are provisioned via POST /merchants. The raw API key is never
stored; only its SHA-256 hex digest is persisted so a DB breach does not
expose live credentials. */
sqlx::query(
"CREATE TABLE IF NOT EXISTS merchants (
id TEXT PRIMARY KEY,
api_key_hash TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
)",
)
.execute(pool)
.await?;
/* API keys, one row per credential rather than one per merchant, so a key
can be rotated (issue a second, revoke the first) and revoked individually
without disturbing the merchant record.
Only the SHA-256 digest is stored; `prefix` keeps the first few characters
of the raw key so an operator can tell two keys apart in a list without the
secret being recoverable. `revoked_at` is a tombstone rather than a delete
so an audit trail survives revocation. */
sqlx::query(
"CREATE TABLE IF NOT EXISTS api_keys (
id TEXT PRIMARY KEY,
merchant_id TEXT NOT NULL,
key_hash TEXT NOT NULL UNIQUE,
prefix TEXT NOT NULL,
label TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
last_used_at TEXT,
revoked_at TEXT
)",
)
.execute(pool)
.await?;
/* Authentication looks a key up by hash on every request, so this index is
load-bearing rather than an optimisation. */
sqlx::query("CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash)")
.execute(&mut *tx)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_api_keys_merchant ON api_keys(merchant_id)")
.execute(&mut *tx)
.await?;
/* Carry pre-existing single-key merchants across. Their raw key is not
recoverable, but the hash is all authentication needs, so keys issued
before this table existed keep working. The prefix is unknown for those
rows — mark them rather than inventing one. */
sqlx::query(
"INSERT OR IGNORE INTO api_keys (id, merchant_id, key_hash, prefix, label, created_at)
SELECT lower(hex(randomblob(16))), id, api_key_hash, 'legacy', 'migrated', created_at
FROM merchants
WHERE api_key_hash IS NOT NULL AND api_key_hash <> ''",
)
.execute(&mut *tx)
.await?;
/* `webhook_deliveries` is queried by payment_id on every delivery listing
and by the redrive worker; without this it is a full scan (issue #112). */
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_payment
ON webhook_deliveries(payment_id)",
)
.execute(pool)
.await?;
/* Partial index covering the redrive worker's per-tick query (issue #239).
The query filters on `status IN ('pending', 'failed')` plus `attempts <
max_attempts`, then applies date arithmetic over `last_attempt` /
`created_at`. Two properties matter here:
1. The `WHERE status IN ('pending', 'failed')` partial clause keeps the
index tiny: in steady state almost every row is `delivered` and therefore
immediately excluded — a full table index would grow without bound and
still need to visit the status check first.
2. Including `attempts`, `last_attempt`, and `created_at` in the index
covers the remaining predicates as much as SQLite's limited expression
indexing allows; the date-arithmetic expression is not sargable, but
narrowing the candidate set to the handful of non-delivered, under-cap
rows first is where the dominant win is.
Verified with EXPLAIN QUERY PLAN: `list_redrivable_deliveries` now shows
"SEARCH webhook_deliveries USING INDEX idx_webhook_deliveries_redrive"
instead of a full table scan (see `redrive_index_is_used` test). */
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_redrive
ON webhook_deliveries(status, attempts, last_attempt, created_at)
WHERE status IN ('pending', 'failed')",
)
.execute(pool)
.await?;
/* Idempotency keys for payment creation. A key is unique per merchant and
maps to the payment id minted for the first request that used it, so a
client retrying after a network blip gets the original payment back
instead of a duplicate intent. */
sqlx::query(
"CREATE TABLE IF NOT EXISTS idempotency_keys (
merchant_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
payment_id TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
PRIMARY KEY (merchant_id, idempotency_key)
)",
)
.execute(pool)
.await?;
/* Every on-chain transaction we credit to an intent, one row per
(payment_id, tx_hash). The cumulative received amount for an intent is the
SUM of `amount_stroops` over its rows, so re-seeing a transaction (on a
later poll cycle, over the stream, or from a concurrent reconciler) is an
idempotent no-op instead of a double-credit. `amount_stroops` is the
integer stroop value so SUM is exact. */
sqlx::query(
"CREATE TABLE IF NOT EXISTS processed_transactions (
payment_id TEXT NOT NULL,
/* The transaction hash is half the dedup key, so an empty value
would make every unhashed record collide on one row and silently
discard all but the first (issue #224). Reject it in the schema as
well as at the write path. */
tx_hash TEXT NOT NULL CHECK (tx_hash <> ''),
amount_stroops INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
PRIMARY KEY (payment_id, tx_hash)
)",
)
.execute(pool)
.await?;
/* Backfill from legacy rows that recorded only the most-recent `tx_hash`
and a cumulative `paid_amount`, so upgrading preserves the received-amount
ledger for intents that are still in flight. Idempotent via ON CONFLICT, so
it is safe to run on every startup. */
let legacy = sqlx::query(
"SELECT id, tx_hash, paid_amount FROM payments
WHERE tx_hash IS NOT NULL AND tx_hash <> '' AND paid_amount IS NOT NULL",
)
.fetch_all(pool)
.await?;
for row in &legacy {
let id: String = row.get("id");
let tx_hash: String = row.get("tx_hash");
let paid_amount: String = row.get("paid_amount");
if let Some(stroops) = crate::money::parse_stroops(&paid_amount) {
sqlx::query(
"INSERT INTO processed_transactions (payment_id, tx_hash, amount_stroops)
VALUES (?, ?, ?)
ON CONFLICT(payment_id, tx_hash) DO NOTHING",
)
.bind(&id)
.bind(&tx_hash)
.bind(stroops)
.execute(pool)
.await?;
}
}
/* Rows written before issue #224 was fixed may carry an empty `tx_hash`,
where two distinct unhashed records collapsed onto one primary key. We do
not delete them — the amount they carry was really received, and dropping
the row would silently reduce an intent's paid total — but we surface them
so an operator can reconcile against the ledger by hand. */
let unhashed: i64 =
sqlx::query_scalar("SELECT COUNT(*) FROM processed_transactions WHERE tx_hash = ''")
.fetch_one(pool)
.await?;
if unhashed > 0 {
tracing::warn!(
rows = unhashed,
"processed_transactions contains rows with an empty tx_hash, written before \
unhashed Horizon records were rejected; these may under-count an intent's \
received amount and should be reconciled against Horizon by hand"
);
}
/* Normalise legacy rows that were written by the old datetime('now') default,
which produced "YYYY-MM-DD HH:MM:SS" (space, no Z). Safe to run on every
startup — the WHERE clause skips rows that are already RFC 3339. */
for tbl_col in [
("payments", "created_at"),
("payments", "updated_at"),
("webhook_deliveries", "created_at"),
] {
let sql = format!(
"UPDATE {} SET {col} = replace({col}, ' ', 'T') || 'Z' WHERE {col} NOT LIKE '%T%'",
tbl_col.0,
col = tbl_col.1
);
sqlx::query(&sql).execute(pool).await?;
}
Ok(())
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Payment {
pub id: String,
pub merchant_id: String,
pub destination_address: String,
pub memo: String,
pub amount: String,
pub asset: String,
/// Issuer of the asset this intent was priced in, as an `G…` account id.
/// `None` means the native asset (XLM), which has no issuer.
///
/// Persisted at creation time from the accepted-asset allow-list so that
/// editing `ACCEPTED_ASSETS` later cannot retroactively change which asset
/// a historical intent refers to (issue #223).
pub asset_issuer: Option<String>,
pub status: String,
pub webhook_url: Option<String>,
pub tx_hash: Option<String>,
pub paid_amount: Option<String>,
pub created_at: String,
pub updated_at: String,
/// When this intent stops being `pending` and is swept to `expired`.
pub expires_at: String,
}
fn row_to_payment(row: &sqlx::sqlite::SqliteRow) -> Payment {
Payment {
id: row.get("id"),
merchant_id: row.get("merchant_id"),
destination_address: row.get("destination_address"),
memo: row.get("memo"),
amount: row.get("amount"),
asset: row.get("asset"),
asset_issuer: row.get("asset_issuer"),
status: row.get("status"),
webhook_url: row.get("webhook_url"),
tx_hash: row.get("tx_hash"),
paid_amount: row.get("paid_amount"),
created_at: normalize_ts(&row.get::<String, _>("created_at")),
updated_at: normalize_ts(&row.get::<String, _>("updated_at")),
expires_at: normalize_ts(&row.get::<String, _>("expires_at")),
}
}
/// Fields needed to insert a new payment intent.
pub struct NewPayment<'a> {
pub id: &'a str,
pub merchant_id: &'a str,
pub destination_address: &'a str,
pub memo: &'a str,
pub amount: &'a str,
/// Issuer of `asset`, or `None` for the native asset. Resolved from the
/// accepted-asset allow-list by the caller and stored alongside the code so
/// the pair is a complete asset identity (issue #223).
pub asset_issuer: Option<&'a str>,
pub asset: &'a str,
pub webhook_url: Option<&'a str>,
/// Seconds from now until the intent expires. The expiry timestamp is
/// computed by SQLite at insert time as `now + ttl_secs`.
pub ttl_secs: i64,
}
pub async fn create_payment(pool: &Db, new: NewPayment<'_>) -> Result<Payment> {
/* Canonicalize the amount: parse to stroops, then convert back to the
canonical string representation. This ensures "10.00", "10.0", and "10"
all serialize identically, eliminating spurious string-based comparisons
across create/get/webhook responses. */
let stroops =
crate::money::parse_stroops(new.amount).ok_or_else(|| anyhow::anyhow!("Invalid amount"))?;
let canonical_amount = crate::money::stroops_to_string(stroops);
/* Compute the expiry as `now + ttl_secs` in SQLite so it shares the exact
clock and RFC 3339 format as created_at. */
let ttl_modifier = format!("{:+} seconds", new.ttl_secs);
sqlx::query(
"INSERT INTO payments (id, merchant_id, destination_address, memo, amount, asset, asset_issuer, webhook_url, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%SZ','now',?))",
)
.bind(new.id)
.bind(new.merchant_id)
.bind(new.destination_address)
.bind(new.memo)
.bind(&canonical_amount)
.bind(new.asset)
.bind(new.asset_issuer)
.bind(new.webhook_url)
.bind(&ttl_modifier)
.execute(pool)
.await?;
get_payment(pool, new.id)
.await?
.ok_or_else(|| anyhow::anyhow!("Payment not found after insert"))
}
/// Look up the payment id previously minted for `(merchant_id, key)`, if any.
pub async fn find_payment_id_by_idempotency_key(
pool: &Db,
merchant_id: &str,
key: &str,
) -> Result<Option<String>> {
let id: Option<String> = sqlx::query_scalar(
"SELECT payment_id FROM idempotency_keys WHERE merchant_id = ? AND idempotency_key = ?",
)
.bind(merchant_id)
.bind(key)
.fetch_optional(pool)
.await?;
Ok(id)
}
/// Record the payment id minted for `(merchant_id, key)`. If the key already
/// exists (e.g. a concurrent request won the race), the existing mapping is left
/// untouched and the winning payment id is returned; otherwise `payment_id` is
/// stored and returned.
pub async fn save_idempotency_key(
pool: &Db,
merchant_id: &str,
key: &str,
payment_id: &str,
) -> Result<String> {
sqlx::query(
"INSERT INTO idempotency_keys (merchant_id, idempotency_key, payment_id)
VALUES (?, ?, ?)
ON CONFLICT(merchant_id, idempotency_key) DO NOTHING",
)
.bind(merchant_id)
.bind(key)
.bind(payment_id)
.execute(pool)
.await?;
// Re-read so a concurrent insert that won the race returns the canonical id.
let stored = find_payment_id_by_idempotency_key(pool, merchant_id, key)
.await?
.unwrap_or_else(|| payment_id.to_string());
Ok(stored)
}
pub async fn get_payment(pool: &Db, id: &str) -> Result<Option<Payment>> {
let row = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE id = ?",
)
.bind(id)
.fetch_optional(pool)
.await?;
Ok(row.as_ref().map(row_to_payment))
}
pub async fn list_payments(
pool: &Db,
merchant_id: &str,
status: Option<&str>,
limit: i64,
offset: i64,
) -> Result<(Vec<Payment>, i64)> {
let (rows, total) = if let Some(s) = status {
let rows = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? AND status = ? ORDER BY created_at DESC LIMIT ? OFFSET ?",
)
.bind(merchant_id)
.bind(s)
.bind(limit)
.bind(offset)
.fetch_all(pool)
.await?;
let total: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM payments WHERE merchant_id = ? AND status = ?",
)
.bind(merchant_id)
.bind(s)
.fetch_one(pool)
.await?;
(rows, total)
} else {
let rows = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?",
)
.bind(merchant_id)
.bind(limit)
.bind(offset)
.fetch_all(pool)
.await?;
let total: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM payments WHERE merchant_id = ?")
.bind(merchant_id)
.fetch_one(pool)
.await?;
(rows, total)
};
Ok((rows.iter().map(row_to_payment).collect(), total))
}
pub async fn list_payments_keyset(
pool: &Db,
merchant_id: &str,
status: Option<&str>,
limit: i64,
cursor: Option<(&str, &str)>,
) -> Result<Vec<Payment>> {
let rows = match (status, cursor) {
(None, None) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(limit)
.fetch_all(pool)
.await?
}
(None, Some((ts, cid))) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE merchant_id = ? AND (created_at < ? OR (created_at = ? AND id < ?))
ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(ts)
.bind(ts)
.bind(cid)
.bind(limit)
.fetch_all(pool)
.await?
}
(Some(s), None) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? AND status = ? ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(s)
.bind(limit)
.fetch_all(pool)
.await?
}
(Some(s), Some((ts, cid))) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE merchant_id = ? AND status = ? AND (created_at < ? OR (created_at = ? AND id < ?))
ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(s)
.bind(ts)
.bind(ts)
.bind(cid)
.bind(limit)
.fetch_all(pool)
.await?
}
};
Ok(rows.iter().map(row_to_payment).collect())
}
/// All payments still awaiting confirmation or top-up, oldest first. Rows whose
/// TTL has elapsed are excluded even if the sweeper hasn't transitioned them
/// yet, so an overdue intent is never polled.
pub async fn list_pending(pool: &Db) -> Result<Vec<Payment>> {
let rows = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE status IN ('pending', 'underpaid')
AND expires_at > strftime('%Y-%m-%dT%H:%M:%SZ','now')
ORDER BY created_at ASC",
)
.fetch_all(pool)
.await?;
Ok(rows.iter().map(row_to_payment).collect())
}
/// Transition every watchable payment whose TTL has elapsed to `expired`,
/// returning the rows that were swept so the caller can fire `payment.expired`
/// webhooks. Each row is updated with a guard on a watchable status so a payment
/// that settles concurrently is left untouched and not double-reported.
pub async fn expire_overdue(pool: &Db) -> Result<Vec<Payment>> {
let overdue = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE status IN ('pending', 'underpaid')
AND expires_at <= strftime('%Y-%m-%dT%H:%M:%SZ','now')
ORDER BY created_at ASC",
)
.fetch_all(pool)
.await?;
let mut expired = Vec::new();
for row in &overdue {
let mut payment = row_to_payment(row);
let result = sqlx::query(
"UPDATE payments
SET status = 'expired',
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ','now')
WHERE id = ? AND status IN ('pending', 'underpaid')",
)
.bind(&payment.id)
.execute(pool)
.await?;
/* Only report rows we actually transitioned; a concurrent settlement
may have flipped the status out from under us. */
if result.rows_affected() == 1 {
payment.status = "expired".to_string();
expired.push(payment);
}
}
Ok(expired)
}
pub async fn find_pending_by_memo(pool: &Db, memo: &str) -> Result<Option<Payment>> {
let row = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE memo = ?
AND status IN ('pending', 'underpaid')
AND expires_at > strftime('%Y-%m-%dT%H:%M:%SZ','now')",
)
.bind(memo)
.fetch_optional(pool)
.await?;
Ok(row.as_ref().map(row_to_payment))
}
/// Like [`find_pending_by_memo`] but matches any status — used to detect
/// payments arriving after an intent has already been settled or expired.
/// Such payments must still be recorded and reported to the merchant (issue
/// #232), even though the intent's terminal status must not change.
pub async fn find_by_memo_any_status(pool: &Db, memo: &str) -> Result<Option<Payment>> {
let row = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE memo = ?
ORDER BY created_at DESC
LIMIT 1",
)
.bind(memo)
.fetch_optional(pool)
.await?;
Ok(row.as_ref().map(row_to_payment))
}
/// Transition a payment to a new status, returning `true` when the row was
/// actually updated.
///
/// The `WHERE … AND status IN ('pending', 'underpaid')` guard is the key to
/// single-settlement under concurrent reconciliation (issue #155): SQLite's
/// serialized write path ensures that exactly one of two racing UPDATE
/// statements will match a row still in a watchable state. The loser sees
/// `rows_affected() == 0` and knows it must skip the webhook.
pub async fn update_payment_status(
pool: &Db,
id: &str,
status: &str,
tx_hash: &str,
paid_amount: &str,
) -> Result<bool> {
let result = sqlx::query(
"UPDATE payments
SET status = ?, tx_hash = ?, paid_amount = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ','now')
WHERE id = ?
AND status IN ('pending', 'underpaid')",
)
.bind(status)
.bind(tx_hash)
.bind(paid_amount)
.bind(id)
.execute(pool)
.await?;
Ok(result.rows_affected() == 1)
}
/// Record that transaction `tx_hash`, worth `amount_stroops`, has been credited
/// to intent `payment_id`. Returns `true` when this is the first time the
/// transaction was recorded for the intent, and `false` when it was already
/// present (a re-seen record on a later poll cycle, over the stream, or from a
/// concurrent reconciler).
///
/// The `(payment_id, tx_hash)` primary key plus `ON CONFLICT DO NOTHING` makes
/// this the atomic dedup point: SQLite serialises writers, so exactly one of
/// two racing inserts for the same transaction observes `rows_affected() == 1`.
pub async fn record_processed_tx(
pool: &Db,
payment_id: &str,
tx_hash: &str,
amount_stroops: i64,
) -> Result<bool> {
/* An empty hash is not a hash: it would make every unhashed record share
one primary key, so the first would be credited and every later one
silently dropped as "already processed" (issue #224). Callers must skip
such records; reaching here with one is a bug, so it is an error rather
than a quiet `false` (which reads as "already recorded"). */
if tx_hash.is_empty() {
anyhow::bail!("refusing to record a processed transaction with an empty tx_hash");
}
let result = sqlx::query(
"INSERT INTO processed_transactions (payment_id, tx_hash, amount_stroops)
VALUES (?, ?, ?)
ON CONFLICT(payment_id, tx_hash) DO NOTHING",
)
.bind(payment_id)
.bind(tx_hash)
.bind(amount_stroops)
.execute(pool)
.await?;
Ok(result.rows_affected() == 1)
}
/// Sum of every transaction recorded against `payment_id`, in stroops. This is
/// the authoritative received-amount ledger for an intent — independent of how
/// many transactions arrived, or the order they were seen in.
pub async fn sum_processed_stroops(pool: &Db, payment_id: &str) -> Result<i64> {
let total: i64 = sqlx::query_scalar(
"SELECT COALESCE(SUM(amount_stroops), 0) FROM processed_transactions WHERE payment_id = ?",
)
.bind(payment_id)
.fetch_one(pool)
.await?;
Ok(total)
}
/// Read a value from the durable key/value state table, if present.
pub async fn get_state(pool: &Db, key: &str) -> Result<Option<String>> {
let value: Option<String> = sqlx::query_scalar("SELECT value FROM kv_state WHERE key = ?")
.bind(key)
.fetch_optional(pool)
.await?;
Ok(value)
}
/// Key recording that the one-off `asset_issuer` backfill has already run, so
/// it is never applied twice.
const ASSET_ISSUER_BACKFILL_KEY: &str = "schema_backfill_asset_issuer_v1";
/// Backfill `payments.asset_issuer` for rows created before the column existed,
/// using the currently-configured accepted-asset allow-list.
///
/// This runs exactly once per database (guarded by a marker in `kv_state`),
/// because it is a *best-effort* reconstruction: the issuer a historical intent
/// was actually priced in was never recorded, so all we can do is assume it was
/// the one configured for that asset code today. Running it repeatedly would
/// let a later `ACCEPTED_ASSETS` edit rewrite history a second time, which is
/// exactly the problem the column exists to prevent (issue #223).
///
/// Native assets are left NULL — they have no issuer. Rows whose asset code is
/// no longer in the allow-list are also left NULL, since there is nothing left
/// to reconstruct from.
pub async fn backfill_asset_issuers(
pool: &Db,
accepted_assets: &[crate::config::AcceptedAsset],
) -> Result<()> {
if get_state(pool, ASSET_ISSUER_BACKFILL_KEY).await?.is_some() {
return Ok(());
}
let mut filled = 0u64;
for asset in accepted_assets {
let Some(issuer) = asset.issuer.as_deref() else {
continue;
};
let result = sqlx::query(
"UPDATE payments SET asset_issuer = ? WHERE asset = ? AND asset_issuer IS NULL",
)
.bind(issuer)
.bind(&asset.code)
.execute(pool)
.await?;
filled += result.rows_affected();
}
set_state(pool, ASSET_ISSUER_BACKFILL_KEY, "done").await?;
if filled > 0 {
tracing::info!(
rows = filled,
"backfilled payments.asset_issuer from the configured accepted assets; \
rows created before this migration are best-effort"
);
}
Ok(())
}
/// Insert or update a value in the durable key/value state table.
pub async fn set_state(pool: &Db, key: &str, value: &str) -> Result<()> {
sqlx::query(
"INSERT INTO kv_state (key, value, updated_at)
VALUES (?, ?, strftime('%Y-%m-%dT%H:%M:%SZ','now'))
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = excluded.updated_at",
)
.bind(key)
.bind(value)
.execute(pool)
.await?;
Ok(())
}
pub async fn memo_exists(pool: &Db, memo: &str) -> Result<bool> {
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM payments WHERE memo = ?")
.bind(memo)
.fetch_one(pool)
.await?;
Ok(count > 0)
}
/// Record an outbound webhook delivery. `event_type` is the event name the
/// payload carries (e.g. `payment.underpaid`); it is persisted so a later
/// redelivery can reproduce the original `X-StellarGate-Event` header.
pub async fn save_webhook_delivery(
pool: &Db,
id: &str,
payment_id: &str,
url: &str,
payload: &str,
event_type: &str,
) -> Result<()> {
sqlx::query(
"INSERT INTO webhook_deliveries (id, payment_id, url, payload, event_type) VALUES (?, ?, ?, ?, ?)",
)
.bind(id)
.bind(payment_id)
.bind(url)
.bind(payload)
.bind(event_type)
.execute(pool)
.await?;
Ok(())
}
pub async fn update_webhook_delivery(
pool: &Db,
id: &str,
status: &str,
attempts: i64,
) -> Result<()> {
sqlx::query(
"UPDATE webhook_deliveries SET status = ?, attempts = ?, last_attempt = strftime('%Y-%m-%dT%H:%M:%SZ','now') WHERE id = ?",
)
.bind(status)
.bind(attempts)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct WebhookDelivery {
pub id: String,
pub payment_id: String,
pub url: String,
pub payload: String,
/// The event this payload represents. `None` only for rows written before
/// the column existed — use [`WebhookDelivery::event`] to read it.
pub event_type: Option<String>,
pub status: String,
pub attempts: i64,
pub last_attempt: Option<String>,
pub created_at: String,
}
/// Event name used when a legacy row has no `event_type` and its stored payload
/// cannot be parsed. This sentinel is intentionally non-actionable: a receiver
/// that routes on `payment.completed` (the old fallback) could fulfil an order
/// because a payload failed to parse — which is precisely the risk #237 closes.
/// Receivers must treat `payment.unknown` as an opaque signal to look the
/// payment up via `GET /v1/payments/:id` rather than acting on the event name
/// directly.
const FALLBACK_EVENT: &str = "payment.unknown";
impl WebhookDelivery {
/// The event name to report for this delivery, falling back to the `event`
/// field of the stored payload for rows written before `event_type`
/// existed (and for which the migration backfill could not extract the
/// field — e.g. corrupted or externally written rows). If neither source
/// yields a value, returns [`FALLBACK_EVENT`] (`"payment.unknown"`), which
/// is intentionally non-actionable: a caller receiving that value must
/// fetch the full record via `GET /v1/payments/:id` rather than acting on
/// the event name directly (issue #237).
pub fn event(&self) -> String {
if let Some(event) = &self.event_type {
return event.clone();
}
// Reach here only for rows whose payload could not be used by the
// migration backfill (or rows written after the column existed but
// somehow NULL — not possible through normal code paths). The backfill
// already tried json_extract; we try a full parse here as a last resort
// before falling back to the sentinel.
serde_json::from_str::<serde_json::Value>(&self.payload)
.ok()
.and_then(|v| v.get("event")?.as_str().map(str::to_string))
.unwrap_or_else(|| FALLBACK_EVENT.to_string())
}