bsv-wallet-toolbox 0.2.23

Pure Rust BSV wallet-toolbox implementation
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
//! Change generation algorithm (generateChangeSdk) ported from TypeScript.
//!
//! Ported from wallet-toolbox/src/storage/methods/generateChange.ts.
//! Handles UTXO selection, change output creation, starvation loops,
//! fee calculation, and excess distribution.

use crate::error::{WalletError, WalletResult};
use crate::storage::action_types::{
    AllocatedChangeInputRef, ChangeOutput, GenerateChangeSdkArgs, GenerateChangeSdkResult,
    MaxPossibleSatoshisAdjustment,
};
use crate::utility::tx_size::transaction_size;

/// Sentinel value: an output with this satoshis amount will be adjusted
/// to the largest fundable amount.
pub const MAX_POSSIBLE_SATOSHIS: u64 = 2_099_999_999_999_999;

/// A pre-fetched available change UTXO for the allocator.
#[derive(Debug, Clone)]
pub struct AvailableChange {
    /// Storage output ID.
    pub output_id: i64,
    /// Value in satoshis.
    pub satoshis: u64,
    /// Whether this output is currently spendable.
    pub spendable: bool,
}

/// In-memory UTXO allocator matching the TS `generateChangeSdkMakeStorage`.
/// Sorts by satoshis ascending, then output_id ascending (prefer smaller).
pub struct ChangeStorage {
    change: Vec<AvailableChange>,
}

impl ChangeStorage {
    /// Create a new ChangeStorage from available change UTXOs.
    pub fn new(available: Vec<AvailableChange>) -> Self {
        let mut change: Vec<AvailableChange> = available
            .into_iter()
            .map(|c| AvailableChange {
                output_id: c.output_id,
                satoshis: c.satoshis,
                spendable: true,
            })
            .collect();
        change.sort_by(|a, b| {
            a.satoshis
                .cmp(&b.satoshis)
                .then(a.output_id.cmp(&b.output_id))
        });
        Self { change }
    }

    /// Allocate a change input. Tries exact match first, then smallest >= target,
    /// then largest available (fallback).
    pub fn allocate(
        &mut self,
        target_satoshis: u64,
        exact_satoshis: Option<u64>,
    ) -> Option<AllocatedChangeInputRef> {
        // Try exact match first
        if let Some(exact) = exact_satoshis {
            if let Some(idx) = self
                .change
                .iter()
                .position(|c| c.spendable && c.satoshis == exact)
            {
                self.change[idx].spendable = false;
                return Some(AllocatedChangeInputRef {
                    output_id: self.change[idx].output_id,
                    satoshis: self.change[idx].satoshis,
                });
            }
        }

        // Try smallest >= target
        if let Some(idx) = self
            .change
            .iter()
            .position(|c| c.spendable && c.satoshis >= target_satoshis)
        {
            self.change[idx].spendable = false;
            return Some(AllocatedChangeInputRef {
                output_id: self.change[idx].output_id,
                satoshis: self.change[idx].satoshis,
            });
        }

        // Fallback: largest available (iterate backwards)
        for i in (0..self.change.len()).rev() {
            if self.change[i].spendable {
                self.change[i].spendable = false;
                return Some(AllocatedChangeInputRef {
                    output_id: self.change[i].output_id,
                    satoshis: self.change[i].satoshis,
                });
            }
        }

        None
    }

    /// Release a previously allocated change input back to the pool.
    pub fn release(&mut self, output_id: i64) {
        if let Some(c) = self.change.iter_mut().find(|c| c.output_id == output_id) {
            c.spendable = true;
        }
    }
}

/// Validate the params for generate_change_sdk.
/// Returns the index of a fixedOutput with MAX_POSSIBLE_SATOSHIS if any.
fn validate_params(args: &GenerateChangeSdkArgs) -> WalletResult<Option<usize>> {
    if args.fee_model.model != "sat/kb" {
        return Err(WalletError::InvalidParameter {
            parameter: "fee_model.model".to_string(),
            must_be: "'sat/kb'".to_string(),
        });
    }

    let mut has_max_possible_output: Option<usize> = None;
    for (i, o) in args.fixed_outputs.iter().enumerate() {
        if o.satoshis == MAX_POSSIBLE_SATOSHIS {
            if has_max_possible_output.is_some() {
                return Err(WalletError::InvalidParameter {
                    parameter: format!("fixed_outputs[{}].satoshis", i),
                    must_be:
                        "valid satoshis amount. Only one 'maxPossibleSatoshis' output allowed."
                            .to_string(),
                });
            }
            has_max_possible_output = Some(i);
        }
    }

    Ok(has_max_possible_output)
}

/// Compute transaction size given current state.
fn compute_size(
    args: &GenerateChangeSdkArgs,
    allocated_len: usize,
    change_len: usize,
    added_inputs: usize,
    added_outputs: usize,
) -> usize {
    let input_script_lengths: Vec<usize> = args
        .fixed_inputs
        .iter()
        .map(|x| x.unlocking_script_length)
        .chain(std::iter::repeat_n(
            args.change_unlocking_script_length,
            allocated_len + added_inputs,
        ))
        .collect();
    let output_script_lengths: Vec<usize> = args
        .fixed_outputs
        .iter()
        .map(|x| x.locking_script_length)
        .chain(std::iter::repeat_n(
            args.change_locking_script_length,
            change_len + added_outputs,
        ))
        .collect();
    transaction_size(&input_script_lengths, &output_script_lengths)
}

/// Compute the target fee for a given state.
fn fee_target(
    args: &GenerateChangeSdkArgs,
    allocated_len: usize,
    change_len: usize,
    added_inputs: usize,
    added_outputs: usize,
) -> u64 {
    let sz = compute_size(args, allocated_len, change_len, added_inputs, added_outputs);
    // ceil(size * sats_per_kb / 1000)
    ((sz as u64) * args.fee_model.value).div_ceil(1000)
}

/// Sum of fixed input satoshis plus allocated change input satoshis.
fn funding(args: &GenerateChangeSdkArgs, allocated: &[AllocatedChangeInputRef]) -> u64 {
    let fixed_sum: u64 = args.fixed_inputs.iter().map(|i| i.satoshis).sum();
    let change_sum: u64 = allocated.iter().map(|i| i.satoshis).sum();
    fixed_sum + change_sum
}

/// Sum of fixed output satoshis.
fn spending(fixed_output_satoshis: &[u64]) -> u64 {
    fixed_output_satoshis.iter().sum()
}

/// Sum of change output satoshis.
fn change_total(outputs: &[ChangeOutput]) -> u64 {
    outputs.iter().map(|o| o.satoshis).sum()
}

/// Compute the excess fee (positive = overfunded, negative = underfunded).
fn fee_excess(
    args: &GenerateChangeSdkArgs,
    allocated: &[AllocatedChangeInputRef],
    change_outputs: &[ChangeOutput],
    fixed_output_satoshis: &[u64],
    added_inputs: usize,
    added_outputs: usize,
) -> i64 {
    let f = funding(args, allocated) as i64;
    let s = spending(fixed_output_satoshis) as i64;
    let c = change_total(change_outputs) as i64;
    let ft = fee_target(
        args,
        allocated.len(),
        change_outputs.len(),
        added_inputs,
        added_outputs,
    ) as i64;
    f - s - c - ft
}

/// Release all allocated change inputs back to the storage pool.
fn release_all(allocated: &mut Vec<AllocatedChangeInputRef>, storage: &mut ChangeStorage) {
    while let Some(input) = allocated.pop() {
        storage.release(input.output_id);
    }
}

/// Core change generation algorithm.
///
/// Synchronous pure computation function. All storage interactions
/// (fetching available UTXOs) must happen before calling this function.
///
/// Faithfully ported from TS `generateChangeSdk` in generateChange.ts.
pub fn generate_change_sdk(
    args: &GenerateChangeSdkArgs,
    available_change: &[AvailableChange],
) -> WalletResult<GenerateChangeSdkResult> {
    let has_max_possible_output = validate_params(args)?;

    let sats_per_kb = args.fee_model.value;
    let mut storage = ChangeStorage::new(available_change.to_vec());

    let mut allocated_change_inputs: Vec<AllocatedChangeInputRef> = Vec::new();
    let mut change_outputs: Vec<ChangeOutput> = Vec::new();

    // Mutable copy of fixed output satoshis for max_possible adjustment
    let mut fixed_output_satoshis: Vec<u64> =
        args.fixed_outputs.iter().map(|o| o.satoshis).collect();

    // fee_excess_now is computed fresh after the starvation loop completes
    // (see line ~458); earlier iterations recompute `fee_excess(...)` inline.
    let mut fee_excess_now: i64;

    let has_target_net_count = args.target_net_count.is_some();
    let target_net_count = args.target_net_count.unwrap_or(0);

    // Net change count = change outputs created - change inputs consumed
    let net_change_count = |co_len: usize, ai_len: usize| -> i64 { co_len as i64 - ai_len as i64 };

    // Whether we should add a change output to balance a new input
    let should_add_output = |has_tnc: bool, co_len: usize, ai_len: usize| -> bool {
        if !has_tnc {
            return false;
        }
        net_change_count(co_len, ai_len) - 1 < target_net_count
    };

    // If we want more change outputs, create them now.
    // They may be removed if we cannot fund them.
    while (has_target_net_count
        && target_net_count > net_change_count(change_outputs.len(), allocated_change_inputs.len()))
        || (change_outputs.is_empty()
            && fee_excess(
                args,
                &allocated_change_inputs,
                &change_outputs,
                &fixed_output_satoshis,
                0,
                0,
            ) > 0)
    {
        let sats = if change_outputs.is_empty() {
            args.change_first_satoshis
        } else {
            args.change_initial_satoshis
        };
        change_outputs.push(ChangeOutput { satoshis: sats });
    }

    // === STARVATION LOOP ===
    // Outer loop: releases all inputs, funds, drops outputs if needed, retries.
    // NOTE: removing_outputs declared OUTSIDE the loop (matches TS behavior).
    // Once true, it stays true for all subsequent iterations.
    let mut removing_outputs = false;
    loop {
        release_all(&mut allocated_change_inputs, &mut storage);
        // Note: fee_excess_now is not used within this loop; each branch
        // recomputes `fee_excess(...)` inline. The post-loop block below
        // (line ~452) assigns fee_excess_now based on the final state.

        // Inner funding loop: add one change input at a time
        while fee_excess(
            args,
            &allocated_change_inputs,
            &change_outputs,
            &fixed_output_satoshis,
            0,
            0,
        ) < 0
        {
            // Attempt to fund: compute target satoshis needed
            let mut exact_satoshis: Option<u64> = None;
            if !has_target_net_count && change_outputs.is_empty() {
                let deficit = -fee_excess(
                    args,
                    &allocated_change_inputs,
                    &change_outputs,
                    &fixed_output_satoshis,
                    1,
                    0,
                );
                if deficit > 0 {
                    exact_satoshis = Some(deficit as u64);
                }
            }

            let ao: usize = if should_add_output(
                has_target_net_count,
                change_outputs.len(),
                allocated_change_inputs.len(),
            ) {
                1
            } else {
                0
            };

            let target_satoshis = {
                let deficit = -fee_excess(
                    args,
                    &allocated_change_inputs,
                    &change_outputs,
                    &fixed_output_satoshis,
                    1,
                    ao,
                );
                let extra = if ao == 1 {
                    2 * args.change_initial_satoshis
                } else {
                    0
                };
                if deficit > 0 {
                    deficit as u64 + extra
                } else {
                    extra
                }
            };

            match storage.allocate(target_satoshis, exact_satoshis) {
                None => break, // No more funding available
                Some(input) => {
                    allocated_change_inputs.push(input);

                    let current_excess = fee_excess(
                        args,
                        &allocated_change_inputs,
                        &change_outputs,
                        &fixed_output_satoshis,
                        0,
                        0,
                    );

                    if !removing_outputs
                        && current_excess > 0
                        && (ao == 1 || change_outputs.is_empty())
                    {
                        let sats = std::cmp::min(
                            current_excess as u64,
                            if change_outputs.is_empty() {
                                args.change_first_satoshis
                            } else {
                                args.change_initial_satoshis
                            },
                        );
                        change_outputs.push(ChangeOutput { satoshis: sats });
                    }
                }
            }
        }

        // Done if balanced/overbalanced or impossible
        let current_fe = fee_excess(
            args,
            &allocated_change_inputs,
            &change_outputs,
            &fixed_output_satoshis,
            0,
            0,
        );
        if current_fe >= 0 || change_outputs.is_empty() {
            break;
        }

        removing_outputs = true;

        // Drop change outputs one at a time until funded or none remain
        while !change_outputs.is_empty()
            && fee_excess(
                args,
                &allocated_change_inputs,
                &change_outputs,
                &fixed_output_satoshis,
                0,
                0,
            ) < 0
        {
            change_outputs.pop();
        }

        if fee_excess(
            args,
            &allocated_change_inputs,
            &change_outputs,
            &fixed_output_satoshis,
            0,
            0,
        ) < 0
        {
            // Not enough funding even without change outputs
            break;
        }

        // Remove change inputs that funded only a single change output
        // to reduce pointless churn
        let mut temp_inputs: Vec<AllocatedChangeInputRef> = allocated_change_inputs.clone();
        while temp_inputs.len() > 1 && change_outputs.len() > 1 {
            let last_output_sats = change_outputs.last().unwrap().satoshis;
            match temp_inputs
                .iter()
                .position(|ci| ci.satoshis <= last_output_sats)
            {
                None => break,
                Some(i) => {
                    change_outputs.pop();
                    temp_inputs.remove(i);
                }
            }
        }
        // and try again...
    }

    // Update fee_excess_now
    fee_excess_now = fee_excess(
        args,
        &allocated_change_inputs,
        &change_outputs,
        &fixed_output_satoshis,
        0,
        0,
    );

    // Handle maxPossibleSatoshis adjustment
    let mut max_possible_adjustment: Option<MaxPossibleSatoshisAdjustment> = None;
    if fee_excess_now < 0 {
        if let Some(idx) = has_max_possible_output {
            if fixed_output_satoshis[idx] != MAX_POSSIBLE_SATOSHIS {
                return Err(WalletError::Internal(
                    "maxPossibleSatoshis output changed unexpectedly".to_string(),
                ));
            }
            let adjusted = (fixed_output_satoshis[idx] as i64 + fee_excess_now) as u64;
            fixed_output_satoshis[idx] = adjusted;
            max_possible_adjustment = Some(MaxPossibleSatoshisAdjustment {
                fixed_output_index: idx,
                satoshis: adjusted,
            });
            fee_excess_now = fee_excess(
                args,
                &allocated_change_inputs,
                &change_outputs,
                &fixed_output_satoshis,
                0,
                0,
            );
        }
    }

    // Insufficient funds check
    if fee_excess_now < 0 {
        let total_needed = spending(&fixed_output_satoshis) as i64
            + fee_target(
                args,
                allocated_change_inputs.len(),
                change_outputs.len(),
                0,
                0,
            ) as i64;
        let more_needed = -fee_excess_now;
        release_all(&mut allocated_change_inputs, &mut storage);
        return Err(WalletError::InsufficientFunds {
            message: format!("Insufficient funds: need {} more satoshis", more_needed),
            total_satoshis_needed: total_needed,
            more_satoshis_needed: more_needed,
        });
    }

    // If no change outputs but excess > 0, need a change output to recapture
    if change_outputs.is_empty() && fee_excess_now > 0 {
        let total_needed = spending(&fixed_output_satoshis) as i64
            + fee_target(
                args,
                allocated_change_inputs.len(),
                change_outputs.len(),
                0,
                0,
            ) as i64;
        release_all(&mut allocated_change_inputs, &mut storage);
        return Err(WalletError::InsufficientFunds {
            message: "Insufficient funds: need change output".to_string(),
            total_satoshis_needed: total_needed,
            more_satoshis_needed: args.change_first_satoshis as i64,
        });
    }

    // === EXCESS DISTRIBUTION ===
    // Distribute excess fees across change outputs (matching TS behavior)
    while !change_outputs.is_empty() && fee_excess_now > 0 {
        if change_outputs.len() == 1 {
            change_outputs[0].satoshis += fee_excess_now as u64;
            fee_excess_now = 0;
        } else if change_outputs[0].satoshis < args.change_initial_satoshis {
            let sats = std::cmp::min(
                fee_excess_now as u64,
                args.change_initial_satoshis - change_outputs[0].satoshis,
            );
            fee_excess_now -= sats as i64;
            change_outputs[0].satoshis += sats;
        } else {
            // In TS this uses random distribution. For determinism in the
            // pure function we distribute 50% to the first output at a time.
            let sats = std::cmp::max(1, fee_excess_now as u64 / 2);
            fee_excess_now -= sats as i64;
            change_outputs[0].satoshis += sats;
        }
    }

    // Compute final size and fee
    let final_size = compute_size(
        args,
        allocated_change_inputs.len(),
        change_outputs.len(),
        0,
        0,
    );
    let actual_fee = {
        let f = funding(args, &allocated_change_inputs);
        let s = spending(&fixed_output_satoshis);
        let c = change_total(&change_outputs);
        f - s - c
    };

    // Validate result: fee must equal target fee
    let expected_fee = fee_target(
        args,
        allocated_change_inputs.len(),
        change_outputs.len(),
        0,
        0,
    );
    if actual_fee != expected_fee {
        return Err(WalletError::Internal(format!(
            "generateChangeSdk error: required fee error {} !== {}",
            expected_fee, actual_fee
        )));
    }

    Ok(GenerateChangeSdkResult {
        change_outputs,
        allocated_change_inputs,
        size: final_size,
        fee: actual_fee,
        sats_per_kb,
        max_possible_satoshis_adjustment: max_possible_adjustment,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::action_types::{FixedInput, FixedOutput, StorageFeeModel};

    fn make_args(
        fixed_inputs: Vec<FixedInput>,
        fixed_outputs: Vec<FixedOutput>,
        target_net_count: Option<i64>,
    ) -> GenerateChangeSdkArgs {
        GenerateChangeSdkArgs {
            fixed_inputs,
            fixed_outputs,
            fee_model: StorageFeeModel {
                model: "sat/kb".to_string(),
                value: 100,
            },
            change_initial_satoshis: 1000,
            change_first_satoshis: 285,
            change_locking_script_length: 25,
            change_unlocking_script_length: 107,
            target_net_count,
        }
    }

    fn make_utxos(satoshis_list: &[u64]) -> Vec<AvailableChange> {
        satoshis_list
            .iter()
            .enumerate()
            .map(|(i, &s)| AvailableChange {
                output_id: (i + 1) as i64,
                satoshis: s,
                spendable: true,
            })
            .collect()
    }

    #[test]
    fn test_zero_inputs_zero_outputs_zero_fee_rate() {
        // Given 0 available UTXOs and 0 fee rate, returns empty result with 0 fee
        let mut args = make_args(vec![], vec![], None);
        args.fee_model.value = 0;
        let available: Vec<AvailableChange> = vec![];
        let result = generate_change_sdk(&args, &available).unwrap();
        assert_eq!(result.change_outputs.len(), 0);
        assert_eq!(result.allocated_change_inputs.len(), 0);
        assert_eq!(result.fee, 0);
    }

    #[test]
    fn test_sufficient_utxos_target_count_1() {
        // Given sufficient UTXOs and target_net_count=1, returns 1 change output
        let args = make_args(
            vec![FixedInput {
                satoshis: 10_000,
                unlocking_script_length: 107,
            }],
            vec![FixedOutput {
                satoshis: 5_000,
                locking_script_length: 25,
            }],
            Some(1),
        );
        let available = make_utxos(&[2000, 5000, 10000]);
        let result = generate_change_sdk(&args, &available).unwrap();
        assert!(
            !result.change_outputs.is_empty(),
            "should have at least 1 change output"
        );
        assert!(result.fee > 0, "fee should be positive");
        // Verify: funding - spending - change = fee
        let total_funding: u64 = 10_000
            + result
                .allocated_change_inputs
                .iter()
                .map(|i| i.satoshis)
                .sum::<u64>();
        let total_spending: u64 = 5_000
            + result
                .change_outputs
                .iter()
                .map(|o| o.satoshis)
                .sum::<u64>();
        assert_eq!(total_funding - total_spending, result.fee);
    }

    #[test]
    fn test_insufficient_utxos_error() {
        // Given insufficient UTXOs, returns WERR_INSUFFICIENT_FUNDS
        let args = make_args(
            vec![],
            vec![FixedOutput {
                satoshis: 100_000,
                locking_script_length: 25,
            }],
            None,
        );
        let available = make_utxos(&[100, 200]);
        let result = generate_change_sdk(&args, &available);
        assert!(result.is_err());
        match result.unwrap_err() {
            WalletError::InsufficientFunds { .. } => {}
            other => panic!("Expected InsufficientFunds, got {:?}", other),
        }
    }

    #[test]
    fn test_starvation_loop_drops_change_outputs() {
        // When unable to fund all requested change outputs, drops them one at a time
        let args = make_args(
            vec![FixedInput {
                satoshis: 2000,
                unlocking_script_length: 107,
            }],
            vec![FixedOutput {
                satoshis: 500,
                locking_script_length: 25,
            }],
            Some(3),
        );
        // Small UTXOs: cannot fund 3 net change outputs
        let available = make_utxos(&[300, 400, 500]);
        let result = generate_change_sdk(&args, &available).unwrap();
        assert!(result.fee > 0);
        // Verify balance
        let total_funding: u64 = 2000
            + result
                .allocated_change_inputs
                .iter()
                .map(|i| i.satoshis)
                .sum::<u64>();
        let total_spending: u64 = 500
            + result
                .change_outputs
                .iter()
                .map(|o| o.satoshis)
                .sum::<u64>();
        assert_eq!(total_funding - total_spending, result.fee);
    }

    #[test]
    fn test_excess_distributed_to_change() {
        // Excess satoshis are distributed to change outputs
        let args = make_args(
            vec![FixedInput {
                satoshis: 50_000,
                unlocking_script_length: 107,
            }],
            vec![FixedOutput {
                satoshis: 1_000,
                locking_script_length: 25,
            }],
            Some(1),
        );
        let available = make_utxos(&[5000]);
        let result = generate_change_sdk(&args, &available).unwrap();
        let change_sum: u64 = result.change_outputs.iter().map(|o| o.satoshis).sum();
        let total_funding: u64 = 50_000
            + result
                .allocated_change_inputs
                .iter()
                .map(|i| i.satoshis)
                .sum::<u64>();
        assert_eq!(total_funding - 1_000 - result.fee, change_sum);
    }

    #[test]
    fn test_fee_calculation_matches_formula() {
        // Fee = ceil(transaction_size * fee_rate / 1000)
        let args = make_args(
            vec![FixedInput {
                satoshis: 10_000,
                unlocking_script_length: 107,
            }],
            vec![FixedOutput {
                satoshis: 5_000,
                locking_script_length: 25,
            }],
            None,
        );
        let available = make_utxos(&[5000]);
        let result = generate_change_sdk(&args, &available).unwrap();
        let expected_fee = ((result.size as u64) * 100).div_ceil(1000);
        assert_eq!(result.fee, expected_fee);
    }

    #[test]
    fn test_configurable_initial_satoshis() {
        // Change outputs use configurable initial satoshis
        let mut args = make_args(
            vec![FixedInput {
                satoshis: 100_000,
                unlocking_script_length: 107,
            }],
            vec![FixedOutput {
                satoshis: 1_000,
                locking_script_length: 25,
            }],
            Some(2),
        );
        args.change_initial_satoshis = 2000;
        args.change_first_satoshis = 500;
        let available = make_utxos(&[5000, 5000]);
        let result = generate_change_sdk(&args, &available).unwrap();
        assert!(!result.change_outputs.is_empty());
        let total_funding: u64 = 100_000
            + result
                .allocated_change_inputs
                .iter()
                .map(|i| i.satoshis)
                .sum::<u64>();
        let total_change: u64 = result.change_outputs.iter().map(|o| o.satoshis).sum();
        assert_eq!(total_funding - 1_000 - result.fee, total_change);
    }

    #[test]
    fn test_max_possible_satoshis_adjustment() {
        // maxPossibleSatoshis correctly limits output to actual funding
        let args = make_args(
            vec![FixedInput {
                satoshis: 5_000,
                unlocking_script_length: 107,
            }],
            vec![FixedOutput {
                satoshis: MAX_POSSIBLE_SATOSHIS,
                locking_script_length: 25,
            }],
            None,
        );
        let available: Vec<AvailableChange> = vec![];
        let result = generate_change_sdk(&args, &available).unwrap();
        assert!(result.max_possible_satoshis_adjustment.is_some());
        let adj = result.max_possible_satoshis_adjustment.unwrap();
        assert_eq!(adj.fixed_output_index, 0);
        assert_eq!(adj.satoshis, 5_000 - result.fee);
    }

    #[test]
    fn test_no_change_exact_funding() {
        // When funding exactly covers spending + fee, no change output needed
        // 1 input (107 unlock) + 1 output (25 lock):
        //   size = 4 + 1 + (32+4+1+107+4) + 1 + (1+25+8) + 4 = 4+1+148+1+34+4 = 192
        //   fee = ceil(192 * 100 / 1000) = ceil(19.2) = 20
        // So we need exactly 5000 + 20 = 5020 in the input
        let args = make_args(
            vec![FixedInput {
                satoshis: 5_020,
                unlocking_script_length: 107,
            }],
            vec![FixedOutput {
                satoshis: 5_000,
                locking_script_length: 25,
            }],
            None,
        );
        let available: Vec<AvailableChange> = vec![];
        let result = generate_change_sdk(&args, &available).unwrap();
        // Should succeed with no change outputs and fee = 20
        assert_eq!(result.change_outputs.len(), 0);
        assert_eq!(result.allocated_change_inputs.len(), 0);
        // Size: 4 + 1 + 148 + 1 + 34 + 4 = 192
        assert_eq!(result.size, 192);
        assert_eq!(result.fee, 20);
    }
}