Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ package may import from a higher layer.
| [`lib/recovery`](lib/recovery/) | Immutable recovery proof graph, session state machine, TLV codec for unilateral exit |
| [`unrollplan`](unrollplan/) | Pure dependency-resolution planner driving unilateral-exit broadcast/sweep ordering |
| [`vhtlcrecovery`](vhtlcrecovery/) | Durable control-plane types for vHTLC on-chain recovery jobs (action, state, script parameters, swap linkage) |
| [`coinselect`](coinselect/) | Coin-type-agnostic coin-selection algorithm (largest-first) shared by vtxo and swapwallet; no wallet or RPC dependencies |

### Layer 2: Infrastructure (Chain, Storage, Messaging)

Expand All @@ -43,6 +44,8 @@ package may import from a higher layer.
| [`lwwallet`](lwwallet/) | Lightweight in-process wallet (btcwallet + Esplora, no external LND) |
| [`btcwbackend`](btcwbackend/) | Neutrino-backed wallet backend (btcwallet + compact block filters) |
| [`walletcore`](walletcore/) | Shared wallet abstractions and boarding logic used by lwwallet and btcwbackend |
| [`chainfees`](chainfees/) | `chainfee.Estimator` implementations and combinators (WalletKit, mempool.space, MinEstimator) |
| [`internal/sqlbase`](internal/sqlbase/) | WASM-only SQL walletdb backend for lwwallet (js/wasm build tag); maps btcwallet nested-bucket semantics to SQL |
| [`proofkeys`](proofkeys/) | Interface for wallet-managed key derivation and indexer proof signing |
| [`fraud`](fraud/) | Fraud detection actor: watches OOR ancestor outpoints on-chain and triggers unilateral exit when an ancestor is spent |
| [`vhtlcrecovery/coordinator`](vhtlcrecovery/coordinator/) | Runtime coordinator for durable vHTLC recovery jobs: arms, escalates into unroll, cancels, and reconciles after restart |
Expand All @@ -61,10 +64,12 @@ package may import from a higher layer.
| [`sdk/ark`](sdk/ark/) | Consumer-facing Go SDK facade: remote or embedded daemon access with typed models |
| [`sdk/swaps`](sdk/swaps/) | Lightning-to-Ark / Ark-to-Lightning atomic swap SDK with durable FSM flows |
| [`sdk/walletdk`](sdk/walletdk/) | Wallet-shaped SDK facade for host apps: embeds the daemon in-process, dials it over a private bufconn transport, exposes typed methods for the seven core wallet verbs (create, unlock, send, recv, list, balance, exit). The highest-level layer in the stack; wraps `walletdkrpc.WalletService`. Wallet RPC methods gated behind `walletdkrpc` (which transitively requires `swapruntime`) |
| [`sdk/walletdk/mobile`](sdk/walletdk/mobile/) | Gomobile-safe JSON-bytes-in/out facade over sdk/walletdk for iOS/Android/WASM targets; singleton lifecycle, pull-based Subscribe |
| [`swapwallet`](swapwallet/) | Optional daemon-side `walletdkrpc.WalletService` implementation (build tags `walletdkrpc swapruntime`): composes the swap subsystem, cooperative leave, boarding, ledger, and unilateral-exit registry behind one flat, swap-vocabulary-free wallet API |
| [`swapclientserver`](swapclientserver/) | Optional daemon-side swap subserver (build tag `swapruntime`): translates `swapclientrpc` RPCs into `sdk/swaps` operations and manages the daemon-local worker registry |
| [`cmd/darepod`](cmd/darepod/) | Daemon entry point |
| [`cmd/darepocli`](cmd/darepocli/) | CLI client |
| [`cmd/walletdk-wasm`](cmd/walletdk-wasm/) | Browser/WASM entry point: installs `walletdkCall` JS bridge over sdk/walletdk/mobile (js/wasm only) |
| [`timeout`](timeout/) | Generic timeout scheduling actor |
| [`indexer`](indexer/) | Server indexing client for receive script registration |
| [`arkrpc`](arkrpc/) | Server-side gRPC service definitions (ArkService, IndexerService) |
Expand Down
48 changes: 48 additions & 0 deletions chainfees/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# chainfees

## Purpose

Provides reusable `chainfee.Estimator` implementations and combinators for
wallet and daemon chain backends. Bundles three concrete estimators —
`WalletKitEstimator` (queries lnd WalletKit), `MempoolSpaceEstimator` (queries
mempool.space API), and `MinEstimator` (selects the lowest successful estimate
across a set of child estimators) — so backends can compose fee estimation
strategies without re-implementing the interface.

## Key Types

- `WalletKitEstimator` — proxies fee estimates to an lndclient WalletKitClient
with configurable timeout and optional degraded-mode fallback on error.
- `WalletKitEstimatorConfig` — config for `WalletKitEstimator`: client,
logger, timeout, fallback flag.
- `MempoolSpaceEstimator` — queries the mempool.space recommended-fee endpoint
with configurable URL, cache TTL, and chain params. Caches the last
successful response to avoid hammering the API on every block.
- `MempoolSpaceConfig` — config for `MempoolSpaceEstimator`.
- `MinEstimator` — queries multiple child estimators and returns the minimum
successful relay fee per KW.
- `NamedEstimator` — wraps a child estimator with a stable name for logging.

## Relationships

- **Depends on**: `lnd/lnwallet/chainfee` (Estimator interface),
`lndclient` (WalletKitClient), `btcd/btcutil`, `btclog`.
- **Depended on by**: `darepod` (daemon fee estimation),
`chainbackends` (lnd-backed fee estimation adapter).
- **Sends**: nothing.
- **Receives**: nothing.

## Invariants

- All three exported estimator types implement
`github.com/lightningnetwork/lnd/lnwallet/chainfee.Estimator`.
- `MempoolSpaceEstimator` caches the last successful response at the
configured TTL; concurrent callers share the cached estimate without
issuing duplicate HTTP requests.
- `WalletKitEstimator` with the fallback flag returns a static relay fee
rather than propagating errors, so fee estimation can degrade gracefully
when lnd is temporarily unreachable.

## Deep Docs

- [ARCHITECTURE.md](../ARCHITECTURE.md) — System-wide package map.
48 changes: 48 additions & 0 deletions chainfees/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# chainfees

## Purpose

Provides reusable `chainfee.Estimator` implementations and combinators for
wallet and daemon chain backends. Bundles three concrete estimators —
`WalletKitEstimator` (queries lnd WalletKit), `MempoolSpaceEstimator` (queries
mempool.space API), and `MinEstimator` (selects the lowest successful estimate
across a set of child estimators) — so backends can compose fee estimation
strategies without re-implementing the interface.

## Key Types

- `WalletKitEstimator` — proxies fee estimates to an lndclient WalletKitClient
with configurable timeout and optional degraded-mode fallback on error.
- `WalletKitEstimatorConfig` — config for `WalletKitEstimator`: client,
logger, timeout, fallback flag.
- `MempoolSpaceEstimator` — queries the mempool.space recommended-fee endpoint
with configurable URL, cache TTL, and chain params. Caches the last
successful response to avoid hammering the API on every block.
- `MempoolSpaceConfig` — config for `MempoolSpaceEstimator`.
- `MinEstimator` — queries multiple child estimators and returns the minimum
successful relay fee per KW.
- `NamedEstimator` — wraps a child estimator with a stable name for logging.

## Relationships

- **Depends on**: `lnd/lnwallet/chainfee` (Estimator interface),
`lndclient` (WalletKitClient), `btcd/btcutil`, `btclog`.
- **Depended on by**: `darepod` (daemon fee estimation),
`chainbackends` (lnd-backed fee estimation adapter).
- **Sends**: nothing.
- **Receives**: nothing.

## Invariants

- All three exported estimator types implement
`github.com/lightningnetwork/lnd/lnwallet/chainfee.Estimator`.
- `MempoolSpaceEstimator` caches the last successful response at the
configured TTL; concurrent callers share the cached estimate without
issuing duplicate HTTP requests.
- `WalletKitEstimator` with the fallback flag returns a static relay fee
rather than propagating errors, so fee estimation can degrade gracefully
when lnd is temporarily unreachable.

## Deep Docs

- [ARCHITECTURE.md](../ARCHITECTURE.md) — System-wide package map.
52 changes: 52 additions & 0 deletions cmd/walletdk-wasm/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# cmd/walletdk-wasm

## Purpose

Browser/WASM entry point for the embedded walletdk runtime. Installs a global
`walletdkCall(method, request)` JavaScript function via `syscall/js` and
dispatches each call to the corresponding `sdk/walletdk/mobile` verb, returning
a JS Promise. The daemon, swap, and OOR machinery all run in-process inside the
browser VM with no separate gateway. The bridge never reaches `walletdk.Client`
directly — it always goes through the mobile facade so WASM behavior stays in
sync with the gomobile bindings.

Only compiles with `GOOS=js GOARCH=wasm -tags "mobile walletdkrpc swapruntime"`.
`stub.go` provides an empty build so `go build ./...` succeeds on other targets.

## Key Types

- `main` — installs `walletdkCall` on `js.Global()`, dispatches a
`walletdk-ready` custom event, then parks the Go runtime so exported
callbacks remain live for the page lifetime.
- `walletCall` — the single JS entry point; dispatches the method name to the
corresponding `mobile.*` verb and wraps the result in a Promise.
- `subscriptionHandle` — wraps `*mobile.Subscription` as a JS object with
`next()` (Promise → next entry JSON or null at EOF) and `close()` methods.

## Relationships

- **Depends on**: `sdk/walletdk/mobile` (all wallet operations proxied through
the mobile facade).
- **Depended on by**: browser host applications, React Native WASM bridges.
- **Sends**: nothing (invokes mobile facade functions in goroutines).
- **Receives** ← JS host: `walletdkCall(method, request)` invocations.

## Invariants

- `walletCall` is the only JS-exported function; all verb dispatch happens
inside its switch. Additional `js.Func` values outside `promise()` must be
released manually — `promise()` already releases its own executor immediately
after the Promise constructor returns to prevent per-call handle leaks.
- The browser data dir defaults to `/darepo` (injected by `startConfig`).
Without this override, `os.UserHomeDir` fails under `wasm_exec.js` with
`"$HOME is not defined"` and aborts start before the wallet boots. Callers
may override via `data_dir` in the start request.
- This package must not import `sdk/walletdk` directly; all access goes through
the `mobile` facade to keep the WASM bridge and gomobile bindings in sync.

## Deep Docs

- [sdk/walletdk/mobile/CLAUDE.md](../../sdk/walletdk/mobile/CLAUDE.md) —
The gomobile facade this package wraps.
- [sdk/walletdk/CLAUDE.md](../../sdk/walletdk/CLAUDE.md) — Underlying Go SDK.
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — System-wide package map.
52 changes: 52 additions & 0 deletions cmd/walletdk-wasm/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# cmd/walletdk-wasm

## Purpose

Browser/WASM entry point for the embedded walletdk runtime. Installs a global
`walletdkCall(method, request)` JavaScript function via `syscall/js` and
dispatches each call to the corresponding `sdk/walletdk/mobile` verb, returning
a JS Promise. The daemon, swap, and OOR machinery all run in-process inside the
browser VM with no separate gateway. The bridge never reaches `walletdk.Client`
directly — it always goes through the mobile facade so WASM behavior stays in
sync with the gomobile bindings.

Only compiles with `GOOS=js GOARCH=wasm -tags "mobile walletdkrpc swapruntime"`.
`stub.go` provides an empty build so `go build ./...` succeeds on other targets.

## Key Types

- `main` — installs `walletdkCall` on `js.Global()`, dispatches a
`walletdk-ready` custom event, then parks the Go runtime so exported
callbacks remain live for the page lifetime.
- `walletCall` — the single JS entry point; dispatches the method name to the
corresponding `mobile.*` verb and wraps the result in a Promise.
- `subscriptionHandle` — wraps `*mobile.Subscription` as a JS object with
`next()` (Promise → next entry JSON or null at EOF) and `close()` methods.

## Relationships

- **Depends on**: `sdk/walletdk/mobile` (all wallet operations proxied through
the mobile facade).
- **Depended on by**: browser host applications, React Native WASM bridges.
- **Sends**: nothing (invokes mobile facade functions in goroutines).
- **Receives** ← JS host: `walletdkCall(method, request)` invocations.

## Invariants

- `walletCall` is the only JS-exported function; all verb dispatch happens
inside its switch. Additional `js.Func` values outside `promise()` must be
released manually — `promise()` already releases its own executor immediately
after the Promise constructor returns to prevent per-call handle leaks.
- The browser data dir defaults to `/darepo` (injected by `startConfig`).
Without this override, `os.UserHomeDir` fails under `wasm_exec.js` with
`"$HOME is not defined"` and aborts start before the wallet boots. Callers
may override via `data_dir` in the start request.
- This package must not import `sdk/walletdk` directly; all access goes through
the `mobile` facade to keep the WASM bridge and gomobile bindings in sync.

## Deep Docs

- [sdk/walletdk/mobile/CLAUDE.md](../../sdk/walletdk/mobile/CLAUDE.md) —
The gomobile facade this package wraps.
- [sdk/walletdk/CLAUDE.md](../../sdk/walletdk/CLAUDE.md) — Underlying Go SDK.
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — System-wide package map.
49 changes: 49 additions & 0 deletions coinselect/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# coinselect

## Purpose

Provides a single, coin-type-agnostic coin-selection algorithm shared across
the client. The package holds no wallet, actor, or RPC dependencies so every
layer that needs a covering subset — the VTXO manager's reservation path and
the swap wallet's send preview alike — selects through the same generic code
rather than growing parallel implementations.

## Key Types

- `Request` — selection parameters: `Target` amount, `MinChange` floor,
`SweepAll` flag. `SweepAll` takes precedence and ignores `Target` and
`MinChange`.
- `Result[T]` — selection outcome: `Selected` subset, `Total`, `Change`.
- `AmountFunc[T]` — callback to extract a `btcutil.Amount` from a candidate
of type `T`.

## Selection Errors

- `ErrSelectionShortfall` — candidate set cannot cover target; `Result.Total`
carries the full candidate sum so callers can render a precise message.
- `ErrChangeBelowMin` — covering selection exists but change is below the
requested minimum and no exact-fit set was found.
- `ErrNoCandidates` — empty candidate set passed to the selector.
- `ErrInvalidTarget` — non-positive target in a bounded selection.

## Relationships

- **Depends on**: `btcd/btcutil` (amount type).
- **Depended on by**: `vtxo` (VTXO manager reservation path),
`swapwallet` (send-preview coin selection).
- **Sends**: nothing.
- **Receives**: nothing.

## Invariants

- `SweepAll` takes precedence: when set, `Target` and `MinChange` are ignored
and every candidate is selected.
- The selector is policy-free: it reports why a pass failed via typed errors
and leaves layer-specific diagnostics (e.g. locked liquidity vs. true
shortfall) to callers.
- Error values carry no total on `ErrNoCandidates` and `ErrInvalidTarget`;
only `ErrSelectionShortfall` and `ErrChangeBelowMin` populate `Result.Total`.

## Deep Docs

- [ARCHITECTURE.md](../ARCHITECTURE.md) — System-wide package map.
49 changes: 49 additions & 0 deletions coinselect/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# coinselect

## Purpose

Provides a single, coin-type-agnostic coin-selection algorithm shared across
the client. The package holds no wallet, actor, or RPC dependencies so every
layer that needs a covering subset — the VTXO manager's reservation path and
the swap wallet's send preview alike — selects through the same generic code
rather than growing parallel implementations.

## Key Types

- `Request` — selection parameters: `Target` amount, `MinChange` floor,
`SweepAll` flag. `SweepAll` takes precedence and ignores `Target` and
`MinChange`.
- `Result[T]` — selection outcome: `Selected` subset, `Total`, `Change`.
- `AmountFunc[T]` — callback to extract a `btcutil.Amount` from a candidate
of type `T`.

## Selection Errors

- `ErrSelectionShortfall` — candidate set cannot cover target; `Result.Total`
carries the full candidate sum so callers can render a precise message.
- `ErrChangeBelowMin` — covering selection exists but change is below the
requested minimum and no exact-fit set was found.
- `ErrNoCandidates` — empty candidate set passed to the selector.
- `ErrInvalidTarget` — non-positive target in a bounded selection.

## Relationships

- **Depends on**: `btcd/btcutil` (amount type).
- **Depended on by**: `vtxo` (VTXO manager reservation path),
`swapwallet` (send-preview coin selection).
- **Sends**: nothing.
- **Receives**: nothing.

## Invariants

- `SweepAll` takes precedence: when set, `Target` and `MinChange` are ignored
and every candidate is selected.
- The selector is policy-free: it reports why a pass failed via typed errors
and leaves layer-specific diagnostics (e.g. locked liquidity vs. true
shortfall) to callers.
- Error values carry no total on `ErrNoCandidates` and `ErrInvalidTarget`;
only `ErrSelectionShortfall` and `ErrChangeBelowMin` populate `Result.Total`.

## Deep Docs

- [ARCHITECTURE.md](../ARCHITECTURE.md) — System-wide package map.
16 changes: 8 additions & 8 deletions db/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,14 @@ For field-level detail, use `go doc github.com/lightninglabs/darepo-client/db.<S
collapsing on `(round_id, event_type, debit_account, credit_account)`.
Renumbered from 000019 to land after `000019_oor_session_registry`,
which merged to main while this work was in review.
- `000021_vhtlc_recovery_job_generations` — rebuilds `vhtlc_recovery_jobs`
to widen the uniqueness key from `(swap_id, action)` to
`(swap_id, action, vtxo_txid, vtxo_vout)`, so a refreshed vHTLC (new
outpoint) arms a new recovery "generation" instead of colliding with the
prior job. SQLite cannot widen a UNIQUE constraint in place, so the table
is recreated, rows are copied, and the state / swap-action / unroll-target
indexes are rebuilt. The down migration collapses each `(swap_id, action)`
to its newest row before restoring the narrower constraint.
Comment on lines +150 to +157

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The migration notes are listed in descending chronological order (from highest migration number to lowest). However, 000021_vhtlc_recovery_job_generations has been placed below 000020_accounting_wallet_sweeps. To maintain the correct descending order, please move the 000021 migration note to the very top of the 'Migration notes' section (above 000020).

- `000018_pending_intents` — generalizes the Board-only
`pending_board_requests` outbox into a supertype/subtype set:
`pending_intent_kinds` (enum table), `pending_intents` (header: 32-byte
Expand All @@ -156,14 +164,6 @@ For field-level detail, use `go doc github.com/lightninglabs/darepo-client/db.<S
anchored outpoint, PK on the outpoint so a newer intent rebinds, FK to the
header). Drops `pending_board_requests` outright (alpha; rows only exist
in the narrow crash window between admission and round seal).
- `000021_vhtlc_recovery_job_generations` — rebuilds `vhtlc_recovery_jobs`
to widen the uniqueness key from `(swap_id, action)` to
`(swap_id, action, vtxo_txid, vtxo_vout)`, so a refreshed vHTLC (new
outpoint) arms a new recovery "generation" instead of colliding with the
prior job. SQLite cannot widen a UNIQUE constraint in place, so the table
is recreated, rows are copied, and the state / swap-action / unroll-target
indexes are rebuilt. The down migration collapses each `(swap_id, action)`
to its newest row before restoring the narrower constraint.
- `000017_spending_reservations` — adds `spending_reservations` table with
`(outpoint_hash, outpoint_index)` PK, `owner_kind`, `owner_id`, and
`created_at`. A row exists IFF the owning spend session was durably
Expand Down
Loading
Loading