bark-rest 0.2.0

a REST server built on top of the bark-wallet crate
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
use std::collections::HashSet;
use std::str::FromStr;

use axum::extract::{Path, Query, State};
use axum::routing::{get, post};
use axum::{debug_handler, Json, Router};
use anyhow::Context;
use bitcoin::FeeRate;
use tracing::info;
use utoipa::OpenApi;

use bark::onchain::ChainSync;
use bark::vtxo::{FilterVtxos, VtxoFilter};
use bitcoin_ext::FeeRateExt;

use crate::ServerState;
use crate::error::{self, HandlerResult, ContextExt, badarg, not_found};

#[derive(OpenApi)]
#[openapi(
	paths(
		get_exit_status_by_vtxo_id,
		get_all_exit_status,
		exit_start_vtxos,
		exit_start_all,
		exit_progress,
		exit_claim_vtxos,
		exit_claim_all,
	),
	components(schemas(
		bark_json::web::ExitStatusRequest,
		bark_json::cli::ExitTransactionStatus,
		bark_json::web::ExitStartRequest,
		bark_json::web::ExitStartResponse,
		bark_json::web::ExitProgressRequest,
		bark_json::cli::ExitProgressResponse,
		bark_json::web::ExitClaimAllRequest,
		bark_json::web::ExitClaimVtxosRequest,
		bark_json::web::ExitClaimResponse,
	)),
	tags((name = "exits", description = "Move bitcoin back on-chain without server cooperation."))
)]
pub struct ExitsApiDoc;

pub fn router() -> Router<ServerState> {
	Router::new()
		.route("/status/{vtxo_id}", get(get_exit_status_by_vtxo_id))
		.route("/status", get(get_all_exit_status))
		.route("/start/vtxos", post(exit_start_vtxos))
		.route("/start/all", post(exit_start_all))
		.route("/progress", post(exit_progress))
		.route("/claim/vtxos", post(exit_claim_vtxos))
		.route("/claim/all", post(exit_claim_all))
}

#[utoipa::path(
	get,
	path = "/status/{vtxo_id}",
	summary = "Get exit status",
	params(
		("vtxo_id" = String, Path, description = "The VTXO to check the exit status of"),
		("history" = Option<bool>, Query, description = "Whether to include the detailed history of the exit process"),
		("transactions" = Option<bool>, Query, description = "Whether to include the exit transactions and their CPFP children")
	),
	responses(
		(status = 200, description = "Returns the exit status", body = bark_json::cli::ExitTransactionStatus),
		(status = 404, description = "VTXO wasn't found", body = error::NotFoundError),
		(status = 500, description = "Internal server error", body = error::InternalServerError)
	),
	description = "Returns the current state of an emergency exit for the specified VTXO, \
		including which phase the exit is in (start, processing, awaiting-delta, \
		claimable, claim-in-progress, or claimed). Optionally includes the full state \
		transition history and the exit transaction packages with their CPFP children.",
	tag = "exits"
)]
#[debug_handler]
pub async fn get_exit_status_by_vtxo_id(
	State(state): State<ServerState>,
	Path(vtxo): Path<String>,
	Query(query): Query<bark_json::web::ExitStatusRequest>,
) -> HandlerResult<Json<bark_json::cli::ExitTransactionStatus>> {
	let wallet = state.require_wallet()?;

	let vtxo_id = ark::VtxoId::from_str(&vtxo).badarg("Invalid VTXO ID")?;

	let status = wallet.exit_mgr().get_exit_status(
		vtxo_id,
		query.history.unwrap_or(false),
		query.transactions.unwrap_or(false)
	).await.context("Failed to get exit status")?;

	match status {
		None => not_found!([vtxo_id], "VTXO not found"),
		Some(status) => Ok(axum::Json(status.into())),
	}
}

#[utoipa::path(
	get,
	path = "/status",
	summary = "List all exit statuses",
	params(
		("history" = Option<bool>, Query, description = "Whether to include the detailed history of the exit process"),
		("transactions" = Option<bool>, Query, description = "Whether to include the exit transactions and their CPFP children")
	),
	responses(
		(status = 200, description = "Returns all exit statuses", body = Vec<bark_json::cli::ExitTransactionStatus>),
		(status = 500, description = "Internal server error", body = error::InternalServerError)
	),
	description = "Returns the current state of every emergency exit in the wallet. Each \
		entry includes which phase the exit is in (start, processing, awaiting-delta, \
		claimable, claim-in-progress, or claimed), and optionally the full state \
		transition history and the exit transaction packages with their CPFP children.",
	tag = "exits"
)]
#[debug_handler]
pub async fn get_all_exit_status(
	State(state): State<ServerState>,
	Query(query): Query<bark_json::web::ExitStatusRequest>,
) -> HandlerResult<Json<Vec<bark_json::cli::ExitTransactionStatus>>> {
	let wallet = state.require_wallet()?;

	let exit_vtxos = wallet.exit_mgr().get_exit_vtxos().await;
	let mut statuses = Vec::with_capacity(exit_vtxos.len());

	for e in &exit_vtxos {
		let status = wallet.exit_mgr().get_exit_status(
			e.id(),
			query.history.unwrap_or(false),
			query.transactions.unwrap_or(false)
		).await.badarg("Failed to get exit status")?.unwrap();

		statuses.push(bark_json::cli::ExitTransactionStatus::from(status));
	}

	Ok(axum::Json(statuses))
}

#[utoipa::path(
	post,
	path = "/start/vtxos",
	summary = "Start exit for specific VTXOs",
	request_body = bark_json::web::ExitStartRequest,
	responses(
		(status = 200, description = "Exit started successfully", body = bark_json::web::ExitStartResponse),
		(status = 400, description = "No VTXO IDs provided, or one of the provided VTXO \
			IDs is invalid", body = error::BadRequestError),
		(status = 404, description = "One the VTXOs wasn't found", body = error::NotFoundError),
		(status = 500, description = "Internal server error", body = error::InternalServerError)
	),
	description = "Registers the specified VTXOs for emergency exit. The daemon \
		automatically progresses registered exits in the background at the cadence \
		defined by `SLOW_INTERVAL`, creating and broadcasting the required \
		transactions in sequence. Once all exit transactions are confirmed and the \
		timelock has elapsed, call `claim` to sweep the resulting outputs to an \
		on-chain address.",
	tag = "exits"
)]
#[debug_handler]
pub async fn exit_start_vtxos(
	State(state): State<ServerState>,
	Json(body): Json<bark_json::web::ExitStartRequest>,
) -> HandlerResult<Json<bark_json::web::ExitStartResponse>> {
	let wallet = state.require_wallet()?;

	if body.vtxos.is_empty() {
		badarg!("No VTXO IDs provided");
	}

	let mut vtxo_ids = Vec::new();
	for s in body.vtxos {
		let id = ark::VtxoId::from_str(&s).badarg("Invalid VTXO ID")?;
		wallet.get_vtxo_by_id(id).await.not_found([id], "VTXO not found")?;
		vtxo_ids.push(id);
	}

	let filter = VtxoFilter::new(&wallet).include_many(vtxo_ids);

	let spendable = wallet.spendable_vtxos_with(&filter).await
		.context("Error fetching spendable VTXOs")?;
	let inround = {
		let mut vtxos = wallet.pending_round_input_vtxos().await
			.context("Error fetching pending round input VTXOs")?;
		filter.filter_vtxos(&mut vtxos).await?;
		vtxos
	};

	let vtxos = spendable.into_iter().chain(inround)
		.map(|v| v.vtxo).collect::<Vec<_>>();

	wallet.exit_mgr().start_exit_for_vtxos(&vtxos).await
		.context("Failed to start exit for VTXOs")?;

	Ok(axum::Json(bark_json::web::ExitStartResponse {
		message: "Exit started successfully".to_string(),
	}))
}

#[utoipa::path(
	post,
	path = "/start/all",
	summary = "Start exit for all VTXOs",
	responses(
		(status = 200, description = "Exit started successfully", body = bark_json::web::ExitStartResponse),
		(status = 500, description = "Internal server error", body = error::InternalServerError)
	),
	description = "Registers all wallet VTXOs for emergency exit. The daemon \
		automatically progresses registered exits in the background at the cadence \
		defined by `SLOW_INTERVAL`, creating and broadcasting the required \
		transactions in sequence. Once all exit transactions are confirmed and the \
		timelock has elapsed, call `claim` to sweep the resulting outputs to an \
		on-chain address.",
	tag = "exits"
)]
#[debug_handler]
pub async fn exit_start_all(
	State(state): State<ServerState>,
) -> HandlerResult<Json<bark_json::web::ExitStartResponse>> {
	let wallet = state.require_wallet()?;

	wallet.exit_mgr().start_exit_for_entire_wallet().await
		.context("Failed to start exit for entire wallet")?;

	Ok(axum::Json(bark_json::web::ExitStartResponse {
		message: "Exit started successfully".to_string(),
	}))
}


#[utoipa::path(
	post,
	path = "/progress",
	summary = "Progress exits",
	request_body = bark_json::web::ExitProgressRequest,
	responses(
		(status = 200, description = "Returns the exit progress", body = bark_json::cli::ExitProgressResponse),
		(status = 500, description = "Internal server error", body = error::InternalServerError)
	),
	description = "Triggers all in-progress exits to advance by one step. The daemon already \
		progresses exits automatically in the background—use this endpoint when you want \
		immediate progress rather than waiting for the next automatic cycle. On each \
		call, the endpoint checks whether previously broadcast transactions have \
		confirmed and, if so, creates and broadcasts the next transaction in the \
		sequence. The on-chain wallet must have sufficient bitcoin to cover transaction \
		fees.",
	tag = "exits"
)]
#[debug_handler]
pub async fn exit_progress(
	State(state): State<ServerState>,
	Json(body): Json<bark_json::web::ExitProgressRequest>,
) -> HandlerResult<Json<bark_json::cli::ExitProgressResponse>> {
	let wallet = state.require_wallet()?;

	let onchain = state.require_onchain()?;
	let mut onchain_lock = onchain.write().await;

	let fee_rate = body.fee_rate.map(FeeRate::from_sat_per_kvb_ceil);

	onchain_lock.sync(wallet.chain()).await
		.context("error syncing on-chain wallet")?;

	wallet.exit_mgr().sync_no_progress(&*onchain_lock).await
		.context("error syncing exit state")?;
	let result = wallet.exit_mgr().progress_exits(&wallet, &mut *onchain_lock, fee_rate).await
		.context("error making progress on exit process")?;

	let done = !wallet.exit_mgr().has_pending_exits().await;
	let claimable_height = wallet.exit_mgr().all_claimable_at_height().await;
	let exits = result.unwrap_or_default();

	Ok(axum::Json(bark_json::cli::ExitProgressResponse {
		done,
		claimable_height,
		exits: exits.into_iter().map(|e| e.into()).collect::<Vec<_>>()
	}))
}

async fn inner_claim_vtxos(
	state: &ServerState,
	address: bitcoin::Address,
	vtxos: &[bark::exit::ExitVtxo],
	fee_rate: Option<FeeRate>,
) -> HandlerResult<Json<bark_json::web::ExitClaimResponse>> {
	let wallet = state.require_wallet()?;
	let onchain = state.require_onchain()?;

	let address_spk = address.script_pubkey();
	let psbt = wallet.exit_mgr().drain_exits(vtxos, &wallet, address, fee_rate).await
		.context("Failed to drain exits")?;
	let tx = psbt.extract_tx()
		.context("Failed to extract transaction")?;
	wallet.chain().broadcast_tx(&tx).await
		.context("Failed to broadcast transaction")?;
	info!("Drain transaction broadcasted: {}", tx.compute_txid());

	let mut onchain_lock = onchain.write().await;

	// Commit the transaction to the wallet if the claim destination is ours
	if onchain_lock.is_mine(address_spk) {
		info!("Adding claim transaction to wallet: {}", tx.compute_txid());
		onchain_lock.apply_unconfirmed_txs([(tx, ark::time::timestamp_secs())]);
	}

	Ok(axum::Json(bark_json::web::ExitClaimResponse {
		message: "Exit claimed successfully".to_string(),
	}))
}

#[utoipa::path(
	post,
	path = "/claim/vtxos",
	summary = "Claim specific exited VTXOs",
	request_body = bark_json::web::ExitClaimVtxosRequest,
	responses(
		(status = 200, description = "Exit claimed successfully", body = bark_json::web::ExitClaimResponse),
		(status = 400, description = "One of the provided VTXO isn't spendable, or \
			the provided destination address is invalid", body = error::BadRequestError),
		(status = 500, description = "Internal server error", body = error::InternalServerError)
	),
	description = "Sweeps the specified claimable exit outputs into a single on-chain \
		transaction sent to the specified address. Unlike `progress`, the daemon does \
		not claim automatically—this endpoint must be called manually. Poll the \
		`status` endpoint or call `progress` and check for `done: true` to know when \
		VTXOs are ready to claim. This is the final step of the emergency exit \
		process—the bitcoin is not considered back on-chain until this transaction \
		confirms.",
	tag = "exits"
)]
#[debug_handler]
pub async fn exit_claim_vtxos(
	State(state): State<ServerState>,
	Json(body): Json<bark_json::web::ExitClaimVtxosRequest>,
) -> HandlerResult<Json<bark_json::web::ExitClaimResponse>> {
	let wallet = state.require_wallet()?;

	let network = wallet.network().await?;
	let address = bitcoin::Address::from_str(&body.destination)
		.badarg("Invalid destination address")?
		.require_network(network)
		.badarg("Address is not valid for configured network")?;

	let claimable = wallet.exit_mgr().list_claimable().await;
	let vtxos = {
		let mut vtxo_ids = HashSet::new();
		for s in body.vtxos {
			let id = ark::VtxoId::from_str(&s).badarg("Invalid VTXO ID")?;
			wallet.get_vtxo_by_id(id).await.not_found([id], "VTXO not found")?;
			vtxo_ids.insert(id);
		}

		let vtxos = claimable.into_iter()
			.filter(|v| vtxo_ids.remove(&v.id()))
			.collect::<Vec<_>>();

		for id in vtxo_ids {
			badarg!("Unspendable VTXO provided: {}", id);
		}
		vtxos
	};

	let fee_rate = body.fee_rate.map(FeeRate::from_sat_per_kvb_ceil);

	inner_claim_vtxos(&state, address, &vtxos, fee_rate).await
}

#[utoipa::path(
	post,
	path = "/claim/all",
	summary = "Claim all exited VTXOs",
	request_body = bark_json::web::ExitClaimAllRequest,
	responses(
		(status = 200, description = "Exit claimed successfully", body = bark_json::web::ExitClaimResponse),
		(status = 400, description = "The provided destination address is invalid", body = error::BadRequestError),
		(status = 500, description = "Internal server error", body = error::InternalServerError)
	),
	description = "Sweeps all claimable exit outputs into a single on-chain transaction \
		sent to the specified address. Unlike `progress`, the daemon does not claim \
		automatically—this endpoint must be called manually. Poll the `status` endpoint \
		or call `progress` and check for `done: true` to know when VTXOs are ready to \
		claim. This is the final step of the emergency exit process—the bitcoin is not \
		considered back on-chain until this transaction confirms.",
	tag = "exits"
)]
#[debug_handler]
pub async fn exit_claim_all(
	State(state): State<ServerState>,
	Json(body): Json<bark_json::web::ExitClaimAllRequest>,
) -> HandlerResult<Json<bark_json::web::ExitClaimResponse>> {
	let wallet = state.require_wallet()?;
	let network = wallet.network().await?;

	let address = bitcoin::Address::from_str(&body.destination)
		.badarg("Invalid destination address")?
		.require_network(network)
		.badarg("Address is not valid for configured network")?;

	let vtxos = wallet.exit_mgr().list_claimable().await;

	let fee_rate = body.fee_rate.map(FeeRate::from_sat_per_kvb_ceil);

	inner_claim_vtxos(&state, address, &vtxos, fee_rate).await
}