53 Commits

Author SHA1 Message Date
tsk
d9e001bee6 refactor(cdk): implement saga pattern for melt operations (#1186)
Restructure melt flow into a multi-step saga with compensation-based rollback.
Remove ProofWriter in favor of explicit compensation actions for improved
reliability and clarity in handling partial failures during melt operations.

Breaks down monolithic change processing logic into smaller, focused methods:
- process_change_outputs: orchestrates full change workflow
- validate_change_outputs: checks for already-signed messages
- calculate_change_fee_and_amounts: fetches keyset configuration
- split_change_amount: splits change into denominations
- prepare_blinded_messages_with_amounts: pairs amounts with blinded messages
- store_change_signatures: handles TX2 database operations
2025-11-03 11:40:21 -05:00
tsk
33c206a310 Swap saga (#1183)
# Implement Saga Pattern for Swap Operations with Recovery Mechanism

## Overview

This PR refactors the swap operation implementation to use the saga pattern - a distributed transaction pattern that provides reliable transaction management through explicit state tracking and compensation-based error handling. The implementation includes a robust recovery mechanism that automatically handles swap operations interrupted by crashes, power loss, or network failures.

## What Changed

**Saga Pattern Implementation:**
- Introduced a strict linear state machine for swaps: `Initial` → `SetupComplete` → `Signed` → `Completed`
- New modular `swap_saga` module with state validation, compensation logic, and saga orchestration
- Automatic rollback of database changes on failure, ensuring atomic swap operations
- Replaced previous swap implementation (`swap.rs`, `blinded_message_writer.rs`) with saga-based approach

**Recovery Mechanism:**
- Added `operation_id` and `operation_kind` columns to database schema for tracking which operation proofs belong to
- New `recover_from_bad_swaps()` method that runs on mint startup to handle incomplete swaps
- For proofs left in `PENDING` state from swap operations:
  - If blind signatures exist: marks proofs as `SPENT` (swap completed but not finalized)
  - If no blind signatures exist: removes proofs from database (swap failed partway through)
- Database migrations included for both PostgreSQL and SQLite
2025-10-22 08:30:33 -05:00
tsk
f173b2da47 feat(cdk): add melt quote state transition validation (#1188)
Add state machine validation for melt quote transitions to prevent
invalid state changes. Includes new error types and validation logic
for Unpaid, Pending, Paid, and Failed states.
2025-10-13 09:21:12 +01:00
tsk
95aa64477a Improve add transaction (#1164)
* fix(wallet): move transaction ID calculation before database operations

* fix(sql): remove on ys from on conflict transaction insert

Since the id is created from the ys we know that if there is a conflict
the ys are the same and do not need to be updated.

* feat: bench for transactio id

* chore: fmt
2025-10-09 16:20:06 +01:00
tsk
c5e5d71701 feat(cdk): add payment request and proof to transaction records (#1155)
Add payment_request and payment_proof fields to Transaction model to store Lightning invoice details and payment preimages. Update database migrations and all transaction creation points across wallet operations (mint, melt, send, receive) to populate these fields.
2025-10-06 14:40:21 +02:00
vnprc
1a493d61f8 feat: optimize SQL balance calculation (#1152)
* feat: optimize SQL balance calculation

replace proof-fetching approach with SUM aggregation

- add get_balance() method to Database trait
- implement SQL SUM aggregation in cdk-sql-common
- update total_balance() to use get_balance() instead of get_unspent_proofs()
- redb impl maintains existing behavior

---------

Co-authored-by: thesimplekid <tsk@thesimplekid.com>
Co-authored-by: Cesar Rodas <cesar@rodasm.com.py>
2025-10-06 10:29:57 +02:00
asmo
cb2e534f81 feat: added postgres to ffi (#1117)
* feat: added postgres to ffi
2025-09-30 14:14:28 +01:00
thesimplekid
4b04d10383 Check change unique (#1112)
* fix(cdk): prevent duplicate blinded message processing with database constraints

Add unique constraints on blinded_message column in both PostgreSQL and SQLite databases, and implement application-level checks to prevent duplicate blinded messages from being processed. Also ensure proper cleanup of melt requests after successful processing.

* feat: db tests for unique

* refactor(cdk-sql): consolidate blinded messages into blind signature table

Migrate from separate blinded_messages table to unified blind_signature table.
Add signed_time column and make c column nullable to track both pending
blind messages (c=NULL) and completed signatures. Update insert/update
logic to handle upsert scenarios for blind signature completion.

* refactor(cdk-sql): remove unique constraint migration and filter queries for signed messages

Remove database-level unique constraint on blinded_message and instead filter
queries to only consider messages with signatures (c IS NOT NULL

* refactor(database): improve blinded message duplicate detection using database constraints

Replace manual duplicate checking with database constraint handling for better
reliability and simplified code flow in melt request processing.

* refactor(cdk-sql): optimize blind signature processing with batch queries

Replace individual queries per blinded message with single batch query
and HashMap lookup to eliminate N+1 query performance issue.

* fix: signed time to swap sigs

* refactor(cdk): split blinded message handling and improve duplicate detection

- Split add_melt_request_and_blinded_messages into separate methods
- Add blinded messages to database before signing in swap operations
- Improve duplicate output detection with proper error handling
- Make add_blinded_messages method accept optional quote_id for flexibility

* refactor(cdk): add BlindedMessageWriter for improved transaction rollback

- Add BlindedMessageWriter component for managing blinded message state
- Implement proper rollback mechanisms in swap operations
- Add delete_blinded_messages database interface for cleanup
- Improve error handling with better state management
2025-09-27 23:51:24 +01:00
thesimplekid
05acb914fe feat: remove delete fns for quotes (#1122) 2025-09-26 14:37:43 +01:00
thesimplekid
df2f9d1c2a Psgl auth db (#1095)
* feat(cdk-mintd): add dedicated auth database configuration support
2025-09-21 16:56:12 +01:00
C
075e25682e Remove generated files (#1097)
After #1088, generated migrations files should not be versioned
2025-09-21 16:55:48 +01:00
vnprc
853f13fc85 fix(build): use OUT_DIR for migration files (#1088)
- write generated migration files to OUT_DIR instead of source directory
- copy migration SQL files to OUT_DIR for inclusion in build artifacts
- use absolute paths from OUT_DIR in include_str! macros
- update consumer modules to include from OUT_DIR using concat! macro

these changes enable cdk to support nix sandbox builds
2025-09-20 16:50:54 +01:00
thesimplekid
aeafab9a10 fix: config overwrite on start up (#1081)
* fix: config overwrite on start up
2025-09-20 16:49:37 +01:00
thesimplekid
2dbb418db7 feat: store melt_request (#1045) 2025-09-16 10:55:36 +01:00
C
0bf5325927 Fixed error with wrong placeholder (#1069)
* Fixed error with wrong placeholder

Add concept of schema, so each test is isolated
2025-09-12 17:17:40 +01:00
asmo
75a3e6d2c7 Prometheus crate (#883)
* feat: introduce `cdk-prometheus` crate with Prometheus server and CDK-specific metrics support
2025-09-09 13:26:03 +01:00
C
841e35d70f Reorganize tests, add mint quote/payment coverage, and prevent over-issuing (#1048)
* Add consistent ordering of sql migrations

Also sort the prefix and not only the filenames

* Reorganize tests, add mint quote/payment coverage, and prevent over-issuing

Reorganizes the mint test suite into clear modules, adds comprehensive mint
quote & payment scenarios, enhances the shared test macro, and hardens SQL
logic to forbid issuing more than what’s been paid.

These tests were added:

* Add quote once; reject duplicates.
* Register multiple payments and verify aggregated amount_paid.
* Read parity between DB and in-TX views.
* Reject duplicate payment_id in same and different transactions.
* Reject over-issuing (same TX, different TX, with/without prior payments).

---------

Co-authored-by: thesimplekid <tsk@thesimplekid.com>
2025-09-08 14:55:41 +01:00
C
4363d14281 Add consistent ordering of sql migrations (#1047)
Also sort the prefix and not only the filenames
2025-09-08 10:17:00 +01:00
thesimplekid
5518ad2654 feat(cdk): add quote_id field to transactions for quote tracking (#1041)
- Add quote_id field to Transaction struct in cdk-common
- Add database migrations for quote_id column in SQLite and PostgreSQL
- Update wallet operations to populate quote_id for mint/melt transactions
- Set quote_id to None for send/receive operations without associated quotes
2025-09-06 19:57:23 +01:00
C
ded165f405 Update the signatory.proto file to match NUT-XXX (#1032)
* Update the signatory.proto file to match NUT-XXX

Source: https://github.com/cashubtc/nuts/pull/250/files

* Add unit tests as requested in https://github.com/cashubtc/cdk/pull/1032#discussion_r2321436860

* Remove unused types from proto file
2025-09-05 19:07:04 -03:00
C
3815c62d88 Fix postgres migration prefixes (#1037)
* Fix migrations ordering

1. Fix postgres migration prefixes for unreleased migrations
2. Fix build script to try to sort, if provided, the filename prefix as a
   number, otherwise fallback to the sorting by filename as string

* Fixed clippy issues
2025-09-05 14:39:54 -03:00
thesimplekid
c6cff3f6f4 feat(cdk): add generic key-value store functionality for mint databases (#1022)
* feat(cdk): add generic key-value store functionality for mint databases

Implements a comprehensive KV store system with transaction support,
namespace-based organization, and validation for mint databases.

- Add KVStoreDatabase and KVStoreTransaction traits for generic storage
- Include namespace and key validation with ASCII character restrictions
- Add database migrations for kv_store table in SQLite and PostgreSQL
- Implement comprehensive test suite for KV store functionality
- Integrate KV store traits into existing Database and Transaction bounds
2025-09-05 13:58:48 +01:00
thesimplekid
734e62b04a refactor: use quote id to string (#1026) 2025-09-02 10:47:26 +01:00
thesimplekid
dca48f4886 fix: get all mint quotes (#1025) 2025-09-02 09:14:39 +01:00
thesimplekid
6067242793 fix: cdk melt quote track payment method (#1021)
Add payment_method field to MeltQuote struct to track whether quotes use BOLT11 or BOLT12 payment methods. Include database migrations for both SQLite and PostgreSQL to support the new field. Update melt operations to set and use the payment method for proper routing between BOLT11 and BOLT12 endpoints.
2025-09-01 08:39:51 +01:00
lollerfirst
f1118b1c7b compatibility for migrating Nutshell Mints quote ids (#984) 2025-08-27 17:12:35 +01:00
thesimplekid
9ab86fabfe Cdk ldk node (#904)
* feat: add LDK Node Lightning backend with comprehensive integration

- Add new cdk-ldk-node crate implementing Lightning backend using LDK Node
- Extend MintPayment trait with start/stop methods for processor lifecycle management
- Add LDK Node configuration support to cdk-mintd with chain source and gossip options
- Enhance mint startup/shutdown to properly manage payment processor lifecycle

---------

Co-authored-by: Erik <78821053+swedishfrenchpress@users.noreply.github.com>
2025-08-25 22:06:00 +01:00
lollerfirst
ea9b9324f6 fix left-over y in blind_signatures table auth database 2025-08-22 13:10:43 +02:00
thesimplekid
ecdc78135d refactor(cdk): defer BOLT12 invoice fetching to payment execution (#978)
* refactor(cdk): defer BOLT12 invoice fetching to payment execution

Move BOLT12 invoice generation from quote creation to payment time, make
request_lookup_id optional for offers, and simplify payment structures by
removing unnecessary boxing and intermediate storage of invoices.
2025-08-20 11:20:30 +01:00
thesimplekid
761ed82554 feat: log to file (#967) 2025-08-19 14:57:14 +01:00
C
28a01398fd Add PostgreSQL support for mint and wallet (#878)
* Add PostgreSQL support for mint and wallet

* Fixed bug to avoid empty calls `get_proofs_states`

* Fixed SQL bug

* Avoid redudant clone()

* Add more tests for the storage layer

* Minor enhacements

* Add a generic function to execute db operations

This function would log slow operations and log errors

* Provision a postgres db for tests

* Update deps for msrv

* Add postgres to pipeline

* feat: add psgl to example and docker

* feat: db url fmt

---------

Co-authored-by: thesimplekid <tsk@thesimplekid.com>
2025-08-18 17:45:11 +01:00
vnprc
5b30ca546d fix: implement atomic keyset counter
- remove get_keyset_counter
- update increment_keyset_counter to atomically increment and return counter value
- replace get+increment pattern with atomic increment everywhere
2025-08-15 11:50:33 +01:00
thesimplekid
51b26eae62 chore: clippy 2025-08-15 11:49:38 +01:00
thesimplekid
8578e8532b Merge pull request #957 from thesimplekid/bump_msrv_1.85
feat: bump msrv from 1.75.0 to 1.85.0
2025-08-13 22:13:51 +01:00
C
64f7b07855 Do not perform external calls during a database transaction. (#954)
The codebase was used to correctly perform signatory calls during a database
transaction, as the signatory was previously exclusively in process. However, a
few months ago, it was changed to be a trait that can be either local or
remote. Making external calls to services, adding latency, during an ongoing
database transaction is a bad idea because it will lock the rows until the
service call is finalized, which is unpredictable.

The issue is even worse in our pipeline where the SQLite storage driver is used
with the ":memory:" path, which forces the Database pool to have a size of 1.
Since our tests run in parallel, they would randomly fail.

This issue was failing in the CI, but the error was not making the pipeline
fail. This bug was fixed as well.
2025-08-13 12:25:59 +01:00
thesimplekid
ec9108d69d feat: bump msrv from 1.75.0 to 1.85.0 2025-08-13 10:56:09 +01:00
thesimplekid
12b707ac3d fix: sqlite drop melt request 2025-08-13 09:00:02 +01:00
thesimplekid
5d98fdf353 Keyset counter (#950)
* feat: refresh keysets

* fix(cdk): resolve keyset counter skipping index 0 in deterministic secret generation

- Modified Database::get_keyset_counter to return u32 instead of Option<u32>
- Added database migrations to increment existing keyset counters by 1
- Removed counter increment logic from wallet operations to use actual counter value
- Ensures deterministic secret generation starts from index 0 instead of skipping it
2025-08-13 08:54:45 +01:00
thesimplekid
69d0cf0818 Merge pull request #952 from thesimplekid/add_payment_method
fix: add payment method to quote
2025-08-13 08:38:04 +01:00
thesimplekid
e87d818137 chore: drop unused mint table melt_request 2025-08-12 13:21:33 +01:00
thesimplekid
12452680ac fix: add payment method to quote 2025-08-12 13:13:23 +01:00
Cesar Rodas
937d9ac43b Introduce run_db_operation_sync and run_db_operation
These functions are designed as a single funnel to talk to the database,
whether it is synchronous or asynchronous.

This single funnel will log SQL queries and slow operations, providing a clear
and unified debug message for the problematic query, so it can be optimized
accordingly (for instance, missing indexes or unbound SQL requests).
2025-08-11 11:55:52 -03:00
Cesar Rodas
2e1099adbe Fixed bug to avoid empty calls get_proofs_states 2025-08-07 22:24:30 -03:00
C
ad8f1ece5c Working on a better database abstraction (#931)
* Working on a better database abstraction

After [this question in the chat](https://matrix.to/#/!oJFtttFHGfnTGrIjvD:matrix.cashu.space/$oJFtttFHGfnTGrIjvD:matrix.cashu.space/$I5ZtjJtBM0ctltThDYpoCwClZFlM6PHzf8q2Rjqmso8)
regarding a database transaction within the same function, I realized a few
design flaws in our SQL database abstraction, particularly regarding
transactions.

1. Our upper abstraction got it right, where a transaction is bound with `&mut
   self`, so Rust knows how to handle its lifetime with' async/await'.
2. The raw database does not; instead, it returns &self, and beginning a
   transaction takes &self as well, which is problematic for Rust, but that's not
   all. It is fundamentally wrong. A transaction should take &mut self when
   beginning a transaction, as that connection is bound to a transaction and
   should not be returned to the pool. Currently, that responsibility lies with
   the implementor. If a mistake is made, a transaction could be executed in two
   or more connections.
3. The way a database is bound to our store layer is through a single struct,
   which may or may not internally utilize our connection pool. This is also
   another design flow, in this PR, a connection pool is owned, and to use a
   connection, it should be requested, and that connection is reference with
   mutable when beginning a transaction

* Improve the abstraction with fewer generics

As suggested by @thesimplekid

* Add BEGIN IMMEDIATE for SQLite
2025-08-06 07:58:03 +01:00
thesimplekid
3c4fce5c45 feat: add keyset u32 mapping migration (#926)
* feat: add keyset u32 mapping migration and duplicate handling

- Add new database migration (version 3) to include u32 representation for keysets
- Implement migration for both redb and SQL databases
- Add duplicate detection and handling for keyset entries
- Create unique index constraint for keyset_u32 column in SQL
- Update keyset storage to include u32 identifiers
- Handle backwards compatibility for existing databases

* chore: clippy

* refactor(cashu): simplify keyset ID verification logic

- Consolidate match expression into a single expression
- Use direct comparison with ensure_cdk macro
- Improve readability of keyset ID validation

* refactor(cdk): rename `fetch_keyset_keys` to `load_keyset_keys` for clarity

- Renamed `fetch_keyset_keys` to `load_keyset_keys` across multiple modules to better reflect its behavior of loading keys from local storage or fetching from mint when missing.
- Added debug logging to indicate when keys are being fetched from the mint.
- Simplified key loading logic in `update_mint_keysets` by removing redundant existence checks.

* chore: remove unused vec
2025-07-31 10:04:38 -04:00
Cesar Rodas
ed7b64b71a Add missing migrations for wallet and auth db 2025-07-29 20:28:09 -03:00
Cesar Rodas
0041c135f7 Fix get_mint_quote_by_request_lookup_id
Fixes #916

The two functions (read and transaction) got out of sync
2025-07-29 11:31:29 -03:00
Cesar Rodas
659518f241 Improve migrations
Add the namespaced migrations and global migrations
2025-07-29 11:31:29 -03:00
C
99ced01e67 Apply suggestions from code review
Co-authored-by: thesimplekid <tsk@thesimplekid.com>
2025-07-29 11:31:29 -03:00
Cesar Rodas
fb4c470a9a Rename still_active to stale 2025-07-29 11:31:29 -03:00