ark-core 0.9.1

Core types and utilities for Ark
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
use crate::server::VirtualTxOutPoint;
use crate::Error;
use bitcoin::Amount;
use bitcoin::SignedAmount;
use bitcoin::Txid;
use std::collections::hash_map::Entry;
use std::collections::HashMap;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Transaction {
    /// A transaction that transforms a UTXO into a boarding output.
    Boarding {
        txid: Txid,
        /// We use [`Amount`] because boarding transactions are always incoming i.e. we receive a
        /// boarding output.
        amount: Amount,
        confirmed_at: Option<i64>,
    },
    /// A transaction that confirms VTXOs.
    Commitment {
        txid: Txid,
        /// We use [`SignedAmount`] because commitment transactions may be incoming or outgoing
        /// i.e. we can send or receive VTXOs.
        amount: SignedAmount,
        created_at: i64,
    },
    /// A transaction that has VTXOs as outputs.
    Ark {
        txid: Txid,
        /// We use [`SignedAmount`] because Ark transactions may be incoming or outgoing i.e.
        /// we can send or receive VTXOs.
        amount: SignedAmount,
        /// An Ark transaction is settled if our outputs in it have been spent. Thus, if we have no
        /// _outputs_ in it, it is considered settled too.
        is_settled: bool,
        created_at: i64,
    },
    /// A transaction that offboards VTXOs to an onchain output.
    Offboard {
        /// The commitment TXID that settles the VTXOs.
        commitment_txid: Txid,
        /// We use [`Amount`] because offboarding transactions are always outgoing.
        amount: Amount,
        /// Confirmation time of the commitment transaction. This information must be provided by
        /// an external source (e.g., esplora).
        confirmed_at: Option<i64>,
    },
}

impl Transaction {
    /// The creation time of the [`Transaction`]. This value can be used for sorting.
    ///
    /// - The creation time of a boarding transaction is based on its confirmation time. If it is
    ///   pending, we return [`None`].
    ///
    /// - The creation time of a commitment transaction is based on the `created_at` of our VTXO
    ///   produced by it.
    ///
    /// - The creation time of an Ark transaction is based on the `created_at` of our VTXO produced
    ///   by it.
    ///
    /// - The creation time of an offboard transaction is based on its confirmation time. If it is
    ///   pending, we return [`None`].
    pub fn created_at(&self) -> Option<i64> {
        match self {
            Transaction::Boarding { confirmed_at, .. }
            | Transaction::Offboard { confirmed_at, .. } => *confirmed_at,
            Transaction::Commitment { created_at, .. } | Transaction::Ark { created_at, .. } => {
                Some(*created_at)
            }
        }
    }

    pub fn txid(&self) -> Txid {
        match self {
            Transaction::Boarding { txid, .. }
            | Transaction::Commitment { txid, .. }
            | Transaction::Ark { txid, .. } => *txid,
            Transaction::Offboard {
                commitment_txid, ..
            } => *commitment_txid,
        }
    }
}

/// Sorts a slice of [`Transaction`] in descending order by creation time.
///
/// Transactions with no creation time (None) are placed first, followed by transactions
/// sorted by creation time in descending order (newest first).
pub fn sort_transactions_by_created_at(txs: &mut [Transaction]) {
    txs.sort_by(|a, b| match (a.created_at(), b.created_at()) {
        (None, None) => std::cmp::Ordering::Equal,
        (None, Some(_)) => std::cmp::Ordering::Less,
        (Some(_), None) => std::cmp::Ordering::Greater,
        (Some(a_time), Some(b_time)) => b_time.cmp(&a_time),
    });
}

/// Generate a list of transactions where we receive VTXOs.
///
/// This list excludes settlements or transactions where we receive a change VTXO.
pub fn generate_incoming_vtxo_transaction_history(
    spent_vtxos: &[VirtualTxOutPoint],
    spendable_vtxos: &[VirtualTxOutPoint],
    // Commitment transactions which take a boarding output of ours as an input.
    boarding_commitment_txs: &[Txid],
) -> Result<Vec<Transaction>, Error> {
    let mut txs = Vec::new();

    let all_vtxos = spent_vtxos.iter().chain(spendable_vtxos.iter());

    let mut spent_vtxos_left_to_check = spent_vtxos.to_vec();

    // We iterate through every VTXO because all VTXOs were incoming at some point.
    for vtxo in all_vtxos {
        // Confirmed settlement of boarding output into VTXO => IGNORED.
        if !vtxo.is_preconfirmed
            && boarding_commitment_txs.contains(
                // There should only be one commitment TXID for confirmed VTXOs.
                &vtxo.commitment_txids[0],
            )
        {
            continue;
        }

        // An incoming VTXO that deserves an entry in the transaction history is the result of an
        // incoming payment. We may receive a VTXO as part of a commitment transaction or through an
        // Ark transaction.

        if vtxo.is_preconfirmed {
            // We compute how much we spent in that Ark transaction.
            let spent_amount = {
                let mut spent_amount = Amount::ZERO;
                let mut remaining_spent_vtxos = Vec::new();
                for spent_vtxo in spent_vtxos_left_to_check.iter() {
                    if spent_vtxo.ark_txid == Some(vtxo.outpoint.txid) {
                        spent_amount += spent_vtxo.amount;
                    } else {
                        remaining_spent_vtxos.push(spent_vtxo.clone());
                    }
                }

                spent_vtxos_left_to_check = remaining_spent_vtxos;

                spent_amount
            };

            let receive_amount = vtxo.amount.to_signed().map_err(Error::ad_hoc)?;
            let spent_amount = spent_amount.to_signed().map_err(Error::ad_hoc)?;

            let net_amount = receive_amount - spent_amount;

            // If net amount is zero, it's a self-payment => IGNORED.
            //
            // If net amount is negative, it's a change VTXO => IGNORED.
            if net_amount.is_positive() {
                txs.push(Transaction::Ark {
                    txid: vtxo.outpoint.txid,
                    amount: net_amount,
                    is_settled: vtxo.spent_by.is_some() ||
                        // To include settled dust outputs too!
                        vtxo.settled_by.is_some(),
                    created_at: vtxo.created_at,
                })
            }
        } else {
            // We compute how much we spent in that batch.
            let spent_amount = {
                let mut spent_amount = Amount::ZERO;
                let mut remaining_spent_vtxos = Vec::new();
                for spent_vtxo in spent_vtxos_left_to_check.iter() {
                    // There should only be one commitment TXID for confirmed VTXOs.
                    let commitment_txid = vtxo.commitment_txids[0];

                    if spent_vtxo.settled_by == Some(commitment_txid) {
                        spent_amount += spent_vtxo.amount;
                    } else {
                        remaining_spent_vtxos.push(spent_vtxo.clone());
                    }
                }

                spent_vtxos_left_to_check = remaining_spent_vtxos;

                spent_amount
            };

            let receive_amount = vtxo.amount.to_signed().map_err(Error::ad_hoc)?;
            let spent_amount = spent_amount.to_signed().map_err(Error::ad_hoc)?;

            let net_amount = receive_amount - spent_amount;

            // If net amount received is zero, it's a VTXO being settled => IGNORED.
            //
            // If net amount received is negative, it's a change VTXO => IGNORED.
            if net_amount.is_positive() {
                txs.push(Transaction::Commitment {
                    txid: vtxo.outpoint.txid,
                    amount: receive_amount,
                    created_at: vtxo.created_at,
                })
            }
        }
    }

    Ok(txs)
}

/// Generate a list of outgoing transactions.
///
/// This includes:
/// - Outgoing Ark transactions (offchain payments)
/// - Offboarding transactions (collaborative redeem to onchain)
///
/// Pure settlements (VTXO refreshes with no net outflow) are excluded.
///
/// # Returns
///
/// An iterator of [`OutgoingTransaction`]s.
///
/// We do not return a list of [`Transaction`]s directly because some outgoing transactions may need
/// additional data to be constructed:
/// - [`OutgoingTransaction::Incomplete`]: needs a [`VirtualTxOutPoint`] to complete.
/// - [`OutgoingTransaction::IncompleteOffboard`]: needs confirmation data from an external source.
///
/// # Example
///
/// ```rust
/// # use ark_core::history::OutgoingTransaction;
/// # use ark_core::history::generate_outgoing_vtxo_transaction_history;
/// # use ark_core::server::VirtualTxOutPoint;
/// # use ark_core::Error;
/// # use bitcoin::OutPoint;
/// # use bitcoin::Txid;
/// # fn fetch_virtual_tx_outpoint(_outpoint: OutPoint) -> Result<Option<VirtualTxOutPoint>, Error> {
/// #     Ok(None)
/// # }
/// # fn fetch_tx_confirmation_time(_txid: Txid) -> Result<Option<i64>, Error> {
/// #     Ok(None)
/// # }
/// #
/// # let spent_vtxos = vec![];
/// # let spendable_vtxos = vec![];
/// let outgoing_txs = generate_outgoing_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos).unwrap();
///
/// let mut complete_outgoing_txs = vec![];
/// for outgoing_tx in outgoing_txs {
///     match outgoing_tx {
///         OutgoingTransaction::Complete(complete_tx) => {
///             complete_outgoing_txs.push(complete_tx);
///         }
///         OutgoingTransaction::Incomplete(incomplete_tx) => {
///             // Need to fetch additional VTXO data to complete.
///             let virtual_tx_outpoint = fetch_virtual_tx_outpoint(incomplete_tx.first_outpoint()).unwrap();
///             if let Some(virtual_tx_outpoint) = virtual_tx_outpoint {
///                 let complete_tx = incomplete_tx.finish(&virtual_tx_outpoint).unwrap();
///                 complete_outgoing_txs.push(complete_tx);
///             }
///         }
///         OutgoingTransaction::IncompleteOffboard(incomplete_offboard) => {
///             // Need to fetch confirmation time from an external source (e.g., esplora).
///             let confirmed_at = fetch_tx_confirmation_time(incomplete_offboard.commitment_txid()).unwrap();
///             let complete_tx = incomplete_offboard.finish(confirmed_at);
///             complete_outgoing_txs.push(complete_tx);
///         }
///     }
/// }
/// ```
pub fn generate_outgoing_vtxo_transaction_history(
    spent_vtxos: &[VirtualTxOutPoint],
    spendable_vtxos: &[VirtualTxOutPoint],
) -> Result<impl Iterator<Item = OutgoingTransaction>, Error> {
    let all_vtxos = [spent_vtxos, spendable_vtxos].concat();

    // We collect all the transactions where one or more VTXOs of ours are spent.
    let mut vtxos_by_spent_by = HashMap::<Txid, Vec<VirtualTxOutPoint>>::new();
    // We collect all the VTXOs that are settled (forfeited) by a commitment transaction.
    let mut vtxos_by_settled_by = HashMap::<Txid, Vec<VirtualTxOutPoint>>::new();

    for spent_vtxo in spent_vtxos.iter() {
        if let Some(settled_by) = spent_vtxo.settled_by {
            // Track settlements to detect offboarding.
            match vtxos_by_settled_by.entry(settled_by) {
                Entry::Occupied(mut occupied_entry) => {
                    occupied_entry.get_mut().push(spent_vtxo.clone());
                }
                Entry::Vacant(e) => {
                    e.insert(vec![spent_vtxo.clone()]);
                }
            }
        } else if let Some(ark_txid) = spent_vtxo.ark_txid {
            if spent_vtxo.spent_by.is_some() {
                match vtxos_by_spent_by.entry(ark_txid) {
                    Entry::Occupied(mut occupied_entry) => {
                        occupied_entry.get_mut().push(spent_vtxo.clone());
                    }
                    Entry::Vacant(e) => {
                        e.insert(vec![spent_vtxo.clone()]);
                    }
                }
            }
        }
    }

    // An outgoing VTXO that warrants an entry in the transaction history is the input to an
    // outgoing payment. We may send a VTXO as part of a commitment transaction or through an Ark
    // transaction.
    let mut outgoing_txs = Vec::new();

    // Process regular outgoing transactions (Ark transactions).
    for (spend_txid, spent_vtxos) in vtxos_by_spent_by.iter() {
        let spent_amount = spent_vtxos
            .iter()
            .fold(Amount::ZERO, |acc, x| acc + x.amount)
            .to_signed()
            .map_err(Error::ad_hoc)?;

        let produced_virtual_tx_outpoints = all_vtxos
            .iter()
            .filter(|v| v.outpoint.txid == *spend_txid)
            .collect::<Vec<_>>();

        let produced_amount = produced_virtual_tx_outpoints
            .iter()
            .fold(Amount::ZERO, |acc, x| acc + x.amount)
            .to_signed()
            .map_err(Error::ad_hoc)?;

        let net_amount = produced_amount - spent_amount;

        if !net_amount.is_negative() {
            // Ignore settlements and self-payments.
            continue;
        }

        let tx = match produced_virtual_tx_outpoints.first() {
            Some(virtual_tx_change_outpoint) => {
                OutgoingTransaction::with_change(virtual_tx_change_outpoint, net_amount)
            }
            None => OutgoingTransaction::without_change(*spend_txid, net_amount),
        };

        outgoing_txs.push(tx);
    }

    // Process settlements to detect offboarding transactions.
    //
    // When VTXOs are settled by a commitment transaction, the inputs may be:
    // 1. Refreshed into new VTXOs of equal value (pure settlement) - ignore.
    // 2. Partially offboarded with some change VTXO remaining - track the offboarded amount.
    // 3. Fully offboarded with no change VTXO - track the entire amount.
    //
    // NOTE: I believe this may not tell the whole story, but it's good enough for now.
    for (commitment_txid, settled_vtxos) in vtxos_by_settled_by.iter() {
        let input_amount = settled_vtxos
            .iter()
            .fold(Amount::ZERO, |acc, x| acc + x.amount)
            .to_signed()
            .map_err(Error::ad_hoc)?;

        // Find VTXOs that were produced by this settlement (have commitment_txid in their
        // commitment_txids).
        let produced_vtxos = all_vtxos
            .iter()
            .filter(|v| v.commitment_txids.contains(commitment_txid))
            .collect::<Vec<_>>();

        let output_amount = produced_vtxos
            .iter()
            .fold(Amount::ZERO, |acc, x| acc + x.amount)
            .to_signed()
            .map_err(Error::ad_hoc)?;

        let offboarded_amount = input_amount - output_amount;

        if offboarded_amount.is_positive() {
            // Some or all of the input was offboarded onchain.
            outgoing_txs.push(OutgoingTransaction::IncompleteOffboard(
                IncompleteOffboardTransaction {
                    commitment_txid: *commitment_txid,
                    amount: offboarded_amount.to_unsigned().map_err(Error::ad_hoc)?,
                },
            ));
        }
        // If offboarded_amount <= 0, it's a pure settlement (refresh) - ignore.
    }

    Ok(OutgoingTransactionIter::new(outgoing_txs))
}

/// An outgoing transaction.
///
/// If the transaction is [`OutgoingTransaction::Complete`], it can be used as is. If the
/// transaction is [`OutgoingTransaction::Incomplete`], you will need to complete it with a
/// [`VirtualTxOutPoint`]. If the transaction is [`OutgoingTransaction::IncompleteOffboard`], you
/// will need to complete it with confirmation data.
///
/// Refer to [`generate_outgoing_vtxo_transaction_history`] for more info on how to use this type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OutgoingTransaction {
    Complete(Transaction),
    Incomplete(IncompleteOutgoingTransaction),
    IncompleteOffboard(IncompleteOffboardTransaction),
}

impl OutgoingTransaction {
    /// Build an outgoing transaction with a change output of ours.
    ///
    /// With the change [`VirtualTxOutPoint`], we can go ahead and build the corresponding
    /// [`Transaction`].
    fn with_change(
        virtual_tx_change_outpoint: &VirtualTxOutPoint,
        net_amount: SignedAmount,
    ) -> Self {
        Self::Complete(build_outgoing_transaction(
            virtual_tx_change_outpoint,
            net_amount,
        ))
    }

    /// Build outgoing transaction data, without a change output of ours.
    ///
    /// Without a change output, we need to look for a foreign [`VirtualTxOutPoint`] to be able to
    /// build the corresponding [`Transaction`].
    fn without_change(txid: Txid, net_amount: SignedAmount) -> Self {
        Self::Incomplete(IncompleteOutgoingTransaction {
            first_outpoint: bitcoin::OutPoint { txid, vout: 0 },
            net_amount,
        })
    }
}

/// An outgoing transaction that is missing data about one of its [`VirtualTxOutPoint`]s so that it
/// can be completed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IncompleteOutgoingTransaction {
    // We take the first one because:
    //
    // - Any outpoint will work.
    // - Every transaction has at least one outpoint.
    first_outpoint: bitcoin::OutPoint,
    net_amount: SignedAmount,
}

/// An offboard transaction that is missing confirmation data so that it can be completed.
///
/// Use [`IncompleteOffboardTransaction::finish`] to complete the transaction with confirmation
/// data from an external source (e.g., esplora).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IncompleteOffboardTransaction {
    commitment_txid: Txid,
    amount: Amount,
}

impl IncompleteOffboardTransaction {
    /// The commitment TXID of this offboard transaction.
    ///
    /// Use this value to query an external source (e.g., esplora) for confirmation data.
    pub fn commitment_txid(&self) -> Txid {
        self.commitment_txid
    }

    /// Transform this incomplete offboard transaction into a [`Transaction`].
    ///
    /// # Arguments
    ///
    /// * `confirmed_at`: The confirmation time of the commitment transaction, or [`None`] if
    ///   unconfirmed.
    pub fn finish(self, confirmed_at: Option<i64>) -> Transaction {
        Transaction::Offboard {
            commitment_txid: self.commitment_txid,
            amount: self.amount,
            confirmed_at,
        }
    }
}

impl IncompleteOutgoingTransaction {
    /// The first [`bitcoin::OutPoint`] of this transaction.
    ///
    /// Use this value to find the corresponding [`VirtualTxOutPoint`], to be able to call
    /// [`IncompleteOutgoingTransaction::finish`] and build a [`Transaction`].
    pub fn first_outpoint(&self) -> bitcoin::OutPoint {
        self.first_outpoint
    }

    /// Transform this incomplete outgoing transaction into a [`Transaction`].
    ///
    /// # Arguments
    ///
    /// * `virtual_tx_outpoint`: a [`VirtualTxOutPoint`].
    ///
    /// # Returns
    ///
    /// A complete [`Transaction`].
    ///
    /// # Errors
    ///
    /// If the TXID of the provided `virtual_tx_outpoint` does not match that of the
    /// `first_outpoint` field, we return an error.
    pub fn finish(self, virtual_tx_outpoint: &VirtualTxOutPoint) -> Result<Transaction, Error> {
        if self.first_outpoint.txid != virtual_tx_outpoint.outpoint.txid {
            return Err(Error::ad_hoc(format!(
                "cannot finish outgoing transaction with unrelated \
                virtual TX outpoint: expected {}, got {}",
                self.first_outpoint.txid, virtual_tx_outpoint.outpoint.txid
            )));
        }

        Ok(build_outgoing_transaction(
            virtual_tx_outpoint,
            self.net_amount,
        ))
    }
}

/// An iterator of [`OutgoingTransaction`]s.
struct OutgoingTransactionIter {
    inner: std::vec::IntoIter<OutgoingTransaction>,
}

impl OutgoingTransactionIter {
    /// Build a new iterator of [`OutgoingTransaction`]s.
    fn new(txs: Vec<OutgoingTransaction>) -> Self {
        Self {
            inner: txs.into_iter(),
        }
    }
}

impl Iterator for OutgoingTransactionIter {
    type Item = OutgoingTransaction;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

/// Build an outgoing [`Transaction`].
fn build_outgoing_transaction(
    // A virtual TX outpoint of the outgoing transaction.
    vtxo_outpoint: &VirtualTxOutPoint,
    // A negative amount representing coins received minus coins sent in the transaction.
    net_amount: SignedAmount,
) -> Transaction {
    let created_at = vtxo_outpoint.created_at;
    match vtxo_outpoint.is_preconfirmed {
        true => Transaction::Ark {
            txid: vtxo_outpoint.outpoint.txid,
            amount: net_amount,
            // For a pre-confirmed outgoing Ark transaction, the sender always considers the
            // transaction settled.
            is_settled: true,
            created_at,
        },
        false => Transaction::Commitment {
            txid: vtxo_outpoint.commitment_txids[0],
            amount: net_amount,
            created_at,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::OutPoint;
    use bitcoin::ScriptBuf;

    // These tests are taken straight from the Go client.
    // NOTE: The go tests disappeared when the client was moved to a different repository.

    #[test]
    fn alice_before_sending() {
        let boarding_commitment_txs = [
            "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                .parse()
                .unwrap(),
        ];

        let spendable_vtxos = [VirtualTxOutPoint {
            outpoint: OutPoint {
                txid: "2646aea682389e1739a33a617d1f3ee28ccc7e4e16210936cece7a823e37527e"
                    .parse()
                    .unwrap(),
                vout: 0,
            },
            created_at: 1730330127,
            expires_at: 1730934927,
            amount: Amount::from_sat(20_000),
            script: ScriptBuf::new(),
            is_preconfirmed: false,
            is_swept: false,
            is_unrolled: false,
            is_spent: false,
            spent_by: None,
            commitment_txids: vec![
                "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                    .parse()
                    .unwrap(),
            ],
            settled_by: None,
            ark_txid: None,
            assets: Vec::new(),
        }];

        let inc_txs = generate_incoming_vtxo_transaction_history(
            &[],
            &spendable_vtxos,
            &boarding_commitment_txs,
        )
        .unwrap();

        let out_txs = generate_outgoing_vtxo_transaction_history(&[], &spendable_vtxos)
            .unwrap()
            .collect::<Vec<_>>();

        assert!(inc_txs.is_empty());
        assert!(out_txs.is_empty());
    }

    #[test]
    fn alice_after_sending() {
        let boarding_commitment_txs = [
            "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                .parse()
                .unwrap(),
        ];

        let spendable_vtxos = [VirtualTxOutPoint {
            outpoint: OutPoint {
                txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                    .parse()
                    .unwrap(),
                vout: 1,
            },
            created_at: 1730330256,
            expires_at: 1730934927,
            amount: Amount::from_sat(18_784),
            script: ScriptBuf::new(),
            is_preconfirmed: true,
            is_swept: false,
            is_unrolled: false,
            is_spent: false,
            spent_by: None,
            commitment_txids: vec![
                "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                    .parse()
                    .unwrap(),
            ],
            settled_by: None,
            ark_txid: None,
            assets: Vec::new(),
        }];

        let spent_vtxos = [VirtualTxOutPoint {
            outpoint: OutPoint {
                txid: "2646aea682389e1739a33a617d1f3ee28ccc7e4e16210936cece7a823e37527e"
                    .parse()
                    .unwrap(),
                vout: 0,
            },
            created_at: 1730330127,
            expires_at: 1730934927,
            amount: Amount::from_sat(20_000),
            script: ScriptBuf::new(),
            is_preconfirmed: false,
            is_swept: false,
            is_unrolled: false,
            is_spent: true,
            spent_by: Some(
                "e3c4f18d0418935db8000c5b8c8fc8d776b5741cd625369eceea9aebb8bcee03"
                    .parse()
                    .unwrap(),
            ),
            commitment_txids: vec![
                "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                    .parse()
                    .unwrap(),
            ],
            settled_by: None,
            ark_txid: Some(
                "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                    .parse()
                    .unwrap(),
            ),
            assets: Vec::new(),
        }];

        let inc_txs = generate_incoming_vtxo_transaction_history(
            &spent_vtxos,
            &spendable_vtxos,
            &boarding_commitment_txs,
        )
        .unwrap();

        let out_txs = generate_outgoing_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos)
            .unwrap()
            .filter_map(|tx| {
                if let OutgoingTransaction::Complete(tx) = tx {
                    Some(tx)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        assert!(inc_txs.is_empty());

        assert_eq!(
            out_txs,
            [Transaction::Ark {
                txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                    .parse()
                    .unwrap(),
                amount: SignedAmount::from_sat(-1_216),
                is_settled: true,
                created_at: 1730330256,
            }]
        );
    }

    #[test]
    fn bob_before_settling() {
        let spendable_vtxos = [
            VirtualTxOutPoint {
                outpoint: OutPoint {
                    txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                        .parse()
                        .unwrap(),
                    vout: 0,
                },
                created_at: 1730330256,
                expires_at: 1730934927,
                amount: Amount::from_sat(1_000),
                script: ScriptBuf::new(),
                is_preconfirmed: true,
                is_swept: false,
                is_unrolled: false,
                is_spent: false,
                spent_by: None,
                commitment_txids: vec![
                    "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                        .parse()
                        .unwrap(),
                ],
                settled_by: None,
                ark_txid: None,
                assets: Vec::new(),
            },
            VirtualTxOutPoint {
                outpoint: OutPoint {
                    txid: "884d85c0db6b52139c39337d54c1f20cd8c5c0d2e83109d69246a345ccc9d169"
                        .parse()
                        .unwrap(),
                    vout: 0,
                },
                created_at: 1730330748,
                expires_at: 1730935548,
                amount: Amount::from_sat(2_000),
                script: ScriptBuf::new(),
                is_preconfirmed: true,
                is_swept: false,
                is_unrolled: false,
                is_spent: false,
                spent_by: None,
                commitment_txids: vec![
                    "a4e91c211398e0be0edad322fb74a739b1c77bb82b9e4ea94b0115b8e4dfe645"
                        .parse()
                        .unwrap(),
                ],
                settled_by: None,
                ark_txid: None,
                assets: Vec::new(),
            },
        ];

        let spent_vtxos = [];

        let mut inc_txs =
            generate_incoming_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos, &[])
                .unwrap();

        sort_transactions_by_created_at(&mut inc_txs);

        let out_txs = generate_outgoing_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos)
            .unwrap()
            .collect::<Vec<_>>();

        assert_eq!(
            inc_txs,
            [
                Transaction::Ark {
                    txid: "884d85c0db6b52139c39337d54c1f20cd8c5c0d2e83109d69246a345ccc9d169"
                        .parse()
                        .unwrap(),
                    amount: SignedAmount::from_sat(2_000),
                    is_settled: false,
                    created_at: 1730330748,
                },
                Transaction::Ark {
                    txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                        .parse()
                        .unwrap(),
                    amount: SignedAmount::from_sat(1_000),
                    is_settled: false,
                    created_at: 1730330256,
                }
            ]
        );

        assert!(out_txs.is_empty());
    }

    #[test]
    fn bob_after_settling() {
        let spendable_vtxos = [VirtualTxOutPoint {
            outpoint: OutPoint {
                txid: "d9c95372c0c419fd007005edd54e21dabac0375a37fc5f17c313bc1e5f483af9"
                    .parse()
                    .unwrap(),
                vout: 0,
            },
            created_at: 1730331035,
            expires_at: 1730935835,
            amount: Amount::from_sat(3_000),
            script: ScriptBuf::new(),
            is_preconfirmed: false,
            is_swept: false,
            is_unrolled: false,
            is_spent: false,
            spent_by: None,
            commitment_txids: vec![
                "7fd65ce87e0f9a7af583593d5b0124aabd65c97e05159525d0a98201d6ae95a4"
                    .parse()
                    .unwrap(),
            ],
            settled_by: None,
            ark_txid: None,
            assets: Vec::new(),
        }];

        let spent_vtxos = [
            VirtualTxOutPoint {
                outpoint: OutPoint {
                    txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                        .parse()
                        .unwrap(),
                    vout: 0,
                },
                created_at: 1730330256,
                expires_at: 1730934927,
                amount: Amount::from_sat(1_000),
                script: ScriptBuf::new(),
                is_preconfirmed: true,
                is_swept: false,
                is_unrolled: false,
                is_spent: true,
                spent_by: Some(
                    "c9bdde5595c5479394e805a8c468657cd94ae75a504172e514030b3c549f3646"
                        .parse()
                        .unwrap(),
                ),
                commitment_txids: vec![
                    "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                        .parse()
                        .unwrap(),
                ],
                settled_by: Some(
                    "7fd65ce87e0f9a7af583593d5b0124aabd65c97e05159525d0a98201d6ae95a4"
                        .parse()
                        .unwrap(),
                ),
                ark_txid: None,
                assets: Vec::new(),
            },
            VirtualTxOutPoint {
                outpoint: OutPoint {
                    txid: "884d85c0db6b52139c39337d54c1f20cd8c5c0d2e83109d69246a345ccc9d169"
                        .parse()
                        .unwrap(),
                    vout: 0,
                },
                created_at: 1730330748,
                expires_at: 1730935548,
                amount: Amount::from_sat(2_000),
                script: ScriptBuf::new(),
                is_preconfirmed: true,
                is_swept: false,
                is_unrolled: false,
                is_spent: true,
                spent_by: Some(
                    "a7c06a495dd145fd95693a5190b26ffa391aa4440c1af26f9ff293166d97d807"
                        .parse()
                        .unwrap(),
                ),
                commitment_txids: vec![
                    "a4e91c211398e0be0edad322fb74a739b1c77bb82b9e4ea94b0115b8e4dfe645"
                        .parse()
                        .unwrap(),
                ],
                settled_by: Some(
                    "7fd65ce87e0f9a7af583593d5b0124aabd65c97e05159525d0a98201d6ae95a4"
                        .parse()
                        .unwrap(),
                ),
                ark_txid: None,
                assets: Vec::new(),
            },
        ];

        let mut inc_txs =
            generate_incoming_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos, &[])
                .unwrap();

        sort_transactions_by_created_at(&mut inc_txs);

        let out_txs = generate_outgoing_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos)
            .unwrap()
            .collect::<Vec<_>>();

        assert_eq!(
            inc_txs,
            [
                Transaction::Ark {
                    txid: "884d85c0db6b52139c39337d54c1f20cd8c5c0d2e83109d69246a345ccc9d169"
                        .parse()
                        .unwrap(),
                    amount: SignedAmount::from_sat(2_000),
                    is_settled: true,
                    created_at: 1730330748,
                },
                Transaction::Ark {
                    txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                        .parse()
                        .unwrap(),
                    amount: SignedAmount::from_sat(1_000),
                    is_settled: true,
                    created_at: 1730330256,
                }
            ]
        );

        assert!(out_txs.is_empty());
    }

    #[test]
    fn bob_after_sending() {
        let spendable_vtxos = [VirtualTxOutPoint {
            outpoint: OutPoint {
                txid: "c59004f8c468a922216f513ec7d63d9b6a13571af0bacd51910709351d27fe55"
                    .parse()
                    .unwrap(),
                vout: 1,
            },
            created_at: 1730331198,
            expires_at: 1730935835,
            amount: Amount::from_sat(684),
            script: ScriptBuf::new(),
            is_preconfirmed: true,
            is_swept: false,
            is_unrolled: false,
            is_spent: false,
            spent_by: None,
            commitment_txids: vec![
                "7fd65ce87e0f9a7af583593d5b0124aabd65c97e05159525d0a98201d6ae95a4"
                    .parse()
                    .unwrap(),
            ],
            settled_by: None,
            ark_txid: None,
            assets: Vec::new(),
        }];

        let spent_vtxos = [
            VirtualTxOutPoint {
                outpoint: OutPoint {
                    txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                        .parse()
                        .unwrap(),
                    vout: 0,
                },
                created_at: 1730330256,
                expires_at: 1730934927,
                amount: Amount::from_sat(1_000),
                script: ScriptBuf::new(),
                is_preconfirmed: true,
                is_swept: false,
                is_unrolled: false,
                is_spent: true,
                spent_by: Some(
                    "c9bdde5595c5479394e805a8c468657cd94ae75a504172e514030b3c549f3646"
                        .parse()
                        .unwrap(),
                ),
                commitment_txids: vec![
                    "c16ae0d917ac400790da18456015975521bec6e1d1962ad728c0070808c564e8"
                        .parse()
                        .unwrap(),
                ],
                settled_by: Some(
                    "7fd65ce87e0f9a7af583593d5b0124aabd65c97e05159525d0a98201d6ae95a4"
                        .parse()
                        .unwrap(),
                ),
                ark_txid: None,
                assets: Vec::new(),
            },
            VirtualTxOutPoint {
                outpoint: OutPoint {
                    txid: "884d85c0db6b52139c39337d54c1f20cd8c5c0d2e83109d69246a345ccc9d169"
                        .parse()
                        .unwrap(),
                    vout: 0,
                },
                created_at: 1730330748,
                expires_at: 1730935548,
                amount: Amount::from_sat(2_000),
                script: ScriptBuf::new(),
                is_preconfirmed: true,
                is_swept: false,
                is_unrolled: false,
                is_spent: true,
                spent_by: Some(
                    "a7c06a495dd145fd95693a5190b26ffa391aa4440c1af26f9ff293166d97d807"
                        .parse()
                        .unwrap(),
                ),
                commitment_txids: vec![
                    "a4e91c211398e0be0edad322fb74a739b1c77bb82b9e4ea94b0115b8e4dfe645"
                        .parse()
                        .unwrap(),
                ],
                settled_by: Some(
                    "7fd65ce87e0f9a7af583593d5b0124aabd65c97e05159525d0a98201d6ae95a4"
                        .parse()
                        .unwrap(),
                ),
                ark_txid: None,
                assets: Vec::new(),
            },
            VirtualTxOutPoint {
                outpoint: OutPoint {
                    txid: "d9c95372c0c419fd007005edd54e21dabac0375a37fc5f17c313bc1e5f483af9"
                        .parse()
                        .unwrap(),
                    vout: 0,
                },
                created_at: 1730331035,
                expires_at: 1730935835,
                amount: Amount::from_sat(3_000),
                script: ScriptBuf::new(),
                is_preconfirmed: false,
                is_swept: false,
                is_unrolled: false,
                is_spent: true,
                spent_by: Some(
                    "cfcfec99c9767162fc2432fac7cac6240eae2ce344d2d0e1600284399f5dd493"
                        .parse()
                        .unwrap(),
                ),
                commitment_txids: vec![
                    "7fd65ce87e0f9a7af583593d5b0124aabd65c97e05159525d0a98201d6ae95a4"
                        .parse()
                        .unwrap(),
                ],
                settled_by: None,
                ark_txid: Some(
                    "c59004f8c468a922216f513ec7d63d9b6a13571af0bacd51910709351d27fe55"
                        .parse()
                        .unwrap(),
                ),
                assets: Vec::new(),
            },
        ];

        let inc_txs =
            generate_incoming_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos, &[])
                .unwrap();

        let out_txs = generate_outgoing_vtxo_transaction_history(&spent_vtxos, &spendable_vtxos)
            .unwrap()
            .filter_map(|tx| {
                if let OutgoingTransaction::Complete(tx) = tx {
                    Some(tx)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        let mut txs = [inc_txs, out_txs].concat();
        sort_transactions_by_created_at(&mut txs);

        assert_eq!(
            txs,
            [
                Transaction::Ark {
                    txid: "c59004f8c468a922216f513ec7d63d9b6a13571af0bacd51910709351d27fe55"
                        .parse()
                        .unwrap(),
                    amount: SignedAmount::from_sat(-2_316),
                    is_settled: true,
                    created_at: 1730331198,
                },
                Transaction::Ark {
                    txid: "884d85c0db6b52139c39337d54c1f20cd8c5c0d2e83109d69246a345ccc9d169"
                        .parse()
                        .unwrap(),
                    amount: SignedAmount::from_sat(2_000),
                    is_settled: true,
                    created_at: 1730330748,
                },
                Transaction::Ark {
                    txid: "33fd8ca9ea9cfb53802c42be10ae428573e19fb89484dfe536d06d43efa82034"
                        .parse()
                        .unwrap(),
                    amount: SignedAmount::from_sat(1_000),
                    is_settled: true,
                    created_at: 1730330256,
                }
            ]
        );
    }
}