ark-lib 0.1.0-beta.7

Primitives for the Ark protocol and bark 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
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
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
//! Utilities to create out-of-round transactions using
//! checkpoint transactions.
//!
//! # Checkpoints keep users and the server safe
//!
//! When an Ark transaction is spent out-of-round a new
//! transaction is added on top of that. In the naive
//! approach we just keep adding transactions and the
//! chain becomes longer.
//!
//! A first problem is that this can become unsafe for the server.
//! If a client performs a partial exit attack the server
//! will have to broadcast a long chain of transactions
//! to get the forfeit published.
//!
//! A second problem is that if one user exits it affects everyone.
//! In their chunk of the tree. The server cannot sweep the funds
//! anymore and all other users are forced to collect their funds
//! from the chain (which can be expensive).
//!
//! # How do they work
//!
//! The core idea is that each out-of-round spent will go through
//! a checkpoint transaction. The checkpoint transaction has the policy
//! `A + S or S after expiry`.
//!
//! Note, that the `A+S` path is fast and will always take priority.
//! Users will still be able to exit their funds at any time.
//! But if a partial exit occurs, the server can just broadcast
//! a single checkpoint transaction and continue like nothing happened.
//!
//! Other users will be fully unaffected by this. Their [Vtxo] will now
//! be anchored in the checkpoint which can be swept after expiry.
//!
//! # Usage
//!
//! This module creates a checkpoint transaction that originates
//! from a single [Vtxo]. It is a low-level construct and the developer
//! has to compute the paid amount, change and fees themselves.
//!
//! The core construct is [ArkoorBuilder] which can be
//! used to build arkoor transactions. The struct is designed to be
//! used by both the client and the server.
//!
//! [ArkoorBuilder::new]  is a constructor that validates
//! the intended transaction. At this point, all transactions that
//! will be constructed are fully designed. You can
//! use [ArkoorBuilder::build_unsigned_vtxos] to construct the
//! vtxos but they will still lack signatures.
//!
//! Constructing the signatures is an interactive process in which the
//! server signs first.
//!
//! The client will call [ArkoorBuilder::generate_user_nonces]
//! which will update the builder-state to  [state::UserGeneratedNonces].
//! The client will create a [CosignRequest] which contains the details
//! about the arkoor payment including the user nonces. The server will
//! respond with a [CosignResponse] which can be used to finalize all
//! signatures. At the end the client can call [ArkoorBuilder::build_signed_vtxos]
//! to get their fully signed VTXOs.
//!
//! The server will also use [ArkoorBuilder::from_cosign_request]
//! to construct a builder. The [ArkoorBuilder::server_cosign]
//! will construct the [CosignResponse] which is sent to the client.
//!

pub mod package;

use std::marker::PhantomData;

use bitcoin::hashes::Hash;
use bitcoin::sighash::{self, SighashCache};
use bitcoin::{
	Amount, OutPoint, ScriptBuf, Sequence, TapSighash, TapSighashType, Transaction, TxIn, TxOut, Txid, Witness
};
use bitcoin::taproot::TapTweakHash;
use bitcoin::secp256k1::{schnorr, Keypair, PublicKey};
use bitcoin_ext::{fee, P2TR_DUST, TxOutExt};
use secp256k1_musig::musig::PublicNonce;

use crate::{musig, scripts, Vtxo, VtxoId, ServerVtxo};
use crate::vtxo::{VtxoPolicy, ServerVtxoPolicy};
use crate::vtxo::genesis::{GenesisItem, GenesisTransition};

pub use package::ArkoorPackageBuilder;


#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
pub enum ArkoorConstructionError {
	#[error("Input amount of {input} does not match output amount of {output}")]
	Unbalanced {
		input: Amount,
		output: Amount,
	},
	#[error("An output is below the dust threshold")]
	Dust,
	#[error("At least one output is required")]
	NoOutputs,
	#[error("Too many inputs provided")]
	TooManyInputs,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
pub enum ArkoorSigningError {
	#[error("An error occurred while building arkoor: {0}")]
	ArkoorConstructionError(ArkoorConstructionError),
	#[error("Wrong number of user nonces provided. Expected {expected}, got {got}")]
	InvalidNbUserNonces {
		expected: usize,
		got: usize,
	},
	#[error("Wrong number of server nonces provided. Expected {expected}, got {got}")]
	InvalidNbServerNonces {
		expected: usize,
		got: usize,
	},
	#[error("Incorrect signing key provided. Expected {expected}, got {got}")]
	IncorrectKey {
		expected: PublicKey,
		got: PublicKey,
	},
	#[error("Wrong number of server partial sigs. Expected {expected}, got {got}")]
	InvalidNbServerPartialSigs {
		expected: usize,
		got: usize
	},
	#[error("Invalid partial signature at index {index}")]
	InvalidPartialSignature {
		index: usize,
	},
	#[error("Wrong number of packages. Expected {expected}, got {got}")]
	InvalidNbPackages {
		expected: usize,
		got: usize,
	},
	#[error("Wrong number of keypairs. Expected {expected}, got {got}")]
	InvalidNbKeypairs {
		expected: usize,
		got: usize,
	},
}

/// The destination of an arkoor pacakage
///
/// Because arkoor does not allow multiple inputs, often the destinations
/// are broken up into multiple VTXOs with the same policy.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct ArkoorDestination {
	pub total_amount: Amount,
	#[serde(with = "crate::encode::serde")]
	pub policy: VtxoPolicy,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArkoorCosignResponse {
	pub server_pub_nonces: Vec<musig::PublicNonce>,
	pub server_partial_sigs: Vec<musig::PartialSignature>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArkoorCosignRequest<V> {
	pub user_pub_nonces: Vec<musig::PublicNonce>,
	pub input: V,
	pub outputs: Vec<ArkoorDestination>,
	pub isolated_outputs: Vec<ArkoorDestination>,
	pub use_checkpoint: bool,
}

impl<V> ArkoorCosignRequest<V> {
	pub fn new(
		user_pub_nonces: Vec<musig::PublicNonce>,
		input: V,
		outputs: Vec<ArkoorDestination>,
		isolated_outputs: Vec<ArkoorDestination>,
		use_checkpoint: bool,
	) -> Self {
		Self {
			user_pub_nonces,
			input,
			outputs,
			isolated_outputs,
			use_checkpoint,
		}
	}

	pub fn all_outputs(&self) -> impl Iterator<Item = &ArkoorDestination> + Clone {
		self.outputs.iter().chain(&self.isolated_outputs)
	}
}

impl ArkoorCosignRequest<VtxoId> {
	pub fn with_vtxo(self, vtxo: Vtxo) -> Result<ArkoorCosignRequest<Vtxo>, &'static str> {
		if self.input != vtxo.id() {
			return Err("Input vtxo id does not match the provided vtxo id")
		}

		Ok(ArkoorCosignRequest::new(
			self.user_pub_nonces,
			vtxo,
			self.outputs,
			self.isolated_outputs,
			self.use_checkpoint,
		))
	}
}


pub mod state {
	/// There are two paths that a can be followed
	///
	/// 1. [Initial] -> [UserGeneratedNonces] -> [UserSigned]
	/// 2. [Initial] -> [ServerCanCosign] -> [ServerSigned]
	///
	/// The first option is taken by the user and the second by the server

	mod sealed {
		pub trait Sealed {}
		impl Sealed for super::Initial {}
		impl Sealed for super::UserGeneratedNonces {}
		impl Sealed for super::UserSigned {}
		impl Sealed for super::ServerCanCosign {}
		impl Sealed for super::ServerSigned {}
	}

	pub trait BuilderState: sealed::Sealed {}

	// The initial state of the builder
	pub struct Initial;
	impl BuilderState for Initial {}

	// The user has generated their nonces
	pub struct UserGeneratedNonces;
	impl BuilderState for UserGeneratedNonces {}

	// The user can sign
	pub struct UserSigned;
	impl BuilderState for UserSigned {}

	// The server can cosign
	pub struct ServerCanCosign;
	impl BuilderState for ServerCanCosign {}


	/// The server has signed and knows the partial signatures
	pub struct ServerSigned;
	impl BuilderState for ServerSigned {}
}

pub struct ArkoorBuilder<S: state::BuilderState> {
	// These variables are provided by the user
	/// The input vtxo to be spent
	input: Vtxo,
	/// Regular output vtxos
	outputs: Vec<ArkoorDestination>,
	/// Isolated outputs that will go through an isolation tx
	///
	/// This is meant to isolate dust outputs from non-dust ones.
	isolated_outputs: Vec<ArkoorDestination>,

	/// Data on the checkpoint tx, if checkpoints are enabled
	///
	/// - the unsigned checkpoint transaction
	/// - the txid of the checkpoint transaction
	checkpoint_data: Option<(Transaction, Txid)>,
	/// The unsigned arkoor transactions (one per normal output)
	unsigned_arkoor_txs: Vec<Transaction>,
	/// The unsigned isolation fanout transaction (only when dust isolation is needed)
	/// Splits the combined dust checkpoint output into k outputs with user's final policies
	unsigned_isolation_fanout_tx: Option<Transaction>,
	/// The sighashes that must be signed
	sighashes: Vec<TapSighash>,
	/// Taptweak derived from the input vtxo's policy.
	input_tweak: TapTweakHash,
	/// Taptweak for all outputs of the checkpoint tx.
	/// NB: Also used for dust isolation outputs even when not using checkpoints.
	checkpoint_policy_tweak: TapTweakHash,
	/// The [VtxoId]s of all new [Vtxo]s that will be created
	new_vtxo_ids: Vec<VtxoId>,

	//  These variables are filled in when the state progresses
	/// We need 1 signature for the checkpoint transaction
	/// We need n signatures. This is one for each arkoor tx
	/// `1+n` public nonces created by the user
	user_pub_nonces: Option<Vec<musig::PublicNonce>>,
	/// `1+n` secret nonces created by the user
	user_sec_nonces: Option<Vec<musig::SecretNonce>>,
	/// `1+n` public nonces created by the server
	server_pub_nonces: Option<Vec<musig::PublicNonce>>,
	/// `1+n` partial signatures created by the server
	server_partial_sigs: Option<Vec<musig::PartialSignature>>,
	/// `1+n` signatures that are signed by the user and server
	full_signatures: Option<Vec<schnorr::Signature>>,

	_state: PhantomData<S>,
}

impl<S: state::BuilderState> ArkoorBuilder<S> {
	/// Access the input VTXO
	pub fn input(&self) -> &Vtxo {
		&self.input
	}

	/// Access the regular (non-isolated) outputs of the builder
	pub fn normal_outputs(&self) -> &[ArkoorDestination] {
		&self.outputs
	}

	/// Access the isolated outputs of the builder
	pub fn isolated_outputs(&self) -> &[ArkoorDestination] {
		&self.isolated_outputs
	}

	/// Access all outputs of the builder
	pub fn all_outputs(
		&self,
	) -> impl Iterator<Item = &ArkoorDestination> + Clone {
		self.outputs.iter().chain(&self.isolated_outputs)
	}

	fn build_checkpoint_vtxo_at(
		&self,
		output_idx: usize,
		checkpoint_sig: Option<schnorr::Signature>
	) -> ServerVtxo {
		let output = &self.outputs[output_idx];
		let (checkpoint_tx, checkpoint_txid) = self.checkpoint_data.as_ref()
			.expect("called checkpoint_vtxo_at in context without checkpoints");

		Vtxo {
			amount: output.total_amount,
			policy: ServerVtxoPolicy::new_checkpoint(self.input.user_pubkey()),
			expiry_height: self.input.expiry_height,
			server_pubkey: self.input.server_pubkey,
			exit_delta: self.input.exit_delta,
			point: OutPoint::new(*checkpoint_txid, output_idx as u32),
			anchor_point: self.input.anchor_point,
			genesis: self.input.genesis.clone().into_iter().chain([
				GenesisItem {
					transition: GenesisTransition::new_arkoor(
						vec![self.input.user_pubkey()],
						self.input.policy().taproot(
							self.input.server_pubkey,
							self.input.exit_delta,
							self.input.expiry_height,
						).tap_tweak(),
						checkpoint_sig,
					),
					output_idx: output_idx as u8,
					other_outputs: checkpoint_tx.output
						.iter().enumerate()
						.filter_map(|(i, txout)| {
							if i == (output_idx as usize) || txout.is_p2a_fee_anchor() {
								None
							} else {
								Some(txout.clone())
							}
						})
						.collect(),
				},
			]).collect(),
		}
	}

	fn build_vtxo_at(
		&self,
		output_idx: usize,
		checkpoint_sig: Option<schnorr::Signature>,
		arkoor_sig: Option<schnorr::Signature>,
	) -> Vtxo {
		let output = &self.outputs[output_idx];

		if let Some((checkpoint_tx, _txid)) = &self.checkpoint_data {
			// Two-transition genesis: Input → Checkpoint → Arkoor
			let checkpoint_policy = ServerVtxoPolicy::new_checkpoint(self.input.user_pubkey());

			Vtxo {
				amount: output.total_amount,
				policy: output.policy.clone(),
				expiry_height: self.input.expiry_height,
				server_pubkey: self.input.server_pubkey,
				exit_delta: self.input.exit_delta,
				point: self.new_vtxo_ids[output_idx].utxo(),
				anchor_point: self.input.anchor_point,
				genesis: self.input.genesis.iter().cloned().chain([
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							self.input.policy.taproot(
								self.input.server_pubkey,
								self.input.exit_delta,
								self.input.expiry_height,
							).tap_tweak(),
							checkpoint_sig,
						),
						output_idx: output_idx as u8,
						other_outputs: checkpoint_tx.output
							.iter().enumerate()
							.filter_map(|(i, txout)| {
								if i == (output_idx as usize) || txout.is_p2a_fee_anchor() {
									None
								} else {
									Some(txout.clone())
								}
							})
							.collect(),
					},
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							checkpoint_policy.taproot(
								self.input.server_pubkey,
								self.input.exit_delta,
								self.input.expiry_height,
							).tap_tweak(),
							arkoor_sig,
						),
						output_idx: 0,
						other_outputs: vec![]
					}
				]).collect(),
			}
		} else {
			// Single-transition genesis: Input → Arkoor
			let arkoor_tx = &self.unsigned_arkoor_txs[0];

			Vtxo {
				amount: output.total_amount,
				policy: output.policy.clone(),
				expiry_height: self.input.expiry_height,
				server_pubkey: self.input.server_pubkey,
				exit_delta: self.input.exit_delta,
				point: OutPoint::new(arkoor_tx.compute_txid(), output_idx as u32),
				anchor_point: self.input.anchor_point,
				genesis: self.input.genesis.iter().cloned().chain([
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							self.input.policy.taproot(
								self.input.server_pubkey,
								self.input.exit_delta,
								self.input.expiry_height,
							).tap_tweak(),
							arkoor_sig,
						),
						output_idx: output_idx as u8,
						other_outputs: arkoor_tx.output
							.iter().enumerate()
							.filter_map(|(idx, txout)| {
								if idx == output_idx || txout.is_p2a_fee_anchor() {
									None
								} else {
									Some(txout.clone())
								}
							})
							.collect(),
					}
				]).collect(),
			}
		}
	}

	/// Build the isolated vtxo at the given index
	///
	/// Only used when dust isolation is active.
	///
	/// The `pre_fanout_tx_sig` is either
	/// - the arkoor tx signature when no checkpoint tx is used, or
	/// - the checkpoint tx signature when a checkpoint tx is used
	fn build_isolated_vtxo_at(
		&self,
		isolated_idx: usize,
		pre_fanout_tx_sig: Option<schnorr::Signature>,
		isolation_fanout_tx_sig: Option<schnorr::Signature>,
	) -> Vtxo {
		let output = &self.isolated_outputs[isolated_idx];
		let checkpoint_policy = ServerVtxoPolicy::new_checkpoint(self.input.user_pubkey());

		let fanout_tx = self.unsigned_isolation_fanout_tx.as_ref()
			.expect("construct_dust_vtxo_at called without dust isolation");

		// The combined dust isolation output is at index outputs.len()
		let dust_isolation_output_idx = self.outputs.len();

		if let Some((checkpoint_tx, _txid)) = &self.checkpoint_data {
			// Two transitions: Input → Checkpoint → Fanout (final vtxo)
			Vtxo {
				amount: output.total_amount,
				policy: output.policy.clone(),
				expiry_height: self.input.expiry_height,
				server_pubkey: self.input.server_pubkey,
				exit_delta: self.input.exit_delta,
				point: OutPoint::new(fanout_tx.compute_txid(), isolated_idx as u32),
				anchor_point: self.input.anchor_point,
				genesis: self.input.genesis.iter().cloned().chain([
					// Transition 1: input -> checkpoint
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							self.input.policy.taproot(
								self.input.server_pubkey,
								self.input.exit_delta,
								self.input.expiry_height,
							).tap_tweak(),
							pre_fanout_tx_sig,
						),
						output_idx: dust_isolation_output_idx as u8,
						// other outputs are the normal outputs
						// (we skip our combined dust output and fee anchor)
						other_outputs: checkpoint_tx.output
							.iter().enumerate()
							.filter_map(|(idx, txout)| {
								if idx == dust_isolation_output_idx || txout.is_p2a_fee_anchor() {
									None
								} else {
									Some(txout.clone())
								}
							})
							.collect(),
					},
					// Transition 2: checkpoint -> isolation fanout tx (final vtxo)
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							checkpoint_policy.taproot(
								self.input.server_pubkey,
								self.input.exit_delta,
								self.input.expiry_height,
							).tap_tweak(),
							isolation_fanout_tx_sig,
						),
						output_idx: isolated_idx as u8,
						// other outputs are the other isolated outputs
						// (we skip our output and fee anchor)
						other_outputs: fanout_tx.output
							.iter().enumerate()
							.filter_map(|(idx, txout)| {
								if idx == isolated_idx || txout.is_p2a_fee_anchor() {
									None
								} else {
									Some(txout.clone())
								}
							})
							.collect(),
					},
				]).collect(),
			}
		} else {
			// Two transitions: Input → Arkoor (with isolation output) → Fanout (final vtxo)
			let arkoor_tx = &self.unsigned_arkoor_txs[0];

			Vtxo {
				amount: output.total_amount,
				policy: output.policy.clone(),
				expiry_height: self.input.expiry_height,
				server_pubkey: self.input.server_pubkey,
				exit_delta: self.input.exit_delta,
				point: OutPoint::new(fanout_tx.compute_txid(), isolated_idx as u32),
				anchor_point: self.input.anchor_point,
				genesis: self.input.genesis.iter().cloned().chain([
					// Transition 1: input -> arkoor tx (which includes isolation output)
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							self.input.policy.taproot(
								self.input.server_pubkey,
								self.input.exit_delta,
								self.input.expiry_height,
							).tap_tweak(),
							pre_fanout_tx_sig,
						),
						output_idx: dust_isolation_output_idx as u8,
						other_outputs: arkoor_tx.output
							.iter().enumerate()
							.filter_map(|(idx, txout)| {
								if idx == dust_isolation_output_idx || txout.is_p2a_fee_anchor() {
									None
								} else {
									Some(txout.clone())
								}
							})
							.collect(),
					},
					// Transition 2: isolation output -> isolation fanout tx (final vtxo)
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							checkpoint_policy.taproot(
								self.input.server_pubkey,
								self.input.exit_delta,
								self.input.expiry_height,
							).tap_tweak(),
							isolation_fanout_tx_sig,
						),
						output_idx: isolated_idx as u8,
						other_outputs: fanout_tx.output
							.iter().enumerate()
							.filter_map(|(idx, txout)| {
								if idx == isolated_idx || txout.is_p2a_fee_anchor() {
									None
								} else {
									Some(txout.clone())
								}
							})
							.collect(),
					},
				]).collect(),
			}
		}
	}

	fn nb_sigs(&self) -> usize {
		let base = if self.checkpoint_data.is_some() {
			1 + self.outputs.len()  // 1 checkpoint + m arkoor txs
		} else {
			1  // 1 direct arkoor tx (regardless of output count)
		};

		if self.unsigned_isolation_fanout_tx.is_some() {
			base + 1  // Just 1 fanout tx signature
		} else {
			base
		}
	}

	pub fn build_unsigned_vtxos<'a>(&'a self) -> impl Iterator<Item = Vtxo> + 'a {
		let regular = (0..self.outputs.len()).map(|i| self.build_vtxo_at(i, None, None));
		let isolated = (0..self.isolated_outputs.len())
			.map(|i| self.build_isolated_vtxo_at(i, None, None));
		regular.chain(isolated)
	}

	/// Builds the unsigned internal VTXOs
	///
	/// Returns the checkpoint outputs (if checkpoinst are used) and the
	/// dust isolation output (if dust isolation is used).
	pub fn build_unsigned_internal_vtxos<'a>(&'a self) -> impl Iterator<Item = ServerVtxo> + 'a {
		let checkpoint_vtxos = {
			let range = if self.checkpoint_data.is_some() {
				0..self.outputs.len()
			} else {
				// none
				0..0
			};
			range.map(|i| self.build_checkpoint_vtxo_at(i, None))
		};

		let isolation_vtxo = if !self.isolated_outputs.is_empty() {
			// isolation comes after all normal outputs
			let output_idx = self.outputs.len();

			// intermediate tx depends on checkpoint
			let (int_tx, int_txid) = if let Some((tx, txid)) = &self.checkpoint_data {
				(tx, *txid)
			} else {
				let arkoor_tx = &self.unsigned_arkoor_txs[0];
				(arkoor_tx, arkoor_tx.compute_txid())
			};

			Some(Vtxo {
				amount: self.isolated_outputs.iter().map(|o| o.total_amount).sum(),
				policy: ServerVtxoPolicy::new_checkpoint(self.input.user_pubkey()),
				expiry_height: self.input.expiry_height,
				server_pubkey: self.input.server_pubkey,
				exit_delta: self.input.exit_delta,
				point: OutPoint::new(int_txid, output_idx as u32),
				anchor_point: self.input.anchor_point,
				genesis: self.input.genesis.clone().into_iter().chain([
					GenesisItem {
						transition: GenesisTransition::new_arkoor(
							vec![self.input.user_pubkey()],
							self.input_tweak,
							None,
						),
						output_idx: output_idx as u8,
						other_outputs: int_tx.output.iter().enumerate()
							.filter_map(|(i, txout)| {
								if i == output_idx || txout.is_p2a_fee_anchor() {
									None
								} else {
									Some(txout.clone())
								}
							})
							.collect(),
					},
				]).collect(),
			})
		} else {
			None
		};

		checkpoint_vtxos.chain(isolation_vtxo)
	}

	/// The returned [VtxoId] is spent out-of-round by [Txid]
	pub fn spend_info(&self) -> Vec<(VtxoId, Txid)> {
		let mut ret = Vec::with_capacity(1 + self.outputs.len());

		if let Some((_tx, checkpoint_txid)) = &self.checkpoint_data {
			// Input vtxo -> checkpoint tx
			ret.push((self.input.id(), *checkpoint_txid));

			// Non-isolated checkpoint outputs -> arkoor txs
			for idx in 0..self.outputs.len() {
				ret.push((
					VtxoId::from(OutPoint::new(*checkpoint_txid, idx as u32)),
					self.unsigned_arkoor_txs[idx].compute_txid()
				));
			}

			// dust isolation paths (if active)
			if let Some(fanout_tx) = &self.unsigned_isolation_fanout_tx {
				let fanout_txid = fanout_tx.compute_txid();

				// Combined isolation checkpoint output -> isolation fanout tx
				let isolated_output_idx = self.outputs.len() as u32;
				ret.push((
					VtxoId::from(OutPoint::new(*checkpoint_txid, isolated_output_idx)),
					fanout_txid,
				));
			}
		} else {
			let arkoor_txid = self.unsigned_arkoor_txs[0].compute_txid();

			// Input vtxo -> arkoor tx
			ret.push((self.input.id(), arkoor_txid));

			// dust isolation paths (if active)
			if let Some(fanout_tx) = &self.unsigned_isolation_fanout_tx {
				let fanout_txid = fanout_tx.compute_txid();

				// Isolation output in arkoor tx -> dust fanout
				let isolation_output_idx = self.outputs.len() as u32;
				ret.push((
					VtxoId::from(OutPoint::new(arkoor_txid, isolation_output_idx)),
					fanout_txid,
				));
			}
		}

		ret
	}

	/// Returns the txids of all virtual transactions in this arkoor:
	/// - checkpoint tx (if checkpoints enabled)
	/// - arkoor txs (one per normal output, exits from checkpoint)
	/// - isolation fanout tx (if dust isolation active)
	pub fn virtual_transactions(&self) -> Vec<Txid> {
		let mut ret = Vec::new();
		// Checkpoint tx
		if let Some((_, txid)) = &self.checkpoint_data {
			ret.push(*txid);
		}
		// Arkoor txs (exits for normal outputs)
		ret.extend(self.unsigned_arkoor_txs.iter().map(|tx| tx.compute_txid()));
		// Isolation fanout tx
		if let Some(tx) = &self.unsigned_isolation_fanout_tx {
			ret.push(tx.compute_txid());
		}
		ret
	}

	fn taptweak_at(&self, idx: usize) -> TapTweakHash {
		if idx == 0 { self.input_tweak } else { self.checkpoint_policy_tweak }
	}

	fn user_pubkey(&self) -> PublicKey {
		self.input.user_pubkey()
	}

	fn server_pubkey(&self) -> PublicKey {
		self.input.server_pubkey()
	}

	/// Construct the checkpoint transaction
	///
	/// When dust isolation is needed, `combined_dust_amount` should be Some
	/// with the total dust amount.
	fn construct_unsigned_checkpoint_tx(
		input: &Vtxo,
		outputs: &[ArkoorDestination],
		dust_isolation_amount: Option<Amount>,
	) -> Transaction {
		// All outputs on the checkpoint transaction will use exactly the same policy.
		let output_policy = ServerVtxoPolicy::new_checkpoint(input.user_pubkey());
		let checkpoint_spk = output_policy
			.script_pubkey(input.server_pubkey(), input.exit_delta(), input.expiry_height());

		Transaction {
			version: bitcoin::transaction::Version(3),
			lock_time: bitcoin::absolute::LockTime::ZERO,
			input: vec![TxIn {
				previous_output: input.point(),
				script_sig: ScriptBuf::new(),
				sequence: Sequence::ZERO,
				witness: Witness::new(),
			}],
			output: outputs.iter().map(|o| {
				TxOut {
					value: o.total_amount,
					script_pubkey: checkpoint_spk.clone(),
				}
			})
				// add dust isolation output when required
				.chain(dust_isolation_amount.map(|amt| {
					TxOut {
						value: amt,
						script_pubkey: checkpoint_spk.clone(),
					}
				}))
				.chain([fee::fee_anchor()]).collect()
		}
	}

	fn construct_unsigned_arkoor_txs(
		input: &Vtxo,
		outputs: &[ArkoorDestination],
		checkpoint_txid: Option<Txid>,
		dust_isolation_amount: Option<Amount>,
	) -> Vec<Transaction> {
		if let Some(checkpoint_txid) = checkpoint_txid {
			// Checkpoint mode: create separate arkoor tx for each output
			let mut arkoor_txs = Vec::with_capacity(outputs.len());

			for (vout, output) in outputs.iter().enumerate() {
				let transaction = Transaction {
					version: bitcoin::transaction::Version(3),
					lock_time: bitcoin::absolute::LockTime::ZERO,
					input: vec![TxIn {
						previous_output: OutPoint::new(checkpoint_txid, vout as u32),
						script_sig: ScriptBuf::new(),
						sequence: Sequence::ZERO,
						witness: Witness::new(),
					}],
					output: vec![
						output.policy.txout(
							output.total_amount,
							input.server_pubkey(),
							input.exit_delta(),
							input.expiry_height(),
						),
						fee::fee_anchor(),
					]
				};
				arkoor_txs.push(transaction);
			}

			arkoor_txs
		} else {
			// Direct mode: create single arkoor tx with all outputs + optional isolation output
			let checkpoint_policy = ServerVtxoPolicy::new_checkpoint(input.user_pubkey());
			let checkpoint_spk = checkpoint_policy.script_pubkey(
				input.server_pubkey(),
				input.exit_delta(),
				input.expiry_height()
			);

			let transaction = Transaction {
				version: bitcoin::transaction::Version(3),
				lock_time: bitcoin::absolute::LockTime::ZERO,
				input: vec![TxIn {
					previous_output: input.point(),
					script_sig: ScriptBuf::new(),
					sequence: Sequence::ZERO,
					witness: Witness::new(),
				}],
				output: outputs.iter()
					.map(|o| o.policy.txout(
						o.total_amount,
						input.server_pubkey(),
						input.exit_delta(),
						input.expiry_height(),
					))
					// Add isolation output if dust is present
					.chain(dust_isolation_amount.map(|amt| TxOut {
						value: amt,
						script_pubkey: checkpoint_spk.clone(),
					}))
					.chain([fee::fee_anchor()])
					.collect()
			};
			vec![transaction]
		}
	}

	/// Construct the dust isolation transaction that splits the combined
	/// dust output into individual outputs
	///
	/// Each output uses the user's final policy directly.
	/// Called only when dust isolation is needed.
	///
	/// `parent_txid` is either the checkpoint txid (checkpoint mode) or arkoor txid (direct mode)
	fn construct_unsigned_isolation_fanout_tx(
		input: &Vtxo,
		isolated_outputs: &[ArkoorDestination],
		parent_txid: Txid,  // Either checkpoint txid or arkoor txid
		dust_isolation_output_vout: u32,  // Output index containing the dust isolation output
	) -> Transaction {
		let mut tx_outputs: Vec<TxOut> = isolated_outputs.iter().map(|o| {
			TxOut {
				value: o.total_amount,
				script_pubkey: o.policy.script_pubkey(
					input.server_pubkey(),
					input.exit_delta(),
					input.expiry_height(),
				),
			}
		}).collect();

		// Add fee anchor
		tx_outputs.push(fee::fee_anchor());

		Transaction {
			version: bitcoin::transaction::Version(3),
			lock_time: bitcoin::absolute::LockTime::ZERO,
			input: vec![TxIn {
				previous_output: OutPoint::new(parent_txid, dust_isolation_output_vout),
				script_sig: ScriptBuf::new(),
				sequence: Sequence::ZERO,
				witness: Witness::new(),
			}],
			output: tx_outputs,
		}
	}

	fn validate_amounts(
		input: &Vtxo,
		outputs: &[ArkoorDestination],
		isolation_outputs: &[ArkoorDestination],
	) -> Result<(), ArkoorConstructionError> {
		// Check if inputs and outputs are balanced
		// We need to build transactions that pay exactly 0 in onchain fees
		// to ensure our transaction with an ephemeral anchor is standard.
		// We need `==` for standardness and we can't be lenient
		let input_amount = input.amount();
		let output_amount = outputs.iter().chain(isolation_outputs.iter())
			.map(|o| o.total_amount).sum::<Amount>();

		if input_amount != output_amount {
			return Err(ArkoorConstructionError::Unbalanced {
				input: input_amount,
				output: output_amount,
			})
		}

		// We need at least one output in the outputs vec
		if outputs.is_empty() {
			return Err(ArkoorConstructionError::NoOutputs)
		}

		// If isolation is provided, the sum must be over dust threshold
		if !isolation_outputs.is_empty() {
			let isolation_sum: Amount = isolation_outputs.iter()
				.map(|o| o.total_amount).sum();
			if isolation_sum < P2TR_DUST {
				return Err(ArkoorConstructionError::Dust)
			}
		}

		Ok(())
	}


	fn to_state<S2: state::BuilderState>(self) -> ArkoorBuilder<S2> {
		ArkoorBuilder {
			input: self.input,
			outputs: self.outputs,
			isolated_outputs: self.isolated_outputs,
			checkpoint_data: self.checkpoint_data,
			unsigned_arkoor_txs: self.unsigned_arkoor_txs,
			unsigned_isolation_fanout_tx: self.unsigned_isolation_fanout_tx,
			new_vtxo_ids: self.new_vtxo_ids,
			sighashes: self.sighashes,
			input_tweak: self.input_tweak,
			checkpoint_policy_tweak: self.checkpoint_policy_tweak,
			user_pub_nonces: self.user_pub_nonces,
			user_sec_nonces: self.user_sec_nonces,
			server_pub_nonces: self.server_pub_nonces,
			server_partial_sigs: self.server_partial_sigs,
			full_signatures: self.full_signatures,
			_state: PhantomData,
		}
	}
}

impl ArkoorBuilder<state::Initial> {
	/// Create builder with checkpoint transaction
	pub fn new_with_checkpoint(
		input: Vtxo,
		outputs: Vec<ArkoorDestination>,
		isolated_outputs: Vec<ArkoorDestination>,
	) -> Result<Self, ArkoorConstructionError> {
		Self::new(input, outputs, isolated_outputs, true)
	}

	/// Create builder without checkpoint transaction
	pub fn new_without_checkpoint(
		input: Vtxo,
		outputs: Vec<ArkoorDestination>,
		isolated_outputs: Vec<ArkoorDestination>,
	) -> Result<Self, ArkoorConstructionError> {
		Self::new(input, outputs, isolated_outputs, false)
	}

	/// Create builder with checkpoint and automatic dust isolation
	///
	/// This constructor takes a single list of outputs and automatically
	/// determines the best strategy for handling dust.
	pub fn new_with_checkpoint_isolate_dust(
		input: Vtxo,
		outputs: Vec<ArkoorDestination>,
	) -> Result<Self, ArkoorConstructionError> {
		Self::new_isolate_dust(input, outputs, true)
	}

	pub(crate) fn new_isolate_dust(
		input: Vtxo,
		outputs: Vec<ArkoorDestination>,
		use_checkpoints: bool,
	) -> Result<Self, ArkoorConstructionError> {
		// fast track if they're either all dust or all non dust
		if outputs.iter().all(|v| v.total_amount >= P2TR_DUST)
			|| outputs.iter().all(|v| v.total_amount < P2TR_DUST)
		{
			return Self::new(input, outputs, vec![], use_checkpoints);
		}

		// else split them up by dust limit
		let (mut dust, mut non_dust) = outputs.iter().cloned()
			.partition::<Vec<_>, _>(|v| v.total_amount < P2TR_DUST);

		let dust_sum = dust.iter().map(|o| o.total_amount).sum::<Amount>();
		if dust_sum >= P2TR_DUST {
			return Self::new(input, non_dust, dust, use_checkpoints);
		}

		// if breaking would result in additional dust, just accept
		let non_dust_sum = non_dust.iter().map(|o| o.total_amount).sum::<Amount>();
		if non_dust_sum < P2TR_DUST * 2 {
			return Self::new(input, outputs, vec![], use_checkpoints);
		}

		// now it get's interesting, we need to break a vtxo in two
		let deficit = P2TR_DUST - dust_sum;
		// Find first viable output to split
		// Viable = output.total_amount - deficit >= P2TR_DUST (won't create two dust)
		let split_idx = non_dust.iter()
			.position(|o| o.total_amount - deficit >= P2TR_DUST);

		if let Some(idx) = split_idx {
			let output_to_split = non_dust[idx].clone();

			let dust_piece = ArkoorDestination {
				total_amount: deficit,
				policy: output_to_split.policy.clone(),
			};
			let leftover = ArkoorDestination {
				total_amount: output_to_split.total_amount - deficit,
				policy: output_to_split.policy,
			};

			non_dust[idx] = leftover;
			// we want to push it to the front
			dust.insert(0, dust_piece);

			return Self::new(input, non_dust, dust, use_checkpoints);
		} else {
			// No viable split found, allow mixing without isolation
			let all_outputs = non_dust.into_iter().chain(dust).collect();
			return Self::new(input, all_outputs, vec![], use_checkpoints);
		}
	}

	pub(crate) fn new(
		input: Vtxo,
		outputs: Vec<ArkoorDestination>,
		isolated_outputs: Vec<ArkoorDestination>,
		use_checkpoint: bool,
	) -> Result<Self, ArkoorConstructionError> {
		// Do some validation on the amounts
		Self::validate_amounts(&input, &outputs, &isolated_outputs)?;

		// Compute combined dust amount if dust isolation is needed
		let combined_dust_amount = if !isolated_outputs.is_empty() {
			Some(isolated_outputs.iter().map(|o| o.total_amount).sum())
		} else {
			None
		};

		// Conditionally construct checkpoint transaction
		let unsigned_checkpoint_tx = if use_checkpoint {
			let tx = Self::construct_unsigned_checkpoint_tx(
				&input,
				&outputs,
				combined_dust_amount,
			);
			let txid = tx.compute_txid();
			Some((tx, txid))
		} else {
			None
		};

		// Construct arkoor transactions
		let unsigned_arkoor_txs = Self::construct_unsigned_arkoor_txs(
			&input,
			&outputs,
			unsigned_checkpoint_tx.as_ref().map(|t| t.1),
			combined_dust_amount,
		);

		// Construct dust fanout tx if dust isolation is needed
		let unsigned_isolation_fanout_tx = if !isolated_outputs.is_empty() {
			// Combined dust isolation output is at index outputs.len()
			// (after all normal outputs)
			let dust_isolation_output_vout = outputs.len() as u32;

			let parent_txid = if let Some((_tx, txid)) = &unsigned_checkpoint_tx {
				*txid
			} else {
				unsigned_arkoor_txs[0].compute_txid()
			};

			Some(Self::construct_unsigned_isolation_fanout_tx(
				&input,
				&isolated_outputs,
				parent_txid,
				dust_isolation_output_vout,
			))
		} else {
			None
		};

		// Compute all vtx-ids
		let new_vtxo_ids = unsigned_arkoor_txs.iter()
			.map(|tx| OutPoint::new(tx.compute_txid(), 0))
			.map(|outpoint| VtxoId::from(outpoint))
			.collect();

		// Compute all sighashes
		let mut sighashes = Vec::new();

		if let Some((checkpoint_tx, _txid)) = &unsigned_checkpoint_tx {
			// Checkpoint signature
			sighashes.push(arkoor_sighash(&input.txout(), checkpoint_tx));

			// Arkoor transaction signatures (one per tx)
			for vout in 0..outputs.len() {
				let prevout = checkpoint_tx.output[vout].clone();
				sighashes.push(arkoor_sighash(&prevout, &unsigned_arkoor_txs[vout]));
			}
		} else {
			// Single direct arkoor transaction signature
			sighashes.push(arkoor_sighash(&input.txout(), &unsigned_arkoor_txs[0]));
		}

		// Add dust sighash
		if let Some(ref tx) = unsigned_isolation_fanout_tx {
			let dust_output_vout = outputs.len();  // Same for both modes
			let prevout = if let Some((checkpoint_tx, _txid)) = &unsigned_checkpoint_tx {
				checkpoint_tx.output[dust_output_vout].clone()
			} else {
				// In direct mode, it's the isolation output from the arkoor tx
				unsigned_arkoor_txs[0].output[dust_output_vout].clone()
			};
			sighashes.push(arkoor_sighash(&prevout, tx));
		}

		// Compute taptweaks
		let policy = ServerVtxoPolicy::new_checkpoint(input.user_pubkey());
		let input_tweak = input.output_taproot().tap_tweak();
		let checkpoint_policy_tweak = policy.taproot(
			input.server_pubkey(),
			input.exit_delta(),
			input.expiry_height(),
		).tap_tweak();

		Ok(Self {
			input: input,
			outputs: outputs,
			isolated_outputs,
			sighashes: sighashes,
			input_tweak,
			checkpoint_policy_tweak,
			checkpoint_data: unsigned_checkpoint_tx,
			unsigned_arkoor_txs: unsigned_arkoor_txs,
			unsigned_isolation_fanout_tx,
			new_vtxo_ids: new_vtxo_ids,
			user_pub_nonces: None,
			user_sec_nonces: None,
			server_pub_nonces: None,
			server_partial_sigs: None,
			full_signatures: None,
			_state: PhantomData,
		})
	}

	/// Generates the user nonces and moves the builder to the [state::UserGeneratedNonces] state
	/// This is the path that is used by the user
	pub fn generate_user_nonces(
		mut self,
		user_keypair: Keypair,
	) -> ArkoorBuilder<state::UserGeneratedNonces> {
		let mut user_pub_nonces = Vec::with_capacity(self.nb_sigs());
		let mut user_sec_nonces = Vec::with_capacity(self.nb_sigs());

		for idx in 0..self.nb_sigs() {
			let sighash = &self.sighashes[idx].to_byte_array();
			let (sec_nonce, pub_nonce) = musig::nonce_pair_with_msg(&user_keypair, sighash);

			user_pub_nonces.push(pub_nonce);
			user_sec_nonces.push(sec_nonce);
		}

		self.user_pub_nonces = Some(user_pub_nonces);
		self.user_sec_nonces = Some(user_sec_nonces);

		self.to_state::<state::UserGeneratedNonces>()
	}

	/// Sets the pub nonces that a user has generated.
	/// When this has happened the server can cosign.
	///
	/// If you are implementing a client, use [Self::generate_user_nonces] instead.
	/// If you are implementing a server you should look at
	/// [ArkoorBuilder::from_cosign_request].
	fn set_user_pub_nonces(
		mut self,
		user_pub_nonces: Vec<musig::PublicNonce>,
	) -> Result<ArkoorBuilder<state::ServerCanCosign>, ArkoorSigningError> {
		if user_pub_nonces.len() != self.nb_sigs() {
			return Err(ArkoorSigningError::InvalidNbUserNonces {
				expected: self.nb_sigs(),
				got: user_pub_nonces.len()
			})
		}

		self.user_pub_nonces = Some(user_pub_nonces);
		Ok(self.to_state::<state::ServerCanCosign>())
	}
}

impl<'a> ArkoorBuilder<state::ServerCanCosign> {
	pub fn from_cosign_request(
		cosign_request: ArkoorCosignRequest<Vtxo>,
	) -> Result<ArkoorBuilder<state::ServerCanCosign>, ArkoorSigningError> {
		let ret = ArkoorBuilder::new(
			cosign_request.input,
			cosign_request.outputs,
			cosign_request.isolated_outputs,
			cosign_request.use_checkpoint,
		)
			.map_err(ArkoorSigningError::ArkoorConstructionError)?
			.set_user_pub_nonces(cosign_request.user_pub_nonces.clone())?;
		Ok(ret)
	}

	pub fn server_cosign(
		mut self,
		server_keypair: &Keypair,
	) -> Result<ArkoorBuilder<state::ServerSigned>, ArkoorSigningError> {
		// Verify that the provided keypair is correct
		if server_keypair.public_key() != self.input.server_pubkey() {
			return Err(ArkoorSigningError::IncorrectKey {
				expected: self.input.server_pubkey(),
				got: server_keypair.public_key(),
			});
		}

		let mut server_pub_nonces = Vec::with_capacity(self.outputs.len() + 1);
		let mut server_partial_sigs = Vec::with_capacity(self.outputs.len() + 1);

		for idx in 0..self.nb_sigs() {
			let (server_pub_nonce, server_partial_sig) = musig::deterministic_partial_sign(
				&server_keypair,
				[self.input.user_pubkey()],
				&[&self.user_pub_nonces.as_ref().expect("state-invariant")[idx]],
				self.sighashes[idx].to_byte_array(),
				Some(self.taptweak_at(idx).to_byte_array()),
			);

			server_pub_nonces.push(server_pub_nonce);
			server_partial_sigs.push(server_partial_sig);
		};

		self.server_pub_nonces = Some(server_pub_nonces);
		self.server_partial_sigs = Some(server_partial_sigs);
		Ok(self.to_state::<state::ServerSigned>())
	}
}

impl ArkoorBuilder<state::ServerSigned> {
	pub fn user_pub_nonces(&self) -> Vec<musig::PublicNonce> {
		self.user_pub_nonces.as_ref().expect("state invariant").clone()
	}

	pub fn server_partial_signatures(&self) -> Vec<musig::PartialSignature> {
		self.server_partial_sigs.as_ref().expect("state invariant").clone()
	}

	pub fn cosign_response(&self) -> ArkoorCosignResponse {
		ArkoorCosignResponse {
			server_pub_nonces: self.server_pub_nonces.as_ref()
				.expect("state invariant").clone(),
			server_partial_sigs: self.server_partial_sigs.as_ref()
				.expect("state invariant").clone(),
		}
	}
}

impl ArkoorBuilder<state::UserGeneratedNonces> {
	pub fn user_pub_nonces(&self) -> &[PublicNonce] {
		self.user_pub_nonces.as_ref().expect("State invariant")
	}

	pub fn cosign_request(&self) -> ArkoorCosignRequest<Vtxo> {
		ArkoorCosignRequest {
			user_pub_nonces: self.user_pub_nonces().to_vec(),
			input: self.input.clone(),
			outputs: self.outputs.clone(),
			isolated_outputs: self.isolated_outputs.clone(),
			use_checkpoint: self.checkpoint_data.is_some(),
		}
	}

	fn validate_server_cosign_response(
		&self,
		data: &ArkoorCosignResponse,
	) -> Result<(), ArkoorSigningError> {

		// Check if the correct number of nonces is provided
		if data.server_pub_nonces.len() != self.nb_sigs() {
			return Err(ArkoorSigningError::InvalidNbServerNonces {
				expected: self.nb_sigs(),
				got: data.server_pub_nonces.len(),
			});
		}

		if data.server_partial_sigs.len() != self.nb_sigs() {
			return Err(ArkoorSigningError::InvalidNbServerPartialSigs {
				expected: self.nb_sigs(),
				got: data.server_partial_sigs.len(),
			})
		}

		// Check if the partial signatures is valid
		for idx in 0..self.nb_sigs() {
			let is_valid_sig = scripts::verify_partial_sig(
				self.sighashes[idx],
				self.taptweak_at(idx),
				(self.input.server_pubkey(), &data.server_pub_nonces[idx]),
				(self.input.user_pubkey(), &self.user_pub_nonces()[idx]),
				&data.server_partial_sigs[idx]
			);

			if !is_valid_sig {
				return Err(ArkoorSigningError::InvalidPartialSignature {
					index: idx,
				});
			}
		}
		Ok(())
	}

	pub fn user_cosign(
		mut self,
		user_keypair: &Keypair,
		server_cosign_data: &ArkoorCosignResponse,
	) -> Result<ArkoorBuilder<state::UserSigned>, ArkoorSigningError> {
		// Verify that the correct user keypair is provided
		if user_keypair.public_key() != self.input.user_pubkey() {
			return Err(ArkoorSigningError::IncorrectKey {
				expected: self.input.user_pubkey(),
				got: user_keypair.public_key(),
			});
		}

		// Verify that the server cosign data is valid
		self.validate_server_cosign_response(&server_cosign_data)?;

		let mut sigs = Vec::with_capacity(self.nb_sigs());

		// Takes the secret nonces out of the [ArkoorBuilder].
		// Note, that we can't clone nonces so we can only sign once
		let user_sec_nonces = self.user_sec_nonces.take().expect("state invariant");

		for (idx, user_sec_nonce) in user_sec_nonces.into_iter().enumerate() {
			let user_pub_nonce = self.user_pub_nonces()[idx];
			let server_pub_nonce = server_cosign_data.server_pub_nonces[idx];
			let agg_nonce = musig::nonce_agg(&[&user_pub_nonce, &server_pub_nonce]);

			let (_partial, maybe_sig) = musig::partial_sign(
				[self.user_pubkey(), self.server_pubkey()],
				agg_nonce,
				&user_keypair,
				user_sec_nonce,
				self.sighashes[idx].to_byte_array(),
				Some(self.taptweak_at(idx).to_byte_array()),
				Some(&[&server_cosign_data.server_partial_sigs[idx]])
			);

			let sig = maybe_sig.expect("The full signature exists. The server did sign first");
			sigs.push(sig);
		}

		self.full_signatures = Some(sigs);

		Ok(self.to_state::<state::UserSigned>())
	}
}


impl<'a> ArkoorBuilder<state::UserSigned> {
	pub fn build_signed_vtxos(&self) -> Vec<Vtxo> {
		let sigs = self.full_signatures.as_ref().expect("state invariant");
		let mut ret = Vec::with_capacity(self.outputs.len() + self.isolated_outputs.len());

		if self.checkpoint_data.is_some() {
			let checkpoint_sig = sigs[0];

			// Build regular vtxos (signatures 1..1+m)
			for i in 0..self.outputs.len() {
				let arkoor_sig = sigs[1 + i];
				ret.push(self.build_vtxo_at(i, Some(checkpoint_sig), Some(arkoor_sig)));
			}

			// Build isolated vtxos if present
			if self.unsigned_isolation_fanout_tx.is_some() {
				let m = self.outputs.len();
				let fanout_tx_sig = sigs[1 + m];

				for i in 0..self.isolated_outputs.len() {
					ret.push(self.build_isolated_vtxo_at(
						i,
						Some(checkpoint_sig),
						Some(fanout_tx_sig),
					));
				}
			}
		} else {
			// Direct mode: no checkpoint signature
			let arkoor_sig = sigs[0];

			// Build regular vtxos (all use same arkoor signature)
			for i in 0..self.outputs.len() {
				ret.push(self.build_vtxo_at(i, None, Some(arkoor_sig)));
			}

			// Build isolation vtxos if present
			if self.unsigned_isolation_fanout_tx.is_some() {
				let fanout_tx_sig = sigs[1];

				for i in 0..self.isolated_outputs.len() {
					ret.push(self.build_isolated_vtxo_at(
						i,
						Some(arkoor_sig),  // In direct mode, first sig is arkoor, not checkpoint
						Some(fanout_tx_sig),
					));
				}
			}
		}

		ret
	}
}

fn arkoor_sighash(prevout: &TxOut, arkoor_tx: &Transaction) -> TapSighash {
	let mut shc = SighashCache::new(arkoor_tx);

	shc.taproot_key_spend_signature_hash(
		0, &sighash::Prevouts::All(&[prevout]), TapSighashType::Default,
	).expect("sighash error")
}

#[cfg(test)]
mod test {
	use super::*;

	use std::collections::HashSet;

	use bitcoin::Amount;
	use bitcoin::secp256k1::Keypair;
	use bitcoin::secp256k1::rand;

	use crate::SECP;
	use crate::test_util::dummy::DummyTestVtxoSpec;
	use crate::vtxo::VtxoId;

	/// Verify properties of spend_info(), build_unsigned_internal_vtxos(), and final vtxos.
	fn verify_builder<S: state::BuilderState>(
		builder: &ArkoorBuilder<S>,
		input: &Vtxo,
		outputs: &[ArkoorDestination],
		isolated_outputs: &[ArkoorDestination],
	) {
		let has_isolation = !isolated_outputs.is_empty();

		let spend_info = builder.spend_info();
		let spend_vtxo_ids: HashSet<VtxoId> = spend_info.iter().map(|(id, _)| *id).collect();

		// the input vtxo is the first to be spent
		assert_eq!(spend_info[0].0, input.id());

		// no vtxo should be spent twice
		assert_eq!(spend_vtxo_ids.len(), spend_info.len());

		// all intermediate vtxos are spent and use checkpoint policy for efficient cosigning
		let internal_vtxos: Vec<ServerVtxo> = builder.build_unsigned_internal_vtxos().collect();
		let internal_vtxo_ids: HashSet<VtxoId> = internal_vtxos.iter().map(|v| v.id()).collect();
		for internal_vtxo in &internal_vtxos {
			assert!(spend_vtxo_ids.contains(&internal_vtxo.id()));
			assert!(matches!(internal_vtxo.policy(), ServerVtxoPolicy::Checkpoint(_)));
		}

		// all spent vtxos except the input are internal vtxos
		for (vtxo_id, _) in &spend_info[1..] {
			assert!(internal_vtxo_ids.contains(vtxo_id));
		}

		// isolation vtxo holds combined value of all dust outputs
		if has_isolation {
			let isolation_vtxo = internal_vtxos.last().unwrap();
			let expected_isolation_amount: Amount = isolated_outputs.iter()
				.map(|o| o.total_amount)
				.sum();
			assert_eq!(isolation_vtxo.amount(), expected_isolation_amount);
		}

		// final vtxos are unspent outputs that recipients receive
		let final_vtxos: Vec<Vtxo> = builder.build_unsigned_vtxos().collect();
		for final_vtxo in &final_vtxos {
			assert!(!spend_vtxo_ids.contains(&final_vtxo.id()));
		}

		// final vtxos match requested destinations
		let all_destinations: Vec<&ArkoorDestination> = outputs.iter()
			.chain(isolated_outputs.iter())
			.collect();
		for (vtxo, dest) in final_vtxos.iter().zip(all_destinations.iter()) {
			assert_eq!(vtxo.amount(), dest.total_amount);
			assert_eq!(vtxo.policy, dest.policy);
		}

		// total value is conserved
		let total_output_amount: Amount = final_vtxos.iter().map(|v| v.amount()).sum();
		assert_eq!(total_output_amount, input.amount());
	}

	#[test]
	fn build_checkpointed_arkoor() {
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		println!("Alice keypair: {}", alice_keypair.public_key());
		println!("Bob keypair: {}", bob_keypair.public_key());
		println!("Server keypair: {}", server_keypair.public_key());
		println!("-----------------------------------------------");

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(100_000),
			expiry_height: 1000,
			exit_delta : 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		// Validate Alice her vtxo
		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		let dest = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(96_000),
				policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
			},
			ArkoorDestination {
				total_amount: Amount::from_sat(4_000),
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			}
		];

		let user_builder = ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			dest.clone(),
			vec![], // no isolation outputs
		).expect("Valid arkoor request");

		verify_builder(&user_builder, &alice_vtxo, &dest, &[]);

		let user_builder = user_builder.generate_user_nonces(alice_keypair);
		let cosign_request = user_builder.cosign_request();

		// The server will cosign the request
		let server_builder = ArkoorBuilder::from_cosign_request(cosign_request)
			.expect("Invalid cosign request")
			.server_cosign(&server_keypair)
			.expect("Incorrect key");

		let cosign_data = server_builder.cosign_response();

		// The user will cosign the request and construct their vtxos
		let vtxos = user_builder
			.user_cosign(&alice_keypair, &cosign_data)
			.expect("Valid cosign data and correct key")
			.build_signed_vtxos();

		for vtxo in vtxos.into_iter() {
			// Check if the vtxo is considered valid
			vtxo.validate(&funding_tx).expect("Invalid VTXO");

			// Check all transactions using libbitcoin-kernel
			let mut prev_tx = funding_tx.clone();
			for tx in vtxo.transactions().map(|item| item.tx) {
				let prev_outpoint: OutPoint = tx.input[0].previous_output;
				let prev_txout: TxOut = prev_tx.output[prev_outpoint.vout as usize].clone();
				crate::test_util::verify_tx(&[prev_txout], 0, &tx).expect("Valid transaction");
				prev_tx = tx;
			}
		}

	}

	#[test]
	fn build_checkpointed_arkoor_with_dust_isolation() {
		// Test mixed outputs: some dust, some non-dust
		// This should activate dust isolation
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let charlie_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(100_000),
			expiry_height: 1000,
			exit_delta : 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		// Validate Alice her vtxo
		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		// Non-dust outputs (>= 330 sats)
		let outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(99_600),
				policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
			},
		];

		// dust outputs (< 330 sats each, but combined >= 330)
		let dust_outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(200),  // < 330, truly dust
				policy: VtxoPolicy::new_pubkey(charlie_keypair.public_key())
			},
			ArkoorDestination {
				total_amount: Amount::from_sat(200),  // < 330, truly dust
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			}
		];

		let user_builder = ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			outputs.clone(),
			dust_outputs.clone(),
		).expect("Valid arkoor request with dust isolation");

		verify_builder(&user_builder, &alice_vtxo, &outputs, &dust_outputs);

		// Verify dust isolation is active
		assert!(
			user_builder.unsigned_isolation_fanout_tx.is_some(),
			"Dust isolation should be active",
		);

		// Check signature count: 1 checkpoint + 1 arkoor + 1 dust fanout = 3
		assert_eq!(user_builder.nb_sigs(), 3);

		let user_builder = user_builder.generate_user_nonces(alice_keypair);
		let cosign_request = user_builder.cosign_request();

		// The server will cosign the request
		let server_builder = ArkoorBuilder::from_cosign_request(cosign_request)
			.expect("Invalid cosign request")
			.server_cosign(&server_keypair)
			.expect("Incorrect key");

		let cosign_data = server_builder.cosign_response();

		// The user will cosign the request and construct their vtxos
		let vtxos = user_builder
			.user_cosign(&alice_keypair, &cosign_data)
			.expect("Valid cosign data and correct key")
			.build_signed_vtxos();

		// Should have 3 vtxos: 1 non-dust + 2 dust
		assert_eq!(vtxos.len(), 3);

		for vtxo in vtxos.into_iter() {
			// Check if the vtxo is considered valid
			vtxo.validate(&funding_tx).expect("Invalid VTXO");

			// Check all transactions using libbitcoin-kernel
			let mut prev_tx = funding_tx.clone();
			for tx in vtxo.transactions().map(|item| item.tx) {
				let prev_outpoint: OutPoint = tx.input[0].previous_output;
				let prev_txout: TxOut = prev_tx.output[prev_outpoint.vout as usize].clone();
				crate::test_util::verify_tx(&[prev_txout], 0, &tx).expect("Valid transaction");
				prev_tx = tx;
			}
		}
	}

	#[test]
	fn build_no_checkpoint_arkoor() {
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		println!("Alice keypair: {}", alice_keypair.public_key());
		println!("Bob keypair: {}", bob_keypair.public_key());
		println!("Server keypair: {}", server_keypair.public_key());
		println!("-----------------------------------------------");

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(100_000),
			expiry_height: 1000,
			exit_delta : 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		// Validate Alice her vtxo
		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		let dest = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(96_000),
				policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
			},
			ArkoorDestination {
				total_amount: Amount::from_sat(4_000),
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			}
		];

		let user_builder = ArkoorBuilder::new_without_checkpoint(
			alice_vtxo.clone(),
			dest.clone(),
			vec![], // no isolation outputs
		).expect("Valid arkoor request");

		verify_builder(&user_builder, &alice_vtxo, &dest, &[]);

		let user_builder = user_builder.generate_user_nonces(alice_keypair);
		let cosign_request = user_builder.cosign_request();

		// The server will cosign the request
		let server_builder = ArkoorBuilder::from_cosign_request(cosign_request)
			.expect("Invalid cosign request")
			.server_cosign(&server_keypair)
			.expect("Incorrect key");

		let cosign_data = server_builder.cosign_response();

		// The user will cosign the request and construct their vtxos
		let vtxos = user_builder
			.user_cosign(&alice_keypair, &cosign_data)
			.expect("Valid cosign data and correct key")
			.build_signed_vtxos();

		for vtxo in vtxos.into_iter() {
			// Check if the vtxo is considered valid
			vtxo.validate(&funding_tx).expect("Invalid VTXO");

			// Check all transactions using libbitcoin-kernel
			let mut prev_tx = funding_tx.clone();
			for tx in vtxo.transactions().map(|item| item.tx) {
				let prev_outpoint: OutPoint = tx.input[0].previous_output;
				let prev_txout: TxOut = prev_tx.output[prev_outpoint.vout as usize].clone();
				crate::test_util::verify_tx(&[prev_txout], 0, &tx).expect("Valid transaction");
				prev_tx = tx;
			}
		}

	}

	#[test]
	fn build_no_checkpoint_arkoor_with_dust_isolation() {
		// Test mixed outputs: some dust, some non-dust
		// This should activate dust isolation
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let charlie_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(100_000),
			expiry_height: 1000,
			exit_delta : 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		// Validate Alice her vtxo
		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		// Non-dust outputs (>= 330 sats)
		let outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(99_600),
				policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
			},
		];

		// dust outputs (< 330 sats each, but combined >= 330)
		let dust_outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(200),  // < 330, truly dust
				policy: VtxoPolicy::new_pubkey(charlie_keypair.public_key())
			},
			ArkoorDestination {
				total_amount: Amount::from_sat(200),  // < 330, truly dust
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			}
		];

		let user_builder = ArkoorBuilder::new_without_checkpoint(
			alice_vtxo.clone(),
			outputs.clone(),
			dust_outputs.clone(),
		).expect("Valid arkoor request with dust isolation");

		verify_builder(&user_builder, &alice_vtxo, &outputs, &dust_outputs);

		// Verify dust isolation is active
		assert!(
			user_builder.unsigned_isolation_fanout_tx.is_some(),
			"Dust isolation should be active",
		);

		// Check signature count: 1 arkoor + 1 dust fanout = 2
		// (no checkpoint in non-checkpointed mode)
		assert_eq!(user_builder.nb_sigs(), 2);

		let user_builder = user_builder.generate_user_nonces(alice_keypair);
		let cosign_request = user_builder.cosign_request();

		// The server will cosign the request
		let server_builder = ArkoorBuilder::from_cosign_request(cosign_request)
			.expect("Invalid cosign request")
			.server_cosign(&server_keypair)
			.expect("Incorrect key");

		let cosign_data = server_builder.cosign_response();

		// The user will cosign the request and construct their vtxos
		let vtxos = user_builder
			.user_cosign(&alice_keypair, &cosign_data)
			.expect("Valid cosign data and correct key")
			.build_signed_vtxos();

		// Should have 3 vtxos: 1 non-dust + 2 dust
		assert_eq!(vtxos.len(), 3);

		for vtxo in vtxos.into_iter() {
			// Check if the vtxo is considered valid
			vtxo.validate(&funding_tx).expect("Invalid VTXO");

			// Check all transactions using libbitcoin-kernel
			let mut prev_tx = funding_tx.clone();
			for tx in vtxo.transactions().map(|item| item.tx) {
				let prev_outpoint: OutPoint = tx.input[0].previous_output;
				let prev_txout: TxOut = prev_tx.output[prev_outpoint.vout as usize].clone();
				crate::test_util::verify_tx(&[prev_txout], 0, &tx).expect("Valid transaction");
				prev_tx = tx;
			}
		}
	}

	#[test]
	fn build_checkpointed_arkoor_outputs_must_be_above_dust_if_mixed() {
		// Test that outputs in the outputs list must be >= P2TR_DUST
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(1000),
			expiry_height: 1000,
			exit_delta : 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		// only dust is allowed
		ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(100),  // < 330 sats (P2TR_DUST)
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}; 10
			],
			vec![],
		).unwrap();

		// empty outputs vec is not allowed (need at least one normal output)
		let res_empty = ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			vec![],
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(100),  // < 330 sats (P2TR_DUST)
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}; 10
			],
		);
		match res_empty {
			Err(ArkoorConstructionError::NoOutputs) => {},
			_ => panic!("Expected NoOutputs error for empty outputs"),
		}

		// normal case: non-dust in normal outputs and dust in isolation
		ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(330),  // >= 330 sats
					policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
				}; 2
			],
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(170),
					policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
				}; 2
			],
		).unwrap();

		// mixing with isolation sum < 330 should fail
		let res_mixed_small = ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(500),
					policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(300),
					policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
				}
			],
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(100),
					policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
				}; 2  // sum = 200, which is < 330
			],
		);
		match res_mixed_small {
			Err(ArkoorConstructionError::Dust) => {},
			_ => panic!("Expected Dust error for isolation sum < 330"),
		}
	}

	#[test]
	fn build_checkpointed_arkoor_dust_sum_too_small() {
		// Test that dust_sum < P2TR_DUST is now allowed after removing validation
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(100_000),
			expiry_height: 1000,
			exit_delta : 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		// Non-dust outputs
		let outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(99_900),
				policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
			},
		];

		// dust outputs with combined sum < P2TR_DUST (330)
		let dust_outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(50),
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			},
			ArkoorDestination {
				total_amount: Amount::from_sat(50),
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			}
		];

		// This should fail because isolation sum (100) < P2TR_DUST (330)
		let result = ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			outputs.clone(),
			dust_outputs.clone(),
		);
		match result {
			Err(ArkoorConstructionError::Dust) => {},
			_ => panic!("Expected Dust error for isolation sum < 330"),
		}
	}

	#[test]
	fn spend_dust_vtxo() {
		// Test the "all dust" case: create a 200 sat vtxo and split into two 100 sat outputs
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		// Create a 200 sat input vtxo (this is dust since 200 < 330)
		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(200),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		// Split into two 100 sat outputs
		// outputs is empty, all outputs go to dust_outputs
		let dust_outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(100),
				policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
			},
			ArkoorDestination {
				total_amount: Amount::from_sat(100),
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			}
		];

		let user_builder = ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			dust_outputs,
			vec![],
		).expect("Valid arkoor request for all-dust case");

		// Verify dust isolation is NOT active (all-dust case, no mixing)
		assert!(
			user_builder.unsigned_isolation_fanout_tx.is_none(),
			"Dust isolation should NOT be active",
		);

		// Check we have 2 outputs
		assert_eq!(user_builder.outputs.len(), 2);

		// Check signature count: 1 checkpoint + 2 arkoor = 3
		assert_eq!(user_builder.nb_sigs(), 3);

		// The user generates their nonces
		let user_builder = user_builder.generate_user_nonces(alice_keypair);
		let cosign_request = user_builder.cosign_request();

		// The server will cosign the request
		let server_builder = ArkoorBuilder::from_cosign_request(cosign_request)
			.expect("Invalid cosign request")
			.server_cosign(&server_keypair)
			.expect("Incorrect key");

		let cosign_data = server_builder.cosign_response();

		// The user will cosign the request and construct their vtxos
		let vtxos = user_builder
			.user_cosign(&alice_keypair, &cosign_data)
			.expect("Valid cosign data and correct key")
			.build_signed_vtxos();

		// Should have 2 vtxos
		assert_eq!(vtxos.len(), 2);

		for vtxo in vtxos.into_iter() {
			// Check if the vtxo is considered valid
			vtxo.validate(&funding_tx).expect("Invalid VTXO");

			// Verify amount is 100 sats
			assert_eq!(vtxo.amount(), Amount::from_sat(100));

			// Check all transactions using libbitcoin-kernel
			let mut prev_tx = funding_tx.clone();
			for tx in vtxo.transactions().map(|item| item.tx) {
				let prev_outpoint: OutPoint = tx.input[0].previous_output;
				let prev_txout: TxOut = prev_tx.output[prev_outpoint.vout as usize].clone();
				crate::test_util::verify_tx(&[prev_txout], 0, &tx).expect("Valid transaction");
				prev_tx = tx;
			}
		}
	}

	#[test]
	fn spend_nondust_vtxo_to_dust() {
		// Test: take a 500 sat vtxo (above dust) and split into two 250 sat vtxos (below dust)
		// Input is non-dust, outputs are all dust - no dust isolation needed
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		// Create a 500 sat input vtxo (this is above P2TR_DUST of 330)
		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(500),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("The unsigned vtxo is valid");

		// Split into two 250 sat outputs (each below P2TR_DUST)
		// outputs is empty, all outputs go to dust_outputs
		let dust_outputs = vec![
			ArkoorDestination {
				total_amount: Amount::from_sat(250),
				policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
			},
			ArkoorDestination {
				total_amount: Amount::from_sat(250),
				policy: VtxoPolicy::new_pubkey(alice_keypair.public_key())
			}
		];

		let user_builder = ArkoorBuilder::new_with_checkpoint(
			alice_vtxo.clone(),
			dust_outputs,
			vec![],
		).expect("Valid arkoor request for non-dust to dust case");

		// Verify dust isolation is NOT active (all-dust case, no mixing)
		assert!(
			user_builder.unsigned_isolation_fanout_tx.is_none(),
			"Dust isolation should NOT be active",
		);

		// Check we have 2 outputs
		assert_eq!(user_builder.outputs.len(), 2);

		// Check signature count: 1 checkpoint + 2 arkoor = 3
		assert_eq!(user_builder.nb_sigs(), 3);

		// The user generates their nonces
		let user_builder = user_builder.generate_user_nonces(alice_keypair);
		let cosign_request = user_builder.cosign_request();

		// The server will cosign the request
		let server_builder = ArkoorBuilder::from_cosign_request(cosign_request)
			.expect("Invalid cosign request")
			.server_cosign(&server_keypair)
			.expect("Incorrect key");

		let cosign_data = server_builder.cosign_response();

		// The user will cosign the request and construct their vtxos
		let vtxos = user_builder
			.user_cosign(&alice_keypair, &cosign_data)
			.expect("Valid cosign data and correct key")
			.build_signed_vtxos();

		// Should have 2 vtxos
		assert_eq!(vtxos.len(), 2);

		for vtxo in vtxos.into_iter() {
			// Check if the vtxo is considered valid
			vtxo.validate(&funding_tx).expect("Invalid VTXO");

			// Verify amount is 250 sats
			assert_eq!(vtxo.amount(), Amount::from_sat(250));

			// Check all transactions using libbitcoin-kernel
			let mut prev_tx = funding_tx.clone();
			for tx in vtxo.transactions().map(|item| item.tx) {
				let prev_outpoint: OutPoint = tx.input[0].previous_output;
				let prev_txout: TxOut = prev_tx.output[prev_outpoint.vout as usize].clone();
				crate::test_util::verify_tx(&[prev_txout], 0, &tx).expect("Valid transaction");
				prev_tx = tx;
			}
		}
	}

	#[test]
	fn isolate_dust_all_nondust() {
		// Test scenario: All outputs >= 330 sats
		// Should use normal path without isolation
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(1000),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("Valid vtxo");

		let builder = ArkoorBuilder::new_with_checkpoint_isolate_dust(
			alice_vtxo,
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(500),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(500),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}
			],
		).unwrap();

		// Should not have dust isolation active
		assert!(builder.unsigned_isolation_fanout_tx.is_none());

		// Should have 2 regular outputs
		assert_eq!(builder.outputs.len(), 2);
		assert_eq!(builder.isolated_outputs.len(), 0);
	}

	#[test]
	fn isolate_dust_all_dust() {
		// Test scenario: All outputs < 330 sats
		// Should use all-dust path
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(400),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("Valid vtxo");

		let builder = ArkoorBuilder::new_with_checkpoint_isolate_dust(
			alice_vtxo,
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(200),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(200),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}
			],
		).unwrap();

		// Should not have dust isolation active (all dust)
		assert!(builder.unsigned_isolation_fanout_tx.is_none());

		// All outputs should be in outputs vec (no isolation needed)
		assert_eq!(builder.outputs.len(), 2);
		assert_eq!(builder.isolated_outputs.len(), 0);
	}

	#[test]
	fn isolate_dust_sufficient_dust() {
		// Test scenario: Mixed with dust sum >= 330
		// Should use dust isolation
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(1000),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("Valid vtxo");

		// 600 non-dust + 200 + 200 dust = 400 dust total (>= 330)
		let builder = ArkoorBuilder::new_with_checkpoint_isolate_dust(
			alice_vtxo,
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(600),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(200),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(200),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}
			],
		).unwrap();

		// Should have dust isolation active
		assert!(builder.unsigned_isolation_fanout_tx.is_some());

		// 1 regular output, 2 isolated dust outputs
		assert_eq!(builder.outputs.len(), 1);
		assert_eq!(builder.isolated_outputs.len(), 2);
	}

	#[test]
	fn isolate_dust_split_successful() {
		// Test scenario: Mixed with dust sum < 330, but can split
		// 800 non-dust + 100 + 100 dust = 200 dust, need 130 more
		// Should split 800 into 670 + 130
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(1000),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("Valid vtxo");

		let builder = ArkoorBuilder::new_with_checkpoint_isolate_dust(
			alice_vtxo,
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(800),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(100),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(100),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}
			],
		).unwrap();

		// Should have dust isolation active (split successful)
		assert!(builder.unsigned_isolation_fanout_tx.is_some());

		// 1 regular output (670), 3 isolated dust outputs (130 + 100 + 100 = 330)
		assert_eq!(builder.outputs.len(), 1);
		assert_eq!(builder.isolated_outputs.len(), 3);

		// Verify the split amounts
		assert_eq!(builder.outputs[0].total_amount, Amount::from_sat(670));
		let isolated_sum: Amount = builder.isolated_outputs.iter().map(|o| o.total_amount).sum();
		assert_eq!(isolated_sum, P2TR_DUST);
	}

	#[test]
	fn isolate_dust_split_impossible() {
		// Test scenario: Mixed with dust sum < 330, can't split
		// 400 non-dust + 100 + 100 dust = 200 dust, need 130 more
		// 400 - 130 = 270 < 330, can't split without creating two dust
		// Should allow mixing without isolation
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(600),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("Valid vtxo");

		let builder = ArkoorBuilder::new_with_checkpoint_isolate_dust(
			alice_vtxo,
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(400),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(100),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(100),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}
			],
		).unwrap();

		// Should not have dust isolation (mixing allowed)
		assert!(builder.unsigned_isolation_fanout_tx.is_none());

		// All 3 outputs should be in outputs vec (mixed without isolation)
		assert_eq!(builder.outputs.len(), 3);
		assert_eq!(builder.isolated_outputs.len(), 0);
	}

	#[test]
	fn isolate_dust_exactly_boundary() {
		// Test scenario: dust sum is already >= 330 (exactly at boundary)
		// 660 non-dust + 170 + 170 dust = 340 dust (>= 330)
		// Should use isolation without splitting
		let alice_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let bob_keypair = Keypair::new(&SECP, &mut rand::thread_rng());
		let server_keypair = Keypair::new(&SECP, &mut rand::thread_rng());

		let (funding_tx, alice_vtxo) = DummyTestVtxoSpec {
			amount: Amount::from_sat(1000),
			expiry_height: 1000,
			exit_delta: 128,
			user_keypair: alice_keypair.clone(),
			server_keypair: server_keypair.clone()
		}.build();

		alice_vtxo.validate(&funding_tx).expect("Valid vtxo");

		let builder = ArkoorBuilder::new_with_checkpoint_isolate_dust(
			alice_vtxo,
			vec![
				ArkoorDestination {
					total_amount: Amount::from_sat(660),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(170),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				},
				ArkoorDestination {
					total_amount: Amount::from_sat(170),
					policy: VtxoPolicy::new_pubkey(bob_keypair.public_key())
				}
			],
		).unwrap();

		// Should have dust isolation active (340 >= 330)
		assert!(builder.unsigned_isolation_fanout_tx.is_some());

		// 1 regular output, 2 isolated dust outputs
		assert_eq!(builder.outputs.len(), 1);
		assert_eq!(builder.isolated_outputs.len(), 2);

		// Verify amounts weren't modified
		assert_eq!(builder.outputs[0].total_amount, Amount::from_sat(660));
		assert_eq!(builder.isolated_outputs[0].total_amount, Amount::from_sat(170));
		assert_eq!(builder.isolated_outputs[1].total_amount, Amount::from_sat(170));
	}
}