Skip to main content

lexe_api_core/models/
command.rs

1use std::collections::BTreeSet;
2
3use bitcoin::{address::NetworkUnchecked, bip32::Xpub};
4#[cfg(doc)]
5use lexe_common::root_seed::RootSeed;
6#[cfg(any(test, feature = "test-utils"))]
7use lexe_common::test_utils::arbitrary;
8use lexe_common::{
9    api::user::{NodePk, UserPk},
10    ln::{
11        amount::Amount,
12        balance::{LightningBalance, OnchainBalance},
13        channel::{LxChannelDetails, LxChannelId, LxUserChannelId},
14        hashes::Txid,
15        priority::ConfirmationPriority,
16        route::LxRoute,
17    },
18    ppm::Ppm,
19    time::TimestampMs,
20};
21use lexe_enclave::enclave::Measurement;
22use lexe_serde::hexstr_or_bytes;
23#[cfg(any(test, feature = "test-utils"))]
24use proptest_derive::Arbitrary;
25use serde::{Deserialize, Serialize};
26
27use crate::types::{
28    bounded_string::BoundedString,
29    invoice::Invoice,
30    offer::{MaxQuantity, Offer},
31    payments::{
32        ClientPaymentId, PaymentCreatedIndex, PaymentId, PaymentUpdatedIndex,
33    },
34    username::Username,
35};
36
37// --- General --- //
38
39#[derive(Debug, Serialize, Deserialize)]
40pub struct NodeInfoV1 {
41    pub version: semver::Version,
42    pub measurement: Measurement,
43    pub user_pk: UserPk,
44    pub node_pk: NodePk,
45    pub num_peers: usize,
46
47    pub num_usable_channels: usize,
48    pub num_channels: usize,
49    /// Our lightning channel balance
50    pub lightning_balance: LightningBalance,
51
52    /// Our on-chain wallet balance
53    pub onchain_balance: OnchainBalance,
54    /// The total # of UTXOs tracked by BDK.
55    pub num_utxos: usize,
56    /// The # of confirmed UTXOs tracked by BDK.
57    // TODO(max): LSP metrics should warn if this drops too low, as opening
58    // zeroconf with unconfirmed inputs risks double spending of channel funds.
59    pub num_confirmed_utxos: usize,
60    /// The # of unconfirmed UTXOs tracked by BDK.
61    pub num_unconfirmed_utxos: usize,
62
63    /// The channel manager's best synced block height.
64    pub best_block_height: u32,
65
66    /// The number of pending channel monitor updates.
67    /// If this isn't 0, it's likely that at least one channel is paused.
68    // TODO(max): This field is in the wrong place and should be removed.
69    // To my knowledge it is only used by integration tests (in a hacky way) to
70    // wait for a node to reach a quiescent state. The polling should be done
71    // inside the server handler rather than by the client in the test harness.
72    pub pending_monitor_updates: usize,
73}
74
75/// Information about the Lexe node.
76//
77// This is a cleaned-up version of [`NodeInfoV1`] with diagnostic fields
78// moved to [`DebugInfo`].
79#[derive(Debug, Serialize, Deserialize)]
80pub struct NodeInfo {
81    pub version: semver::Version,
82    pub measurement: Measurement,
83    pub user_pk: UserPk,
84    pub node_pk: NodePk,
85    pub num_peers: usize,
86
87    pub num_usable_channels: usize,
88    pub num_channels: usize,
89    /// Our lightning channel balance.
90    pub lightning_balance: LightningBalance,
91
92    /// Our on-chain wallet balance.
93    pub onchain_balance: OnchainBalance,
94
95    /// The channel manager's best synced block height.
96    pub best_block_height: u32,
97}
98
99impl From<NodeInfoV1> for NodeInfo {
100    fn from(v1: NodeInfoV1) -> Self {
101        Self {
102            version: v1.version,
103            measurement: v1.measurement,
104            user_pk: v1.user_pk,
105            node_pk: v1.node_pk,
106            num_peers: v1.num_peers,
107            num_usable_channels: v1.num_usable_channels,
108            num_channels: v1.num_channels,
109            lightning_balance: v1.lightning_balance,
110            onchain_balance: v1.onchain_balance,
111            best_block_height: v1.best_block_height,
112        }
113    }
114}
115
116/// Diagnostic information for debugging purposes.
117#[derive(Debug, Serialize, Deserialize)]
118pub struct DebugInfo {
119    /// Output descriptors for the on-chain wallet.
120    pub descriptors: OnchainDescriptors,
121    /// Legacy descriptors for wallets created <= node-v0.9.2.
122    /// `None` if the node doesn't have a legacy wallet.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub legacy_descriptors: Option<OnchainDescriptors>,
125
126    /// The total # of UTXOs tracked by BDK.
127    pub num_utxos: usize,
128    /// The # of confirmed UTXOs tracked by BDK.
129    // TODO(max): LSP metrics should warn if this drops too low, as opening
130    // zeroconf with unconfirmed inputs risks double spending of channel funds.
131    pub num_confirmed_utxos: usize,
132    /// The # of unconfirmed UTXOs tracked by BDK.
133    pub num_unconfirmed_utxos: usize,
134
135    /// The number of pending channel monitor updates.
136    /// If this isn't 0, it's likely that at least one channel is paused.
137    // TODO(max): This field is in the wrong place and should be removed.
138    // To my knowledge it is only used by integration tests (in a hacky way) to
139    // wait for a node to reach a quiescent state. The polling should be done
140    // inside the server handler rather than by the client in the test harness.
141    // This field is `Option` precisely so we can easily remove it later.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub pending_monitor_updates: Option<usize>,
144}
145
146/// BIP84 wpkh output descriptors for the on-chain wallet.
147///
148/// Descriptor strings include origin info and checksum. Example:
149/// "wpkh([be83839f/84'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/0/*)#dwvchw0k"
150///
151/// These are copy-pasteable into other wallets like Sparrow.
152#[derive(Clone, Debug, Serialize, Deserialize)]
153pub struct OnchainDescriptors {
154    /// BIP389 multipath descriptor for both keychains:
155    /// `wpkh([fp/84'/0'/0']xpub.../<0;1>/*)#checksum`
156    pub multipath_descriptor: String,
157
158    /// External (receive) keychain descriptor.
159    pub external_descriptor: String,
160
161    /// Internal (change) keychain descriptor.
162    pub internal_descriptor: String,
163
164    /// Account-level xpub at `m/84'/{coin}'/0'` for legacy tools.
165    pub account_xpub: Xpub,
166}
167
168#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
169pub enum GDriveStatus {
170    Ok,
171    Error(String),
172    Disabled,
173}
174
175#[derive(Debug, Serialize, Deserialize)]
176pub struct BackupInfo {
177    pub gdrive_status: GDriveStatus,
178}
179
180/// Request to query which node enclaves need provisioning, given the client's
181/// trusted measurements.
182#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
183#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
184pub struct EnclavesToProvisionRequest {
185    /// The enclave measurements the client trusts.
186    /// Typically the 3 latest from releases.json.
187    pub trusted_measurements: BTreeSet<Measurement>,
188}
189
190#[derive(Debug, PartialEq, Serialize, Deserialize)]
191#[cfg_attr(test, derive(Arbitrary))]
192pub struct SetupGDrive {
193    /// The auth `code` which can used to obtain a set of GDrive credentials.
194    /// - Applicable only in staging/prod.
195    /// - If GDrive has not been setup, the node will acquire the full set of
196    ///   GDrive credentials and persist them (encrypted ofc) in Lexe's DB.
197    #[cfg_attr(test, proptest(strategy = "arbitrary::any_string()"))]
198    pub google_auth_code: String,
199
200    /// The password-encrypted [`RootSeed`] which can be backed up in
201    /// GDrive.
202    /// - Applicable only in staging/prod.
203    /// - If Drive backup is not setup, instance will back up this encrypted
204    ///   [`RootSeed`] in Google Drive. If a backup already exists, it is
205    ///   overwritten.
206    /// - We require the client to password-encrypt prior to sending the
207    ///   provision request to prevent leaking the length of the password. It
208    ///   also shifts the burden of running the 600K HMAC iterations from the
209    ///   provision instance to the mobile app.
210    #[serde(with = "hexstr_or_bytes")]
211    pub encrypted_seed: Vec<u8>,
212}
213// --- Channel Management --- //
214
215#[derive(Serialize, Deserialize)]
216pub struct ListChannelsResponse {
217    pub channels: Vec<LxChannelDetails>,
218}
219
220/// The information required for the user node to open a channel to the LSP.
221#[derive(Serialize, Deserialize)]
222pub struct OpenChannelRequest {
223    /// A user-provided id for this channel that's associated with the channel
224    /// throughout its whole lifetime, as the Lightning protocol channel id is
225    /// only known after negotiating the channel and creating the funding tx.
226    ///
227    /// This id is also used for idempotency. Retrying a request with the same
228    /// `user_channel_id` won't accidentally open another channel.
229    pub user_channel_id: LxUserChannelId,
230    /// The value of the channel we want to open.
231    pub value: Amount,
232}
233
234#[derive(Debug, Serialize, Deserialize)]
235pub struct OpenChannelResponse {
236    /// The Lightning protocol channel id of the newly created channel.
237    pub channel_id: LxChannelId,
238}
239
240#[derive(Serialize, Deserialize)]
241pub struct PreflightOpenChannelRequest {
242    /// The value of the channel we want to open.
243    pub value: Amount,
244}
245
246#[derive(Debug, Serialize, Deserialize)]
247pub struct PreflightOpenChannelResponse {
248    /// The estimated on-chain fee required to execute the channel open.
249    pub fee_estimate: Amount,
250}
251
252#[derive(Serialize, Deserialize)]
253pub struct CloseChannelRequest {
254    /// The id of the channel we want to close.
255    pub channel_id: LxChannelId,
256    /// Set to true if the channel should be force closed (unilateral).
257    /// Set to false if the channel should be cooperatively closed (bilateral).
258    pub force_close: bool,
259    /// The [`NodePk`] of our counterparty.
260    ///
261    /// If set to [`None`], the counterparty's [`NodePk`] will be determined by
262    /// calling [`list_channels`]. Setting this to [`Some`] allows
263    /// `close_channel` to avoid this relatively expensive [`Vec`] allocation.
264    ///
265    /// [`list_channels`]: lightning::ln::channelmanager::ChannelManager::list_channels
266    pub maybe_counterparty: Option<NodePk>,
267}
268
269pub type PreflightCloseChannelRequest = CloseChannelRequest;
270
271#[derive(Serialize, Deserialize)]
272pub struct PreflightCloseChannelResponse {
273    /// The estimated on-chain fee required to execute the channel close.
274    pub fee_estimate: Amount,
275}
276
277// --- Syncing and updating payments data --- //
278
279/// Upgradeable API struct for a [`PaymentId`].
280#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
281#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
282pub struct PaymentIdStruct {
283    /// The id of the payment to be fetched.
284    pub id: PaymentId,
285}
286
287/// An upgradeable version of [`Vec<PaymentId>`].
288#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
289#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
290pub struct VecPaymentId {
291    pub ids: Vec<PaymentId>,
292}
293
294/// Upgradeable API struct for a payment index.
295#[derive(Debug, PartialEq, Serialize, Deserialize)]
296#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
297pub struct PaymentCreatedIndexStruct {
298    /// The index of the payment to be fetched.
299    pub index: PaymentCreatedIndex,
300}
301
302/// Sync a batch of new payments to local storage.
303/// Results are returned in ascending `(created_at, payment_id)` order.
304#[derive(Debug, PartialEq, Serialize, Deserialize)]
305#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
306pub struct GetNewPayments {
307    /// Optional [`PaymentCreatedIndex`] at which the results should start,
308    /// exclusive. Payments with an index less than or equal to this will
309    /// not be returned.
310    pub start_index: Option<PaymentCreatedIndex>,
311    /// (Optional) the maximum number of results that can be returned.
312    pub limit: Option<u16>,
313}
314
315/// Get a batch of payments in ascending `(updated_at, payment_id)` order.
316#[derive(Debug, PartialEq, Serialize, Deserialize)]
317#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
318pub struct GetUpdatedPayments {
319    /// `(updated_at, id)` index at which the results should start, exclusive.
320    /// Payments with an index less than or equal to this will not be returned.
321    pub start_index: Option<PaymentUpdatedIndex>,
322    /// (Optional) the maximum number of results that can be returned.
323    pub limit: Option<u16>,
324}
325
326/// Get a batch of payment metadata in asc `(updated_at, payment_id)` order.
327#[derive(Debug, PartialEq, Serialize, Deserialize)]
328#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
329pub struct GetUpdatedPaymentMetadata {
330    /// `(updated_at, id)` index at which the results should start, exclusive.
331    /// Metadata with an index less than or equal to this will not be returned.
332    pub start_index: Option<PaymentUpdatedIndex>,
333    /// (Optional) the maximum number of results that can be returned.
334    pub limit: Option<u16>,
335}
336
337/// Upgradeable API struct for a list of [`PaymentCreatedIndex`]s.
338#[derive(Debug, PartialEq, Serialize, Deserialize)]
339#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
340pub struct PaymentCreatedIndexes {
341    /// The string-serialized [`PaymentCreatedIndex`]s of the payments to be
342    /// fetched. Typically, the ids passed here correspond to payments that
343    /// the mobile client currently has stored locally as "pending"; the
344    /// goal is to check whether any of these payments have been updated.
345    pub indexes: Vec<PaymentCreatedIndex>,
346}
347
348/// A request to update the personal note on a payment. Pass `None` to clear.
349#[derive(Clone, Serialize, Deserialize)]
350pub struct UpdatePaymentNote {
351    /// The index of the payment whose note should be updated.
352    // TODO(max): The server side only needs the `PaymentId`.
353    // This API should be changed to pass that instead.
354    pub index: PaymentCreatedIndex,
355    /// The updated note, or `None` to clear.
356    pub note: Option<BoundedString>,
357}
358
359// --- BOLT11 Invoice Payments --- //
360
361#[derive(Default, Serialize, Deserialize)]
362pub struct CreateInvoiceRequest {
363    pub expiry_secs: u32,
364
365    /// The amount to encode into the invoice.
366    pub amount: Option<Amount>,
367
368    /// The description to be encoded into the invoice.
369    ///
370    /// If `None`, the `description` field inside the invoice will be an empty
371    /// string (""), as lightning _requires_ a description (or description
372    /// hash) to be set.
373    /// NOTE: If both `description` and `description_hash` are set, node will
374    /// return an error.
375    pub description: Option<String>,
376
377    /// A 256-bit hash. Commonly a hash of a long description.
378    ///
379    /// This field is used to associate description longer than 639 bytes to
380    /// the invoice. Also known as '`h` tag in BOLT11'.
381    ///
382    /// This field is required to build invoices for the LNURL (LUD06)
383    /// receiving flow. Not used in other flows.
384    /// NOTE: If both `description` and `description_hash` are set, node will
385    /// return an error.
386    pub description_hash: Option<[u8; 32]>,
387
388    /// An optional note from the payer, stored with this inbound payment.
389    /// For LNURL-pay, set from the LUD-12 `comment`.
390    pub payer_note: Option<BoundedString>,
391
392    /// The partner's user_pk, if the partner is setting the fee for this
393    /// payment instead of using Lexe's default fees.
394    ///
395    /// This must be set in order for `partner_prop_fee` and `partner_base_fee`
396    /// to take effect.
397    // Added in `node-v0.9.6`
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    pub partner_pk: Option<UserPk>,
400
401    /// The partner-chosen proportional fee to charge on this payment.
402    /// If `partner_pk` is set, this must be set to [`Some`].
403    ///
404    /// Minimum: 5000 ppm (`LSP_USERNODE_SKIM_FEE_PPM`)
405    /// Maximum: 500,000 ppm (50%)
406    // Added in `node-v0.9.6`
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub partner_prop_fee: Option<Ppm>,
409
410    /// The partner-chosen base fee to charge on this payment.
411    ///
412    /// If this is set, the invoice `amount` must also be set.
413    // Added in `node-v0.9.6`
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub partner_base_fee: Option<Amount>,
416}
417
418#[derive(Serialize, Deserialize)]
419pub struct CreateInvoiceResponse {
420    pub invoice: Invoice,
421    /// The [`PaymentCreatedIndex`] of the newly created invoice payment.
422    ///
423    /// Is always `Some` starting at `node-v0.8.10` and `lsp-v0.8.11`.
424    //
425    // TODO(max): Make non-Option once all servers are sufficiently upgraded.
426    pub created_index: Option<PaymentCreatedIndex>,
427}
428
429#[derive(Serialize, Deserialize)]
430pub struct PayInvoiceRequest {
431    /// The invoice we want to pay.
432    pub invoice: Invoice,
433    /// Specifies the amount we will pay if the invoice to be paid is
434    /// amountless. This field must be [`Some`] for amountless invoices.
435    pub fallback_amount: Option<Amount>,
436    /// An optional personal note for this payment, useful if the
437    /// receiver-provided description is insufficient.
438    pub note: Option<BoundedString>,
439    /// An optional payer note to persist with this outbound payment. For
440    /// LNURL-pay, this is the LUD-12 `comment` sent during invoice
441    /// negotiation.
442    pub payer_note: Option<BoundedString>,
443}
444
445#[derive(Serialize, Deserialize)]
446pub struct PayInvoiceResponse {
447    /// When the node registered this payment.
448    /// Used in the [`PaymentCreatedIndex`].
449    pub created_at: TimestampMs,
450}
451
452#[derive(Serialize, Deserialize)]
453pub struct PreflightPayInvoiceRequest {
454    /// The invoice we want to pay.
455    pub invoice: Invoice,
456    /// Specifies the amount we will pay if the invoice to be paid is
457    /// amountless. This field must be [`Some`] for amountless invoices.
458    pub fallback_amount: Option<Amount>,
459}
460
461#[derive(Serialize, Deserialize)]
462pub struct PreflightPayInvoiceResponse {
463    /// The total amount to-be-paid for the pre-flighted [`Invoice`],
464    /// excluding the fees.
465    ///
466    /// This value may be different from the value originally requested if
467    /// we had to reach `htlc_minimum_msat` for some intermediate hops.
468    pub amount: Amount,
469    /// The total amount of fees to-be-paid for the pre-flighted [`Invoice`].
470    pub fees: Amount,
471    /// The route this invoice will be paid over.
472    // Added in node,lsp-v0.7.8
473    // TODO(max): We don't actually pay over this route.
474    pub route: LxRoute,
475}
476
477// --- BOLT12 Offer payments --- //
478
479#[derive(Default, Serialize, Deserialize)]
480pub struct CreateOfferRequest {
481    /// The description to be encoded into the invoice.
482    ///
483    /// If `None`, the `description` field inside the invoice will be an empty
484    /// string (""), as lightning _requires_ a description to be set.
485    pub description: Option<BoundedString>,
486
487    /// The `min_amount` we're requesting for payments using this offer.
488    ///
489    /// If `None`, the offer is variable amount and the payer can choose any
490    /// value.
491    ///
492    /// If `Some`, the offer amount is lower-bounded and the payer must pay
493    /// this value or higher (per item, see `max_quantity`). The offer amount
494    /// must be a non-zero value if set.
495    // Renamed in node-v0.9.4
496    #[serde(alias = "amount")]
497    pub min_amount: Option<Amount>,
498
499    /// An optional expiration for the offer, in seconds from now.
500    pub expiry_secs: Option<u32>,
501
502    /// The max number of items that can be purchased in any one payment for
503    /// the offer.
504    ///
505    /// NOTE: this is not related to single-use vs reusable offers.
506    ///                                                                        
507    /// The expected amount paid for this offer is `offer.min_amount *
508    /// quantity`, where `offer.min_amount` is the value per item and
509    /// `quantity` is the number of items chosen _by the payer_. The
510    /// payer's chosen `quantity` must be in the range: `0 < quantity <=
511    /// offer.max_quantity`.
512    ///
513    /// If `None`, defaults to `MaxQuantity::ONE`, i.e., the expected paid
514    /// `amount` is just `offer.amount`.
515    pub max_quantity: Option<MaxQuantity>,
516
517    /// The issuer of the offer.
518    ///
519    /// If `Some`, offer will encode the string. Bolt12 spec expects this tring
520    /// to be a domain or a `user@domain` address.
521    /// If `None`, offer issuer will encode "lexe.app" as the issuer.
522    pub issuer: Option<BoundedString>,
523    //
524    // TODO(phlip9): add a `single_use` field to the offer request? right now
525    // all offers are reusable.
526}
527
528#[derive(Serialize, Deserialize)]
529pub struct CreateOfferResponse {
530    pub offer: Offer,
531}
532
533#[derive(Serialize, Deserialize)]
534pub struct PreflightPayOfferRequest {
535    /// The user-provided idempotency id for this payment.
536    pub cid: ClientPaymentId,
537    /// The offer we want to pay.
538    pub offer: Offer,
539    /// Specifies the amount we will pay. If the offer specifies a minimum
540    /// amount, `amount` should satisfy that minimum.
541    // Renamed and made non-optional in node-v0.9.4
542    // The old `fallback_amount = None` is technically valid and incompatible
543    // but rare, due to offers not setting amounts often
544    #[serde(alias = "fallback_amount")]
545    pub amount: Amount,
546}
547
548#[derive(Serialize, Deserialize)]
549pub struct PreflightPayOfferResponse {
550    /// The total amount to-be-paid for the pre-flighted [`Offer`],
551    /// excluding the fees.
552    ///
553    /// This value may be different from the value originally requested if
554    /// we had to reach `htlc_minimum_msat` for some intermediate hops.
555    pub amount: Amount,
556    /// The total amount of fees to-be-paid for the pre-flighted [`Offer`].
557    ///
558    /// Since we only approximate the route atm, we likely underestimate the
559    /// actual fee.
560    pub fees: Amount,
561    /// The route this offer will be paid over.
562    ///
563    /// Because we don't yet fetch the actual BOLT 12 invoice during preflight,
564    /// this route is only an approximation of the final route (we can only
565    /// route to the last public node before the offer's blinded path begins).
566    // Added in node,lsp-v0.7.8
567    // TODO(max): We don't actually pay over this route.
568    pub route: LxRoute,
569}
570
571#[derive(Serialize, Deserialize)]
572pub struct PayOfferRequest {
573    /// The user-provided idempotency id for this payment.
574    pub cid: ClientPaymentId,
575    /// The offer we want to pay.
576    pub offer: Offer,
577    /// Specifies the amount we will pay. If the offer specifies a minimum
578    /// amount, `amount` should satisfy that minimum.
579    // Renamed and made non-optional in node-v0.9.4
580    // The old `fallback_amount = None` is technically valid and incompatible
581    // but rare, due to offers not setting amounts often
582    #[serde(alias = "fallback_amount")]
583    pub amount: Amount,
584    /// An optional personal note for this payment, useful if the
585    /// receiver-provided description is insufficient.
586    pub note: Option<BoundedString>,
587    /// An optional note included in the BOLT12 invoice request and visible to
588    /// the recipient.
589    pub payer_note: Option<BoundedString>,
590}
591
592#[derive(Serialize, Deserialize)]
593pub struct PayOfferResponse {
594    /// When the node registered this payment. Used in the
595    /// [`PaymentCreatedIndex`].
596    pub created_at: TimestampMs,
597}
598
599// --- On-chain payments --- //
600
601#[derive(Debug, PartialEq, Serialize, Deserialize)]
602#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
603pub struct GetAddressResponse {
604    #[cfg_attr(
605        any(test, feature = "test-utils"),
606        proptest(strategy = "arbitrary::any_mainnet_addr_unchecked()")
607    )]
608    pub addr: bitcoin::Address<NetworkUnchecked>,
609}
610
611#[derive(Serialize, Deserialize)]
612#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary, Debug))]
613pub struct PayOnchainRequest {
614    /// The identifier to use for this payment.
615    pub cid: ClientPaymentId,
616    /// The address we want to send funds to.
617    #[cfg_attr(
618        any(test, feature = "test-utils"),
619        proptest(strategy = "arbitrary::any_mainnet_addr_unchecked()")
620    )]
621    pub address: bitcoin::Address<NetworkUnchecked>,
622    /// How much Bitcoin we want to send.
623    pub amount: Amount,
624    /// How quickly we want our transaction to be confirmed.
625    /// The higher the priority, the more fees we will pay.
626    // See LexeEsplora for the conversion to the target number of blocks
627    pub priority: ConfirmationPriority,
628    /// An optional personal note for this payment.
629    pub note: Option<BoundedString>,
630}
631
632#[derive(Serialize, Deserialize)]
633pub struct PayOnchainResponse {
634    /// When the node registered this payment. Used in the
635    /// [`PaymentCreatedIndex`].
636    pub created_at: TimestampMs,
637    /// The Bitcoin txid for the transaction we just submitted to the mempool.
638    pub txid: Txid,
639}
640
641#[derive(Debug, PartialEq, Serialize, Deserialize)]
642pub struct PreflightPayOnchainRequest {
643    /// The address we want to send funds to.
644    pub address: bitcoin::Address<NetworkUnchecked>,
645    /// How much Bitcoin we want to send.
646    pub amount: Amount,
647}
648
649#[derive(Serialize, Deserialize)]
650pub struct PreflightPayOnchainResponse {
651    /// Corresponds with [`ConfirmationPriority::High`]
652    ///
653    /// The high estimate is optional--we don't want to block the user from
654    /// sending if they only have enough for a normal tx fee.
655    pub high: Option<FeeEstimate>,
656    /// Corresponds with [`ConfirmationPriority::Normal`]
657    pub normal: FeeEstimate,
658    /// Corresponds with [`ConfirmationPriority::Background`]
659    pub background: FeeEstimate,
660}
661
662#[derive(Serialize, Deserialize)]
663pub struct FeeEstimate {
664    /// The fee amount estimate.
665    pub amount: Amount,
666}
667
668// --- Sync --- //
669
670#[derive(Serialize, Deserialize)]
671pub struct ResyncRequest {
672    /// If true, the LSP will full sync the BDK wallet and do a normal LDK
673    /// sync.
674    pub full_sync: bool,
675}
676
677// --- Username --- //
678
679/// Creates or updates a human Bitcoin address.
680#[derive(Debug, PartialEq, Serialize, Deserialize)]
681#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
682pub struct UpdateHumanBitcoinAddress {
683    /// Username for BIP-353 and LNURL.
684    pub username: Username,
685    /// Offer to be used to fetch invoices on BIP-353.
686    pub offer: Offer,
687}
688
689/// Claims a generated human Bitcoin address.
690///
691/// This endpoint is used during node initialization to claim an auto-generated
692/// human Bitcoin address. The address will have `is_primary: false` and
693/// `is_generated: true`.
694#[derive(Debug, PartialEq, Serialize, Deserialize)]
695#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
696pub struct ClaimGeneratedHumanBitcoinAddress {
697    /// Offer to be used to fetch invoices on BIP-353.
698    pub offer: Offer,
699    /// The username to claim. This must be the username returned by
700    /// `get_generated_username`.
701    pub username: Username,
702}
703
704/// Response for `get_generated_username` endpoint.
705#[derive(Debug, PartialEq, Serialize, Deserialize)]
706#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
707pub struct GetGeneratedUsernameResponse {
708    /// The generated username that can be used for claiming an HBA.
709    pub username: Username,
710    /// Whether this user already has a claimed generated HBA.
711    /// If true, the caller should skip calling
712    /// `claim_generated_human_bitcoin_address`.
713    pub already_claimed: bool,
714}
715
716#[derive(Debug, PartialEq, Serialize, Deserialize)]
717#[cfg_attr(any(test, feature = "test-utils"), derive(Arbitrary))]
718pub struct HumanBitcoinAddress {
719    /// Current username for BIP-353 and LNURL.
720    pub username: Option<Username>,
721    /// Current offer for fetching invoices on BIP-353.
722    pub offer: Option<Offer>,
723    /// Last time the human Bitcoin address was updated.
724    pub updated_at: Option<TimestampMs>,
725    /// Whether the human Bitcoin address can be updated. Always `true` for
726    /// generated addresses; for claimed addresses, depends on time-based
727    /// freeze rules.
728    pub updatable: bool,
729}
730
731#[cfg(any(test, feature = "test-utils"))]
732mod arbitrary_impl {
733    use proptest::{
734        arbitrary::{Arbitrary, any},
735        strategy::{BoxedStrategy, Strategy},
736    };
737
738    use super::*;
739
740    impl Arbitrary for PreflightPayOnchainRequest {
741        type Parameters = ();
742        type Strategy = BoxedStrategy<Self>;
743
744        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
745            (arbitrary::any_mainnet_addr_unchecked(), any::<Amount>())
746                .prop_map(|(address, amount)| Self { address, amount })
747                .boxed()
748        }
749    }
750}
751
752#[cfg(test)]
753mod test {
754    use std::str::FromStr;
755
756    use lexe_common::test_utils::roundtrip;
757
758    use super::*;
759
760    #[test]
761    fn preflight_pay_onchain_roundtrip() {
762        roundtrip::query_string_roundtrip_proptest::<PreflightPayOnchainRequest>(
763        );
764    }
765
766    #[test]
767    fn payment_id_struct_roundtrip() {
768        roundtrip::query_string_roundtrip_proptest::<PaymentIdStruct>();
769    }
770
771    #[test]
772    fn payment_index_struct_roundtrip() {
773        roundtrip::query_string_roundtrip_proptest::<PaymentCreatedIndexStruct>(
774        );
775    }
776
777    #[test]
778    fn get_new_payments_roundtrip() {
779        roundtrip::query_string_roundtrip_proptest::<GetNewPayments>();
780    }
781
782    #[test]
783    fn payment_indexes_roundtrip() {
784        // This is serialized as JSON, not query strings.
785        roundtrip::json_value_roundtrip_proptest::<PaymentCreatedIndexes>();
786    }
787
788    #[test]
789    fn get_address_response_roundtrip() {
790        roundtrip::json_value_roundtrip_proptest::<GetAddressResponse>();
791    }
792
793    #[test]
794    fn setup_gdrive_request_roundtrip() {
795        roundtrip::json_string_roundtrip_proptest::<SetupGDrive>();
796    }
797
798    #[test]
799    fn human_bitcoin_address_request_roundtrip() {
800        roundtrip::json_value_roundtrip_proptest::<UpdateHumanBitcoinAddress>();
801    }
802
803    #[test]
804    fn claim_generated_human_bitcoin_address_request_roundtrip() {
805        roundtrip::json_value_roundtrip_proptest::<
806            ClaimGeneratedHumanBitcoinAddress,
807        >();
808    }
809
810    #[test]
811    fn get_generated_username_response_roundtrip() {
812        roundtrip::json_value_roundtrip_proptest::<GetGeneratedUsernameResponse>(
813        );
814    }
815
816    #[test]
817    fn human_bitcoin_address_response_roundtrip() {
818        roundtrip::json_value_roundtrip_proptest::<HumanBitcoinAddress>();
819    }
820
821    /// Sanity check the `DebugInfo` serialization against a hard-coded string.
822    #[test]
823    fn debug_info_serialization() {
824        // Account-level xpub (from BDK tests)
825        let account_xpub = Xpub::from_str(
826            "xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA"
827        ).unwrap();
828
829        // Descriptors with real checksums (computed via miniscript)
830        let descriptor = "wpkh([be83839f/84'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/<0;1>/*)#c8v4zjyh".to_owned();
831        let external_descriptor = "wpkh([be83839f/84'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/0/*)#dwvchw0k".to_owned();
832        let internal_descriptor = "wpkh([be83839f/84'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/1/*)#u6fe2mlw".to_owned();
833
834        let debug_info = DebugInfo {
835            descriptors: OnchainDescriptors {
836                multipath_descriptor: descriptor.clone(),
837                external_descriptor: external_descriptor.clone(),
838                internal_descriptor: internal_descriptor.clone(),
839                account_xpub,
840            },
841            legacy_descriptors: None,
842            num_utxos: 5,
843            num_confirmed_utxos: 3,
844            num_unconfirmed_utxos: 2,
845            pending_monitor_updates: Some(0),
846        };
847
848        // Serialize and check against expected JSON.
849        // NOTE: Do NOT remove this raw string check. We're sanity-checking how
850        // it looks in serialized form.
851        let json = serde_json::to_string_pretty(&debug_info).unwrap();
852        let expected = r#"{
853  "descriptors": {
854    "multipath_descriptor": "wpkh([be83839f/84'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/<0;1>/*)#c8v4zjyh",
855    "external_descriptor": "wpkh([be83839f/84'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/0/*)#dwvchw0k",
856    "internal_descriptor": "wpkh([be83839f/84'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/1/*)#u6fe2mlw",
857    "account_xpub": "xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA"
858  },
859  "num_utxos": 5,
860  "num_confirmed_utxos": 3,
861  "num_unconfirmed_utxos": 2,
862  "pending_monitor_updates": 0
863}"#;
864        assert_eq!(json, expected);
865
866        // Verify deserialization roundtrips
867        let back: DebugInfo = serde_json::from_str(&json).unwrap();
868        assert_eq!(back.num_utxos, 5);
869        assert_eq!(back.num_confirmed_utxos, 3);
870        assert_eq!(back.num_unconfirmed_utxos, 2);
871        assert_eq!(back.descriptors.multipath_descriptor, descriptor);
872        assert_eq!(back.descriptors.external_descriptor, external_descriptor);
873        assert_eq!(back.descriptors.internal_descriptor, internal_descriptor);
874        assert_eq!(
875            back.descriptors.account_xpub,
876            debug_info.descriptors.account_xpub
877        );
878        assert!(back.legacy_descriptors.is_none());
879        assert_eq!(back.pending_monitor_updates, Some(0));
880    }
881}