Skip to main content

fedimint_client_module/transaction/
builder.rs

1use std::fmt;
2use std::future::Future;
3use std::ops::RangeInclusive;
4use std::sync::Arc;
5
6use bitcoin::key::Keypair;
7use bitcoin::secp256k1;
8use fedimint_core::Amount;
9use fedimint_core::core::{
10    Account, DynInput, DynOutput, IInput, IOutput, IntoDynInstance, ModuleInstanceId,
11};
12use fedimint_core::encoding::{Decodable, Encodable};
13use fedimint_core::module::Amounts;
14use fedimint_core::task::{MaybeSend, MaybeSync};
15use fedimint_core::transaction::{Transaction, TransactionSignature};
16use fedimint_logging::LOG_CLIENT;
17use itertools::multiunzip;
18use rand::{CryptoRng, Rng, RngCore};
19use secp256k1::Secp256k1;
20use tracing::warn;
21
22use crate::error::TransactionSubmitError;
23use crate::module::{IdxRange, OutPointRange, StateGenerator};
24use crate::sm::{self, DynState};
25use crate::{
26    InstancelessDynClientInput, InstancelessDynClientInputBundle, InstancelessDynClientInputSM,
27    InstancelessDynClientOutput, InstancelessDynClientOutputBundle, InstancelessDynClientOutputSM,
28    states_add_instance, states_to_instanceless_dyn,
29};
30
31#[derive(Clone, Debug)]
32pub struct ClientInput<I = DynInput> {
33    pub input: I,
34    pub keys: Vec<Keypair>,
35    pub amounts: Amounts,
36}
37
38#[derive(Clone)]
39pub struct ClientInputSM<S = DynState> {
40    pub state_machines: StateGenerator<S>,
41}
42
43impl<S> fmt::Debug for ClientInputSM<S> {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str("ClientInputSM")
46    }
47}
48
49/// A fake [`sm::Context`] for [`NeverClientStateMachine`]
50#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
51pub enum NeverClientContext {}
52
53impl sm::Context for NeverClientContext {
54    const KIND: Option<fedimint_core::core::ModuleKind> = None;
55}
56
57/// A fake [`sm::State`] that can actually never happen.
58///
59/// Useful as a default for type inference in cases where there are no
60/// state machines involved in [`ClientInputBundle`].
61#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
62pub enum NeverClientStateMachine {}
63
64impl IntoDynInstance for NeverClientStateMachine {
65    type DynType = DynState;
66
67    fn into_dyn(self, _instance_id: ModuleInstanceId) -> Self::DynType {
68        unreachable!()
69    }
70}
71impl sm::State for NeverClientStateMachine {
72    type ModuleContext = NeverClientContext;
73
74    fn transitions(
75        &self,
76        _context: &Self::ModuleContext,
77        _global_context: &crate::DynGlobalClientContext,
78    ) -> Vec<sm::StateTransition<Self>> {
79        unreachable!()
80    }
81
82    fn operation_id(&self) -> fedimint_core::core::OperationId {
83        unreachable!()
84    }
85}
86
87/// A group of inputs and state machines responsible for driving their state
88///
89/// These must be kept together as a whole when including in a transaction.
90#[derive(Clone, Debug)]
91pub struct ClientInputBundle<I = DynInput, S = DynState> {
92    pub(crate) inputs: Vec<ClientInput<I>>,
93    pub(crate) sm_gens: Vec<ClientInputSM<S>>,
94}
95
96impl<I> ClientInputBundle<I, NeverClientStateMachine> {
97    /// A version of [`Self::new`] for times where input does not require any
98    /// state machines
99    ///
100    /// This avoids type inference issues of `S`, and saves some typing.
101    pub fn new_no_sm(inputs: Vec<ClientInput<I>>) -> Self {
102        if inputs.is_empty() {
103            // TODO: Make it return Result or assert?
104            warn!(target: LOG_CLIENT, "Empty input bundle will be illegal in the future");
105        }
106        Self {
107            inputs,
108            sm_gens: vec![],
109        }
110    }
111}
112
113impl<I, S> ClientInputBundle<I, S>
114where
115    I: IInput + MaybeSend + MaybeSync + 'static,
116    S: sm::IState + MaybeSend + MaybeSync + 'static,
117{
118    pub fn new(inputs: Vec<ClientInput<I>>, sm_gens: Vec<ClientInputSM<S>>) -> Self {
119        Self { inputs, sm_gens }
120    }
121
122    pub fn sms(&self) -> &[ClientInputSM<S>] {
123        &self.sm_gens
124    }
125
126    pub fn into_instanceless(self) -> InstancelessDynClientInputBundle {
127        InstancelessDynClientInputBundle {
128            inputs: self
129                .inputs
130                .into_iter()
131                .map(|input| InstancelessDynClientInput {
132                    input: Box::new(input.input),
133                    keys: input.keys,
134                    amounts: input.amounts,
135                })
136                .collect(),
137            sm_gens: self
138                .sm_gens
139                .into_iter()
140                .map(|input_sm| InstancelessDynClientInputSM {
141                    state_machines: states_to_instanceless_dyn(input_sm.state_machines),
142                })
143                .collect(),
144        }
145    }
146}
147
148impl<I, S> ClientInputBundle<I, S> {
149    pub fn inputs(&self) -> &[ClientInput<I>] {
150        &self.inputs
151    }
152
153    pub fn is_empty(&self) -> bool {
154        // Notably, sm_gen will not be called when inputs are empty anyway
155        self.inputs.is_empty()
156    }
157}
158
159impl<I> IntoDynInstance for ClientInput<I>
160where
161    I: IntoDynInstance<DynType = DynInput> + 'static,
162{
163    type DynType = ClientInput;
164
165    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientInput {
166        ClientInput {
167            input: self.input.into_dyn(module_instance_id),
168            keys: self.keys,
169            amounts: self.amounts,
170        }
171    }
172}
173
174impl<S> IntoDynInstance for ClientInputSM<S>
175where
176    S: IntoDynInstance<DynType = DynState> + 'static,
177{
178    type DynType = ClientInputSM;
179
180    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientInputSM {
181        ClientInputSM {
182            state_machines: state_gen_to_dyn(self.state_machines, module_instance_id),
183        }
184    }
185}
186
187impl<I, S> IntoDynInstance for ClientInputBundle<I, S>
188where
189    I: IntoDynInstance<DynType = DynInput> + 'static,
190    S: IntoDynInstance<DynType = DynState> + 'static,
191{
192    type DynType = ClientInputBundle;
193
194    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientInputBundle {
195        ClientInputBundle {
196            inputs: self
197                .inputs
198                .into_iter()
199                .map(|input| input.into_dyn(module_instance_id))
200                .collect::<Vec<ClientInput>>(),
201
202            sm_gens: self
203                .sm_gens
204                .into_iter()
205                .map(|input_sm| input_sm.into_dyn(module_instance_id))
206                .collect::<Vec<ClientInputSM>>(),
207        }
208    }
209}
210
211impl IntoDynInstance for InstancelessDynClientInputBundle {
212    type DynType = ClientInputBundle;
213
214    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientInputBundle {
215        ClientInputBundle {
216            inputs: self
217                .inputs
218                .into_iter()
219                .map(|input| ClientInput {
220                    input: DynInput::from_parts(module_instance_id, input.input),
221                    keys: input.keys,
222                    amounts: input.amounts,
223                })
224                .collect::<Vec<ClientInput>>(),
225
226            sm_gens: self
227                .sm_gens
228                .into_iter()
229                .map(|input_sm| ClientInputSM {
230                    state_machines: states_add_instance(
231                        module_instance_id,
232                        input_sm.state_machines,
233                    ),
234                })
235                .collect::<Vec<ClientInputSM>>(),
236        }
237    }
238}
239
240#[derive(Clone, Debug)]
241pub struct ClientOutputBundle<O = DynOutput, S = DynState> {
242    pub(crate) outputs: Vec<ClientOutput<O>>,
243    pub(crate) sm_gens: Vec<ClientOutputSM<S>>,
244}
245
246#[derive(Clone, Debug)]
247pub struct ClientOutput<O = DynOutput> {
248    pub output: O,
249    pub amounts: Amounts,
250}
251
252#[derive(Clone)]
253pub struct ClientOutputSM<S = DynState> {
254    pub state_machines: StateGenerator<S>,
255}
256
257impl<S> fmt::Debug for ClientOutputSM<S> {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.write_str("ClientOutputSM")
260    }
261}
262impl<O> ClientOutputBundle<O, NeverClientStateMachine> {
263    /// A version of [`Self::new`] for times where output does not require any
264    /// state machines
265    ///
266    /// This avoids type inference issues of `S`, and saves some typing.
267    pub fn new_no_sm(outputs: Vec<ClientOutput<O>>) -> Self {
268        if outputs.is_empty() {
269            // TODO: Make it return Result or assert?
270            warn!(target: LOG_CLIENT, "Empty output bundle will be illegal in the future");
271        }
272        Self {
273            outputs,
274            sm_gens: vec![],
275        }
276    }
277}
278impl<O, S> ClientOutputBundle<O, S> {
279    pub fn outputs(&self) -> &[ClientOutput<O>] {
280        &self.outputs
281    }
282}
283
284impl<O, S> ClientOutputBundle<O, S>
285where
286    O: IOutput + MaybeSend + MaybeSync + 'static,
287    S: sm::IState + MaybeSend + MaybeSync + 'static,
288{
289    pub fn new(outputs: Vec<ClientOutput<O>>, sm_gens: Vec<ClientOutputSM<S>>) -> Self {
290        Self { outputs, sm_gens }
291    }
292
293    pub fn sms(&self) -> &[ClientOutputSM<S>] {
294        &self.sm_gens
295    }
296
297    pub fn with(mut self, other: Self) -> Self {
298        self.outputs.extend(other.outputs);
299        self.sm_gens.extend(other.sm_gens);
300        self
301    }
302
303    pub fn into_instanceless(self) -> InstancelessDynClientOutputBundle {
304        InstancelessDynClientOutputBundle {
305            outputs: self
306                .outputs
307                .into_iter()
308                .map(|output| InstancelessDynClientOutput {
309                    output: Box::new(output.output),
310                    amounts: output.amounts,
311                })
312                .collect(),
313            sm_gens: self
314                .sm_gens
315                .into_iter()
316                .map(|output_sm| InstancelessDynClientOutputSM {
317                    state_machines: states_to_instanceless_dyn(output_sm.state_machines),
318                })
319                .collect(),
320        }
321    }
322}
323
324impl<O, S> ClientOutputBundle<O, S> {
325    pub fn is_empty(&self) -> bool {
326        // Notably, sm_gen will not be called when outputs are empty anyway
327        self.outputs.is_empty()
328    }
329}
330
331impl<I, S> IntoDynInstance for ClientOutputBundle<I, S>
332where
333    I: IntoDynInstance<DynType = DynOutput> + 'static,
334    S: IntoDynInstance<DynType = DynState> + 'static,
335{
336    type DynType = ClientOutputBundle;
337
338    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientOutputBundle {
339        ClientOutputBundle {
340            outputs: self
341                .outputs
342                .into_iter()
343                .map(|output| output.into_dyn(module_instance_id))
344                .collect::<Vec<ClientOutput>>(),
345
346            sm_gens: self
347                .sm_gens
348                .into_iter()
349                .map(|output_sm| output_sm.into_dyn(module_instance_id))
350                .collect::<Vec<ClientOutputSM>>(),
351        }
352    }
353}
354
355impl IntoDynInstance for InstancelessDynClientOutputBundle {
356    type DynType = ClientOutputBundle;
357
358    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientOutputBundle {
359        ClientOutputBundle {
360            outputs: self
361                .outputs
362                .into_iter()
363                .map(|output| ClientOutput {
364                    output: DynOutput::from_parts(module_instance_id, output.output),
365                    amounts: output.amounts,
366                })
367                .collect::<Vec<ClientOutput>>(),
368
369            sm_gens: self
370                .sm_gens
371                .into_iter()
372                .map(|output_sm| ClientOutputSM {
373                    state_machines: states_add_instance(
374                        module_instance_id,
375                        output_sm.state_machines,
376                    ),
377                })
378                .collect::<Vec<ClientOutputSM>>(),
379        }
380    }
381}
382
383impl<I> IntoDynInstance for ClientOutput<I>
384where
385    I: IntoDynInstance<DynType = DynOutput> + 'static,
386{
387    type DynType = ClientOutput;
388
389    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientOutput {
390        ClientOutput {
391            output: self.output.into_dyn(module_instance_id),
392            amounts: self.amounts,
393        }
394    }
395}
396
397impl<S> IntoDynInstance for ClientOutputSM<S>
398where
399    S: IntoDynInstance<DynType = DynState> + 'static,
400{
401    type DynType = ClientOutputSM;
402
403    fn into_dyn(self, module_instance_id: ModuleInstanceId) -> ClientOutputSM {
404        ClientOutputSM {
405            state_machines: state_gen_to_dyn(self.state_machines, module_instance_id),
406        }
407    }
408}
409
410/// The explicit (operation-supplied) side of a transaction, summarized for a
411/// fee quote via `Client::fee_quote`.
412///
413/// A module describes the inputs and outputs its operation would contribute by
414/// their gross value and federation fees (per unit), rather than building the
415/// actual transaction. The primary module for each affected unit then balances
416/// the resulting imbalance with change, and the full breakdown is returned as a
417/// [`FeeQuote`]. This avoids fabricating real inputs/outputs (which may require
418/// cryptographic material not available when quoting), since fees depend only
419/// on amounts and module.
420///
421/// All four fields are multi-unit [`Amounts`], so an operation can describe
422/// explicit items spanning several units (e.g. Bitcoin plus a custom currency);
423/// each unit is then balanced independently by its own primary module, the same
424/// way `Client::finalize_transaction` does.
425///
426/// For a typical receive there are no explicit outputs, so `output_amount` and
427/// `output_fee` are [`Amounts::ZERO`].
428#[derive(Debug, Clone, PartialEq, Eq)]
429pub struct FeeQuoteRequest {
430    /// Gross value of the operation's explicit inputs, per unit.
431    pub input_amount: Amounts,
432    /// Gross value of the operation's explicit outputs, per unit.
433    pub output_amount: Amounts,
434    /// Federation fees charged on the operation's explicit inputs, per unit.
435    pub input_fee: Amounts,
436    /// Federation fees charged on the operation's explicit outputs, per unit.
437    pub output_fee: Amounts,
438    /// Balance the primary module would fund the operation from. The quote
439    /// runs the real balancing against that account's inventory, so it moves
440    /// with the account it names.
441    pub account: Account,
442}
443
444/// Breakdown of the fee finalizing a transaction would incur, as computed by
445/// `Client::fee_quote` (a dry-run of the same balancing the real submission
446/// performs).
447///
448/// This is module-agnostic: the explicit inputs/outputs are described by the
449/// [`FeeQuoteRequest`] from whichever module is quoting (mint, lightning,
450/// wallet, …) and the change is generated by the primary module. The quote is
451/// point-in-time: it depends on the client's current inventory and can move as
452/// funds change.
453///
454/// Each field is a multi-unit [`Amounts`], since the quoted operation may span
455/// several units. The total fee is the sum of the breakdown fields, available
456/// via [`FeeQuote::total`].
457#[derive(Debug, Clone, PartialEq, Eq)]
458pub struct FeeQuote {
459    /// Federation fees charged on the spent (input) items — both the
460    /// transaction's explicit inputs and any inputs the primary module pulls in
461    /// to balance it.
462    pub input: Amounts,
463    /// Federation fees charged on the created (output) items — both the
464    /// transaction's explicit outputs and the change minted to balance it.
465    pub output: Amounts,
466    /// Sub-denomination remainder that cannot form an output and is lost.
467    pub dust: Amounts,
468}
469
470impl FeeQuote {
471    /// A zero fee, for operations that incur no cost at all — e.g. an ecash
472    /// send served entirely from existing exact-change notes, which submits
473    /// no transaction.
474    pub const ZERO: Self = Self {
475        input: Amounts::ZERO,
476        output: Amounts::ZERO,
477        dust: Amounts::ZERO,
478    };
479
480    /// Total fee per unit: everything the gross input value does not become a
481    /// net wallet gain. Equal to `input + output + dust`.
482    pub fn total(&self) -> Amounts {
483        self.input
484            .clone()
485            .checked_add(&self.output)
486            .and_then(|sum| sum.checked_add(&self.dust))
487            .expect("aggregate fee components cannot overflow an Amounts")
488    }
489}
490
491/// Finds the largest send amount payable in full out of `balance` when the
492/// payment carries both an *external* per-amount fee (e.g. a Lightning gateway
493/// routing fee) and the on-federation transaction fee.
494///
495/// Sending an amount `x` requires funding a value `gross_up(x)` on the
496/// federation — the external fee grosses the amount up, e.g. the outgoing
497/// Lightning contract is `x + gateway_fee(x)` — and funding that value costs an
498/// additional federation fee reported by `fee_quote` (the module's output fee
499/// plus the primary module's funding input fees, change output fees and dust).
500/// This returns the largest `x` in `min_amount..=max_amount` satisfying
501///
502/// ```text
503/// gross_up(x) + fee_quote(gross_up(x)).total().get_bitcoin() <= balance
504/// ```
505///
506/// or `Ok(None)` if even `min_amount` is unaffordable.
507///
508/// The cost is not a closed form of `x`: the federation fee is charged per
509/// note, so note selection, denomination rounding, change and dust move it in
510/// steps as `x` crosses thresholds. Rather than invert an analytic formula this
511/// evaluates the real quote via a monotonic binary search — each step a single,
512/// non-committing `fee_quote` dry-run over the current inventory — and only
513/// ever advances the lower bound to a verified-affordable amount, so the result
514/// never overestimates. An `InsufficientFunds` quote counts as unaffordable;
515/// any other quote failure is returned to the caller (a database or federation
516/// failure will not get better by probing a smaller amount, so the search
517/// aborts on the first one instead).
518///
519/// To keep those dry-runs cheap the search is *seeded near the top*: a first
520/// pass binary-searches `gross_up` alone (pure arithmetic, no quotes) for the
521/// largest fundable amount, peeling off the gateway fee for free, so the real
522/// fee quotes only probe the small window the federation fee leaves — a handful
523/// of dry-runs rather than one per bit of the balance.
524///
525/// The LNv2 and LNv1 send-all flows share this solver; they differ only in
526/// `gross_up` (the gateway fee model) and which `fee_quote` they pass.
527pub async fn max_affordable_send_amount<GrossUp, Quote, Fut>(
528    balance: Amount,
529    min_amount: Amount,
530    max_amount: Amount,
531    gross_up: GrossUp,
532    fee_quote: Quote,
533) -> Result<Option<Amount>, TransactionSubmitError>
534where
535    GrossUp: Fn(Amount) -> Amount,
536    Quote: Fn(Amount) -> Fut,
537    Fut: Future<Output = Result<FeeQuote, TransactionSubmitError>>,
538{
539    // Nothing above the balance can ever be funded, so cap the upper bound.
540    let hi_bound = max_amount.msats.min(balance.msats);
541    let lo_bound = min_amount.msats;
542
543    if hi_bound < lo_bound {
544        return Ok(None);
545    }
546
547    // The maximum is never near the bottom of `[lo_bound, hi_bound]`: it sits
548    // just below the largest amount the balance can *fund*, short by only the
549    // federation fee. `gross_up` is a pure, cheap function (no fee quote), so
550    // binary-search it for free to find that fundable ceiling and seed the real
551    // (fee-quoting) search there. This peels off the gateway fee — usually the
552    // larger of the two — for free, leaving the expensive quotes to probe only
553    // the small window the federation fee opens up, instead of the whole balance.
554    if gross_up(Amount::from_msats(lo_bound)).msats > balance.msats {
555        // The balance can't even fund the smallest amount's gross-up.
556        return Ok(None);
557    }
558    let fundable_max = {
559        let mut lo = lo_bound;
560        let mut hi = hi_bound;
561        while lo < hi {
562            let mid = lo + (hi - lo).div_ceil(2);
563            if gross_up(Amount::from_msats(mid)).msats <= balance.msats {
564                lo = mid;
565            } else {
566                hi = mid - 1;
567            }
568        }
569        lo
570    };
571
572    let mut lo = lo_bound;
573    let mut hi = fundable_max;
574    let mut lo_affordable = false;
575
576    // Probe the fee once at `fundable_max`. The send overhead (the gross-up plus
577    // the federation fee, less the amount) is monotone non-decreasing, so the
578    // overhead here is an upper bound on the overhead at the true maximum, and
579    // `balance - overhead` is therefore a proven-affordable, tight lower bound.
580    // If the quote reports `InsufficientFunds` — real note selection can't fund
581    // a value this large — the seed is skipped and the search falls back to the
582    // full bracket below. Any other failure is fatal and returned immediately.
583    let funded = gross_up(Amount::from_msats(fundable_max));
584    match fee_quote(funded).await {
585        Ok(quote) => {
586            let total = funded
587                .msats
588                .saturating_add(quote.total().get_bitcoin().msats);
589            if total <= balance.msats {
590                // Even the largest fundable amount fits once the fee is included.
591                return Ok(Some(Amount::from_msats(fundable_max)));
592            }
593            let overhead = total.saturating_sub(fundable_max);
594            let seed = balance
595                .msats
596                .saturating_sub(overhead)
597                .clamp(lo_bound, fundable_max);
598            if send_amount_affordable(Amount::from_msats(seed), balance, &gross_up, &fee_quote)
599                .await?
600            {
601                lo = seed;
602                lo_affordable = true;
603            }
604        }
605        Err(e) if e.is_insufficient_funds() => {}
606        Err(e) => return Err(e),
607    }
608
609    // Without a usable seed the search must still start from a verified
610    // affordable lower bound, or give up if even `lo_bound` is unaffordable.
611    if !lo_affordable
612        && !send_amount_affordable(Amount::from_msats(lo_bound), balance, &gross_up, &fee_quote)
613            .await?
614    {
615        return Ok(None);
616    }
617
618    // Exact maximum within the (now tight) `[lo, hi]` bracket.
619    while lo < hi {
620        // Bias the midpoint up so the search converges toward `hi`.
621        let mid = lo + (hi - lo).div_ceil(2);
622
623        if send_amount_affordable(Amount::from_msats(mid), balance, &gross_up, &fee_quote).await? {
624            lo = mid;
625        } else {
626            hi = mid - 1;
627        }
628    }
629
630    Ok(Some(Amount::from_msats(lo)))
631}
632
633/// Whether sending `amount` is payable in full out of `balance`: the funded
634/// value `gross_up(amount)` plus its federation `fee_quote` must fit within the
635/// balance. An `InsufficientFunds` quote counts as unaffordable, making this
636/// safe as the monotone predicate for [`max_affordable_send_amount`]; any other
637/// quote failure is propagated, since it will not get better by probing a
638/// smaller amount.
639async fn send_amount_affordable<GrossUp, Quote, Fut>(
640    amount: Amount,
641    balance: Amount,
642    gross_up: &GrossUp,
643    fee_quote: &Quote,
644) -> Result<bool, TransactionSubmitError>
645where
646    GrossUp: Fn(Amount) -> Amount,
647    Quote: Fn(Amount) -> Fut,
648    Fut: Future<Output = Result<FeeQuote, TransactionSubmitError>>,
649{
650    let funded_amount = gross_up(amount);
651
652    if balance < funded_amount {
653        return Ok(false);
654    }
655
656    match fee_quote(funded_amount).await {
657        Ok(quote) => Ok(funded_amount + quote.total().get_bitcoin() <= balance),
658        Err(e) if e.is_insufficient_funds() => Ok(false),
659        Err(e) => Err(e),
660    }
661}
662
663#[derive(Clone, Debug)]
664pub struct TransactionBuilder {
665    inputs: Vec<ClientInputBundle>,
666    outputs: Vec<ClientOutputBundle>,
667    account: Account,
668}
669
670impl TransactionBuilder {
671    /// A transaction acting on `account`: the primary module funds it from
672    /// that account's balance and credits its change back to the same one.
673    ///
674    /// Taken rather than defaulted, so a module that forgets to thread an
675    /// account through fails to compile instead of quietly spending the
676    /// primary balance.
677    pub fn new(account: Account) -> Self {
678        Self {
679            inputs: Vec::new(),
680            outputs: Vec::new(),
681            account,
682        }
683    }
684
685    /// The account the primary module funds this transaction from and credits
686    /// its change to.
687    pub fn account(&self) -> Account {
688        self.account
689    }
690
691    pub fn with_inputs(mut self, inputs: ClientInputBundle) -> Self {
692        self.inputs.push(inputs);
693        self
694    }
695
696    pub fn with_outputs(mut self, outputs: ClientOutputBundle) -> Self {
697        self.outputs.push(outputs);
698        self
699    }
700
701    pub fn build<C, R: RngCore + CryptoRng>(
702        self,
703        secp_ctx: &Secp256k1<C>,
704        mut rng: R,
705    ) -> (Transaction, Vec<DynState>)
706    where
707        C: secp256k1::Signing + secp256k1::Verification,
708    {
709        // `input_idx_to_bundle_idx[input_idx]` stores the index of a bundle the input
710        // at `input_idx` comes from, so we can call state machines of the
711        // corresponding bundle for every input bundle. It is always
712        // monotonically increasing, e.g. `[0, 0, 1, 2, 2, 2, 4]`
713        let (input_idx_to_bundle_idx, inputs, input_keys): (Vec<_>, Vec<_>, Vec<_>) = multiunzip(
714            self.inputs
715                .iter()
716                .enumerate()
717                .flat_map(|(bundle_idx, bundle)| {
718                    bundle
719                        .inputs
720                        .iter()
721                        .map(move |input| (bundle_idx, input.input.clone(), input.keys.clone()))
722                }),
723        );
724        // `output_idx_to_bundle` works exactly like `input_idx_to_bundle_idx` above,
725        // but for outputs.
726        let (output_idx_to_bundle_idx, outputs): (Vec<_>, Vec<_>) = multiunzip(
727            self.outputs
728                .iter()
729                .enumerate()
730                .flat_map(|(bundle_idx, bundle)| {
731                    bundle
732                        .outputs
733                        .iter()
734                        .map(move |output| (bundle_idx, output.output.clone()))
735                }),
736        );
737        let nonce: [u8; 8] = rng.r#gen();
738
739        let txid = Transaction::tx_hash_from_parts(&inputs, &outputs, nonce);
740        let msg = secp256k1::Message::from_digest_slice(&txid[..]).expect("txid has right length");
741
742        let signatures = input_keys
743            .iter()
744            .flatten()
745            .map(|keypair| secp_ctx.sign_schnorr(&msg, keypair))
746            .collect();
747
748        let transaction = Transaction {
749            inputs,
750            outputs,
751            nonce,
752            signatures: TransactionSignature::NaiveMultisig(signatures),
753        };
754
755        let input_states = self
756            .inputs
757            .into_iter()
758            .enumerate()
759            .filter(|(_, bundle)| !bundle.is_empty())
760            .flat_map(|(bundle_idx, bundle)| {
761                let input_idxs = find_range_of_matching_items(&input_idx_to_bundle_idx, bundle_idx)
762                    .expect("Non empty bundles must always have a match");
763                bundle.sm_gens.into_iter().flat_map(move |sm| {
764                    (sm.state_machines)(OutPointRange::new(
765                        txid,
766                        IdxRange::from_inclusive(input_idxs.clone()).expect("can't overflow"),
767                    ))
768                })
769            });
770
771        let output_states = self
772            .outputs
773            .into_iter()
774            .enumerate()
775            .filter(|(_, bundle)| !bundle.is_empty())
776            .flat_map(|(bundle_idx, bundle)| {
777                let output_idxs =
778                    find_range_of_matching_items(&output_idx_to_bundle_idx, bundle_idx)
779                        .expect("Non empty bundles must always have a match");
780                bundle.sm_gens.into_iter().flat_map(move |sm| {
781                    (sm.state_machines)(OutPointRange::new(
782                        txid,
783                        IdxRange::from_inclusive(output_idxs.clone())
784                            .expect("can't possibly overflow"),
785                    ))
786                })
787            });
788        (transaction, input_states.chain(output_states).collect())
789    }
790
791    pub fn inputs(&self) -> impl Iterator<Item = &ClientInput> {
792        self.inputs.iter().flat_map(|i| i.inputs.iter())
793    }
794
795    pub fn outputs(&self) -> impl Iterator<Item = &ClientOutput> {
796        self.outputs.iter().flat_map(|i| i.outputs.iter())
797    }
798}
799
800/// Find the range of indexes in an monotonically increasing `arr`, that is
801/// equal to `item`
802fn find_range_of_matching_items(arr: &[usize], item: usize) -> Option<RangeInclusive<u64>> {
803    // `arr` must be monotonically increasing
804    debug_assert!(arr.windows(2).all(|w| w[0] <= w[1]));
805
806    arr.iter()
807        .enumerate()
808        .filter_map(|(arr_idx, arr_item)| (*arr_item == item).then_some(arr_idx as u64))
809        .fold(None, |cur: Option<(u64, u64)>, idx| {
810            Some(cur.map_or((idx, idx), |cur| (cur.0.min(idx), cur.1.max(idx))))
811        })
812        .map(|(start, end)| start..=end)
813}
814
815#[test]
816fn find_range_of_matching_items_sanity() {
817    assert_eq!(find_range_of_matching_items(&[0, 0], 0), Some(0..=1));
818    assert_eq!(find_range_of_matching_items(&[0, 0, 1], 0), Some(0..=1));
819    assert_eq!(find_range_of_matching_items(&[0, 0, 1], 1), Some(2..=2));
820    assert_eq!(find_range_of_matching_items(&[0, 0, 1], 2), None);
821    assert_eq!(find_range_of_matching_items(&[], 0), None);
822}
823
824fn state_gen_to_dyn<S>(
825    state_gen: StateGenerator<S>,
826    module_instance: ModuleInstanceId,
827) -> StateGenerator<DynState>
828where
829    S: IntoDynInstance<DynType = DynState> + 'static,
830{
831    Arc::new(move |out_point_range| {
832        let states = state_gen(out_point_range);
833        states
834            .into_iter()
835            .map(|state| state.into_dyn(module_instance))
836            .collect()
837    })
838}
839
840#[cfg(test)]
841mod tests;