lightning 0.1.0-beta1

A Bitcoin Lightning library in Rust. Does most of the hard work, without implying a specific runtime, requiring clients implement basic network logic, chain interactions and disk storage. Still missing tons of error-handling. See GitHub issues for suggested projects if you want to contribute. Don't have to bother telling you not to use this for anything serious, because you'd have to build a client around it to even try.
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
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

use crate::io_extras::sink;
use crate::prelude::*;

use bitcoin::absolute::LockTime as AbsoluteLockTime;
use bitcoin::amount::Amount;
use bitcoin::consensus::Encodable;
use bitcoin::constants::WITNESS_SCALE_FACTOR;
use bitcoin::policy::MAX_STANDARD_TX_WEIGHT;
use bitcoin::secp256k1::PublicKey;
use bitcoin::transaction::Version;
use bitcoin::{OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Weight, Witness};

use crate::chain::chaininterface::fee_for_weight;
use crate::events::bump_transaction::{BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT};
use crate::events::MessageSendEvent;
use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
use crate::ln::msgs;
use crate::ln::msgs::{SerialId, TxSignatures};
use crate::ln::types::ChannelId;
use crate::sign::{EntropySource, P2TR_KEY_PATH_WITNESS_WEIGHT, P2WPKH_WITNESS_WEIGHT};
use crate::util::ser::TransactionU16LenLimited;

use core::fmt::Display;
use core::ops::Deref;

/// The number of received `tx_add_input` messages during a negotiation at which point the
/// negotiation MUST be failed.
const MAX_RECEIVED_TX_ADD_INPUT_COUNT: u16 = 4096;

/// The number of received `tx_add_output` messages during a negotiation at which point the
/// negotiation MUST be failed.
const MAX_RECEIVED_TX_ADD_OUTPUT_COUNT: u16 = 4096;

/// The number of inputs or outputs that the state machine can have, before it MUST fail the
/// negotiation.
const MAX_INPUTS_OUTPUTS_COUNT: usize = 252;

/// The total weight of the common fields whose fee is paid by the initiator of the interactive
/// transaction construction protocol.
pub(crate) const TX_COMMON_FIELDS_WEIGHT: u64 = (4 /* version */ + 4 /* locktime */ + 1 /* input count */ +
	1 /* output count */) * WITNESS_SCALE_FACTOR as u64 + 2 /* segwit marker + flag */;

// BOLT 3 - Lower bounds for input weights

/// Lower bound for P2WPKH input weight
pub(crate) const P2WPKH_INPUT_WEIGHT_LOWER_BOUND: u64 =
	BASE_INPUT_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT + P2WPKH_WITNESS_WEIGHT;

/// Lower bound for P2WSH input weight is chosen as same as P2WPKH input weight in BOLT 3
pub(crate) const P2WSH_INPUT_WEIGHT_LOWER_BOUND: u64 = P2WPKH_INPUT_WEIGHT_LOWER_BOUND;

/// Lower bound for P2TR input weight is chosen as the key spend path.
/// Not specified in BOLT 3, but a reasonable lower bound.
pub(crate) const P2TR_INPUT_WEIGHT_LOWER_BOUND: u64 =
	BASE_INPUT_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT + P2TR_KEY_PATH_WITNESS_WEIGHT;

/// Lower bound for unknown segwit version input weight is chosen the same as P2WPKH in BOLT 3
pub(crate) const UNKNOWN_SEGWIT_VERSION_INPUT_WEIGHT_LOWER_BOUND: u64 =
	P2WPKH_INPUT_WEIGHT_LOWER_BOUND;

trait SerialIdExt {
	fn is_for_initiator(&self) -> bool;
	fn is_for_non_initiator(&self) -> bool;
}

impl SerialIdExt for SerialId {
	fn is_for_initiator(&self) -> bool {
		self % 2 == 0
	}

	fn is_for_non_initiator(&self) -> bool {
		!self.is_for_initiator()
	}
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum AbortReason {
	InvalidStateTransition,
	UnexpectedCounterpartyMessage,
	ReceivedTooManyTxAddInputs,
	ReceivedTooManyTxAddOutputs,
	IncorrectInputSequenceValue,
	IncorrectSerialIdParity,
	SerialIdUnknown,
	DuplicateSerialId,
	PrevTxOutInvalid,
	ExceededMaximumSatsAllowed,
	ExceededNumberOfInputsOrOutputs,
	TransactionTooLarge,
	BelowDustLimit,
	InvalidOutputScript,
	InsufficientFees,
	OutputsValueExceedsInputsValue,
	InvalidTx,
	/// No funding (shared) output found.
	MissingFundingOutput,
	/// More than one funding (shared) output found.
	DuplicateFundingOutput,
	/// The intended local part of the funding output is higher than the actual shared funding output,
	/// if funding output is provided by the peer this is an interop error,
	/// if provided by the same node than internal input consistency error.
	InvalidLowFundingOutputValue,
}

impl AbortReason {
	pub fn into_tx_abort_msg(self, channel_id: ChannelId) -> msgs::TxAbort {
		msgs::TxAbort { channel_id, data: self.to_string().into_bytes() }
	}
}

impl Display for AbortReason {
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.write_str(match self {
			AbortReason::InvalidStateTransition => "State transition was invalid",
			AbortReason::UnexpectedCounterpartyMessage => "Unexpected message",
			AbortReason::ReceivedTooManyTxAddInputs => "Too many `tx_add_input`s received",
			AbortReason::ReceivedTooManyTxAddOutputs => "Too many `tx_add_output`s received",
			AbortReason::IncorrectInputSequenceValue => {
				"Input has a sequence value greater than 0xFFFFFFFD"
			},
			AbortReason::IncorrectSerialIdParity => "Parity for `serial_id` was incorrect",
			AbortReason::SerialIdUnknown => "The `serial_id` is unknown",
			AbortReason::DuplicateSerialId => "The `serial_id` already exists",
			AbortReason::PrevTxOutInvalid => "Invalid previous transaction output",
			AbortReason::ExceededMaximumSatsAllowed => {
				"Output amount exceeded total bitcoin supply"
			},
			AbortReason::ExceededNumberOfInputsOrOutputs => "Too many inputs or outputs",
			AbortReason::TransactionTooLarge => "Transaction weight is too large",
			AbortReason::BelowDustLimit => "Output amount is below the dust limit",
			AbortReason::InvalidOutputScript => "The output script is non-standard",
			AbortReason::InsufficientFees => "Insufficient fees paid",
			AbortReason::OutputsValueExceedsInputsValue => {
				"Total value of outputs exceeds total value of inputs"
			},
			AbortReason::InvalidTx => "The transaction is invalid",
			AbortReason::MissingFundingOutput => "No shared funding output found",
			AbortReason::DuplicateFundingOutput => "More than one funding output found",
			AbortReason::InvalidLowFundingOutputValue => {
				"Local part of funding output value is greater than the funding output value"
			},
		})
	}
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ConstructedTransaction {
	holder_is_initiator: bool,

	inputs: Vec<InteractiveTxInput>,
	outputs: Vec<InteractiveTxOutput>,

	local_inputs_value_satoshis: u64,
	local_outputs_value_satoshis: u64,

	remote_inputs_value_satoshis: u64,
	remote_outputs_value_satoshis: u64,

	lock_time: AbsoluteLockTime,
	holder_sends_tx_signatures_first: bool,
}

impl ConstructedTransaction {
	fn new(context: NegotiationContext) -> Self {
		let local_inputs_value_satoshis = context
			.inputs
			.iter()
			.fold(0u64, |value, (_, input)| value.saturating_add(input.local_value()));

		let local_outputs_value_satoshis = context
			.outputs
			.iter()
			.fold(0u64, |value, (_, output)| value.saturating_add(output.local_value()));

		let remote_inputs_value_satoshis = context.remote_inputs_value();
		let remote_outputs_value_satoshis = context.remote_outputs_value();
		let mut inputs: Vec<InteractiveTxInput> = context.inputs.into_values().collect();
		let mut outputs: Vec<InteractiveTxOutput> = context.outputs.into_values().collect();
		// Inputs and outputs must be sorted by serial_id
		inputs.sort_unstable_by_key(|input| input.serial_id());
		outputs.sort_unstable_by_key(|output| output.serial_id);

		// There is a strict ordering for `tx_signatures` exchange to prevent deadlocks.
		let holder_sends_tx_signatures_first =
			if local_inputs_value_satoshis == remote_inputs_value_satoshis {
				// If the amounts are the same then the peer with the lowest pubkey lexicographically sends its
				// tx_signatures first
				context.holder_node_id.serialize() < context.counterparty_node_id.serialize()
			} else {
				// Otherwise the peer with the lowest contributed input value sends its tx_signatures first.
				local_inputs_value_satoshis < remote_inputs_value_satoshis
			};

		Self {
			holder_is_initiator: context.holder_is_initiator,

			local_inputs_value_satoshis,
			local_outputs_value_satoshis,

			remote_inputs_value_satoshis,
			remote_outputs_value_satoshis,

			inputs,
			outputs,

			lock_time: context.tx_locktime,
			holder_sends_tx_signatures_first,
		}
	}

	pub fn weight(&self) -> Weight {
		let inputs_weight = self.inputs.iter().fold(Weight::from_wu(0), |weight, input| {
			weight.checked_add(estimate_input_weight(input.prev_output())).unwrap_or(Weight::MAX)
		});
		let outputs_weight = self.outputs.iter().fold(Weight::from_wu(0), |weight, output| {
			weight.checked_add(get_output_weight(output.script_pubkey())).unwrap_or(Weight::MAX)
		});
		Weight::from_wu(TX_COMMON_FIELDS_WEIGHT)
			.checked_add(inputs_weight)
			.and_then(|weight| weight.checked_add(outputs_weight))
			.unwrap_or(Weight::MAX)
	}

	pub fn build_unsigned_tx(&self) -> Transaction {
		let ConstructedTransaction { inputs, outputs, .. } = self;

		let input: Vec<TxIn> = inputs.iter().map(|input| input.txin().clone()).collect();
		let output: Vec<TxOut> = outputs.iter().map(|output| output.tx_out().clone()).collect();

		Transaction { version: Version::TWO, lock_time: self.lock_time, input, output }
	}

	pub fn outputs(&self) -> impl Iterator<Item = &InteractiveTxOutput> {
		self.outputs.iter()
	}

	pub fn inputs(&self) -> impl Iterator<Item = &InteractiveTxInput> {
		self.inputs.iter()
	}

	pub fn compute_txid(&self) -> Txid {
		self.build_unsigned_tx().compute_txid()
	}

	/// Adds provided holder witnesses to holder inputs of unsigned transaction.
	///
	/// Note that it is assumed that the witness count equals the holder input count.
	fn add_local_witnesses(&mut self, witnesses: Vec<Witness>) {
		self.inputs
			.iter_mut()
			.filter(|input| {
				!is_serial_id_valid_for_counterparty(self.holder_is_initiator, input.serial_id())
			})
			.map(|input| input.txin_mut())
			.zip(witnesses)
			.for_each(|(input, witness)| input.witness = witness);
	}

	/// Adds counterparty witnesses to counterparty inputs of unsigned transaction.
	///
	/// Note that it is assumed that the witness count equals the counterparty input count.
	fn add_remote_witnesses(&mut self, witnesses: Vec<Witness>) {
		self.inputs
			.iter_mut()
			.filter(|input| {
				is_serial_id_valid_for_counterparty(self.holder_is_initiator, input.serial_id())
			})
			.map(|input| input.txin_mut())
			.zip(witnesses)
			.for_each(|(input, witness)| input.witness = witness);
	}
}

/// The InteractiveTxSigningSession coordinates the signing flow of interactively constructed
/// transactions from exhange of `commitment_signed` to ensuring proper ordering of `tx_signature`
/// message exchange.
///
/// See the specification for more details:
/// https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-commitment_signed-message
/// https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#sharing-funding-signatures-tx_signatures
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct InteractiveTxSigningSession {
	pub unsigned_tx: ConstructedTransaction,
	holder_sends_tx_signatures_first: bool,
	received_commitment_signed: bool,
	holder_tx_signatures: Option<TxSignatures>,
	counterparty_sent_tx_signatures: bool,
}

impl InteractiveTxSigningSession {
	pub fn received_commitment_signed(&mut self) -> Option<TxSignatures> {
		self.received_commitment_signed = true;
		if self.holder_sends_tx_signatures_first {
			self.holder_tx_signatures.clone()
		} else {
			None
		}
	}

	pub fn get_tx_signatures(&self) -> Option<TxSignatures> {
		if self.received_commitment_signed {
			self.holder_tx_signatures.clone()
		} else {
			None
		}
	}

	/// Handles a `tx_signatures` message received from the counterparty.
	///
	/// Returns an error if the witness count does not equal the counterparty's input count in the
	/// unsigned transaction.
	pub fn received_tx_signatures(
		&mut self, tx_signatures: TxSignatures,
	) -> Result<(Option<TxSignatures>, Option<Transaction>), ()> {
		if self.counterparty_sent_tx_signatures {
			return Ok((None, None));
		};
		if self.remote_inputs_count() != tx_signatures.witnesses.len() {
			return Err(());
		}
		self.unsigned_tx.add_remote_witnesses(tx_signatures.witnesses.clone());
		self.counterparty_sent_tx_signatures = true;

		let holder_tx_signatures = if !self.holder_sends_tx_signatures_first {
			self.holder_tx_signatures.clone()
		} else {
			None
		};

		let funding_tx = if self.holder_tx_signatures.is_some() {
			Some(self.finalize_funding_tx())
		} else {
			None
		};

		Ok((holder_tx_signatures, funding_tx))
	}

	/// Provides the holder witnesses for the unsigned transaction.
	///
	/// Returns an error if the witness count does not equal the holder's input count in the
	/// unsigned transaction.
	pub fn provide_holder_witnesses(
		&mut self, channel_id: ChannelId, witnesses: Vec<Witness>,
	) -> Result<Option<TxSignatures>, ()> {
		if self.local_inputs_count() != witnesses.len() {
			return Err(());
		}

		self.unsigned_tx.add_local_witnesses(witnesses.clone());
		self.holder_tx_signatures = Some(TxSignatures {
			channel_id,
			tx_hash: self.unsigned_tx.compute_txid(),
			witnesses: witnesses.into_iter().collect(),
			shared_input_signature: None,
		});
		if self.received_commitment_signed
			&& (self.holder_sends_tx_signatures_first || self.counterparty_sent_tx_signatures)
		{
			Ok(self.holder_tx_signatures.clone())
		} else {
			Ok(None)
		}
	}

	pub fn remote_inputs_count(&self) -> usize {
		self.unsigned_tx
			.inputs
			.iter()
			.filter(|input| {
				is_serial_id_valid_for_counterparty(
					self.unsigned_tx.holder_is_initiator,
					input.serial_id(),
				)
			})
			.count()
	}

	pub fn local_inputs_count(&self) -> usize {
		self.unsigned_tx
			.inputs
			.iter()
			.filter(|input| {
				!is_serial_id_valid_for_counterparty(
					self.unsigned_tx.holder_is_initiator,
					input.serial_id(),
				)
			})
			.count()
	}

	fn finalize_funding_tx(&mut self) -> Transaction {
		let lock_time = self.unsigned_tx.lock_time;
		let ConstructedTransaction { inputs, outputs, .. } = &mut self.unsigned_tx;

		Transaction {
			version: Version::TWO,
			lock_time,
			input: inputs.iter().cloned().map(|input| input.into_txin()).collect(),
			output: outputs.iter().cloned().map(|output| output.into_tx_out()).collect(),
		}
	}
}

#[derive(Debug)]
struct NegotiationContext {
	holder_node_id: PublicKey,
	counterparty_node_id: PublicKey,
	holder_is_initiator: bool,
	received_tx_add_input_count: u16,
	received_tx_add_output_count: u16,
	inputs: HashMap<SerialId, InteractiveTxInput>,
	/// The output script intended to be the new funding output script.
	/// The script pubkey is used to determine which output is the funding output.
	/// When an output with the same script pubkey is added by any of the nodes, it will be
	/// treated as the shared output.
	/// The value is the holder's intended contribution to the shared funding output.
	/// The rest is the counterparty's contribution.
	/// When the funding output is added (recognized by its output script pubkey), it will be marked
	/// as shared, and split between the peers according to the local value.
	/// If the local value is found to be larger than the actual funding output, an error is generated.
	expected_shared_funding_output: (ScriptBuf, u64),
	/// The actual new funding output, set only after the output has actually been added.
	/// NOTE: this output is also included in `outputs`.
	actual_new_funding_output: Option<SharedOwnedOutput>,
	prevtx_outpoints: HashSet<OutPoint>,
	/// The outputs added so far.
	outputs: HashMap<SerialId, InteractiveTxOutput>,
	/// The locktime of the funding transaction.
	tx_locktime: AbsoluteLockTime,
	/// The fee rate used for the transaction
	feerate_sat_per_kw: u32,
}

pub(crate) fn estimate_input_weight(prev_output: &TxOut) -> Weight {
	Weight::from_wu(if prev_output.script_pubkey.is_p2wpkh() {
		P2WPKH_INPUT_WEIGHT_LOWER_BOUND
	} else if prev_output.script_pubkey.is_p2wsh() {
		P2WSH_INPUT_WEIGHT_LOWER_BOUND
	} else if prev_output.script_pubkey.is_p2tr() {
		P2TR_INPUT_WEIGHT_LOWER_BOUND
	} else {
		UNKNOWN_SEGWIT_VERSION_INPUT_WEIGHT_LOWER_BOUND
	})
}

pub(crate) fn get_output_weight(script_pubkey: &ScriptBuf) -> Weight {
	Weight::from_wu(
		(8 /* value */ + script_pubkey.consensus_encode(&mut sink()).unwrap() as u64)
			* WITNESS_SCALE_FACTOR as u64,
	)
}

fn is_serial_id_valid_for_counterparty(holder_is_initiator: bool, serial_id: SerialId) -> bool {
	// A received `SerialId`'s parity must match the role of the counterparty.
	holder_is_initiator == serial_id.is_for_non_initiator()
}

impl NegotiationContext {
	fn new(
		holder_node_id: PublicKey, counterparty_node_id: PublicKey, holder_is_initiator: bool,
		expected_shared_funding_output: (ScriptBuf, u64), tx_locktime: AbsoluteLockTime,
		feerate_sat_per_kw: u32,
	) -> Self {
		NegotiationContext {
			holder_node_id,
			counterparty_node_id,
			holder_is_initiator,
			received_tx_add_input_count: 0,
			received_tx_add_output_count: 0,
			inputs: new_hash_map(),
			expected_shared_funding_output,
			actual_new_funding_output: None,
			prevtx_outpoints: new_hash_set(),
			outputs: new_hash_map(),
			tx_locktime,
			feerate_sat_per_kw,
		}
	}

	fn set_actual_new_funding_output(
		&mut self, tx_out: TxOut,
	) -> Result<SharedOwnedOutput, AbortReason> {
		if self.actual_new_funding_output.is_some() {
			return Err(AbortReason::DuplicateFundingOutput);
		}
		let value = tx_out.value.to_sat();
		let local_owned = self.expected_shared_funding_output.1;
		// Sanity check
		if local_owned > value {
			return Err(AbortReason::InvalidLowFundingOutputValue);
		}
		let shared_output = SharedOwnedOutput::new(tx_out, local_owned);
		self.actual_new_funding_output = Some(shared_output.clone());
		Ok(shared_output)
	}

	fn is_serial_id_valid_for_counterparty(&self, serial_id: &SerialId) -> bool {
		is_serial_id_valid_for_counterparty(self.holder_is_initiator, *serial_id)
	}

	fn remote_inputs_value(&self) -> u64 {
		self.inputs.iter().fold(0u64, |acc, (_, input)| acc.saturating_add(input.remote_value()))
	}

	fn remote_outputs_value(&self) -> u64 {
		self.outputs.iter().fold(0u64, |acc, (_, output)| acc.saturating_add(output.remote_value()))
	}

	fn remote_inputs_weight(&self) -> Weight {
		Weight::from_wu(
			self.inputs
				.iter()
				.filter(|(serial_id, _)| self.is_serial_id_valid_for_counterparty(serial_id))
				.fold(0u64, |weight, (_, input)| {
					weight.saturating_add(estimate_input_weight(input.prev_output()).to_wu())
				}),
		)
	}

	fn remote_outputs_weight(&self) -> Weight {
		Weight::from_wu(
			self.outputs
				.iter()
				.filter(|(serial_id, _)| self.is_serial_id_valid_for_counterparty(serial_id))
				.fold(0u64, |weight, (_, output)| {
					weight.saturating_add(get_output_weight(output.script_pubkey()).to_wu())
				}),
		)
	}

	fn local_inputs_value(&self) -> u64 {
		self.inputs
			.iter()
			.fold(0u64, |acc, (_, input)| acc.saturating_add(input.prev_output().value.to_sat()))
	}

	fn received_tx_add_input(&mut self, msg: &msgs::TxAddInput) -> Result<(), AbortReason> {
		// The interactive-txs spec calls for us to fail negotiation if the `prevtx` we receive is
		// invalid. However, we would not need to account for this explicit negotiation failure
		// mode here since `PeerManager` would already disconnect the peer if the `prevtx` is
		// invalid; implicitly ending the negotiation.

		if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
			// The receiving node:
			//  - MUST fail the negotiation if:
			//     - the `serial_id` has the wrong parity
			return Err(AbortReason::IncorrectSerialIdParity);
		}

		self.received_tx_add_input_count += 1;
		if self.received_tx_add_input_count > MAX_RECEIVED_TX_ADD_INPUT_COUNT {
			// The receiving node:
			//  - MUST fail the negotiation if:
			//     - if has received 4096 `tx_add_input` messages during this negotiation
			return Err(AbortReason::ReceivedTooManyTxAddInputs);
		}

		if msg.sequence >= 0xFFFFFFFE {
			// The receiving node:
			//  - MUST fail the negotiation if:
			//    - `sequence` is set to `0xFFFFFFFE` or `0xFFFFFFFF`
			return Err(AbortReason::IncorrectInputSequenceValue);
		}

		let transaction = msg.prevtx.as_transaction();
		let txid = transaction.compute_txid();

		if let Some(tx_out) = transaction.output.get(msg.prevtx_out as usize) {
			if !tx_out.script_pubkey.is_witness_program() {
				// The receiving node:
				//  - MUST fail the negotiation if:
				//     - the `scriptPubKey` is not a witness program
				return Err(AbortReason::PrevTxOutInvalid);
			}

			if !self.prevtx_outpoints.insert(OutPoint { txid, vout: msg.prevtx_out }) {
				// The receiving node:
				//  - MUST fail the negotiation if:
				//     - the `prevtx` and `prevtx_vout` are identical to a previously added
				//       (and not removed) input's
				return Err(AbortReason::PrevTxOutInvalid);
			}
		} else {
			// The receiving node:
			//  - MUST fail the negotiation if:
			//     - `prevtx_vout` is greater or equal to the number of outputs on `prevtx`
			return Err(AbortReason::PrevTxOutInvalid);
		}

		let prev_out = if let Some(prev_out) = transaction.output.get(msg.prevtx_out as usize) {
			prev_out.clone()
		} else {
			return Err(AbortReason::PrevTxOutInvalid);
		};
		match self.inputs.entry(msg.serial_id) {
			hash_map::Entry::Occupied(_) => {
				// The receiving node:
				//  - MUST fail the negotiation if:
				//    - the `serial_id` is already included in the transaction
				Err(AbortReason::DuplicateSerialId)
			},
			hash_map::Entry::Vacant(entry) => {
				let prev_outpoint = OutPoint { txid, vout: msg.prevtx_out };
				entry.insert(InteractiveTxInput::Remote(LocalOrRemoteInput {
					serial_id: msg.serial_id,
					input: TxIn {
						previous_output: prev_outpoint,
						sequence: Sequence(msg.sequence),
						..Default::default()
					},
					prev_output: prev_out,
				}));
				self.prevtx_outpoints.insert(prev_outpoint);
				Ok(())
			},
		}
	}

	fn received_tx_remove_input(&mut self, msg: &msgs::TxRemoveInput) -> Result<(), AbortReason> {
		if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
			return Err(AbortReason::IncorrectSerialIdParity);
		}

		self.inputs
			.remove(&msg.serial_id)
			// The receiving node:
			//  - MUST fail the negotiation if:
			//    - the input or output identified by the `serial_id` was not added by the sender
			//    - the `serial_id` does not correspond to a currently added input
			.ok_or(AbortReason::SerialIdUnknown)
			.map(|_| ())
	}

	fn received_tx_add_output(&mut self, msg: &msgs::TxAddOutput) -> Result<(), AbortReason> {
		// The receiving node:
		//  - MUST fail the negotiation if:
		//     - the serial_id has the wrong parity
		if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
			return Err(AbortReason::IncorrectSerialIdParity);
		}

		self.received_tx_add_output_count += 1;
		if self.received_tx_add_output_count > MAX_RECEIVED_TX_ADD_OUTPUT_COUNT {
			// The receiving node:
			//  - MUST fail the negotiation if:
			//     - if has received 4096 `tx_add_output` messages during this negotiation
			return Err(AbortReason::ReceivedTooManyTxAddOutputs);
		}

		if msg.sats < msg.script.minimal_non_dust().to_sat() {
			// The receiving node:
			// - MUST fail the negotiation if:
			//		- the sats amount is less than the dust_limit
			return Err(AbortReason::BelowDustLimit);
		}

		// Check that adding this output would not cause the total output value to exceed the total
		// bitcoin supply.
		let mut outputs_value: u64 = 0;
		for output in self.outputs.iter() {
			outputs_value = outputs_value.saturating_add(output.1.value());
		}
		if outputs_value.saturating_add(msg.sats) > TOTAL_BITCOIN_SUPPLY_SATOSHIS {
			// The receiving node:
			// - MUST fail the negotiation if:
			//		- the sats amount is greater than 2,100,000,000,000,000 (TOTAL_BITCOIN_SUPPLY_SATOSHIS)
			return Err(AbortReason::ExceededMaximumSatsAllowed);
		}

		// The receiving node:
		//   - MUST accept P2WSH, P2WPKH, P2TR scripts
		//   - MAY fail the negotiation if script is non-standard
		//
		// We can actually be a bit looser than the above as only witness version 0 has special
		// length-based standardness constraints to match similar consensus rules. All witness scripts
		// with witness versions V1 and up are always considered standard. Yes, the scripts can be
		// anyone-can-spend-able, but if our counterparty wants to add an output like that then it's none
		// of our concern really ¯\_(ツ)_/¯
		//
		// TODO: The last check would be simplified when https://github.com/rust-bitcoin/rust-bitcoin/commit/1656e1a09a1959230e20af90d20789a4a8f0a31b
		// hits the next release of rust-bitcoin.
		if !(msg.script.is_p2wpkh()
			|| msg.script.is_p2wsh()
			|| (msg.script.is_witness_program()
				&& msg.script.witness_version().map(|v| v.to_num() >= 1).unwrap_or(false)))
		{
			return Err(AbortReason::InvalidOutputScript);
		}

		let txout = TxOut { value: Amount::from_sat(msg.sats), script_pubkey: msg.script.clone() };
		let is_shared = msg.script == self.expected_shared_funding_output.0;
		let output = if is_shared {
			// this is a shared funding output
			let shared_output = self.set_actual_new_funding_output(txout)?;
			InteractiveTxOutput {
				serial_id: msg.serial_id,
				added_by: AddingRole::Remote,
				output: OutputOwned::Shared(shared_output),
			}
		} else {
			InteractiveTxOutput {
				serial_id: msg.serial_id,
				added_by: AddingRole::Remote,
				output: OutputOwned::Single(txout),
			}
		};
		match self.outputs.entry(msg.serial_id) {
			hash_map::Entry::Occupied(_) => {
				// The receiving node:
				//  - MUST fail the negotiation if:
				//    - the `serial_id` is already included in the transaction
				Err(AbortReason::DuplicateSerialId)
			},
			hash_map::Entry::Vacant(entry) => {
				entry.insert(output);
				Ok(())
			},
		}
	}

	fn received_tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput) -> Result<(), AbortReason> {
		if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
			return Err(AbortReason::IncorrectSerialIdParity);
		}
		if self.outputs.remove(&msg.serial_id).is_some() {
			Ok(())
		} else {
			// The receiving node:
			//  - MUST fail the negotiation if:
			//    - the input or output identified by the `serial_id` was not added by the sender
			//    - the `serial_id` does not correspond to a currently added input
			Err(AbortReason::SerialIdUnknown)
		}
	}

	fn sent_tx_add_input(&mut self, msg: &msgs::TxAddInput) -> Result<(), AbortReason> {
		let tx = msg.prevtx.as_transaction();
		let txin = TxIn {
			previous_output: OutPoint { txid: tx.compute_txid(), vout: msg.prevtx_out },
			sequence: Sequence(msg.sequence),
			..Default::default()
		};
		if !self.prevtx_outpoints.insert(txin.previous_output) {
			// We have added an input that already exists
			return Err(AbortReason::PrevTxOutInvalid);
		}
		let vout = txin.previous_output.vout as usize;
		let prev_output = tx.output.get(vout).ok_or(AbortReason::PrevTxOutInvalid)?.clone();
		let input = InteractiveTxInput::Local(LocalOrRemoteInput {
			serial_id: msg.serial_id,
			input: txin,
			prev_output,
		});
		self.inputs.insert(msg.serial_id, input);
		Ok(())
	}

	fn sent_tx_add_output(&mut self, msg: &msgs::TxAddOutput) -> Result<(), AbortReason> {
		let txout = TxOut { value: Amount::from_sat(msg.sats), script_pubkey: msg.script.clone() };
		let is_shared = msg.script == self.expected_shared_funding_output.0;
		let output = if is_shared {
			// this is a shared funding output
			let shared_output = self.set_actual_new_funding_output(txout)?;
			InteractiveTxOutput {
				serial_id: msg.serial_id,
				added_by: AddingRole::Local,
				output: OutputOwned::Shared(shared_output),
			}
		} else {
			InteractiveTxOutput {
				serial_id: msg.serial_id,
				added_by: AddingRole::Local,
				output: OutputOwned::Single(txout),
			}
		};
		self.outputs.insert(msg.serial_id, output);
		Ok(())
	}

	fn sent_tx_remove_input(&mut self, msg: &msgs::TxRemoveInput) -> Result<(), AbortReason> {
		self.inputs.remove(&msg.serial_id);
		Ok(())
	}

	fn sent_tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput) -> Result<(), AbortReason> {
		self.outputs.remove(&msg.serial_id);
		Ok(())
	}

	fn check_counterparty_fees(
		&self, counterparty_fees_contributed: u64,
	) -> Result<(), AbortReason> {
		let counterparty_weight_contributed = self
			.remote_inputs_weight()
			.to_wu()
			.saturating_add(self.remote_outputs_weight().to_wu());
		let mut required_counterparty_contribution_fee =
			fee_for_weight(self.feerate_sat_per_kw, counterparty_weight_contributed);
		if !self.holder_is_initiator {
			// if is the non-initiator:
			// 	- the initiator's fees do not cover the common fields (version, segwit marker + flag,
			// 		input count, output count, locktime)
			let tx_common_fields_fee =
				fee_for_weight(self.feerate_sat_per_kw, TX_COMMON_FIELDS_WEIGHT);
			required_counterparty_contribution_fee += tx_common_fields_fee;
		}
		if counterparty_fees_contributed < required_counterparty_contribution_fee {
			return Err(AbortReason::InsufficientFees);
		}
		Ok(())
	}

	fn validate_tx(self) -> Result<ConstructedTransaction, AbortReason> {
		// The receiving node:
		// MUST fail the negotiation if:

		// - the peer's total input satoshis is less than their outputs
		let remote_inputs_value = self.remote_inputs_value();
		let remote_outputs_value = self.remote_outputs_value();
		if remote_inputs_value < remote_outputs_value {
			return Err(AbortReason::OutputsValueExceedsInputsValue);
		}

		// - there are more than 252 inputs
		// - there are more than 252 outputs
		if self.inputs.len() > MAX_INPUTS_OUTPUTS_COUNT
			|| self.outputs.len() > MAX_INPUTS_OUTPUTS_COUNT
		{
			return Err(AbortReason::ExceededNumberOfInputsOrOutputs);
		}

		if self.actual_new_funding_output.is_none() {
			return Err(AbortReason::MissingFundingOutput);
		}

		// - the peer's paid feerate does not meet or exceed the agreed feerate (based on the minimum fee).
		self.check_counterparty_fees(remote_inputs_value.saturating_sub(remote_outputs_value))?;

		let constructed_tx = ConstructedTransaction::new(self);

		if constructed_tx.weight().to_wu() > MAX_STANDARD_TX_WEIGHT as u64 {
			return Err(AbortReason::TransactionTooLarge);
		}

		Ok(constructed_tx)
	}
}

// The interactive transaction construction protocol allows two peers to collaboratively build a
// transaction for broadcast.
//
// The protocol is turn-based, so we define different states here that we store depending on whose
// turn it is to send the next message. The states are defined so that their types ensure we only
// perform actions (only send messages) via defined state transitions that do not violate the
// protocol.
//
// An example of a full negotiation and associated states follows:
//
//     +------------+                         +------------------+---- Holder state after message sent/received ----+
//     |            |--(1)- tx_add_input ---->|                  |                  SentChangeMsg                   +
//     |            |<-(2)- tx_complete ------|                  |                ReceivedTxComplete                +
//     |            |--(3)- tx_add_output --->|                  |                  SentChangeMsg                   +
//     |            |<-(4)- tx_complete ------|                  |                ReceivedTxComplete                +
//     |            |--(5)- tx_add_input ---->|                  |                  SentChangeMsg                   +
//     |   Holder   |<-(6)- tx_add_input -----|   Counterparty   |                ReceivedChangeMsg                 +
//     |            |--(7)- tx_remove_output >|                  |                  SentChangeMsg                   +
//     |            |<-(8)- tx_add_output ----|                  |                ReceivedChangeMsg                 +
//     |            |--(9)- tx_complete ----->|                  |                  SentTxComplete                  +
//     |            |<-(10) tx_complete ------|                  |                NegotiationComplete               +
//     +------------+                         +------------------+--------------------------------------------------+

/// Negotiation states that can send & receive `tx_(add|remove)_(input|output)` and `tx_complete`
trait State {}

/// Category of states where we have sent some message to the counterparty, and we are waiting for
/// a response.
trait SentMsgState: State {
	fn into_negotiation_context(self) -> NegotiationContext;
}

/// Category of states that our counterparty has put us in after we receive a message from them.
trait ReceivedMsgState: State {
	fn into_negotiation_context(self) -> NegotiationContext;
}

// This macro is a helper for implementing the above state traits for various states subsequently
// defined below the macro.
macro_rules! define_state {
	(SENT_MSG_STATE, $state: ident, $doc: expr) => {
		define_state!($state, NegotiationContext, $doc);
		impl SentMsgState for $state {
			fn into_negotiation_context(self) -> NegotiationContext {
				self.0
			}
		}
	};
	(RECEIVED_MSG_STATE, $state: ident, $doc: expr) => {
		define_state!($state, NegotiationContext, $doc);
		impl ReceivedMsgState for $state {
			fn into_negotiation_context(self) -> NegotiationContext {
				self.0
			}
		}
	};
	($state: ident, $inner: ident, $doc: expr) => {
		#[doc = $doc]
		#[derive(Debug)]
		struct $state($inner);
		impl State for $state {}
	};
}

define_state!(
	SENT_MSG_STATE,
	SentChangeMsg,
	"We have sent a message to the counterparty that has affected our negotiation state."
);
define_state!(
	SENT_MSG_STATE,
	SentTxComplete,
	"We have sent a `tx_complete` message and are awaiting the counterparty's."
);
define_state!(
	RECEIVED_MSG_STATE,
	ReceivedChangeMsg,
	"We have received a message from the counterparty that has affected our negotiation state."
);
define_state!(
	RECEIVED_MSG_STATE,
	ReceivedTxComplete,
	"We have received a `tx_complete` message and the counterparty is awaiting ours."
);
define_state!(NegotiationComplete, InteractiveTxSigningSession, "We have exchanged consecutive `tx_complete` messages with the counterparty and the transaction negotiation is complete.");
define_state!(
	NegotiationAborted,
	AbortReason,
	"The negotiation has failed and cannot be continued."
);

type StateTransitionResult<S> = Result<S, AbortReason>;

trait StateTransition<NewState: State, TransitionData> {
	fn transition(self, data: TransitionData) -> StateTransitionResult<NewState>;
}

// This macro helps define the legal transitions between the states above by implementing
// the `StateTransition` trait for each of the states that follow this declaration.
macro_rules! define_state_transitions {
	(SENT_MSG_STATE, [$(DATA $data: ty, TRANSITION $transition: ident),+]) => {
		$(
			impl<S: SentMsgState> StateTransition<ReceivedChangeMsg, $data> for S {
				fn transition(self, data: $data) -> StateTransitionResult<ReceivedChangeMsg> {
					let mut context = self.into_negotiation_context();
					context.$transition(data)?;
					Ok(ReceivedChangeMsg(context))
				}
			}
		 )*
	};
	(RECEIVED_MSG_STATE, [$(DATA $data: ty, TRANSITION $transition: ident),+]) => {
		$(
			impl<S: ReceivedMsgState> StateTransition<SentChangeMsg, $data> for S {
				fn transition(self, data: $data) -> StateTransitionResult<SentChangeMsg> {
					let mut context = self.into_negotiation_context();
					context.$transition(data)?;
					Ok(SentChangeMsg(context))
				}
			}
		 )*
	};
	(TX_COMPLETE, $from_state: ident, $tx_complete_state: ident) => {
		impl StateTransition<NegotiationComplete, &msgs::TxComplete> for $tx_complete_state {
			fn transition(self, _data: &msgs::TxComplete) -> StateTransitionResult<NegotiationComplete> {
				let context = self.into_negotiation_context();
				let tx = context.validate_tx()?;
				let signing_session = InteractiveTxSigningSession {
					holder_sends_tx_signatures_first: tx.holder_sends_tx_signatures_first,
					unsigned_tx: tx,
					received_commitment_signed: false,
					holder_tx_signatures: None,
					counterparty_sent_tx_signatures: false,
				};
				Ok(NegotiationComplete(signing_session))
			}
		}

		impl StateTransition<$tx_complete_state, &msgs::TxComplete> for $from_state {
			fn transition(self, _data: &msgs::TxComplete) -> StateTransitionResult<$tx_complete_state> {
				Ok($tx_complete_state(self.into_negotiation_context()))
			}
		}
	};
}

// State transitions when we have sent our counterparty some messages and are waiting for them
// to respond.
define_state_transitions!(SENT_MSG_STATE, [
	DATA &msgs::TxAddInput, TRANSITION received_tx_add_input,
	DATA &msgs::TxRemoveInput, TRANSITION received_tx_remove_input,
	DATA &msgs::TxAddOutput, TRANSITION received_tx_add_output,
	DATA &msgs::TxRemoveOutput, TRANSITION received_tx_remove_output
]);
// State transitions when we have received some messages from our counterparty and we should
// respond.
define_state_transitions!(RECEIVED_MSG_STATE, [
	DATA &msgs::TxAddInput, TRANSITION sent_tx_add_input,
	DATA &msgs::TxRemoveInput, TRANSITION sent_tx_remove_input,
	DATA &msgs::TxAddOutput, TRANSITION sent_tx_add_output,
	DATA &msgs::TxRemoveOutput, TRANSITION sent_tx_remove_output
]);
define_state_transitions!(TX_COMPLETE, SentChangeMsg, ReceivedTxComplete);
define_state_transitions!(TX_COMPLETE, ReceivedChangeMsg, SentTxComplete);

#[derive(Debug)]
enum StateMachine {
	Indeterminate,
	SentChangeMsg(SentChangeMsg),
	ReceivedChangeMsg(ReceivedChangeMsg),
	SentTxComplete(SentTxComplete),
	ReceivedTxComplete(ReceivedTxComplete),
	NegotiationComplete(NegotiationComplete),
	NegotiationAborted(NegotiationAborted),
}

impl Default for StateMachine {
	fn default() -> Self {
		Self::Indeterminate
	}
}

// The `StateMachine` internally executes the actual transition between two states and keeps
// track of the current state. This macro defines _how_ those state transitions happen to
// update the internal state.
macro_rules! define_state_machine_transitions {
	($transition: ident, $msg: ty, [$(FROM $from_state: ident, TO $to_state: ident),+]) => {
		fn $transition(self, msg: $msg) -> StateMachine {
			match self {
				$(
					Self::$from_state(s) => match s.transition(msg) {
						Ok(new_state) => StateMachine::$to_state(new_state),
						Err(abort_reason) => StateMachine::NegotiationAborted(NegotiationAborted(abort_reason)),
					}
				 )*
				_ => StateMachine::NegotiationAborted(NegotiationAborted(AbortReason::UnexpectedCounterpartyMessage)),
			}
		}
	};
}

impl StateMachine {
	fn new(
		holder_node_id: PublicKey, counterparty_node_id: PublicKey, feerate_sat_per_kw: u32,
		is_initiator: bool, tx_locktime: AbsoluteLockTime,
		expected_shared_funding_output: (ScriptBuf, u64),
	) -> Self {
		let context = NegotiationContext::new(
			holder_node_id,
			counterparty_node_id,
			is_initiator,
			expected_shared_funding_output,
			tx_locktime,
			feerate_sat_per_kw,
		);
		if is_initiator {
			Self::ReceivedChangeMsg(ReceivedChangeMsg(context))
		} else {
			Self::SentChangeMsg(SentChangeMsg(context))
		}
	}

	// TxAddInput
	define_state_machine_transitions!(sent_tx_add_input, &msgs::TxAddInput, [
		FROM ReceivedChangeMsg, TO SentChangeMsg,
		FROM ReceivedTxComplete, TO SentChangeMsg
	]);
	define_state_machine_transitions!(received_tx_add_input, &msgs::TxAddInput, [
		FROM SentChangeMsg, TO ReceivedChangeMsg,
		FROM SentTxComplete, TO ReceivedChangeMsg
	]);

	// TxAddOutput
	define_state_machine_transitions!(sent_tx_add_output, &msgs::TxAddOutput, [
		FROM ReceivedChangeMsg, TO SentChangeMsg,
		FROM ReceivedTxComplete, TO SentChangeMsg
	]);
	define_state_machine_transitions!(received_tx_add_output, &msgs::TxAddOutput, [
		FROM SentChangeMsg, TO ReceivedChangeMsg,
		FROM SentTxComplete, TO ReceivedChangeMsg
	]);

	// TxRemoveInput
	define_state_machine_transitions!(sent_tx_remove_input, &msgs::TxRemoveInput, [
		FROM ReceivedChangeMsg, TO SentChangeMsg,
		FROM ReceivedTxComplete, TO SentChangeMsg
	]);
	define_state_machine_transitions!(received_tx_remove_input, &msgs::TxRemoveInput, [
		FROM SentChangeMsg, TO ReceivedChangeMsg,
		FROM SentTxComplete, TO ReceivedChangeMsg
	]);

	// TxRemoveOutput
	define_state_machine_transitions!(sent_tx_remove_output, &msgs::TxRemoveOutput, [
		FROM ReceivedChangeMsg, TO SentChangeMsg,
		FROM ReceivedTxComplete, TO SentChangeMsg
	]);
	define_state_machine_transitions!(received_tx_remove_output, &msgs::TxRemoveOutput, [
		FROM SentChangeMsg, TO ReceivedChangeMsg,
		FROM SentTxComplete, TO ReceivedChangeMsg
	]);

	// TxComplete
	define_state_machine_transitions!(sent_tx_complete, &msgs::TxComplete, [
		FROM ReceivedChangeMsg, TO SentTxComplete,
		FROM ReceivedTxComplete, TO NegotiationComplete
	]);
	define_state_machine_transitions!(received_tx_complete, &msgs::TxComplete, [
		FROM SentChangeMsg, TO ReceivedTxComplete,
		FROM SentTxComplete, TO NegotiationComplete
	]);
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AddingRole {
	Local,
	Remote,
}

/// Represents an input -- local or remote (both have the same fields)
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LocalOrRemoteInput {
	serial_id: SerialId,
	input: TxIn,
	prev_output: TxOut,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum InteractiveTxInput {
	Local(LocalOrRemoteInput),
	Remote(LocalOrRemoteInput),
	// TODO(splicing) SharedInput should be added
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SharedOwnedOutput {
	tx_out: TxOut,
	local_owned: u64,
}

impl SharedOwnedOutput {
	fn new(tx_out: TxOut, local_owned: u64) -> SharedOwnedOutput {
		debug_assert!(
			local_owned <= tx_out.value.to_sat(),
			"SharedOwnedOutput: Inconsistent local_owned value {}, larger than output value {}",
			local_owned,
			tx_out.value
		);
		SharedOwnedOutput { tx_out, local_owned }
	}

	fn remote_owned(&self) -> u64 {
		self.tx_out.value.to_sat().saturating_sub(self.local_owned)
	}
}

/// Represents an output, with information about
/// its control -- exclusive by the adder or shared --, and
/// its ownership -- value fully owned by the adder or jointly
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OutputOwned {
	/// Belongs to a single party -- controlled exclusively and fully belonging to a single party
	Single(TxOut),
	/// Output with shared control, but fully belonging to local node
	SharedControlFullyOwned(TxOut),
	/// Output with shared control and joint ownership
	Shared(SharedOwnedOutput),
}

impl OutputOwned {
	fn tx_out(&self) -> &TxOut {
		match self {
			OutputOwned::Single(tx_out) | OutputOwned::SharedControlFullyOwned(tx_out) => tx_out,
			OutputOwned::Shared(output) => &output.tx_out,
		}
	}

	fn into_tx_out(self) -> TxOut {
		match self {
			OutputOwned::Single(tx_out) | OutputOwned::SharedControlFullyOwned(tx_out) => tx_out,
			OutputOwned::Shared(output) => output.tx_out,
		}
	}

	fn value(&self) -> u64 {
		self.tx_out().value.to_sat()
	}

	fn is_shared(&self) -> bool {
		match self {
			OutputOwned::Single(_) => false,
			OutputOwned::SharedControlFullyOwned(_) => true,
			OutputOwned::Shared(_) => true,
		}
	}

	fn local_value(&self, local_role: AddingRole) -> u64 {
		match self {
			OutputOwned::Single(tx_out) | OutputOwned::SharedControlFullyOwned(tx_out) => {
				match local_role {
					AddingRole::Local => tx_out.value.to_sat(),
					AddingRole::Remote => 0,
				}
			},
			OutputOwned::Shared(output) => output.local_owned,
		}
	}

	fn remote_value(&self, local_role: AddingRole) -> u64 {
		match self {
			OutputOwned::Single(tx_out) | OutputOwned::SharedControlFullyOwned(tx_out) => {
				match local_role {
					AddingRole::Local => 0,
					AddingRole::Remote => tx_out.value.to_sat(),
				}
			},
			OutputOwned::Shared(output) => output.remote_owned(),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct InteractiveTxOutput {
	serial_id: SerialId,
	added_by: AddingRole,
	output: OutputOwned,
}

impl InteractiveTxOutput {
	pub fn tx_out(&self) -> &TxOut {
		self.output.tx_out()
	}

	pub fn into_tx_out(self) -> TxOut {
		self.output.into_tx_out()
	}

	pub fn value(&self) -> u64 {
		self.tx_out().value.to_sat()
	}

	pub fn local_value(&self) -> u64 {
		self.output.local_value(self.added_by)
	}

	pub fn remote_value(&self) -> u64 {
		self.output.remote_value(self.added_by)
	}

	pub fn script_pubkey(&self) -> &ScriptBuf {
		&self.output.tx_out().script_pubkey
	}
}

impl InteractiveTxInput {
	pub fn serial_id(&self) -> SerialId {
		match self {
			InteractiveTxInput::Local(input) => input.serial_id,
			InteractiveTxInput::Remote(input) => input.serial_id,
		}
	}

	pub fn txin(&self) -> &TxIn {
		match self {
			InteractiveTxInput::Local(input) => &input.input,
			InteractiveTxInput::Remote(input) => &input.input,
		}
	}

	pub fn txin_mut(&mut self) -> &mut TxIn {
		match self {
			InteractiveTxInput::Local(input) => &mut input.input,
			InteractiveTxInput::Remote(input) => &mut input.input,
		}
	}

	pub fn into_txin(self) -> TxIn {
		match self {
			InteractiveTxInput::Local(input) => input.input,
			InteractiveTxInput::Remote(input) => input.input,
		}
	}

	pub fn prev_output(&self) -> &TxOut {
		match self {
			InteractiveTxInput::Local(input) => &input.prev_output,
			InteractiveTxInput::Remote(input) => &input.prev_output,
		}
	}

	pub fn value(&self) -> u64 {
		self.prev_output().value.to_sat()
	}

	pub fn local_value(&self) -> u64 {
		match self {
			InteractiveTxInput::Local(input) => input.prev_output.value.to_sat(),
			InteractiveTxInput::Remote(_input) => 0,
		}
	}

	pub fn remote_value(&self) -> u64 {
		match self {
			InteractiveTxInput::Local(_input) => 0,
			InteractiveTxInput::Remote(input) => input.prev_output.value.to_sat(),
		}
	}
}

pub(super) struct InteractiveTxConstructor {
	state_machine: StateMachine,
	initiator_first_message: Option<InteractiveTxMessageSend>,
	channel_id: ChannelId,
	inputs_to_contribute: Vec<(SerialId, TxIn, TransactionU16LenLimited)>,
	outputs_to_contribute: Vec<(SerialId, OutputOwned)>,
}

#[allow(clippy::enum_variant_names)] // Clippy doesn't like the repeated `Tx` prefix here
pub(crate) enum InteractiveTxMessageSend {
	TxAddInput(msgs::TxAddInput),
	TxAddOutput(msgs::TxAddOutput),
	TxComplete(msgs::TxComplete),
}

impl InteractiveTxMessageSend {
	pub fn into_msg_send_event(self, counterparty_node_id: PublicKey) -> MessageSendEvent {
		match self {
			InteractiveTxMessageSend::TxAddInput(msg) => {
				MessageSendEvent::SendTxAddInput { node_id: counterparty_node_id, msg }
			},
			InteractiveTxMessageSend::TxAddOutput(msg) => {
				MessageSendEvent::SendTxAddOutput { node_id: counterparty_node_id, msg }
			},
			InteractiveTxMessageSend::TxComplete(msg) => {
				MessageSendEvent::SendTxComplete { node_id: counterparty_node_id, msg }
			},
		}
	}
}

pub(super) struct InteractiveTxMessageSendResult(
	pub Result<InteractiveTxMessageSend, msgs::TxAbort>,
);

impl InteractiveTxMessageSendResult {
	pub fn into_msg_send_event(self, counterparty_node_id: PublicKey) -> MessageSendEvent {
		match self.0 {
			Ok(interactive_tx_msg_send) => {
				interactive_tx_msg_send.into_msg_send_event(counterparty_node_id)
			},
			Err(tx_abort_msg) => {
				MessageSendEvent::SendTxAbort { node_id: counterparty_node_id, msg: tx_abort_msg }
			},
		}
	}
}

// This macro executes a state machine transition based on a provided action.
macro_rules! do_state_transition {
	($self: ident, $transition: ident, $msg: expr) => {{
		let state_machine = core::mem::take(&mut $self.state_machine);
		$self.state_machine = state_machine.$transition($msg);
		match &$self.state_machine {
			StateMachine::NegotiationAborted(state) => Err(state.0.clone()),
			_ => Ok(()),
		}
	}};
}

fn generate_holder_serial_id<ES: Deref>(entropy_source: &ES, is_initiator: bool) -> SerialId
where
	ES::Target: EntropySource,
{
	let rand_bytes = entropy_source.get_secure_random_bytes();
	let mut serial_id_bytes = [0u8; 8];
	serial_id_bytes.copy_from_slice(&rand_bytes[..8]);
	let mut serial_id = u64::from_be_bytes(serial_id_bytes);
	if serial_id.is_for_initiator() != is_initiator {
		serial_id ^= 1;
	}
	serial_id
}

pub(super) enum HandleTxCompleteValue {
	SendTxMessage(InteractiveTxMessageSend),
	SendTxComplete(InteractiveTxMessageSend, InteractiveTxSigningSession),
	NegotiationComplete(InteractiveTxSigningSession),
}

impl HandleTxCompleteValue {
	pub fn into_msg_send_event_or_signing_session(
		self, counterparty_node_id: PublicKey,
	) -> (Option<MessageSendEvent>, Option<InteractiveTxSigningSession>) {
		match self {
			HandleTxCompleteValue::SendTxMessage(msg) => {
				(Some(msg.into_msg_send_event(counterparty_node_id)), None)
			},
			HandleTxCompleteValue::SendTxComplete(msg, signing_session) => {
				(Some(msg.into_msg_send_event(counterparty_node_id)), Some(signing_session))
			},
			HandleTxCompleteValue::NegotiationComplete(signing_session) => {
				(None, Some(signing_session))
			},
		}
	}
}

pub(super) struct HandleTxCompleteResult(pub Result<HandleTxCompleteValue, msgs::TxAbort>);

impl HandleTxCompleteResult {
	pub fn into_msg_send_event_or_signing_session(
		self, counterparty_node_id: PublicKey,
	) -> (Option<MessageSendEvent>, Option<InteractiveTxSigningSession>) {
		match self.0 {
			Ok(interactive_tx_msg_send) => {
				interactive_tx_msg_send.into_msg_send_event_or_signing_session(counterparty_node_id)
			},
			Err(tx_abort_msg) => (
				Some(MessageSendEvent::SendTxAbort {
					node_id: counterparty_node_id,
					msg: tx_abort_msg,
				}),
				None,
			),
		}
	}
}

pub(super) struct InteractiveTxConstructorArgs<'a, ES: Deref>
where
	ES::Target: EntropySource,
{
	pub entropy_source: &'a ES,
	pub holder_node_id: PublicKey,
	pub counterparty_node_id: PublicKey,
	pub channel_id: ChannelId,
	pub feerate_sat_per_kw: u32,
	pub is_initiator: bool,
	pub funding_tx_locktime: AbsoluteLockTime,
	pub inputs_to_contribute: Vec<(TxIn, TransactionU16LenLimited)>,
	pub outputs_to_contribute: Vec<OutputOwned>,
	pub expected_remote_shared_funding_output: Option<(ScriptBuf, u64)>,
}

impl InteractiveTxConstructor {
	/// Instantiates a new `InteractiveTxConstructor`.
	///
	/// `expected_remote_shared_funding_output`: In the case when the local node doesn't
	/// add a shared output, but it expects a shared output to be added by the remote node,
	/// it has to specify the script pubkey, used to determine the shared output,
	/// and its (local) contribution from the shared output:
	///   0 when the whole value belongs to the remote node, or
	///   positive if owned also by local.
	/// Note: The local value cannot be larger than the actual shared output.
	///
	/// If the holder is the initiator, they need to send the first message which is a `TxAddInput`
	/// message.
	pub fn new<ES: Deref>(args: InteractiveTxConstructorArgs<ES>) -> Result<Self, AbortReason>
	where
		ES::Target: EntropySource,
	{
		let InteractiveTxConstructorArgs {
			entropy_source,
			holder_node_id,
			counterparty_node_id,
			channel_id,
			feerate_sat_per_kw,
			is_initiator,
			funding_tx_locktime,
			inputs_to_contribute,
			outputs_to_contribute,
			expected_remote_shared_funding_output,
		} = args;
		// Sanity check: There can be at most one shared output, local-added or remote-added
		let mut expected_shared_funding_output: Option<(ScriptBuf, u64)> = None;
		for output in &outputs_to_contribute {
			let new_output = match output {
				OutputOwned::Single(_tx_out) => None,
				OutputOwned::SharedControlFullyOwned(tx_out) => {
					Some((tx_out.script_pubkey.clone(), tx_out.value.to_sat()))
				},
				OutputOwned::Shared(output) => {
					// Sanity check
					if output.local_owned >= output.tx_out.value.to_sat() {
						return Err(AbortReason::InvalidLowFundingOutputValue);
					}
					Some((output.tx_out.script_pubkey.clone(), output.local_owned))
				},
			};
			if new_output.is_some() {
				if expected_shared_funding_output.is_some()
					|| expected_remote_shared_funding_output.is_some()
				{
					// more than one local-added shared output or
					// one local-added and one remote-expected shared output
					return Err(AbortReason::DuplicateFundingOutput);
				}
				expected_shared_funding_output = new_output;
			}
		}
		if let Some(expected_remote_shared_funding_output) = expected_remote_shared_funding_output {
			expected_shared_funding_output = Some(expected_remote_shared_funding_output);
		}
		if let Some(expected_shared_funding_output) = expected_shared_funding_output {
			let state_machine = StateMachine::new(
				holder_node_id,
				counterparty_node_id,
				feerate_sat_per_kw,
				is_initiator,
				funding_tx_locktime,
				expected_shared_funding_output,
			);
			let mut inputs_to_contribute: Vec<(SerialId, TxIn, TransactionU16LenLimited)> =
				inputs_to_contribute
					.into_iter()
					.map(|(input, tx)| {
						let serial_id = generate_holder_serial_id(entropy_source, is_initiator);
						(serial_id, input, tx)
					})
					.collect();
			// We'll sort by the randomly generated serial IDs, effectively shuffling the order of the inputs
			// as the user passed them to us to avoid leaking any potential categorization of transactions
			// before we pass any of the inputs to the counterparty.
			inputs_to_contribute.sort_unstable_by_key(|(serial_id, _, _)| *serial_id);
			let mut outputs_to_contribute: Vec<_> = outputs_to_contribute
				.into_iter()
				.map(|output| {
					let serial_id = generate_holder_serial_id(entropy_source, is_initiator);
					(serial_id, output)
				})
				.collect();
			// In the same manner and for the same rationale as the inputs above, we'll shuffle the outputs.
			outputs_to_contribute.sort_unstable_by_key(|(serial_id, _)| *serial_id);
			let mut constructor = Self {
				state_machine,
				initiator_first_message: None,
				channel_id,
				inputs_to_contribute,
				outputs_to_contribute,
			};
			// We'll store the first message for the initiator.
			if is_initiator {
				constructor.initiator_first_message = Some(constructor.maybe_send_message()?);
			}
			Ok(constructor)
		} else {
			Err(AbortReason::MissingFundingOutput)
		}
	}

	pub fn take_initiator_first_message(&mut self) -> Option<InteractiveTxMessageSend> {
		self.initiator_first_message.take()
	}

	fn maybe_send_message(&mut self) -> Result<InteractiveTxMessageSend, AbortReason> {
		// We first attempt to send inputs we want to add, then outputs. Once we are done sending
		// them both, then we always send tx_complete.
		if let Some((serial_id, input, prevtx)) = self.inputs_to_contribute.pop() {
			let msg = msgs::TxAddInput {
				channel_id: self.channel_id,
				serial_id,
				prevtx,
				prevtx_out: input.previous_output.vout,
				sequence: input.sequence.to_consensus_u32(),
				shared_input_txid: None,
			};
			do_state_transition!(self, sent_tx_add_input, &msg)?;
			Ok(InteractiveTxMessageSend::TxAddInput(msg))
		} else if let Some((serial_id, output)) = self.outputs_to_contribute.pop() {
			let msg = msgs::TxAddOutput {
				channel_id: self.channel_id,
				serial_id,
				sats: output.tx_out().value.to_sat(),
				script: output.tx_out().script_pubkey.clone(),
			};
			do_state_transition!(self, sent_tx_add_output, &msg)?;
			Ok(InteractiveTxMessageSend::TxAddOutput(msg))
		} else {
			let msg = msgs::TxComplete { channel_id: self.channel_id };
			do_state_transition!(self, sent_tx_complete, &msg)?;
			Ok(InteractiveTxMessageSend::TxComplete(msg))
		}
	}

	pub fn handle_tx_add_input(
		&mut self, msg: &msgs::TxAddInput,
	) -> Result<InteractiveTxMessageSend, AbortReason> {
		do_state_transition!(self, received_tx_add_input, msg)?;
		self.maybe_send_message()
	}

	pub fn handle_tx_remove_input(
		&mut self, msg: &msgs::TxRemoveInput,
	) -> Result<InteractiveTxMessageSend, AbortReason> {
		do_state_transition!(self, received_tx_remove_input, msg)?;
		self.maybe_send_message()
	}

	pub fn handle_tx_add_output(
		&mut self, msg: &msgs::TxAddOutput,
	) -> Result<InteractiveTxMessageSend, AbortReason> {
		do_state_transition!(self, received_tx_add_output, msg)?;
		self.maybe_send_message()
	}

	pub fn handle_tx_remove_output(
		&mut self, msg: &msgs::TxRemoveOutput,
	) -> Result<InteractiveTxMessageSend, AbortReason> {
		do_state_transition!(self, received_tx_remove_output, msg)?;
		self.maybe_send_message()
	}

	pub fn handle_tx_complete(
		&mut self, msg: &msgs::TxComplete,
	) -> Result<HandleTxCompleteValue, AbortReason> {
		do_state_transition!(self, received_tx_complete, msg)?;
		match &self.state_machine {
			StateMachine::ReceivedTxComplete(_) => {
				let msg_send = self.maybe_send_message()?;
				match &self.state_machine {
					StateMachine::NegotiationComplete(s) => {
						Ok(HandleTxCompleteValue::SendTxComplete(msg_send, s.0.clone()))
					},
					StateMachine::SentChangeMsg(_) => {
						Ok(HandleTxCompleteValue::SendTxMessage(msg_send))
					}, // We either had an input or output to contribute.
					_ => {
						debug_assert!(false, "We cannot transition to any other states after receiving `tx_complete` and responding");
						Err(AbortReason::InvalidStateTransition)
					},
				}
			},
			StateMachine::NegotiationComplete(s) => {
				Ok(HandleTxCompleteValue::NegotiationComplete(s.0.clone()))
			},
			_ => {
				debug_assert!(
					false,
					"We cannot transition to any other states after receiving `tx_complete`"
				);
				Err(AbortReason::InvalidStateTransition)
			},
		}
	}
}

#[cfg(test)]
mod tests {
	use crate::chain::chaininterface::{fee_for_weight, FEERATE_FLOOR_SATS_PER_KW};
	use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
	use crate::ln::interactivetxs::{
		generate_holder_serial_id, AbortReason, HandleTxCompleteValue, InteractiveTxConstructor,
		InteractiveTxConstructorArgs, InteractiveTxMessageSend, MAX_INPUTS_OUTPUTS_COUNT,
		MAX_RECEIVED_TX_ADD_INPUT_COUNT, MAX_RECEIVED_TX_ADD_OUTPUT_COUNT,
	};
	use crate::ln::types::ChannelId;
	use crate::sign::EntropySource;
	use crate::util::atomic_counter::AtomicCounter;
	use crate::util::ser::TransactionU16LenLimited;
	use bitcoin::absolute::LockTime as AbsoluteLockTime;
	use bitcoin::amount::Amount;
	use bitcoin::hashes::Hash;
	use bitcoin::key::UntweakedPublicKey;
	use bitcoin::opcodes;
	use bitcoin::script::Builder;
	use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, SecretKey};
	use bitcoin::transaction::Version;
	use bitcoin::{
		OutPoint, PubkeyHash, ScriptBuf, Sequence, Transaction, TxIn, TxOut, WPubkeyHash,
	};
	use core::ops::Deref;

	use super::{
		get_output_weight, AddingRole, OutputOwned, SharedOwnedOutput,
		P2TR_INPUT_WEIGHT_LOWER_BOUND, P2WPKH_INPUT_WEIGHT_LOWER_BOUND,
		P2WSH_INPUT_WEIGHT_LOWER_BOUND, TX_COMMON_FIELDS_WEIGHT,
	};

	const TEST_FEERATE_SATS_PER_KW: u32 = FEERATE_FLOOR_SATS_PER_KW * 10;

	// A simple entropy source that works based on an atomic counter.
	struct TestEntropySource(AtomicCounter);
	impl EntropySource for TestEntropySource {
		fn get_secure_random_bytes(&self) -> [u8; 32] {
			let mut res = [0u8; 32];
			let increment = self.0.next();
			for (i, byte) in res.iter_mut().enumerate() {
				// Rotate the increment value by 'i' bits to the right, to avoid clashes
				// when `generate_local_serial_id` does a parity flip on consecutive calls for the
				// same party.
				let rotated_increment = increment.rotate_right(i as u32);
				*byte = (rotated_increment & 0xff) as u8;
			}
			res
		}
	}

	// An entropy source that deliberately returns you the same seed every time. We use this
	// to test if the constructor would catch inputs/outputs that are attempting to be added
	// with duplicate serial ids.
	struct DuplicateEntropySource;
	impl EntropySource for DuplicateEntropySource {
		fn get_secure_random_bytes(&self) -> [u8; 32] {
			let mut res = [0u8; 32];
			let count = 1u64;
			res[0..8].copy_from_slice(&count.to_be_bytes());
			res
		}
	}

	#[derive(Debug, PartialEq, Eq)]
	enum ErrorCulprit {
		NodeA,
		NodeB,
		// Some error values are only checked at the end of the negotiation and are not easy to attribute
		// to a particular party. Both parties would indicate an `AbortReason` in this case.
		// e.g. Exceeded max inputs and outputs after negotiation.
		Indeterminate,
	}

	struct TestSession {
		description: &'static str,
		inputs_a: Vec<(TxIn, TransactionU16LenLimited)>,
		outputs_a: Vec<OutputOwned>,
		inputs_b: Vec<(TxIn, TransactionU16LenLimited)>,
		outputs_b: Vec<OutputOwned>,
		expect_error: Option<(AbortReason, ErrorCulprit)>,
		/// A node adds no shared output, but expects the peer to add one, with the specific script pubkey, and local contribution
		a_expected_remote_shared_output: Option<(ScriptBuf, u64)>,
		/// B node adds no shared output, but expects the peer to add one, with the specific script pubkey, and local contribution
		b_expected_remote_shared_output: Option<(ScriptBuf, u64)>,
	}

	fn do_test_interactive_tx_constructor(session: TestSession) {
		let entropy_source = TestEntropySource(AtomicCounter::new());
		do_test_interactive_tx_constructor_internal(session, &&entropy_source);
	}

	fn do_test_interactive_tx_constructor_with_entropy_source<ES: Deref>(
		session: TestSession, entropy_source: ES,
	) where
		ES::Target: EntropySource,
	{
		do_test_interactive_tx_constructor_internal(session, &entropy_source);
	}

	fn do_test_interactive_tx_constructor_internal<ES: Deref>(
		session: TestSession, entropy_source: &ES,
	) where
		ES::Target: EntropySource,
	{
		let channel_id = ChannelId(entropy_source.get_secure_random_bytes());
		let funding_tx_locktime = AbsoluteLockTime::from_height(1337).unwrap();
		let holder_node_id = PublicKey::from_secret_key(
			&Secp256k1::signing_only(),
			&SecretKey::from_slice(&[42; 32]).unwrap(),
		);
		let counterparty_node_id = PublicKey::from_secret_key(
			&Secp256k1::signing_only(),
			&SecretKey::from_slice(&[43; 32]).unwrap(),
		);

		// funding output sanity check
		let shared_outputs_by_a: Vec<_> =
			session.outputs_a.iter().filter(|o| o.is_shared()).collect();
		if shared_outputs_by_a.len() > 1 {
			println!("Test warning: Expected at most one shared output. NodeA");
		}
		let shared_output_by_a = if !shared_outputs_by_a.is_empty() {
			Some(shared_outputs_by_a[0].value())
		} else {
			None
		};
		let shared_outputs_by_b: Vec<_> =
			session.outputs_b.iter().filter(|o| o.is_shared()).collect();
		if shared_outputs_by_b.len() > 1 {
			println!("Test warning: Expected at most one shared output. NodeB");
		}
		let shared_output_by_b = if !shared_outputs_by_b.is_empty() {
			Some(shared_outputs_by_b[0].value())
		} else {
			None
		};
		if session.a_expected_remote_shared_output.is_some()
			|| session.b_expected_remote_shared_output.is_some()
		{
			let expected_by_a = if let Some(a_expected_remote_shared_output) =
				&session.a_expected_remote_shared_output
			{
				a_expected_remote_shared_output.1
			} else if !shared_outputs_by_a.is_empty() {
				shared_outputs_by_a[0].local_value(AddingRole::Local)
			} else {
				0
			};
			let expected_by_b = if let Some(b_expected_remote_shared_output) =
				&session.b_expected_remote_shared_output
			{
				b_expected_remote_shared_output.1
			} else if !shared_outputs_by_b.is_empty() {
				shared_outputs_by_b[0].local_value(AddingRole::Local)
			} else {
				0
			};

			let expected_sum = expected_by_a + expected_by_b;
			let actual_shared_output =
				shared_output_by_a.unwrap_or(shared_output_by_b.unwrap_or(0));
			if expected_sum != actual_shared_output {
				println!("Test warning: Sum of expected shared output values does not match actual shared output value, {} {}   {} {}   {} {}", expected_sum, actual_shared_output, expected_by_a, expected_by_b, shared_output_by_a.unwrap_or(0), shared_output_by_b.unwrap_or(0));
			}
		}

		let mut constructor_a = match InteractiveTxConstructor::new(InteractiveTxConstructorArgs {
			entropy_source,
			channel_id,
			feerate_sat_per_kw: TEST_FEERATE_SATS_PER_KW,
			holder_node_id,
			counterparty_node_id,
			is_initiator: true,
			funding_tx_locktime,
			inputs_to_contribute: session.inputs_a,
			outputs_to_contribute: session.outputs_a.to_vec(),
			expected_remote_shared_funding_output: session.a_expected_remote_shared_output,
		}) {
			Ok(r) => r,
			Err(abort_reason) => {
				assert_eq!(
					Some((abort_reason, ErrorCulprit::NodeA)),
					session.expect_error,
					"Test: {}",
					session.description
				);
				return;
			},
		};
		let mut constructor_b = match InteractiveTxConstructor::new(InteractiveTxConstructorArgs {
			entropy_source,
			holder_node_id,
			counterparty_node_id,
			channel_id,
			feerate_sat_per_kw: TEST_FEERATE_SATS_PER_KW,
			is_initiator: false,
			funding_tx_locktime,
			inputs_to_contribute: session.inputs_b,
			outputs_to_contribute: session.outputs_b.to_vec(),
			expected_remote_shared_funding_output: session.b_expected_remote_shared_output,
		}) {
			Ok(r) => r,
			Err(abort_reason) => {
				assert_eq!(
					Some((abort_reason, ErrorCulprit::NodeB)),
					session.expect_error,
					"Test: {}",
					session.description
				);
				return;
			},
		};

		let handle_message_send =
			|msg: InteractiveTxMessageSend, for_constructor: &mut InteractiveTxConstructor| {
				match msg {
					InteractiveTxMessageSend::TxAddInput(msg) => for_constructor
						.handle_tx_add_input(&msg)
						.map(|msg_send| (Some(msg_send), None)),
					InteractiveTxMessageSend::TxAddOutput(msg) => for_constructor
						.handle_tx_add_output(&msg)
						.map(|msg_send| (Some(msg_send), None)),
					InteractiveTxMessageSend::TxComplete(msg) => {
						for_constructor.handle_tx_complete(&msg).map(|value| match value {
							HandleTxCompleteValue::SendTxMessage(msg_send) => {
								(Some(msg_send), None)
							},
							HandleTxCompleteValue::SendTxComplete(msg_send, tx) => {
								(Some(msg_send), Some(tx))
							},
							HandleTxCompleteValue::NegotiationComplete(tx) => (None, Some(tx)),
						})
					},
				}
			};

		let mut message_send_a = constructor_a.take_initiator_first_message();
		let mut message_send_b = None;
		let mut final_tx_a = None;
		let mut final_tx_b = None;
		while final_tx_a.is_none() || final_tx_b.is_none() {
			if let Some(message_send_a) = message_send_a.take() {
				match handle_message_send(message_send_a, &mut constructor_b) {
					Ok((msg_send, interactive_signing_session)) => {
						message_send_b = msg_send;
						final_tx_b = interactive_signing_session
							.map(|session| session.unsigned_tx.compute_txid());
					},
					Err(abort_reason) => {
						let error_culprit = match abort_reason {
							AbortReason::ExceededNumberOfInputsOrOutputs => {
								ErrorCulprit::Indeterminate
							},
							_ => ErrorCulprit::NodeA,
						};
						assert_eq!(
							Some((abort_reason, error_culprit)),
							session.expect_error,
							"Test: {}",
							session.description
						);
						assert!(message_send_b.is_none(), "Test: {}", session.description);
						return;
					},
				}
			}
			if let Some(message_send_b) = message_send_b.take() {
				match handle_message_send(message_send_b, &mut constructor_a) {
					Ok((msg_send, interactive_signing_session)) => {
						message_send_a = msg_send;
						final_tx_a = interactive_signing_session
							.map(|session| session.unsigned_tx.compute_txid());
					},
					Err(abort_reason) => {
						let error_culprit = match abort_reason {
							AbortReason::ExceededNumberOfInputsOrOutputs => {
								ErrorCulprit::Indeterminate
							},
							_ => ErrorCulprit::NodeB,
						};
						assert_eq!(
							Some((abort_reason, error_culprit)),
							session.expect_error,
							"Test: {}",
							session.description
						);
						assert!(message_send_a.is_none(), "Test: {}", session.description);
						return;
					},
				}
			}
		}
		assert!(message_send_a.is_none());
		assert!(message_send_b.is_none());
		assert_eq!(final_tx_a.unwrap(), final_tx_b.unwrap());
		assert!(
			session.expect_error.is_none(),
			"Missing expected error {:?}, Test: {}",
			session.expect_error,
			session.description,
		);
	}

	#[derive(Debug, Clone, Copy)]
	enum TestOutput {
		P2WPKH(u64),
		/// P2WSH, but with the specific script used for the funding output
		P2WSH(u64),
		P2TR(u64),
		// Non-witness type to test rejection.
		P2PKH(u64),
	}

	fn generate_tx(outputs: &[TestOutput]) -> Transaction {
		generate_tx_with_locktime(outputs, 1337)
	}

	fn generate_txout(output: &TestOutput) -> TxOut {
		let secp_ctx = Secp256k1::new();
		let (value, script_pubkey) = match output {
			TestOutput::P2WPKH(value) => (*value, generate_p2wpkh_script_pubkey()),
			TestOutput::P2WSH(value) => (*value, generate_funding_script_pubkey()),
			TestOutput::P2TR(value) => (
				*value,
				ScriptBuf::new_p2tr(
					&secp_ctx,
					UntweakedPublicKey::from_keypair(
						&Keypair::from_seckey_slice(&secp_ctx, &[3; 32]).unwrap(),
					)
					.0,
					None,
				),
			),
			TestOutput::P2PKH(value) => {
				(*value, ScriptBuf::new_p2pkh(&PubkeyHash::from_slice(&[4; 20]).unwrap()))
			},
		};

		TxOut { value: Amount::from_sat(value), script_pubkey }
	}

	fn generate_tx_with_locktime(outputs: &[TestOutput], locktime: u32) -> Transaction {
		Transaction {
			version: Version::TWO,
			lock_time: AbsoluteLockTime::from_height(locktime).unwrap(),
			input: vec![TxIn { ..Default::default() }],
			output: outputs.iter().map(generate_txout).collect(),
		}
	}

	fn generate_inputs(outputs: &[TestOutput]) -> Vec<(TxIn, TransactionU16LenLimited)> {
		let tx = generate_tx(outputs);
		let txid = tx.compute_txid();
		tx.output
			.iter()
			.enumerate()
			.map(|(idx, _)| {
				let input = TxIn {
					previous_output: OutPoint { txid, vout: idx as u32 },
					script_sig: Default::default(),
					sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
					witness: Default::default(),
				};
				(input, TransactionU16LenLimited::new(tx.clone()).unwrap())
			})
			.collect()
	}

	fn generate_p2wsh_script_pubkey() -> ScriptBuf {
		Builder::new().push_opcode(opcodes::OP_TRUE).into_script().to_p2wsh()
	}

	fn generate_p2wpkh_script_pubkey() -> ScriptBuf {
		ScriptBuf::new_p2wpkh(&WPubkeyHash::from_slice(&[1; 20]).unwrap())
	}

	fn generate_funding_script_pubkey() -> ScriptBuf {
		Builder::new().push_int(33).into_script().to_p2wsh()
	}

	fn generate_output_nonfunding_one(output: &TestOutput) -> OutputOwned {
		OutputOwned::Single(generate_txout(output))
	}

	fn generate_outputs(outputs: &[TestOutput]) -> Vec<OutputOwned> {
		outputs.iter().map(generate_output_nonfunding_one).collect()
	}

	/// Generate a single output that is the funding output
	fn generate_output(output: &TestOutput) -> Vec<OutputOwned> {
		vec![OutputOwned::SharedControlFullyOwned(generate_txout(output))]
	}

	/// Generate a single P2WSH output that is the funding output
	fn generate_funding_output(value: u64) -> Vec<OutputOwned> {
		generate_output(&TestOutput::P2WSH(value))
	}

	/// Generate a single P2WSH output with shared contribution that is the funding output
	fn generate_shared_funding_output_one(value: u64, local_value: u64) -> OutputOwned {
		OutputOwned::Shared(SharedOwnedOutput {
			tx_out: generate_txout(&TestOutput::P2WSH(value)),
			local_owned: local_value,
		})
	}

	/// Generate a single P2WSH output with shared contribution that is the funding output
	fn generate_shared_funding_output(value: u64, local_value: u64) -> Vec<OutputOwned> {
		vec![generate_shared_funding_output_one(value, local_value)]
	}

	fn generate_fixed_number_of_inputs(count: u16) -> Vec<(TxIn, TransactionU16LenLimited)> {
		// Generate transactions with a total `count` number of outputs such that no transaction has a
		// serialized length greater than u16::MAX.
		let max_outputs_per_prevtx = 1_500;
		let mut remaining = count;
		let mut inputs: Vec<(TxIn, TransactionU16LenLimited)> = Vec::with_capacity(count as usize);

		while remaining > 0 {
			let tx_output_count = remaining.min(max_outputs_per_prevtx);
			remaining -= tx_output_count;

			// Use unique locktime for each tx so outpoints are different across transactions
			let tx = generate_tx_with_locktime(
				&vec![TestOutput::P2WPKH(1_000_000); tx_output_count as usize],
				(1337 + remaining).into(),
			);
			let txid = tx.compute_txid();

			let mut temp: Vec<(TxIn, TransactionU16LenLimited)> = tx
				.output
				.iter()
				.enumerate()
				.map(|(idx, _)| {
					let input = TxIn {
						previous_output: OutPoint { txid, vout: idx as u32 },
						script_sig: Default::default(),
						sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
						witness: Default::default(),
					};
					(input, TransactionU16LenLimited::new(tx.clone()).unwrap())
				})
				.collect();

			inputs.append(&mut temp);
		}

		inputs
	}

	fn generate_fixed_number_of_outputs(count: u16) -> Vec<OutputOwned> {
		// Set a constant value for each TxOut
		generate_outputs(&vec![TestOutput::P2WPKH(1_000_000); count as usize])
	}

	fn generate_p2sh_script_pubkey() -> ScriptBuf {
		Builder::new().push_opcode(opcodes::OP_TRUE).into_script().to_p2sh()
	}

	fn generate_non_witness_output(value: u64) -> OutputOwned {
		OutputOwned::Single(TxOut {
			value: Amount::from_sat(value),
			script_pubkey: generate_p2sh_script_pubkey(),
		})
	}

	#[test]
	fn test_interactive_tx_constructor() {
		do_test_interactive_tx_constructor(TestSession {
			description: "No contributions",
			inputs_a: vec![],
			outputs_a: vec![],
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::MissingFundingOutput, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: None,
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution, no initiator inputs",
			inputs_a: vec![],
			outputs_a: generate_output(&TestOutput::P2WPKH(1_000_000)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::OutputsValueExceedsInputsValue, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution, no initiator outputs",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(1_000_000)]),
			outputs_a: vec![],
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::MissingFundingOutput, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: None,
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution, no fees",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(1_000_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(1_000_000)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		let p2wpkh_fee = fee_for_weight(TEST_FEERATE_SATS_PER_KW, P2WPKH_INPUT_WEIGHT_LOWER_BOUND);
		let outputs_fee = fee_for_weight(
			TEST_FEERATE_SATS_PER_KW,
			get_output_weight(&generate_p2wpkh_script_pubkey()).to_wu(),
		);
		let tx_common_fields_fee =
			fee_for_weight(TEST_FEERATE_SATS_PER_KW, TX_COMMON_FIELDS_WEIGHT);

		let amount_adjusted_with_p2wpkh_fee =
			1_000_000 - p2wpkh_fee - outputs_fee - tx_common_fields_fee;
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution, with P2WPKH input, insufficient fees",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(1_000_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(
				amount_adjusted_with_p2wpkh_fee + 1, /* makes fees insuffcient for initiator */
			)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution with P2WPKH input, sufficient fees",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(1_000_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(amount_adjusted_with_p2wpkh_fee)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: None,
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		let p2wsh_fee = fee_for_weight(TEST_FEERATE_SATS_PER_KW, P2WSH_INPUT_WEIGHT_LOWER_BOUND);
		let amount_adjusted_with_p2wsh_fee =
			1_000_000 - p2wsh_fee - outputs_fee - tx_common_fields_fee;
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution, with P2WSH input, insufficient fees",
			inputs_a: generate_inputs(&[TestOutput::P2WSH(1_000_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(
				amount_adjusted_with_p2wsh_fee + 1, /* makes fees insuffcient for initiator */
			)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution with P2WSH input, sufficient fees",
			inputs_a: generate_inputs(&[TestOutput::P2WSH(1_000_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(amount_adjusted_with_p2wsh_fee)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: None,
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		let p2tr_fee = fee_for_weight(TEST_FEERATE_SATS_PER_KW, P2TR_INPUT_WEIGHT_LOWER_BOUND);
		let amount_adjusted_with_p2tr_fee =
			1_000_000 - p2tr_fee - outputs_fee - tx_common_fields_fee;
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution, with P2TR input, insufficient fees",
			inputs_a: generate_inputs(&[TestOutput::P2TR(1_000_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(
				amount_adjusted_with_p2tr_fee + 1, /* makes fees insuffcient for initiator */
			)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Single contribution with P2TR input, sufficient fees",
			inputs_a: generate_inputs(&[TestOutput::P2TR(1_000_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(amount_adjusted_with_p2tr_fee)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: None,
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Initiator contributes sufficient fees, but non-initiator does not",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(1_000_000)]),
			outputs_a: vec![],
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(100_000)]),
			outputs_b: generate_output(&TestOutput::P2WPKH(100_000)),
			expect_error: Some((AbortReason::InsufficientFees, ErrorCulprit::NodeB)),
			a_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
			b_expected_remote_shared_output: None,
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Multi-input-output contributions from both sides",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(1_000_000); 2]),
			outputs_a: vec![
				generate_shared_funding_output_one(1_000_000, 200_000),
				generate_output_nonfunding_one(&TestOutput::P2WPKH(200_000)),
			],
			inputs_b: generate_inputs(&[
				TestOutput::P2WPKH(1_000_000),
				TestOutput::P2WPKH(500_000),
			]),
			outputs_b: vec![generate_output_nonfunding_one(&TestOutput::P2WPKH(400_000))],
			expect_error: None,
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 800_000)),
		});

		do_test_interactive_tx_constructor(TestSession {
			description: "Prevout from initiator is not a witness program",
			inputs_a: generate_inputs(&[TestOutput::P2PKH(1_000_000)]),
			outputs_a: vec![],
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});

		let tx =
			TransactionU16LenLimited::new(generate_tx(&[TestOutput::P2WPKH(1_000_000)])).unwrap();
		let invalid_sequence_input = TxIn {
			previous_output: OutPoint { txid: tx.as_transaction().compute_txid(), vout: 0 },
			..Default::default()
		};
		do_test_interactive_tx_constructor(TestSession {
			description: "Invalid input sequence from initiator",
			inputs_a: vec![(invalid_sequence_input, tx.clone())],
			outputs_a: generate_output(&TestOutput::P2WPKH(1_000_000)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::IncorrectInputSequenceValue, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		let duplicate_input = TxIn {
			previous_output: OutPoint { txid: tx.as_transaction().compute_txid(), vout: 0 },
			sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
			..Default::default()
		};
		do_test_interactive_tx_constructor(TestSession {
			description: "Duplicate prevout from initiator",
			inputs_a: vec![(duplicate_input.clone(), tx.clone()), (duplicate_input, tx.clone())],
			outputs_a: generate_output(&TestOutput::P2WPKH(1_000_000)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeB)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		// Non-initiator uses same prevout as initiator.
		let duplicate_input = TxIn {
			previous_output: OutPoint { txid: tx.as_transaction().compute_txid(), vout: 0 },
			sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
			..Default::default()
		};
		do_test_interactive_tx_constructor(TestSession {
			description: "Non-initiator uses same prevout as initiator",
			inputs_a: vec![(duplicate_input.clone(), tx.clone())],
			outputs_a: generate_shared_funding_output(1_000_000, 905_000),
			inputs_b: vec![(duplicate_input.clone(), tx.clone())],
			outputs_b: vec![],
			expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 95_000)),
		});
		let duplicate_input = TxIn {
			previous_output: OutPoint { txid: tx.as_transaction().compute_txid(), vout: 0 },
			sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
			..Default::default()
		};
		do_test_interactive_tx_constructor(TestSession {
			description: "Non-initiator uses same prevout as initiator",
			inputs_a: vec![(duplicate_input.clone(), tx.clone())],
			outputs_a: generate_output(&TestOutput::P2WPKH(1_000_000)),
			inputs_b: vec![(duplicate_input.clone(), tx.clone())],
			outputs_b: vec![],
			expect_error: Some((AbortReason::PrevTxOutInvalid, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_p2wpkh_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Initiator sends too many TxAddInputs",
			inputs_a: generate_fixed_number_of_inputs(MAX_RECEIVED_TX_ADD_INPUT_COUNT + 1),
			outputs_a: vec![],
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::ReceivedTooManyTxAddInputs, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor_with_entropy_source(
			TestSession {
				// We use a deliberately bad entropy source, `DuplicateEntropySource` to simulate this.
				description: "Attempt to queue up two inputs with duplicate serial ids",
				inputs_a: generate_fixed_number_of_inputs(2),
				outputs_a: vec![],
				inputs_b: vec![],
				outputs_b: vec![],
				expect_error: Some((AbortReason::DuplicateSerialId, ErrorCulprit::NodeA)),
				a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
				b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			},
			&DuplicateEntropySource,
		);
		do_test_interactive_tx_constructor(TestSession {
			description: "Initiator sends too many TxAddOutputs",
			inputs_a: vec![],
			outputs_a: generate_fixed_number_of_outputs(MAX_RECEIVED_TX_ADD_OUTPUT_COUNT + 1),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::ReceivedTooManyTxAddOutputs, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Initiator sends an output below dust value",
			inputs_a: vec![],
			outputs_a: generate_funding_output(
				generate_p2wsh_script_pubkey().minimal_non_dust().to_sat() - 1,
			),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::BelowDustLimit, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Initiator sends an output above maximum sats allowed",
			inputs_a: vec![],
			outputs_a: generate_output(&TestOutput::P2WPKH(TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::ExceededMaximumSatsAllowed, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Initiator sends an output without a witness program",
			inputs_a: vec![],
			outputs_a: vec![generate_non_witness_output(1_000_000)],
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::InvalidOutputScript, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor_with_entropy_source(
			TestSession {
				// We use a deliberately bad entropy source, `DuplicateEntropySource` to simulate this.
				description: "Attempt to queue up two outputs with duplicate serial ids",
				inputs_a: vec![],
				outputs_a: generate_fixed_number_of_outputs(2),
				inputs_b: vec![],
				outputs_b: vec![],
				expect_error: Some((AbortReason::DuplicateSerialId, ErrorCulprit::NodeA)),
				a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
				b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			},
			&DuplicateEntropySource,
		);

		do_test_interactive_tx_constructor(TestSession {
			description: "Peer contributed more output value than inputs",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(100_000)]),
			outputs_a: generate_output(&TestOutput::P2WPKH(1_000_000)),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((AbortReason::OutputsValueExceedsInputsValue, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});

		do_test_interactive_tx_constructor(TestSession {
			description: "Peer contributed more than allowed number of inputs",
			inputs_a: generate_fixed_number_of_inputs(MAX_INPUTS_OUTPUTS_COUNT as u16 + 1),
			outputs_a: vec![],
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((
				AbortReason::ExceededNumberOfInputsOrOutputs,
				ErrorCulprit::Indeterminate,
			)),
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});
		do_test_interactive_tx_constructor(TestSession {
			description: "Peer contributed more than allowed number of outputs",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(TOTAL_BITCOIN_SUPPLY_SATOSHIS)]),
			outputs_a: generate_fixed_number_of_outputs(MAX_INPUTS_OUTPUTS_COUNT as u16 + 1),
			inputs_b: vec![],
			outputs_b: vec![],
			expect_error: Some((
				AbortReason::ExceededNumberOfInputsOrOutputs,
				ErrorCulprit::Indeterminate,
			)),
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});

		// Adding multiple outputs to the funding output pubkey is an error
		do_test_interactive_tx_constructor(TestSession {
			description: "Adding two outputs to the funding output pubkey",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(1_000_000)]),
			outputs_a: generate_funding_output(100_000),
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(1_001_000)]),
			outputs_b: generate_funding_output(100_000),
			expect_error: Some((AbortReason::DuplicateFundingOutput, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: None,
		});

		// We add the funding output, but we contribute a little
		do_test_interactive_tx_constructor(TestSession {
			description: "Funding output by us, small contribution",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(12_000)]),
			outputs_a: generate_shared_funding_output(1_000_000, 10_000),
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(992_000)]),
			outputs_b: vec![],
			expect_error: None,
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 990_000)),
		});

		// They add the funding output, and we contribute a little
		do_test_interactive_tx_constructor(TestSession {
			description: "Funding output by them, small contribution",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(12_000)]),
			outputs_a: vec![],
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(992_000)]),
			outputs_b: generate_shared_funding_output(1_000_000, 990_000),
			expect_error: None,
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 10_000)),
			b_expected_remote_shared_output: None,
		});

		// We add the funding output, and we contribute most
		do_test_interactive_tx_constructor(TestSession {
			description: "Funding output by us, large contribution",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(992_000)]),
			outputs_a: generate_shared_funding_output(1_000_000, 990_000),
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(12_000)]),
			outputs_b: vec![],
			expect_error: None,
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 10_000)),
		});

		// They add the funding output, but we contribute most
		do_test_interactive_tx_constructor(TestSession {
			description: "Funding output by them, large contribution",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(992_000)]),
			outputs_a: vec![],
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(12_000)]),
			outputs_b: generate_shared_funding_output(1_000_000, 10_000),
			expect_error: None,
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 990_000)),
			b_expected_remote_shared_output: None,
		});

		// During a splice-out, with peer providing more output value than input value
		// but still pays enough fees due to their to_remote_value_satoshis portion in
		// the shared input.
		do_test_interactive_tx_constructor(TestSession {
			description: "Splice out with sufficient initiator balance",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(100_000), TestOutput::P2WPKH(50_000)]),
			outputs_a: generate_funding_output(120_000),
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(50_000)]),
			outputs_b: vec![],
			expect_error: None,
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});

		// During a splice-out, with peer providing more output value than input value
		// and the to_remote_value_satoshis portion in
		// the shared input cannot cover fees
		do_test_interactive_tx_constructor(TestSession {
			description: "Splice out with insufficient initiator balance",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(100_000), TestOutput::P2WPKH(15_000)]),
			outputs_a: generate_funding_output(120_000),
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(85_000)]),
			outputs_b: vec![],
			expect_error: Some((AbortReason::OutputsValueExceedsInputsValue, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 0)),
		});

		// The actual funding output value is lower than the intended local contribution by the same node
		do_test_interactive_tx_constructor(TestSession {
			description: "Splice in, invalid intended local contribution",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(100_000), TestOutput::P2WPKH(15_000)]),
			outputs_a: generate_shared_funding_output(100_000, 120_000), // local value is higher than the output value
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(85_000)]),
			outputs_b: vec![],
			expect_error: Some((AbortReason::InvalidLowFundingOutputValue, ErrorCulprit::NodeA)),
			a_expected_remote_shared_output: None,
			b_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 20_000)),
		});

		// The actual funding output value is lower than the intended local contribution of the other node
		do_test_interactive_tx_constructor(TestSession {
			description: "Splice in, invalid intended local contribution",
			inputs_a: generate_inputs(&[TestOutput::P2WPKH(100_000), TestOutput::P2WPKH(15_000)]),
			outputs_a: vec![],
			inputs_b: generate_inputs(&[TestOutput::P2WPKH(85_000)]),
			outputs_b: generate_funding_output(100_000),
			// The error is caused by NodeA, it occurs when nodeA prepares the message to be sent to NodeB, that's why here it shows up as NodeB
			expect_error: Some((AbortReason::InvalidLowFundingOutputValue, ErrorCulprit::NodeB)),
			a_expected_remote_shared_output: Some((generate_funding_script_pubkey(), 120_000)), // this is higher than the actual output value
			b_expected_remote_shared_output: None,
		});
	}

	#[test]
	fn test_generate_local_serial_id() {
		let entropy_source = TestEntropySource(AtomicCounter::new());

		// Initiators should have even serial id, non-initiators should have odd serial id.
		assert_eq!(generate_holder_serial_id(&&entropy_source, true) % 2, 0);
		assert_eq!(generate_holder_serial_id(&&entropy_source, false) % 2, 1)
	}
}