use std::borrow::Borrow;
use std::time::Duration;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{Amount, FeeRate, Txid, SignedAmount};
use chrono::DateTime;
#[cfg(feature = "utoipa")]
use utoipa::ToSchema;
use ark::lightning::{PaymentHash, Preimage};
use ark::VtxoId;
use bark::movement::{MovementId, MovementStatus};
use bitcoin_ext::{BlockDelta, BlockHeight};
use crate::exit::error::ExitError;
use crate::exit::package::ExitTransactionPackage;
use crate::exit::ExitState;
use crate::primitives::{VtxoInfo, WalletVtxoInfo};
use crate::serde_utils;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct ArkInfo {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub network: bitcoin::Network,
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub server_pubkey: PublicKey,
#[serde(with = "serde_utils::duration")]
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub round_interval: Duration,
pub nb_round_nonces: usize,
pub vtxo_exit_delta: BlockDelta,
pub vtxo_expiry_delta: BlockDelta,
pub htlc_send_expiry_delta: BlockDelta,
pub htlc_expiry_delta: BlockDelta,
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub max_vtxo_amount: Option<Amount>,
pub max_arkoor_depth: u16,
pub required_board_confirmations: usize,
pub max_user_invoice_cltv_delta: u16,
#[serde(rename = "min_board_amount_sat", with = "bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub min_board_amount: Amount,
pub offboard_feerate_sat_per_kvb: u64,
pub ln_receive_anti_dos_required: bool,
}
impl<T: Borrow<ark::ArkInfo>> From<T> for ArkInfo {
fn from(v: T) -> Self {
let v = v.borrow();
ArkInfo {
network: v.network,
server_pubkey: v.server_pubkey,
round_interval: v.round_interval,
nb_round_nonces: v.nb_round_nonces,
vtxo_exit_delta: v.vtxo_exit_delta,
vtxo_expiry_delta: v.vtxo_expiry_delta,
htlc_send_expiry_delta: v.htlc_send_expiry_delta,
htlc_expiry_delta: v.htlc_expiry_delta,
max_vtxo_amount: v.max_vtxo_amount,
max_arkoor_depth: v.max_arkoor_depth,
required_board_confirmations: v.required_board_confirmations,
max_user_invoice_cltv_delta: v.max_user_invoice_cltv_delta,
min_board_amount: v.min_board_amount,
offboard_feerate_sat_per_kvb: v.offboard_feerate.to_sat_per_kwu() * 4,
ln_receive_anti_dos_required: v.ln_receive_anti_dos_required,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct LightningReceiveBalance {
#[serde(rename = "total_sat", with = "bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub total: Amount,
#[serde(rename = "claimable_sat", with = "bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub claimable: Amount,
}
impl From<bark::LightningReceiveBalance> for LightningReceiveBalance {
fn from(v: bark::LightningReceiveBalance) -> Self {
LightningReceiveBalance {
total: v.total,
claimable: v.claimable,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct Balance {
#[serde(rename = "spendable_sat", with = "bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub spendable: Amount,
#[serde(rename = "pending_lightning_send_sat", with = "bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub pending_lightning_send: Amount,
pub pending_lightning_receive: LightningReceiveBalance,
#[serde(rename = "pending_in_round_sat", with = "bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub pending_in_round: Amount,
#[serde(rename = "pending_board_sat", with = "bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub pending_board: Amount,
#[serde(
default,
rename = "pending_exit_sat",
with = "bitcoin::amount::serde::as_sat::opt",
skip_serializing_if = "Option::is_none",
)]
#[cfg_attr(feature = "utoipa", schema(value_type = u64, nullable=true))]
pub pending_exit: Option<Amount>,
}
impl From<bark::Balance> for Balance {
fn from(v: bark::Balance) -> Self {
Balance {
spendable: v.spendable,
pending_in_round: v.pending_in_round,
pending_lightning_send: v.pending_lightning_send,
pending_lightning_receive: v.pending_lightning_receive.into(),
pending_exit: v.pending_exit,
pending_board: v.pending_board,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct Config {
pub ark: String,
pub bitcoind: Option<String>,
pub bitcoind_cookie: Option<String>,
pub bitcoind_user: Option<String>,
pub bitcoind_pass: Option<String>,
pub esplora: Option<String>,
pub vtxo_refresh_expiry_threshold: BlockHeight,
#[serde(rename = "fallback_fee_rate_kvb", with = "serde_utils::fee_rate_sats_per_kvb")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64, nullable = true))]
pub fallback_fee_rate: Option<FeeRate>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct ExitProgressResponse {
pub exits: Vec<ExitProgressStatus>,
pub done: bool,
pub claimable_height: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct ExitProgressStatus {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub vtxo_id: VtxoId,
pub state: ExitState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ExitError>,
}
impl From<bark::exit::models::ExitProgressStatus> for ExitProgressStatus {
fn from(v: bark::exit::models::ExitProgressStatus) -> Self {
ExitProgressStatus {
vtxo_id: v.vtxo_id,
state: v.state.into(),
error: v.error.map(ExitError::from),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct ExitTransactionStatus {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub vtxo_id: VtxoId,
pub state: ExitState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub history: Option<Vec<ExitState>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub transactions: Vec<ExitTransactionPackage>,
}
impl From<bark::exit::models::ExitTransactionStatus> for ExitTransactionStatus {
fn from(v: bark::exit::models::ExitTransactionStatus) -> Self {
ExitTransactionStatus {
vtxo_id: v.vtxo_id,
state: v.state.into(),
history: v.history.map(|h| h.into_iter().map(ExitState::from).collect()),
transactions: v.transactions.into_iter().map(ExitTransactionPackage::from).collect(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct Board {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub funding_txid: Txid,
pub vtxos: Vec<VtxoInfo>,
}
impl From<bark::Board> for Board {
fn from(v: bark::Board) -> Self {
Board {
funding_txid: v.funding_txid,
vtxos: v.vtxos.into_iter().map(VtxoInfo::from).collect(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct Movement {
#[cfg_attr(feature = "utoipa", schema(value_type = u32))]
pub id: MovementId,
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub status: MovementStatus,
pub subsystem: MovementSubsystem,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<String>,
#[serde(rename="intended_balance_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = i64))]
pub intended_balance: SignedAmount,
#[serde(rename="effective_balance_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = i64))]
pub effective_balance: SignedAmount,
#[serde(rename="offchain_fee_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub offchain_fee: Amount,
pub sent_to: Vec<MovementDestination>,
pub received_on: Vec<MovementDestination>,
#[cfg_attr(feature = "utoipa", schema(value_type = Vec<String>))]
pub input_vtxos: Vec<VtxoId>,
#[cfg_attr(feature = "utoipa", schema(value_type = Vec<String>))]
pub output_vtxos: Vec<VtxoId>,
#[cfg_attr(feature = "utoipa", schema(value_type = Vec<String>))]
pub exited_vtxos: Vec<VtxoId>,
pub time: MovementTimestamp,
}
impl TryFrom<bark::movement::Movement> for Movement {
type Error = serde_json::Error;
fn try_from(m: bark::movement::Movement) -> Result<Self, Self::Error> {
Ok(Movement {
id: m.id,
status: m.status,
subsystem: MovementSubsystem::from(m.subsystem),
metadata: if m.metadata.is_empty() { None } else {
Some(serde_json::to_string(&m.metadata)?)
},
intended_balance: m.intended_balance,
effective_balance: m.effective_balance,
offchain_fee: m.offchain_fee,
sent_to: m.sent_to.into_iter().map(MovementDestination::from).collect(),
received_on: m.received_on.into_iter().map(MovementDestination::from).collect(),
input_vtxos: m.input_vtxos,
output_vtxos: m.output_vtxos,
exited_vtxos: m.exited_vtxos,
time: MovementTimestamp::from(m.time),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct MovementDestination {
pub destination: String,
#[serde(rename="amount_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub amount: Amount,
}
impl From<bark::movement::MovementDestination> for MovementDestination {
fn from(d: bark::movement::MovementDestination) -> Self {
MovementDestination {
destination: d.destination,
amount: d.amount,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct MovementSubsystem {
pub name: String,
pub kind: String,
}
impl From<bark::movement::MovementSubsystem> for MovementSubsystem {
fn from(s: bark::movement::MovementSubsystem) -> Self {
MovementSubsystem {
name: s.name,
kind: s.kind,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct MovementTimestamp {
pub created_at: DateTime<chrono::Utc>,
pub updated_at: DateTime<chrono::Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub completed_at: Option<DateTime<chrono::Utc>>,
}
impl From<bark::movement::MovementTimestamp> for MovementTimestamp {
fn from(t: bark::movement::MovementTimestamp) -> Self {
MovementTimestamp {
created_at: t.created_at,
updated_at: t.updated_at,
completed_at: t.completed_at,
}
}
}
pub mod onchain {
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct Send {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub txid: Txid,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct Address {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub address: bitcoin::Address<bitcoin::address::NetworkUnchecked>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct OnchainBalance {
#[serde(rename="total_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub total: Amount,
#[serde(rename="trusted_spendable_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub trusted_spendable: Amount,
#[serde(rename="immature_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub immature: Amount,
#[serde(rename="trusted_pending_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub trusted_pending: Amount,
#[serde(rename="untrusted_pending_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub untrusted_pending: Amount,
#[serde(rename="confirmed_sat", with="bitcoin::amount::serde::as_sat")]
#[cfg_attr(feature = "utoipa", schema(value_type = u64))]
pub confirmed: Amount,
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "result", rename_all = "lowercase")]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub enum RoundStatus {
Confirmed {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
funding_txid: Txid,
},
Unconfirmed {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
funding_txid: Txid,
},
Pending {
#[cfg_attr(feature = "utoipa", schema(value_type = Vec<String>))]
unsigned_funding_txids: Vec<Txid>,
},
Failed {
error: String,
},
}
impl RoundStatus {
pub fn is_final(&self) -> bool {
match self {
Self::Confirmed { .. } => true,
Self::Unconfirmed { .. } => false,
Self::Pending { .. } => false,
Self::Failed { .. } => true,
}
}
pub fn is_success(&self) -> bool {
match self {
Self::Confirmed { .. } => true,
Self::Unconfirmed { .. } => true,
Self::Pending { .. } => false,
Self::Failed { .. } => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct InvoiceInfo {
pub invoice: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
pub struct LightningReceiveInfo {
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub payment_hash: PaymentHash,
#[cfg_attr(feature = "utoipa", schema(value_type = String))]
pub payment_preimage: Preimage,
pub preimage_revealed_at: Option<chrono::DateTime<chrono::Utc>>,
pub invoice: String,
#[cfg_attr(feature = "utoipa", schema(value_type = Vec<WalletVtxoInfo>, nullable = true))]
pub htlc_vtxos: Option<Vec<WalletVtxoInfo>>,
}
impl From<bark::persist::models::LightningReceive> for LightningReceiveInfo {
fn from(v: bark::persist::models::LightningReceive) -> Self {
LightningReceiveInfo {
payment_hash: v.payment_hash,
payment_preimage: v.payment_preimage,
preimage_revealed_at: v.preimage_revealed_at.map(|ts| {
chrono::DateTime::from_timestamp_secs(ts as i64)
.expect("timestamp is valid")
}),
invoice: v.invoice.to_string(),
htlc_vtxos: v.htlc_vtxos.map(|vtxos| vtxos.into_iter()
.map(crate::primitives::WalletVtxoInfo::from).collect()),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn ark_info_fields() {
#[allow(unused)]
fn convert(j: ArkInfo) -> ark::ArkInfo {
ark::ArkInfo {
network: j.network,
server_pubkey: j.server_pubkey,
round_interval: j.round_interval,
nb_round_nonces: j.nb_round_nonces,
vtxo_exit_delta: j.vtxo_exit_delta,
vtxo_expiry_delta: j.vtxo_expiry_delta,
htlc_send_expiry_delta: j.htlc_send_expiry_delta,
htlc_expiry_delta: j.htlc_expiry_delta,
max_vtxo_amount: j.max_vtxo_amount,
max_arkoor_depth: j.max_arkoor_depth,
required_board_confirmations: j.required_board_confirmations,
max_user_invoice_cltv_delta: j.max_user_invoice_cltv_delta,
min_board_amount: j.min_board_amount,
offboard_feerate: FeeRate::from_sat_per_kwu(j.offboard_feerate_sat_per_kvb / 4),
ln_receive_anti_dos_required: j.ln_receive_anti_dos_required,
}
}
}
}