1use anyhow::Context;
2use bdk_esplora::esplora_client::Amount;
3use bitcoin::key::Keypair;
4use bitcoin::{Address, OutPoint, Psbt};
5use log::{error, info, trace, warn};
6
7use ark::{ProtocolEncoding, VtxoId};
8use ark::board::{BoardBuilder, BOARD_FUNDING_TX_VTXO_VOUT};
9use ark::fees::validate_and_subtract_fee;
10use bitcoin_ext::{BlockHeight, TxStatus};
11use server_rpc::protos;
12
13use crate::{onchain, Wallet, WalletVtxo};
14use crate::movement::MovementStatus;
15use crate::movement::update::MovementUpdate;
16use crate::persist::models::PendingBoard;
17use crate::subsystem::{BoardMovement, Subsystem};
18use crate::vtxo::{VtxoState, VtxoStateKind};
19
20impl Wallet {
21 pub async fn board_amount(
25 &self,
26 onchain: &mut dyn onchain::Board,
27 amount: Amount,
28 ) -> anyhow::Result<PendingBoard> {
29 let (user_keypair, _) = self.derive_store_next_keypair().await?;
30 self.board(onchain, Some(amount), user_keypair).await
31 }
32
33 pub async fn board_all(
35 &self,
36 onchain: &mut dyn onchain::Board,
37 ) -> anyhow::Result<PendingBoard> {
38 let (user_keypair, _) = self.derive_store_next_keypair().await?;
39 self.board(onchain, None, user_keypair).await
40 }
41
42 pub async fn pending_boards(&self) -> anyhow::Result<Vec<PendingBoard>> {
43 let boarding_vtxo_ids = self.inner.db.get_all_pending_board_ids().await?;
44 let mut boards = Vec::with_capacity(boarding_vtxo_ids.len());
45 for vtxo_id in boarding_vtxo_ids {
46 let board = self.inner.db.get_pending_board_by_vtxo_id(vtxo_id).await?
47 .expect("id just retrieved from db");
48 boards.push(board);
49 }
50 Ok(boards)
51 }
52
53 pub async fn pending_board_vtxos(&self) -> anyhow::Result<Vec<WalletVtxo>> {
58 let vtxo_ids = self.pending_boards().await?.into_iter()
59 .flat_map(|b| b.vtxos.into_iter())
60 .collect::<Vec<_>>();
61
62 let mut vtxos = Vec::with_capacity(vtxo_ids.len());
63 for vtxo_id in vtxo_ids {
64 let vtxo = self.get_vtxo_by_id(vtxo_id).await
65 .expect("vtxo id just got retrieved from db");
66 vtxos.push(vtxo);
67 }
68
69 debug_assert!(vtxos.iter().all(|v| matches!(v.state.kind(), VtxoStateKind::Locked)),
70 "all pending board vtxos should be locked"
71 );
72
73 Ok(vtxos)
74 }
75
76 pub async fn sync_pending_boards(&self) -> anyhow::Result<()> {
80 let (_, ark_info) = self.require_server().await?;
81 let current_height = self.inner.chain.tip().await?;
82 let unregistered_boards = self.pending_boards().await?;
83 let mut registered_boards = 0;
84
85 if unregistered_boards.is_empty() {
86 return Ok(());
87 }
88
89 trace!("Attempting registration of sufficiently confirmed boards");
90
91 for board in unregistered_boards {
92 let [vtxo_id] = board.vtxos.try_into()
93 .map_err(|_| anyhow!("multiple board vtxos is not supported yet"))?;
94
95 let vtxo = self.get_vtxo_by_id(vtxo_id).await?;
96
97 let anchor = vtxo.chain_anchor();
98 let confs = match self.inner.chain.tx_status(anchor.txid).await {
99 Ok(TxStatus::Confirmed(block_ref)) => Some(current_height - (block_ref.height - 1)),
100 Ok(TxStatus::Mempool) => Some(0),
101 Ok(TxStatus::NotFound) => None,
102 Err(_) => None,
103 };
104
105 if let Some(confs) = confs {
106 if confs >= ark_info.required_board_confirmations as BlockHeight {
107 if let Err(e) = self.register_board(vtxo.id()).await {
108 warn!("Failed to register board {}: {:#}", vtxo.id(), e);
109 } else {
110 info!("Registered board {}", vtxo.id());
111 registered_boards += 1;
112 continue;
113 }
114 }
115 }
116
117 if vtxo.expiry_height() < current_height + ark_info.required_board_confirmations as BlockHeight {
118 warn!("VTXO {} expired before its board was confirmed, removing board and marking VTXO for exit", vtxo.id());
119 self.inner.exit.start_exit_for_vtxos(&[vtxo.vtxo]).await?;
120 self.inner.movements.finish_movement_with_update(
121 board.movement_id,
122 MovementStatus::Failed,
123 MovementUpdate::new()
124 .exited_vtxo(vtxo_id),
125 ).await?;
126
127 self.inner.db.remove_pending_board(&vtxo_id).await?;
128 }
129 };
130
131 if registered_boards > 0 {
132 info!("Registered {registered_boards} sufficiently confirmed boards");
133 }
134 Ok(())
135 }
136
137 async fn board(
138 &self,
139 wallet: &mut dyn onchain::Board,
140 amount: Option<Amount>,
141 user_keypair: Keypair,
142 ) -> anyhow::Result<PendingBoard> {
143 let (addr, expiry_height) = self.board_funding_address(&user_keypair).await?;
144 let fee_rate = self.inner.chain.fee_rates().await.regular;
145
146 let board_psbt = if let Some(amount) = amount {
147 wallet.prepare_tx(&[(addr, amount)], fee_rate)?
148 } else {
149 wallet.prepare_drain_tx(addr, fee_rate)?
150 };
151
152 let signed_psbt = wallet.finish_psbt(board_psbt).await?;
153 self.board_tx(signed_psbt, user_keypair, expiry_height).await
154 }
155
156 pub async fn board_funding_address(
161 &self,
162 user_keypair: &Keypair,
163 ) -> anyhow::Result<(Address, BlockHeight)> {
164 let (_, ark_info) = self.require_server().await?;
165 let properties = self.inner.db.read_properties().await?.context("Missing config")?;
166 let current_height = self.inner.chain.tip().await?;
167
168 let expiry_height = current_height + ark_info.vtxo_expiry_delta as BlockHeight;
169 let builder = BoardBuilder::new(
170 user_keypair.public_key(),
171 expiry_height,
172 ark_info.server_pubkey,
173 ark_info.vtxo_exit_delta,
174 );
175
176 let addr = bitcoin::Address::from_script(
177 &builder.funding_script_pubkey(),
178 properties.network,
179 )?;
180
181 Ok((addr, expiry_height))
182 }
183
184 pub async fn board_tx(
189 &self,
190 board_psbt: Psbt,
191 user_keypair: Keypair,
192 expiry_height: BlockHeight,
193 ) -> anyhow::Result<PendingBoard> {
194 let (mut srv, ark_info) = self.require_server().await?;
195
196 let builder = BoardBuilder::new(
197 user_keypair.public_key(),
198 expiry_height,
199 ark_info.server_pubkey,
200 ark_info.vtxo_exit_delta,
201 );
202
203 let board_output = board_psbt.unsigned_tx.output.get(BOARD_FUNDING_TX_VTXO_VOUT as usize)
204 .context("PSBT does not have output at board funding vout index")?;
205 let expected_script = builder.funding_script_pubkey();
206 ensure!(
207 board_output.script_pubkey == expected_script,
208 "PSBT output does not pay to the expected board funding address",
209 );
210
211 let amount = board_output.value;
212 ensure!(amount >= ark_info.min_board_amount,
213 "board amount of {amount} is less than minimum board amount required by server ({})",
214 ark_info.min_board_amount,
215 );
216 let fee = ark_info.fees.board.calculate(amount).context("fee overflowed")?;
217 validate_and_subtract_fee(amount, fee)?;
218
219 let utxo = OutPoint::new(board_psbt.unsigned_tx.compute_txid(), BOARD_FUNDING_TX_VTXO_VOUT);
220 let builder = builder
221 .set_funding_details(amount, fee, utxo)
222 .context("error setting funding details for board")?
223 .generate_user_nonces();
224
225 let cosign_resp = srv.client.request_board_cosign(protos::BoardCosignRequest {
226 amount: amount.to_sat(),
227 utxo: bitcoin::consensus::serialize(&utxo), expiry_height,
229 user_pubkey: user_keypair.public_key().serialize().to_vec(),
230 pub_nonce: builder.user_pub_nonce().serialize().to_vec(),
231 }).await.context("error requesting board cosign")?
232 .into_inner().try_into().context("invalid cosign response from server")?;
233
234 ensure!(builder.verify_cosign_response(&cosign_resp),
235 "invalid board cosignature received from server",
236 );
237
238 let vtxo = builder.build_vtxo(&cosign_resp, &user_keypair)?;
240
241 let onchain_fee = board_psbt.fee()?;
242 let movement_id = self.inner.movements.new_movement_with_update(
243 Subsystem::BOARD,
244 BoardMovement::Board.to_string(),
245 MovementUpdate::new()
246 .intended_balance(amount.to_signed()?)
247 .effective_balance(vtxo.amount().to_signed()?)
248 .fee(fee)
249 .produced_vtxo(&vtxo)
250 .metadata(BoardMovement::metadata(utxo, onchain_fee)),
251 ).await?;
252 self.store_locked_vtxos(
253 [&vtxo],
254 Some(crate::vtxo::VtxoLockHolder::Movement { id: movement_id }),
255 ).await?;
256
257 let tx = board_psbt.extract_tx()?;
258 self.inner.db.store_pending_board(&vtxo, &tx, movement_id).await?;
259
260 trace!("Broadcasting board tx: {}", bitcoin::consensus::encode::serialize_hex(&tx));
261 self.inner.chain.broadcast_tx(&tx).await?;
262
263 info!("Board broadcasted");
264 Ok(self.inner.db.get_pending_board_by_vtxo_id(vtxo.id()).await?.expect("board should be stored"))
265 }
266
267 async fn register_board(&self, vtxo_id: VtxoId) -> anyhow::Result<()> {
269 trace!("Attempting to register board {} to server", vtxo_id);
270 let (mut srv, _) = self.require_server().await?;
271
272 let vtxo = self.inner.db.get_full_vtxo(vtxo_id).await?
275 .with_context(|| format!("VTXO doesn't exist: {}", vtxo_id))?;
276
277 srv.client.register_board_vtxo(protos::BoardVtxoRequest {
279 board_vtxo: vtxo.serialize(),
280 }).await.context("error registering board with the Ark server")?;
281
282 self.inner.db.update_vtxo_state_checked(
285 vtxo.id(), VtxoState::Spendable, &VtxoStateKind::UNSPENT_STATES,
286 ).await?;
287
288 if let Err(e) = self.post_recovery_vtxo_ids([vtxo.id()]).await {
290 error!("Failed to post recovery vtxo ID to server: {:#}", e);
291 }
292
293 let board = self.inner.db.get_pending_board_by_vtxo_id(vtxo.id()).await?
294 .context("pending board not found")?;
295
296 self.inner.movements.finish_movement(board.movement_id, MovementStatus::Successful).await?;
297 self.inner.db.remove_pending_board(&vtxo.id()).await?;
298
299 Ok(())
300 }
301}