bark/onchain/
mod.rs

1//! Onchain wallet integration interfaces.
2//!
3//! This module defines the traits and types that an external onchain wallet must
4//! implement to be used by the library. The goal is to let integrators plug in
5//! their own wallet implementation, so features like boarding (moving onchain funds
6//! into Ark) and unilateral exit (claiming VTXOs onchain without server cooperation)
7//! are supported.
8//!
9//! Key concepts exposed here:
10//! - [Utxo], [LocalUtxo] & [SpendableExit]: lightweight types representing wallet UTXOs and
11//!   spendable exit outputs.
12//! - [PreparePsbt] & [SignPsbt]: funding and signing interfaces for building transactions.
13//! - [GetBalance], [GetWalletTx], [GetSpendingTx]: read-access to wallet state for balance
14//!   and [Transaction] lookups required by various parts of the library.
15//! - [MakeCpfp]: CPFP construction interfaces used for create child transactions.
16//! - [ExitUnilaterally]: a convenience trait that aggregates the required capabilities a
17//!   wallet must provide to support unilateral exits.
18//!
19//! A reference implementation based on BDK is available behind the `onchain-bdk`
20//! cargo feature. Enable it to use the provided [OnchainWallet] implementation.
21//! You can use all features from BDK because [bdk_wallet] is re-exported.
22
23#[cfg(feature = "onchain-bdk")]
24mod bdk;
25
26#[cfg(feature = "onchain-bdk")]
27pub use bdk_wallet;
28
29pub use bitcoin_ext::cpfp::{CpfpError, MakeCpfpFees};
30
31/// BDK-backed onchain wallet implementation.
32///
33/// Available only when the `onchain-bdk` feature is enabled.
34#[cfg(feature = "onchain-bdk")]
35pub use crate::onchain::bdk::{OnchainWallet, TxBuilderExt};
36
37use std::sync::Arc;
38
39use bitcoin::{
40	Address, Amount, FeeRate, OutPoint, Psbt, Transaction, Txid
41};
42
43use ark::Vtxo;
44use ark::vtxo::Full;
45use bitcoin_ext::{BlockHeight, BlockRef};
46
47use crate::chain::ChainSource;
48
49/// Represents an onchain UTXO known to the wallet.
50///
51/// This can be either:
52/// - `Local`: a standard wallet UTXO
53/// - `Exit`: a spendable exit output produced by the Ark exit mechanism
54#[derive(Debug, Clone)]
55pub enum Utxo {
56	Local(LocalUtxo),
57	Exit(SpendableExit),
58}
59
60/// A standard wallet [Utxo] owned by the local wallet implementation.
61#[derive(Debug, Clone)]
62pub struct LocalUtxo {
63	/// The outpoint referencing the UTXO.
64	pub outpoint: OutPoint,
65	/// The amount contained in the UTXO.
66	pub amount: Amount,
67	/// Optional confirmation height; `None` if unconfirmed.
68	pub confirmation_height: Option<BlockHeight>,
69}
70
71/// A spendable unilateral exit of a [Vtxo] which can be claimed onchain.
72///
73/// When exiting unilaterally, the wallet will end up with onchain outputs that correspond to
74/// previously-held VTXOs. These can be claimed and used for further spending.
75#[derive(Debug, Clone)]
76pub struct SpendableExit {
77	/// The VTXO being exited.
78	pub vtxo: Vtxo<Full>,
79	/// The block height associated with the exits' validity window.
80	pub height: BlockHeight,
81}
82
83/// Ability to finalize a [Psbt] into a fully signed [Transaction].
84///
85/// Wallets should apply all necessary signatures and finalize inputs according
86/// to their internal key management and policies.
87#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
88#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
89pub trait SignPsbt {
90	/// Consume a [Psbt] and return a fully signed and finalized [Transaction].
91	async fn finish_tx(&mut self, psbt: Psbt) -> anyhow::Result<Transaction>;
92}
93
94/// Ability to query the wallets' total balance.
95///
96/// This is used by higher-level flows to decide when onchain funds are available for boarding or
97/// fee bumping, and to present balance information to users.
98pub trait GetBalance {
99	/// Get the total balance of the wallet.
100	fn get_balance(&self) -> Amount;
101}
102
103/// Ability to look up transactions known to the wallet.
104///
105/// Implementations should return wallet-related transactions and, when possible,
106/// the block information those transactions confirmed in.
107pub trait GetWalletTx {
108	/// Retrieve the wallet [Transaction] for the given [Txid] if any.
109	fn get_wallet_tx(&self, txid: Txid) -> Option<Arc<Transaction>>;
110
111	/// Retrieve information about the block, if any, a given wallet transaction was confirmed in.
112	fn get_wallet_tx_confirmed_block(&self, txid: Txid) -> anyhow::Result<Option<BlockRef>>;
113}
114
115/// Ability to construct funded PSBTs for specific destinations or to drain the wallet.
116///
117/// These methods are used to build transactions for boarding, exits, and fee bumping.
118pub trait PreparePsbt {
119	/// Prepare a [Transaction] which will send to the given destinations.
120	fn prepare_tx(
121		&mut self,
122		destinations: &[(Address, Amount)],
123		fee_rate: FeeRate,
124	) -> anyhow::Result<Psbt>;
125
126	/// Prepare a [Transaction] for sending all wallet funds to the given destination.
127	fn prepare_drain_tx(
128		&mut self,
129		destination: Address,
130		fee_rate: FeeRate,
131	) -> anyhow::Result<Psbt>;
132}
133
134/// Ability to find wallet-local spends of a specific [OutPoint].
135///
136/// This helps identify if the wallet has already spent an exit or parent [Transaction].
137pub trait GetSpendingTx {
138	/// This should search the wallet and look for any [Transaction] that spends the given
139	/// [OutPoint]. The intent of the function is to only look at spends which happen in the wallet
140	/// itself.
141	fn get_spending_tx(&self, outpoint: OutPoint) -> Option<Arc<Transaction>>;
142}
143
144/// Ability to create and persist CPFP transactions for spending P2A outputs.
145#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
146#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
147pub trait MakeCpfp {
148	/// Creates a signed Child Pays for Parent (CPFP) transaction using a Pay-to-Anchor (P2A) output
149	/// to broadcast unilateral exits and other TRUC transactions.
150	///
151	/// For more information please see [BIP431](https://github.com/bitcoin/bips/blob/master/bip-0431.mediawiki#topologically-restricted-until-confirmation).
152	///
153	/// # Arguments
154	///
155	/// * `tx` - A parent `Transaction` that is guaranteed to have one P2A output which
156	///          implementations must spend so that both the parent and child transactions can be
157	///          broadcast to the network as a v3 transaction package.
158	/// * `fees` - Informs the implementation how fees should be paid by the child transaction. Note
159	///            that an effective fee rate should be calculated using the weight of both the
160	///            parent and child transactions.
161	///
162	/// # Returns
163	///
164	/// Returns a `Result` containing:
165	/// * `Transaction` - The signed CPFP transaction ready to be broadcasted to the network with
166	///                   the given parent transaction if construction and signing were successful.
167	/// * `CpfpError` - An error indicating the reason for failure in constructing the CPFP
168	///                 transaction (e.g., insufficient funds, invalid parent transaction, or
169	///                 signing failure).
170	fn make_signed_p2a_cpfp(
171		&mut self,
172		tx: &Transaction,
173		fees: MakeCpfpFees,
174	) -> Result<Transaction, CpfpError>;
175
176	/// Persist the signed CPFP transaction so it can be rebroadcast or retrieved as needed.
177	async fn store_signed_p2a_cpfp(&mut self, tx: &Transaction) -> anyhow::Result<(), CpfpError>;
178}
179
180/// Trait alias for wallets that support boarding.
181///
182/// Any wallet type implementing these component traits automatically implements
183/// `Board`. The trait requires Send + Sync because boarding flows may be
184/// executed from async tasks and across threads.
185///
186/// Required capabilities:
187/// - [SignPsbt]: to finalize transactions
188/// - [GetWalletTx]: to query related transactions and their confirmations
189/// - [PreparePsbt]: to prepare transactions for boarding
190pub trait Board: PreparePsbt + SignPsbt + GetWalletTx + Send + Sync {}
191
192impl <W: PreparePsbt + SignPsbt + GetWalletTx + Send + Sync> Board for W {}
193
194/// Trait alias for wallets that support unilateral exit end-to-end.
195///
196/// Any wallet type implementing these component traits automatically implements
197/// `ExitUnilaterally`. The trait requires Send + Sync because exit flows may be
198/// executed from async tasks and across threads.
199///
200/// Required capabilities:
201/// - [GetBalance]: to evaluate available funds
202/// - [GetWalletTx]: to query related transactions and their confirmations
203/// - [MakeCpfp]: to accelerate slow/pinned exits
204/// - [SignPsbt]: to finalize transactions
205/// - [GetSpendingTx]: to detect local spends relevant to exit coordination
206pub trait ExitUnilaterally:
207	GetBalance +
208	GetWalletTx +
209	MakeCpfp +
210	SignPsbt +
211	GetSpendingTx +
212	Send + Sync + {}
213
214impl <W: GetBalance +
215	GetWalletTx +
216	MakeCpfp +
217	SignPsbt +
218	GetSpendingTx +
219	Send + Sync> ExitUnilaterally for W {}
220
221/// Ability to sync the wallet with the onchain network.
222#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
223#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
224pub trait ChainSync {
225	/// Sync the wallet with the onchain network.
226	async fn sync(&mut self, chain: &ChainSource) -> anyhow::Result<()>;
227}
228
229/// Trait that covers the requirements to use an onchain wallet with
230/// [Wallet::run_daemon](crate::Wallet::run_daemon).
231pub trait DaemonizableOnchainWallet: ExitUnilaterally + ChainSync {}
232impl <W: ExitUnilaterally + ChainSync> DaemonizableOnchainWallet for W {}