cdk-bdk 0.17.6

CDK onchain backend with bdk
Documentation
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
use std::str::FromStr;

use uuid::Uuid;

use super::{
    outpoint_to_key, BdkStorage, FailedSendAttemptRecord, FinalizedSendIntentRecord, BDK_NAMESPACE,
    FINALIZED_INTENT_NAMESPACE, FINALIZED_SEND_INTENT_QUOTE_ID_NAMESPACE, SEND_INTENT_NAMESPACE,
    SEND_INTENT_QUOTE_ID_NAMESPACE, SEND_OUTPOINT_QUOTE_ID_BACKFILL_KEY,
    SEND_OUTPOINT_QUOTE_ID_NAMESPACE, STORAGE_MIGRATION_NAMESPACE,
};
use crate::error::Error;
use crate::send::batch_transaction::record::{SendBatchRecord, SendBatchState};
use crate::send::payment_intent::record::{SendIntentRecord, SendIntentState};

impl BdkStorage {
    // ── Send Intent storage ──────────────────────────────────────────

    /// Store a new send intent and quote-id index atomically.
    pub async fn create_send_intent_if_absent(
        &self,
        intent: &SendIntentRecord,
    ) -> Result<(), Error> {
        let mut tx = self
            .kv_store
            .begin_transaction()
            .await
            .map_err(Error::from)?;

        let active = tx
            .kv_read(
                BDK_NAMESPACE,
                SEND_INTENT_QUOTE_ID_NAMESPACE,
                &intent.quote_id,
            )
            .await
            .map_err(Error::from)?;

        if active.is_some() {
            tx.rollback().await.map_err(Error::from)?;
            return Err(Error::DuplicateQuoteId(intent.quote_id.clone()));
        }

        let finalized = tx
            .kv_read(
                BDK_NAMESPACE,
                FINALIZED_SEND_INTENT_QUOTE_ID_NAMESPACE,
                &intent.quote_id,
            )
            .await
            .map_err(Error::from)?;

        if finalized.is_some() {
            tx.rollback().await.map_err(Error::from)?;
            return Err(Error::DuplicateQuoteId(intent.quote_id.clone()));
        }

        let serialized = serde_json::to_vec(intent)?;
        tx.kv_write(
            BDK_NAMESPACE,
            SEND_INTENT_NAMESPACE,
            &intent.intent_id.to_string(),
            &serialized,
        )
        .await
        .map_err(Error::from)?;
        tx.kv_write(
            BDK_NAMESPACE,
            SEND_INTENT_QUOTE_ID_NAMESPACE,
            &intent.quote_id,
            intent.intent_id.to_string().as_bytes(),
        )
        .await
        .map_err(Error::from)?;
        if let SendIntentState::AwaitingConfirmation { outpoint, .. } = &intent.state {
            tx.kv_write(
                BDK_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                &outpoint_to_key(outpoint),
                intent.quote_id.as_bytes(),
            )
            .await
            .map_err(Error::from)?;
        }
        tx.commit().await.map_err(Error::from)?;
        Ok(())
    }

    /// Store a new send intent, or re-queue an existing failed intent with
    /// the same quote id.
    pub async fn create_or_retry_failed_send_intent(
        &self,
        intent: &SendIntentRecord,
    ) -> Result<SendIntentRecord, Error> {
        let mut tx = self
            .kv_store
            .begin_transaction()
            .await
            .map_err(Error::from)?;

        let finalized = tx
            .kv_read(
                BDK_NAMESPACE,
                FINALIZED_SEND_INTENT_QUOTE_ID_NAMESPACE,
                &intent.quote_id,
            )
            .await
            .map_err(Error::from)?;

        if finalized.is_some() {
            tx.rollback().await.map_err(Error::from)?;
            return Err(Error::DuplicateQuoteId(intent.quote_id.clone()));
        }

        let active = tx
            .kv_read(
                BDK_NAMESPACE,
                SEND_INTENT_QUOTE_ID_NAMESPACE,
                &intent.quote_id,
            )
            .await
            .map_err(Error::from)?;

        let record = if let Some(intent_id_bytes) = active {
            let intent_id_str = std::str::from_utf8(&intent_id_bytes)
                .map_err(|e| Error::Wallet(format!("Invalid quote-id index entry: {}", e)))?;
            let intent_id = Uuid::from_str(intent_id_str)
                .map_err(|e| Error::Wallet(format!("Invalid indexed intent id: {}", e)))?;
            let intent_bytes = tx
                .kv_read(BDK_NAMESPACE, SEND_INTENT_NAMESPACE, &intent_id.to_string())
                .await
                .map_err(Error::from)?
                .ok_or(Error::SendIntentNotFound(intent_id))?;
            let existing: SendIntentRecord = serde_json::from_slice(&intent_bytes)?;

            if !matches!(existing.state, SendIntentState::Failed { .. }) {
                tx.rollback().await.map_err(Error::from)?;
                return Err(Error::DuplicateQuoteId(intent.quote_id.clone()));
            }

            SendIntentRecord {
                intent_id,
                quote_id: intent.quote_id.clone(),
                address: intent.address.clone(),
                amount_sat: intent.amount_sat,
                max_fee_amount_sat: intent.max_fee_amount_sat,
                tier: intent.tier,
                metadata: intent.metadata.clone(),
                state: intent.state.clone(),
            }
        } else {
            tx.kv_write(
                BDK_NAMESPACE,
                SEND_INTENT_QUOTE_ID_NAMESPACE,
                &intent.quote_id,
                intent.intent_id.to_string().as_bytes(),
            )
            .await
            .map_err(Error::from)?;
            intent.clone()
        };

        let serialized = serde_json::to_vec(&record)?;
        tx.kv_write(
            BDK_NAMESPACE,
            SEND_INTENT_NAMESPACE,
            &record.intent_id.to_string(),
            &serialized,
        )
        .await
        .map_err(Error::from)?;
        if let SendIntentState::AwaitingConfirmation { outpoint, .. } = &record.state {
            tx.kv_write(
                BDK_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                &outpoint_to_key(outpoint),
                record.quote_id.as_bytes(),
            )
            .await
            .map_err(Error::from)?;
        }
        tx.commit().await.map_err(Error::from)?;
        Ok(record)
    }

    /// Get a send intent by ID
    pub async fn get_send_intent(
        &self,
        intent_id: &Uuid,
    ) -> Result<Option<SendIntentRecord>, Error> {
        self.get_record::<SendIntentRecord>(&intent_id.to_string())
            .await
    }

    /// Update a send intent's state
    pub async fn update_send_intent(
        &self,
        intent_id: &Uuid,
        new_state: &SendIntentState,
    ) -> Result<(), Error> {
        let Some(mut intent) = self.get_send_intent(intent_id).await? else {
            return Err(Error::SendIntentNotFound(*intent_id));
        };
        let previous_outpoint = match &intent.state {
            SendIntentState::AwaitingConfirmation { outpoint, .. } => Some(outpoint.clone()),
            _ => None,
        };
        let new_outpoint = match new_state {
            SendIntentState::AwaitingConfirmation { outpoint, .. } => Some(outpoint.clone()),
            _ => None,
        };
        intent.state = new_state.clone();

        let serialized = serde_json::to_vec(&intent)?;
        let mut tx = self
            .kv_store
            .begin_transaction()
            .await
            .map_err(Error::from)?;
        tx.kv_write(
            BDK_NAMESPACE,
            SEND_INTENT_NAMESPACE,
            &intent_id.to_string(),
            &serialized,
        )
        .await
        .map_err(Error::from)?;
        if let Some(outpoint) =
            previous_outpoint.filter(|outpoint| Some(outpoint) != new_outpoint.as_ref())
        {
            tx.kv_remove(
                BDK_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                &outpoint_to_key(&outpoint),
            )
            .await
            .map_err(Error::from)?;
        }
        if let Some(outpoint) = new_outpoint {
            tx.kv_write(
                BDK_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                &outpoint_to_key(&outpoint),
                intent.quote_id.as_bytes(),
            )
            .await
            .map_err(Error::from)?;
        }
        tx.commit().await.map_err(Error::from)
    }

    /// Delete a send intent
    pub async fn delete_send_intent(&self, intent_id: &Uuid) -> Result<(), Error> {
        let Some(intent) = self.get_send_intent(intent_id).await? else {
            return Ok(());
        };

        let mut tx = self
            .kv_store
            .begin_transaction()
            .await
            .map_err(Error::from)?;
        tx.kv_remove(BDK_NAMESPACE, SEND_INTENT_NAMESPACE, &intent_id.to_string())
            .await
            .map_err(Error::from)?;
        tx.kv_remove(
            BDK_NAMESPACE,
            SEND_INTENT_QUOTE_ID_NAMESPACE,
            &intent.quote_id,
        )
        .await
        .map_err(Error::from)?;
        if let SendIntentState::AwaitingConfirmation { outpoint, .. } = intent.state {
            tx.kv_remove(
                BDK_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                &outpoint_to_key(&outpoint),
            )
            .await
            .map_err(Error::from)?;
        }
        tx.commit().await.map_err(Error::from)?;
        Ok(())
    }

    /// Get all send intents
    pub async fn get_all_send_intents(&self) -> Result<Vec<SendIntentRecord>, Error> {
        self.list_records::<SendIntentRecord>().await
    }

    /// Get all pending send intents (filtering by state)
    pub async fn get_pending_send_intents(&self) -> Result<Vec<SendIntentRecord>, Error> {
        let all = self.get_all_send_intents().await?;
        Ok(all
            .into_iter()
            .filter(|i| matches!(i.state, SendIntentState::Pending { .. }))
            .collect())
    }

    /// Store a failed pre-sign send attempt tombstone.
    pub async fn add_failed_send_attempt(
        &self,
        record: &FailedSendAttemptRecord,
    ) -> Result<(), Error> {
        self.put_record(record).await
    }

    /// List failed pre-sign send attempts for a quote id.
    pub async fn get_failed_send_attempts_by_quote_id(
        &self,
        quote_id: &str,
    ) -> Result<Vec<FailedSendAttemptRecord>, Error> {
        let all = self.list_records::<FailedSendAttemptRecord>().await?;
        Ok(all
            .into_iter()
            .filter(|record| record.quote_id == quote_id)
            .collect())
    }

    // ── Send Batch storage ───────────────────────────────────────────

    /// Store a new send batch
    pub async fn store_send_batch(&self, batch: &SendBatchRecord) -> Result<(), Error> {
        self.put_record(batch).await
    }

    /// Get a send batch by ID
    pub async fn get_send_batch(&self, batch_id: &Uuid) -> Result<Option<SendBatchRecord>, Error> {
        self.get_record::<SendBatchRecord>(&batch_id.to_string())
            .await
    }

    /// Update a send batch's state
    pub async fn update_send_batch(
        &self,
        batch_id: &Uuid,
        new_state: &SendBatchState,
    ) -> Result<(), Error> {
        let key = batch_id.to_string();
        if self.get_send_batch(batch_id).await?.is_none() {
            return Err(Error::SendBatchNotFound(*batch_id));
        }

        self.update_record_state::<SendBatchRecord, SendBatchState>(&key, new_state)
            .await
    }

    /// Delete a send batch
    pub async fn delete_send_batch(&self, batch_id: &Uuid) -> Result<(), Error> {
        self.delete_record::<SendBatchRecord>(&batch_id.to_string())
            .await
    }

    /// Get all send batches
    pub async fn get_all_send_batches(&self) -> Result<Vec<SendBatchRecord>, Error> {
        self.list_records::<SendBatchRecord>().await
    }

    // ── Finalized Intent storage (tombstones) ────────────────────────

    /// Look up a finalized intent tombstone by intent ID.
    pub async fn get_finalized_intent(
        &self,
        intent_id: &Uuid,
    ) -> Result<Option<FinalizedSendIntentRecord>, Error> {
        self.get_record::<FinalizedSendIntentRecord>(&intent_id.to_string())
            .await
    }

    /// Get all finalized send intent tombstones.
    pub async fn get_all_finalized_send_intents(
        &self,
    ) -> Result<Vec<FinalizedSendIntentRecord>, Error> {
        self.list_records::<FinalizedSendIntentRecord>().await
    }

    /// Look up a quote ID by the transaction output assigned to a send intent.
    pub async fn get_quote_id_by_send_outpoint(
        &self,
        outpoint: &str,
    ) -> Result<Option<String>, Error> {
        let quote_id_bytes = self
            .kv_store
            .kv_read(
                BDK_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                &outpoint_to_key(outpoint),
            )
            .await
            .map_err(Error::from)?;

        match quote_id_bytes {
            Some(quote_id_bytes) => String::from_utf8(quote_id_bytes)
                .map(Some)
                .map_err(|e| Error::Wallet(format!("Invalid quote-id index entry: {}", e))),
            None => Ok(None),
        }
    }

    /// Populate the send output quote index for records written by older versions.
    pub(crate) async fn ensure_send_outpoint_quote_id_index(&self) -> Result<(), Error> {
        if self
            .kv_store
            .kv_read(
                BDK_NAMESPACE,
                STORAGE_MIGRATION_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_BACKFILL_KEY,
            )
            .await
            .map_err(Error::from)?
            .is_some()
        {
            return Ok(());
        }

        let (send_intents, finalized_send_intents) = tokio::try_join!(
            self.get_all_send_intents(),
            self.get_all_finalized_send_intents(),
        )?;
        let mut tx = self
            .kv_store
            .begin_transaction()
            .await
            .map_err(Error::from)?;

        for intent in send_intents {
            if let SendIntentState::AwaitingConfirmation { outpoint, .. } = intent.state {
                tx.kv_write(
                    BDK_NAMESPACE,
                    SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                    &outpoint_to_key(&outpoint),
                    intent.quote_id.as_bytes(),
                )
                .await
                .map_err(Error::from)?;
            }
        }
        for intent in finalized_send_intents {
            tx.kv_write(
                BDK_NAMESPACE,
                SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
                &outpoint_to_key(&intent.outpoint),
                intent.quote_id.as_bytes(),
            )
            .await
            .map_err(Error::from)?;
        }
        tx.kv_write(
            BDK_NAMESPACE,
            STORAGE_MIGRATION_NAMESPACE,
            SEND_OUTPOINT_QUOTE_ID_BACKFILL_KEY,
            b"complete",
        )
        .await
        .map_err(Error::from)?;
        tx.commit().await.map_err(Error::from)
    }

    /// Look up a finalized intent tombstone by quote ID.
    pub async fn get_finalized_intent_by_quote_id(
        &self,
        quote_id: &str,
    ) -> Result<Option<FinalizedSendIntentRecord>, Error> {
        let Some(intent_id_bytes) = self
            .kv_store
            .kv_read(
                BDK_NAMESPACE,
                FINALIZED_SEND_INTENT_QUOTE_ID_NAMESPACE,
                quote_id,
            )
            .await
            .map_err(Error::from)?
        else {
            return Ok(None);
        };

        let intent_id_str = std::str::from_utf8(&intent_id_bytes)
            .map_err(|e| Error::Wallet(format!("Invalid intent-id index entry: {}", e)))?;
        let intent_id = Uuid::from_str(intent_id_str)
            .map_err(|e| Error::Wallet(format!("Invalid indexed intent id: {}", e)))?;

        self.get_record::<FinalizedSendIntentRecord>(&intent_id.to_string())
            .await
    }

    /// Look up a send intent by quote ID.
    ///
    /// Scans all active intents and returns the first match.
    pub async fn get_send_intent_by_quote_id(
        &self,
        quote_id: &str,
    ) -> Result<Option<SendIntentRecord>, Error> {
        let Some(intent_id_bytes) = self
            .kv_store
            .kv_read(BDK_NAMESPACE, SEND_INTENT_QUOTE_ID_NAMESPACE, quote_id)
            .await
            .map_err(Error::from)?
        else {
            return Ok(None);
        };

        let intent_id = std::str::from_utf8(&intent_id_bytes)
            .map_err(|e| Error::Wallet(format!("Invalid quote-id index entry: {}", e)))?;
        let intent_id = Uuid::from_str(intent_id)
            .map_err(|e| Error::Wallet(format!("Invalid indexed intent id: {}", e)))?;

        self.get_send_intent(&intent_id).await
    }

    /// Atomically finalize an active send intent and create a tombstone.
    pub async fn finalize_send_intent(
        &self,
        intent_id: &Uuid,
        record: &FinalizedSendIntentRecord,
    ) -> Result<(), Error> {
        let Some(intent) = self.get_send_intent(intent_id).await? else {
            return Err(Error::SendIntentNotFound(*intent_id));
        };

        let serialized = serde_json::to_vec(record)?;
        let mut tx = self
            .kv_store
            .begin_transaction()
            .await
            .map_err(Error::from)?;
        tx.kv_write(
            BDK_NAMESPACE,
            FINALIZED_INTENT_NAMESPACE,
            &record.intent_id.to_string(),
            &serialized,
        )
        .await
        .map_err(Error::from)?;
        tx.kv_write(
            BDK_NAMESPACE,
            FINALIZED_SEND_INTENT_QUOTE_ID_NAMESPACE,
            &intent.quote_id,
            record.intent_id.to_string().as_bytes(),
        )
        .await
        .map_err(Error::from)?;
        tx.kv_write(
            BDK_NAMESPACE,
            SEND_OUTPOINT_QUOTE_ID_NAMESPACE,
            &outpoint_to_key(&record.outpoint),
            record.quote_id.as_bytes(),
        )
        .await
        .map_err(Error::from)?;
        tx.kv_remove(BDK_NAMESPACE, SEND_INTENT_NAMESPACE, &intent_id.to_string())
            .await
            .map_err(Error::from)?;
        tx.kv_remove(
            BDK_NAMESPACE,
            SEND_INTENT_QUOTE_ID_NAMESPACE,
            &intent.quote_id,
        )
        .await
        .map_err(Error::from)?;
        tx.commit().await.map_err(Error::from)?;
        Ok(())
    }
}