sidestr-core 0.3.3

sidestr user-activated sidechains beside a Bitcoin-family parent: the chain document, the parents table, signed blocks generic over the header family (BIP-325 challenge, no subsidy), the peg-in claim and peg-out burn rules, Knots' unified sighash, the block file and an in-memory validating chain. A port of siding by Melvin Carvalho.
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
//! The parent chain as a producer or a signer sees it (SPEC 6, 7, 11; the
//! level-2 view): peg-ins found in the parent's blocks, whether one is still
//! unspent and how deep, the peg wallet's payment of a burn, the producer's
//! checkpoint, and the reconciliation of burns against what the wallet has
//! already paid. A port of `siding/lib/parent.mjs` and
//! `siding/lib/checkpoint.mjs` (Melvin Carvalho, AGPL-3.0).
//!
//! The node is behind two traits — [`ParentRpc`] for the chain (read-only)
//! and [`PegWallet`] for the peg wallet's own RPCs — and everything that
//! decides is a pure function of what they return: [`find_pegin`] over a
//! decoded transaction and the peg holders' ownership of its outputs, [`claimable`] over found peg-ins and the chain's
//! records, [`pegout_payment`] and [`checkpoint_payment`] as the outputs a
//! `send` call takes, [`reconcile`] over the chain's burns and the wallet's
//! history. One blocking JSON-RPC implementation, Bitcoin Core's, is behind
//! the `rpc` feature (`parent::rpc::CoreRpc`); a test doubles the traits in memory.
//!
//! Blocks come back as decoded transactions (`getblock` verbosity 2, each
//! transaction's `hex`), never as a raw block: a BLAKE2b parent's blocks have
//! 164-byte headers that the parent's serialisation library does not read,
//! and the transaction format is the same on every family.
//!
//! ```
//! use bitcoin::hashes::Hash;
//! use sidestr_core::marker::Burn;
//! use sidestr_core::parent::{checkpoint_payment, pegout_payment, reconcile, SendOutput};
//! use sidestr_core::parents::resolve_parent;
//!
//! // SPEC 7: the peg holders pay a burn on the parent — the value to the script the burn named,
//! // and `pegout:<chain id>:<sidechain txid>` so a validator with a parent view pairs the two
//! let burn = Burn { txid: "c".repeat(64), vout: 1, script: format!("5120{}", "e9".repeat(32)), value: 50_000, height: 133 };
//! let outs = pegout_payment("sidestr:trial", &burn, resolve_parent("tbtc4").unwrap()).unwrap();
//! assert!(matches!(&outs[0], SendOutput::Pay { address, btc } if address.starts_with("tb1p") && btc == "0.00050000"));
//! assert!(matches!(&outs[1], SendOutput::Data(d) if d.starts_with(b"pegout:sidestr:trial:")));
//!
//! // SPEC 11: a checkpoint is one data output; the wallet adds change
//! let ck = checkpoint_payment("sidestr:trial", 70_000, &bitcoin::BlockHash::all_zeros().to_string()).unwrap();
//! assert_eq!(ck.len(), 1);
//!
//! // reconciliation: a burn the wallet's history shows paid is paid, the rest are owed
//! let mut paid = std::collections::BTreeMap::new();
//! paid.insert("c".repeat(64), bitcoin::Txid::all_zeros());
//! let r = reconcile(&[burn.clone(), Burn { txid: "d".repeat(64), ..burn }], &paid);
//! assert_eq!((r.paid.len(), r.outstanding.len()), (1, 1));
//! ```

use std::collections::BTreeMap;

use bitcoin::{Address, BlockHash, Network, OutPoint, Script, ScriptBuf, Transaction, Txid};

use crate::error::{Error, Result};
use crate::marker::{
    checkpoint_data, parse_checkpoint, parse_peg_marker, parse_pegout_marker, pegout_marker_data,
    Burn,
};
use crate::parents::Parent;
use crate::state::ClaimRequest;

/// The parent's 80-byte `OP_RETURN` relay policy (`siding/lib/marker.mjs`:
/// "inside the 80-byte OP_RETURN policy limit").
pub const PARENT_DATA_LIMIT: usize = 80;

/// The rust-bitcoin network a SPEC 3.2 parent's addresses are encoded for:
/// the BLAKE2b forks share Bitcoin's address encodings with their origins.
/// `None` for a reserved parent (`ltc`, `vtc`).
pub fn parent_network(parent: &Parent) -> Option<Network> {
    match parent.alias {
        "btc" | "xbt" => Some(Network::Bitcoin),
        "tbtc4" | "txbt4" => Some(Network::Testnet4),
        _ => None,
    }
}

/// `sats` as Bitcoin Core writes an amount: `"0.00250000"`.
pub fn btc_string(sats: u64) -> String {
    format!("{}.{:08}", sats / 100_000_000, sats % 100_000_000)
}

/// A parent block as the view needs it: its height, hash, time and decoded
/// transactions (`getblock <hash> 2`, each `tx[i].hex`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParentBlock {
    /// The block's height.
    pub height: u32,
    /// Its hash.
    pub hash: BlockHash,
    /// Its header time.
    pub time: u32,
    /// Every transaction, coinbase first.
    pub txs: Vec<Transaction>,
    /// The address the node reported for each output (`getblock … 2`,
    /// `tx[i].vout[n].scriptPubKey.address`): `addresses[i][n]`, `None` where
    /// the node gave none. Empty, or of the wrong shape for a transaction,
    /// when the source reports transactions only (a test double); addresses
    /// are then derived from the scripts for the parent's network.
    pub addresses: Vec<Vec<Option<String>>>,
}

/// What `gettxout` says of an unspent output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TxOutStatus {
    /// Confirmations (0 in the mempool).
    pub confirmations: u32,
    /// Sats.
    pub value: u64,
    /// The output script.
    pub script_pubkey: ScriptBuf,
}

/// The parent chain, read-only (`parent.mjs makeParent().rpc`).
pub trait ParentRpc {
    /// `getblockcount`.
    fn block_count(&self) -> Result<u32>;
    /// `getblockhash`.
    fn block_hash(&self, height: u32) -> Result<BlockHash>;
    /// `getblock <hash> 2`, transactions decoded.
    fn block(&self, hash: &BlockHash) -> Result<ParentBlock>;
    /// `gettxout <txid> <vout> true`: `None` when spent or unknown.
    fn tx_out(&self, txid: &Txid, vout: u32) -> Result<Option<TxOutStatus>>;
    /// The block at a height.
    fn block_at(&self, height: u32) -> Result<ParentBlock> {
        self.block(&self.block_hash(height)?)
    }
}

/// One output of a Core `send`: `{address: btc}` or `{data: hex}`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SendOutput {
    /// Pay an address an amount, as Core writes it (`"0.00250000"`).
    Pay {
        /// The parent address.
        address: String,
        /// The amount, eight decimals.
        btc: String,
    },
    /// An `OP_RETURN` carrying these bytes.
    Data(Vec<u8>),
}

/// Where a wallet transaction sits (`gettransaction`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WalletTxStatus {
    /// Confirmations, 0 when unconfirmed.
    pub confirmations: u32,
    /// The parent block's height, when confirmed.
    pub block_height: Option<u32>,
    /// The parent block's hash, when confirmed.
    pub block_hash: Option<BlockHash>,
    /// The parent block's time, when confirmed.
    pub time: Option<u32>,
}

/// The peg wallet's own RPCs at `/wallet/<name>` (`parent.mjs
/// makeParent().walletRpc`). Without a wallet the parent is read-only.
pub trait PegWallet {
    /// `lockunspent`: keep (or release) these outputs out of the wallet's
    /// own payments; returns how many the node accepted.
    fn lock_outputs(&self, outpoints: &[OutPoint], lock: bool) -> Result<usize>;
    /// `send [outputs, null, "unset", 1]`: the wallet funds, signs and
    /// broadcasts; the txid comes back.
    fn send(&self, outputs: &[SendOutput]) -> Result<Txid>;
    /// Every transaction the wallet sent, decoded (`listtransactions` then
    /// `gettransaction … true true`).
    fn sent_transactions(&self) -> Result<Vec<(Txid, Transaction)>>;
    /// Where one of the wallet's transactions sits.
    fn transaction_status(&self, txid: &Txid) -> Result<WalletTxStatus>;
    /// Whether the wallet owns a parent address: its own keys, or an
    /// imported k-of-n descriptor (`parent.mjs ownedByPegWallet`,
    /// `getaddressinfo` `ismine || iswatchonly || solvable`). A failed call
    /// reads as not owned, as it does in the reference: a peg-in is never
    /// found on an error.
    fn owns_address(&self, address: &str) -> bool;
}

// --- peg-ins (SPEC 6) --------------------------------------------------------------

/// A peg-in found on the parent (`parent.mjs scanPegins`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FoundPegin {
    /// Parent txid, display order.
    pub txid: String,
    /// The peg output's index.
    pub vout: u32,
    /// Its value in sats.
    pub amount: u64,
    /// The sidechain script the marker named.
    pub script: ScriptBuf,
    /// The parent block's height.
    pub height: u32,
    /// The peg output's parent address, when the network is known.
    pub parent_address: Option<String>,
}

/// Who owns a parent output: the peg holders' view (SPEC 6, 0.0.3), asked
/// of each taproot output with its script and its parent address — the one
/// the node reported, or one derived for the parent's network — or `None`
/// when there is no address. Level 1: the producer's parent wallet
/// ([`owned_by_peg_wallet`]). Level 2: the chain's challenge
/// (`|s, _| s == challenge`), or the peg wallet that imported the k-of-n
/// descriptor, as the reference asks it.
pub type PegOwner<'a> = &'a dyn Fn(&Script, Option<&str>) -> bool;

/// The peg-in a parent transaction makes for `chain_id`, if any
/// (`parent.mjs scanPegins`, SPEC 6 as of 0.0.3). A marker naming this chain
/// gives the sidechain script; the peg output is then the first taproot
/// output `owner` says the peg holders own, **at any position** — a wallet
/// may place its change before the peg — and a marker beside nothing they
/// own is not a peg-in. With no `owner` (a read-only producer with no peg
/// wallet to ask) the first taproot output is taken, as the reference does
/// and as 0.0.1 and 0.0.2 did for every producer. Addresses are derived from
/// the scripts for `network`; [`scan_pegins`] uses the node's own instead.
/// Since SPEC 0.0.4 the signer also announces the peg script, taken first:
/// [`find_pegin_announced`].
///
/// ```
/// use bitcoin::script::PushBytesBuf;
/// use bitcoin::{absolute::LockTime, transaction::Version, Amount, Script, ScriptBuf, Transaction, TxOut};
/// use sidestr_core::marker::peg_marker_data;
/// use sidestr_core::parent::find_pegin;
///
/// let tr = |b: u8| ScriptBuf::from_hex(&format!("5120{}", format!("{b:02x}").repeat(32))).unwrap();
/// let named = tr(0xee);
/// let marker = ScriptBuf::new_op_return(PushBytesBuf::try_from(peg_marker_data("sidestr:scan", &named)).unwrap());
/// // txsign-test.mjs: the wallet's change (0xaa) comes first, the peg (0xbb) last
/// let tx = Transaction { version: Version::TWO, lock_time: LockTime::ZERO, input: vec![], output: vec![
///     TxOut { value: Amount::from_sat(20_000_000), script_pubkey: tr(0xaa) },
///     TxOut { value: Amount::ZERO, script_pubkey: marker },
///     TxOut { value: Amount::from_sat(50_000), script_pubkey: tr(0xbb) },
/// ] };
/// let peg = tr(0xbb);
/// let ours = |s: &Script, _: Option<&str>| s == peg.as_script();
/// let found = find_pegin(&tx, "sidestr:scan", 1, None, Some(&ours)).unwrap();
/// assert_eq!((found.vout, found.amount, &found.script), (2, 50_000, &named));
/// // a marker beside nothing the peg holders own is not a peg-in
/// assert!(find_pegin(&tx, "sidestr:scan", 1, None, Some(&|_: &Script, _: Option<&str>| false)).is_none());
/// // no owner to ask: the first taproot output, as before 0.0.3
/// assert_eq!(find_pegin(&tx, "sidestr:scan", 1, None, None).unwrap().vout, 0);
/// ```
pub fn find_pegin(
    tx: &Transaction,
    chain_id: &str,
    height: u32,
    network: Option<Network>,
    owner: Option<PegOwner<'_>>,
) -> Option<FoundPegin> {
    pegin_at(
        tx,
        chain_id,
        height,
        &derived_addresses(tx, network),
        None,
        owner,
    )
}

/// [`find_pegin`] as SPEC 0.0.4 reads a peg-in (`parent.mjs scanPegins`
/// with `pegScript`): a taproot output paying `announced`, the peg script
/// the signer announces with every tip, is the peg **wherever it sits**, so
/// a third party tells peg from change with the announcement alone. Only
/// when no output pays it does `owner` decide, and with no owner the first
/// taproot output, as before.
///
/// ```
/// use bitcoin::script::PushBytesBuf;
/// use bitcoin::{absolute::LockTime, transaction::Version, Amount, Script, ScriptBuf, Transaction, TxOut};
/// use sidestr_core::marker::peg_marker_data;
/// use sidestr_core::parent::find_pegin_announced;
///
/// let tr = |b: u8| ScriptBuf::from_hex(&format!("5120{}", format!("{b:02x}").repeat(32))).unwrap();
/// let named = tr(0xee);
/// let marker = ScriptBuf::new_op_return(PushBytesBuf::try_from(peg_marker_data("sidestr:scan", &named)).unwrap());
/// // the wallet's change (0xaa) first, the announced peg (0xbb) last
/// let tx = Transaction { version: Version::TWO, lock_time: LockTime::ZERO, input: vec![], output: vec![
///     TxOut { value: Amount::from_sat(20_000_000), script_pubkey: tr(0xaa) },
///     TxOut { value: Amount::ZERO, script_pubkey: marker },
///     TxOut { value: Amount::from_sat(50_000), script_pubkey: tr(0xbb) },
/// ] };
/// let announced = tr(0xbb);
/// // no wallet to ask, and still the peg, not the change
/// let found = find_pegin_announced(&tx, "sidestr:scan", 1, None, Some(&announced), None).unwrap();
/// assert_eq!((found.vout, found.amount), (2, 50_000));
/// ```
pub fn find_pegin_announced(
    tx: &Transaction,
    chain_id: &str,
    height: u32,
    network: Option<Network>,
    announced: Option<&Script>,
    owner: Option<PegOwner<'_>>,
) -> Option<FoundPegin> {
    pegin_at(
        tx,
        chain_id,
        height,
        &derived_addresses(tx, network),
        announced,
        owner,
    )
}

/// Each output's address for `network`, where it has one.
fn derived_addresses(tx: &Transaction, network: Option<Network>) -> Vec<Option<String>> {
    tx.output
        .iter()
        .map(|o| {
            network
                .and_then(|n| Address::from_script(&o.script_pubkey, n).ok())
                .map(|a| a.to_string())
        })
        .collect()
}

/// [`find_pegin`] with each output's address given (`addresses[n]`, as long
/// as the outputs): what the owner is asked and what the peg-in records.
fn pegin_at(
    tx: &Transaction,
    chain_id: &str,
    height: u32,
    addresses: &[Option<String>],
    announced: Option<&Script>,
    owner: Option<PegOwner<'_>>,
) -> Option<FoundPegin> {
    let script = tx
        .output
        .iter()
        .find_map(|o| parse_peg_marker(&o.script_pubkey, chain_id))?;
    let address = |n: usize| addresses.get(n).and_then(Option::as_deref);
    let mut taproots = tx
        .output
        .iter()
        .enumerate()
        .filter(|(_, o)| o.script_pubkey.is_p2tr());
    // SPEC 0.0.4: a taproot output paying the announced peg script first,
    // then the owner's, then (no owner to ask) the first taproot output
    let paying = announced.and_then(|a| {
        tx.output
            .iter()
            .enumerate()
            .find(|(_, o)| o.script_pubkey.is_p2tr() && o.script_pubkey.as_script() == a)
    });
    let (vout, peg) = match (paying, owner) {
        (Some(p), _) => p,
        (None, Some(owns)) => taproots.find(|(n, o)| owns(&o.script_pubkey, address(*n)))?,
        (None, None) => taproots.next()?,
    };
    Some(FoundPegin {
        txid: tx.compute_txid().to_string(),
        vout: vout as u32,
        amount: peg.value.to_sat(),
        script,
        height,
        parent_address: address(vout).map(str::to_string),
    })
}

/// The level-1 owner: the peg wallet, asked about each taproot output's
/// parent address (`parent.mjs ownedByPegWallet`: `getaddressinfo` says
/// `ismine`, `iswatchonly` or `solvable`). An output with no address is not
/// owned, as the reference skips an output the node gives no address.
pub fn owned_by_peg_wallet<W: PegWallet + ?Sized>(
    wallet: &W,
) -> impl Fn(&Script, Option<&str>) -> bool + '_ {
    move |_, address| address.is_some_and(|a| wallet.owns_address(a))
}

/// The outputs of `tx` paying `script`: `(vout, sats)`. What a wallet's
/// funding looks like from the chain's side.
pub fn find_payments(tx: &Transaction, script: &Script) -> Vec<(u32, u64)> {
    tx.output
        .iter()
        .enumerate()
        .filter(|(_, o)| o.script_pubkey.as_script() == script)
        .map(|(i, o)| (i as u32, o.value.to_sat()))
        .collect()
}

/// Peg-ins for `chain_id` in the parent's blocks `from..=to`
/// (`parent.mjs scanPegins`), each judged as [`find_pegin`] judges it with
/// `owner`, over the addresses the node reported
/// ([`ParentBlock::addresses`]) where it reported them — an output the node
/// gave no address is never owned — and addresses derived for `network`
/// otherwise; `on_block` hears each block as it is read.
pub fn scan_pegins<R: ParentRpc + ?Sized>(
    rpc: &R,
    chain_id: &str,
    from: u32,
    to: u32,
    network: Option<Network>,
    owner: Option<PegOwner<'_>>,
    on_block: impl FnMut(&ParentBlock),
) -> Result<Vec<FoundPegin>> {
    scan_pegins_announced(rpc, chain_id, from, to, network, None, owner, on_block)
}

/// [`scan_pegins`] with the peg script the signer announces
/// (`parent.mjs scanPegins` `pegScript`, SPEC 0.0.4), judged per transaction
/// as [`find_pegin_announced`] judges it.
#[allow(clippy::too_many_arguments)]
pub fn scan_pegins_announced<R: ParentRpc + ?Sized>(
    rpc: &R,
    chain_id: &str,
    from: u32,
    to: u32,
    network: Option<Network>,
    announced: Option<&Script>,
    owner: Option<PegOwner<'_>>,
    mut on_block: impl FnMut(&ParentBlock),
) -> Result<Vec<FoundPegin>> {
    let mut found = Vec::new();
    for h in from..=to {
        let block = rpc.block_at(h)?;
        on_block(&block);
        for (i, tx) in block.txs.iter().enumerate() {
            // the node's own addresses when it reported them for every output
            let reported = block
                .addresses
                .get(i)
                .filter(|a| a.len() == tx.output.len());
            let found_here = match reported {
                Some(a) => pegin_at(tx, chain_id, h, a, announced, owner),
                None => pegin_at(
                    tx,
                    chain_id,
                    h,
                    &derived_addresses(tx, network),
                    announced,
                    owner,
                ),
            };
            found.extend(found_here);
        }
    }
    Ok(found)
}

/// Still unspent on the parent, and how many confirmations
/// (`parent.mjs pegStatus`): `None` confirmations when spent or unknown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PegStatus {
    /// The output is unspent.
    pub unspent: bool,
    /// Its confirmations, when unspent.
    pub confirmations: Option<u32>,
}

/// [`PegStatus`] of an outpoint.
pub fn peg_status<R: ParentRpc + ?Sized>(rpc: &R, txid: &Txid, vout: u32) -> Result<PegStatus> {
    Ok(match rpc.tx_out(txid, vout)? {
        None => PegStatus {
            unspent: false,
            confirmations: None,
        },
        Some(o) => PegStatus {
            unspent: true,
            confirmations: Some(o.confirmations),
        },
    })
}

/// The peg-ins the producer may claim in its next block: found on the parent
/// at least `peg_confirmations` deep at `parent_tip`, and not yet claimed
/// (`siding/bin/siding.mjs produce`, the scan-and-claim loop; SPEC 6). The
/// confirmation count is `tip + 1 - height`, compared in `u64` so a parent
/// height or confirmation count at `u32::MAX` cannot overflow.
pub fn claimable(
    found: &[FoundPegin],
    parent_tip: u32,
    peg_confirmations: u32,
    claimed: impl Fn(&str, u32) -> bool,
) -> Vec<ClaimRequest> {
    found
        .iter()
        .filter(|p| u64::from(parent_tip) + 1 >= u64::from(p.height) + u64::from(peg_confirmations))
        .filter(|p| !claimed(&p.txid, p.vout))
        .map(|p| ClaimRequest {
            txid: p.txid.clone(),
            vout: p.vout,
            amount: p.amount,
            script: p.script.clone(),
        })
        .collect()
}

/// The outpoints the peg wallet must not spend: peg-ins found but not yet
/// claimed (`parent.mjs lockOutputs`: "a spent peg-in is refused as a
/// claim"). A claimed one is unlocked and joins the reserve.
pub fn outpoints_to_lock(
    found: &[FoundPegin],
    claimed: impl Fn(&str, u32) -> bool,
) -> Vec<OutPoint> {
    found
        .iter()
        .filter(|p| !claimed(&p.txid, p.vout))
        .filter_map(|p| {
            Some(OutPoint {
                txid: p.txid.parse().ok()?,
                vout: p.vout,
            })
        })
        .collect()
}

// --- peg-outs (SPEC 7): the parent side ------------------------------------------------

/// The peg wallet's payment of one burn (`parent.mjs payPegout`): the parent
/// script the burn named gets the burned value, and `OP_RETURN
/// pegout:<chain id>:<sidechain txid, 32 raw bytes>` rides along so a
/// validator with a parent view pairs each burn with its payment. The
/// address comes from the script for the parent's network (siding asks the
/// node with `decodescript`); a script with no address is refused.
pub fn pegout_payment(chain_id: &str, burn: &Burn, parent: &Parent) -> Result<Vec<SendOutput>> {
    let network = parent_network(parent).ok_or(Error::ReservedParent {
        alias: parent.alias,
        label: parent.label,
    })?;
    let script = ScriptBuf::from_hex(&burn.script).map_err(|e| Error::Encoding(e.to_string()))?;
    let address = Address::from_script(&script, network).map_err(|_| {
        Error::Parent(format!(
            "script {}… has no address on the parent",
            &burn.script[..burn.script.len().min(16)]
        ))
    })?;
    Ok(vec![
        SendOutput::Pay {
            address: address.to_string(),
            btc: btc_string(burn.value),
        },
        SendOutput::Data(pegout_marker_data(chain_id, &burn.txid)?),
    ])
}

/// Every burn the peg wallet has already paid, from the wallet's own
/// transactions (`parent.mjs paidPegouts`): sidechain txid → parent txid.
pub fn paid_pegouts_in(txs: &[(Txid, Transaction)], chain_id: &str) -> BTreeMap<String, Txid> {
    let mut paid = BTreeMap::new();
    for (parent_txid, tx) in txs {
        for o in &tx.output {
            if let Some(side) = parse_pegout_marker(&o.script_pubkey, chain_id) {
                paid.insert(side, *parent_txid);
            }
        }
    }
    paid
}

/// Burns paired with their parent payments, and burns still owed.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Reconciled {
    /// Burns the wallet's history shows paid, with the paying parent txid.
    pub paid: Vec<(Burn, Txid)>,
    /// Burns with no payment yet, oldest first.
    pub outstanding: Vec<Burn>,
}

/// Pair the chain's burns ([`crate::state::StateOf::pegouts`]) with the
/// payments the wallet has made ([`paid_pegouts_in`])
/// (`siding/bin/siding.mjs produce`, `reconcile`). Pure: what to do about
/// the outstanding ones — pay them, or hand them to a round — is the
/// caller's.
pub fn reconcile(burns: &[Burn], paid: &BTreeMap<String, Txid>) -> Reconciled {
    let mut r = Reconciled::default();
    for b in burns {
        match paid.get(&b.txid) {
            Some(t) => r.paid.push((b.clone(), *t)),
            None => r.outstanding.push(b.clone()),
        }
    }
    r.outstanding.sort_by_key(|b| b.height);
    r
}

// --- checkpoints (SPEC 11) ------------------------------------------------------------

/// The producer's checkpoint (`checkpoint.mjs sendCheckpoint`): one data
/// output, `ckpt:<chain id>:<height LE u32>:<32-byte hash>`; the wallet adds
/// change. Refused when the chain id makes it exceed 80 bytes.
pub fn checkpoint_payment(chain_id: &str, height: u32, hash: &str) -> Result<Vec<SendOutput>> {
    let data = checkpoint_data(chain_id, height, hash)?;
    if data.len() > PARENT_DATA_LIMIT {
        return Err(Error::Parent(format!(
            "checkpoint of {} bytes exceeds the 80-byte data limit; the chain id is too long",
            data.len()
        )));
    }
    Ok(vec![SendOutput::Data(data)])
}

/// The checkpoints the peg wallet has already sent, from its own
/// transactions (`checkpoint.mjs sentCheckpoints`): `(height, hash)` → parent txid.
pub fn sent_checkpoints_in(
    txs: &[(Txid, Transaction)],
    chain_id: &str,
) -> BTreeMap<(u32, String), Txid> {
    let mut out = BTreeMap::new();
    for (parent_txid, tx) in txs {
        for o in &tx.output {
            if let Some(c) = parse_checkpoint(&o.script_pubkey, chain_id) {
                out.insert(c, *parent_txid);
            }
        }
    }
    out
}

/// Bitcoin Core's JSON-RPC over HTTP, blocking, cookie-authenticated
/// (feature `rpc`).
#[cfg(feature = "rpc")]
pub mod rpc {
    use std::path::PathBuf;
    use std::sync::Mutex;

    use bitcoin::consensus::encode::deserialize;
    use bitcoin::{BlockHash, OutPoint, ScriptBuf, Transaction, Txid};
    use serde_json::{json, Value};

    use super::{ParentBlock, ParentRpc, PegWallet, SendOutput, TxOutStatus, WalletTxStatus};
    use crate::error::{Error, Result};

    /// A node's JSON-RPC endpoint with its cookie file (`parent.mjs
    /// makeParent`). The cookie is minted anew every time the node starts, so
    /// it is read again on a 401 rather than dying with it — a node upgrade on
    /// 21 September left every producer sending a stale cookie until
    /// restarted. With a `wallet`, the wallet's RPCs go to `/wallet/<name>`;
    /// without one the parent is read-only.
    #[derive(Debug)]
    pub struct CoreRpc {
        url: String,
        cookie_file: PathBuf,
        wallet: Option<String>,
        auth: Mutex<Option<String>>,
        agent: ureq::Agent,
    }

    fn base64(bytes: &[u8]) -> String {
        const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
        for chunk in bytes.chunks(3) {
            let n = chunk
                .iter()
                .enumerate()
                .fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i)));
            for i in 0..4 {
                if i <= chunk.len() {
                    out.push(T[((n >> (18 - 6 * i)) & 63) as usize] as char);
                } else {
                    out.push('=');
                }
            }
        }
        out
    }

    impl CoreRpc {
        /// A client for `url` (e.g. `http://127.0.0.1:48332/`) reading
        /// `user:password` from `cookie_file`, optionally for `wallet`.
        pub fn new(url: &str, cookie_file: impl Into<PathBuf>, wallet: Option<&str>) -> Self {
            Self {
                url: url.trim_end_matches('/').to_string(),
                cookie_file: cookie_file.into(),
                wallet: wallet.map(str::to_string),
                auth: Mutex::new(None),
                agent: ureq::Agent::new_with_config(
                    ureq::Agent::config_builder()
                        .http_status_as_error(false)
                        .build(),
                ),
            }
        }

        /// The wallet the wallet RPCs address, if any.
        pub fn wallet(&self) -> Option<&str> {
            self.wallet.as_deref()
        }

        fn read_auth(&self) -> Result<String> {
            let cookie = std::fs::read_to_string(&self.cookie_file)?;
            Ok(format!("Basic {}", base64(cookie.trim().as_bytes())))
        }

        fn auth(&self, refresh: bool) -> Result<String> {
            let mut a = self
                .auth
                .lock()
                .map_err(|_| Error::Parent("auth lock".into()))?;
            if refresh || a.is_none() {
                *a = Some(self.read_auth()?);
            }
            Ok(a.clone().expect("set above"))
        }

        fn post(
            &self,
            endpoint: &str,
            method: &str,
            params: Value,
            refreshed: bool,
        ) -> Result<Value> {
            let body =
                json!({ "jsonrpc": "1.0", "id": "sidestr", "method": method, "params": params });
            let mut r = self
                .agent
                .post(endpoint)
                .header("authorization", &self.auth(refreshed)?)
                .content_type("text/plain")
                .send(body.to_string().as_bytes())
                .map_err(|e| Error::Parent(format!("{method}: {e}")))?;
            if r.status() == 401 {
                if !refreshed {
                    return self.post(endpoint, method, params, true);
                }
                return Err(Error::Parent(format!(
                    "{method}: the node refused the cookie at {}",
                    self.cookie_file.display()
                )));
            }
            let text = r
                .body_mut()
                .read_to_string()
                .map_err(|e| Error::Parent(format!("{method}: {e}")))?;
            let v: Value = serde_json::from_str(&text)
                .map_err(|e| Error::Parent(format!("{method}: not JSON-RPC: {e}")))?;
            if let Some(e) = v.get("error").filter(|e| !e.is_null()) {
                return Err(Error::Parent(format!(
                    "{method}: {}",
                    e.get("message").and_then(Value::as_str).unwrap_or("error")
                )));
            }
            Ok(v.get("result").cloned().unwrap_or(Value::Null))
        }

        /// A raw call on the node.
        pub fn call(&self, method: &str, params: Value) -> Result<Value> {
            self.post(&self.url, method, params, false)
        }

        /// A raw call on the wallet endpoint.
        pub fn wallet_call(&self, method: &str, params: Value) -> Result<Value> {
            let wallet = self
                .wallet
                .as_deref()
                .ok_or_else(|| Error::Parent("no peg wallet: no wallet name was given".into()))?;
            let endpoint = format!("{}/wallet/{}", self.url, urlencode(wallet));
            self.post(&endpoint, method, params, false)
        }
    }

    fn urlencode(s: &str) -> String {
        s.bytes()
            .map(|b| match b {
                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                    (b as char).to_string()
                }
                _ => format!("%{b:02X}"),
            })
            .collect()
    }

    fn str_of<'a>(v: &'a Value, key: &str) -> Result<&'a str> {
        v.get(key)
            .and_then(Value::as_str)
            .ok_or_else(|| Error::Parent(format!("reply lacks {key}")))
    }

    fn u32_of(v: &Value, key: &str) -> Result<u32> {
        v.get(key)
            .and_then(Value::as_u64)
            .and_then(|n| u32::try_from(n).ok())
            .ok_or_else(|| Error::Parent(format!("reply lacks {key}")))
    }

    /// Core prints amounts in BTC as a JSON number; sats are the nearest
    /// integer of `value × 10⁸`, as siding reads them (`Math.round(o.value * 1e8)`).
    fn sats_of(v: &Value) -> Result<u64> {
        let f = v
            .as_f64()
            .ok_or_else(|| Error::Parent(format!("amount {v}")))?;
        if !(0.0..=21_000_000.0).contains(&f) {
            return Err(Error::Parent(format!("amount {v}")));
        }
        Ok((f * 100_000_000.0).round() as u64)
    }

    fn tx_of(v: &Value) -> Result<Transaction> {
        let hex = str_of(v, "hex")?;
        deserialize(&hex::decode(hex).map_err(|e| Error::Encoding(e.to_string()))?)
            .map_err(|e| Error::Encoding(e.to_string()))
    }

    impl ParentRpc for CoreRpc {
        fn block_count(&self) -> Result<u32> {
            let v = self.call("getblockcount", json!([]))?;
            v.as_u64()
                .and_then(|n| u32::try_from(n).ok())
                .ok_or_else(|| Error::Parent("getblockcount: not a height".into()))
        }
        fn block_hash(&self, height: u32) -> Result<BlockHash> {
            let v = self.call("getblockhash", json!([height]))?;
            v.as_str()
                .and_then(|s| s.parse().ok())
                .ok_or_else(|| Error::Parent("getblockhash: not a hash".into()))
        }
        fn block(&self, hash: &BlockHash) -> Result<ParentBlock> {
            let v = self.call("getblock", json!([hash.to_string(), 2]))?;
            let decoded = v
                .get("tx")
                .and_then(Value::as_array)
                .ok_or_else(|| Error::Parent("getblock: no tx array".into()))?;
            let txs = decoded.iter().map(tx_of).collect::<Result<Vec<_>>>()?;
            // what the node says each output's address is (`parent.mjs` reads
            // `o.scriptPubKey.address`); `None` where it says none
            let addresses = decoded
                .iter()
                .map(|t| {
                    t.get("vout")
                        .and_then(Value::as_array)
                        .map(|outs| {
                            outs.iter()
                                .map(|o| {
                                    o.get("scriptPubKey")
                                        .and_then(|s| s.get("address"))
                                        .and_then(Value::as_str)
                                        .map(str::to_string)
                                })
                                .collect()
                        })
                        .unwrap_or_default()
                })
                .collect();
            Ok(ParentBlock {
                height: u32_of(&v, "height")?,
                hash: str_of(&v, "hash")?
                    .parse()
                    .map_err(|_| Error::Parent("getblock: bad hash".into()))?,
                time: u32_of(&v, "time")?,
                txs,
                addresses,
            })
        }
        fn tx_out(&self, txid: &Txid, vout: u32) -> Result<Option<TxOutStatus>> {
            let v = self.call("gettxout", json!([txid.to_string(), vout, true]))?;
            if v.is_null() {
                return Ok(None);
            }
            let spk = v
                .get("scriptPubKey")
                .and_then(|s| s.get("hex"))
                .and_then(Value::as_str)
                .ok_or_else(|| Error::Parent("gettxout: no scriptPubKey".into()))?;
            Ok(Some(TxOutStatus {
                confirmations: u32_of(&v, "confirmations")?,
                value: sats_of(v.get("value").unwrap_or(&Value::Null))?,
                script_pubkey: ScriptBuf::from_hex(spk)
                    .map_err(|e| Error::Encoding(e.to_string()))?,
            }))
        }
    }

    impl PegWallet for CoreRpc {
        fn lock_outputs(&self, outpoints: &[OutPoint], lock: bool) -> Result<usize> {
            let mut n = 0;
            for o in outpoints {
                let r = self.wallet_call(
                    "lockunspent",
                    json!([!lock, [{ "txid": o.txid.to_string(), "vout": o.vout }]]),
                );
                if r.is_ok() {
                    n += 1;
                }
            }
            Ok(n)
        }
        fn send(&self, outputs: &[SendOutput]) -> Result<Txid> {
            let outs: Vec<Value> = outputs
                .iter()
                .map(|o| match o {
                    SendOutput::Pay { address, btc } => json!({ address: btc }),
                    SendOutput::Data(d) => json!({ "data": hex::encode(d) }),
                })
                .collect();
            let r = self.wallet_call("send", json!([outs, Value::Null, "unset", 1]))?;
            if r.get("complete").and_then(Value::as_bool) != Some(true) {
                return Err(Error::Parent(format!("send did not complete: {r}")));
            }
            str_of(&r, "txid")?
                .parse()
                .map_err(|_| Error::Parent("send: bad txid".into()))
        }
        fn sent_transactions(&self) -> Result<Vec<(Txid, Transaction)>> {
            let list = self.wallet_call("listtransactions", json!(["*", 10000, 0, true]))?;
            let mut seen = std::collections::BTreeSet::new();
            let mut out = Vec::new();
            for t in list.as_array().into_iter().flatten() {
                if t.get("category").and_then(Value::as_str) != Some("send") {
                    continue;
                }
                let Ok(txid) = str_of(t, "txid")?.parse::<Txid>() else {
                    continue;
                };
                if !seen.insert(txid) {
                    continue;
                }
                let g =
                    self.wallet_call("gettransaction", json!([txid.to_string(), true, true]))?;
                out.push((txid, tx_of(&g)?));
            }
            Ok(out)
        }
        fn owns_address(&self, address: &str) -> bool {
            self.wallet_call("getaddressinfo", json!([address]))
                .map(|i| {
                    ["ismine", "iswatchonly", "solvable"]
                        .iter()
                        .any(|k| i.get(*k).and_then(Value::as_bool) == Some(true))
                })
                .unwrap_or(false)
        }
        fn transaction_status(&self, txid: &Txid) -> Result<WalletTxStatus> {
            let g = self.wallet_call("gettransaction", json!([txid.to_string()]))?;
            Ok(WalletTxStatus {
                confirmations: g
                    .get("confirmations")
                    .and_then(Value::as_i64)
                    .map(|c| u32::try_from(c.max(0)).unwrap_or(0))
                    .unwrap_or(0),
                block_height: g
                    .get("blockheight")
                    .and_then(Value::as_u64)
                    .and_then(|n| u32::try_from(n).ok()),
                block_hash: g
                    .get("blockhash")
                    .and_then(Value::as_str)
                    .and_then(|s| s.parse().ok()),
                time: g
                    .get("blocktime")
                    .and_then(Value::as_u64)
                    .and_then(|n| u32::try_from(n).ok()),
            })
        }
    }

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

        #[test]
        fn base64_and_amounts() {
            assert_eq!(base64(b"user:pass"), "dXNlcjpwYXNz");
            assert_eq!(base64(b"ab"), "YWI=");
            assert_eq!(base64(b"a"), "YQ==");
            assert_eq!(sats_of(&json!(0.001)).unwrap(), 100_000);
            assert_eq!(sats_of(&json!(1)).unwrap(), 100_000_000);
            assert_eq!(sats_of(&json!(0.00000001)).unwrap(), 1);
            assert_eq!(sats_of(&json!(0.1)).unwrap(), 10_000_000);
            assert_eq!(
                sats_of(&json!(20999999.99999999)).unwrap(),
                2_099_999_999_999_999
            );
            assert!(sats_of(&json!(-1)).is_err());
            assert!(sats_of(&json!("1")).is_err());
            assert_eq!(urlencode("sidestr-peg"), "sidestr-peg");
            assert_eq!(urlencode("a b/c"), "a%20b%2Fc");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::marker::peg_marker_data;
    use crate::parents::resolve_parent;
    use bitcoin::hashes::Hash;
    use bitcoin::script::PushBytesBuf;
    use bitcoin::transaction::Version;
    use bitcoin::{absolute::LockTime, Amount, TxOut};

    fn tx(outputs: Vec<TxOut>) -> Transaction {
        Transaction {
            version: Version::TWO,
            lock_time: LockTime::ZERO,
            input: vec![],
            output: outputs,
        }
    }
    fn out(value: u64, spk: ScriptBuf) -> TxOut {
        TxOut {
            value: Amount::from_sat(value),
            script_pubkey: spk,
        }
    }
    fn data(d: &[u8]) -> ScriptBuf {
        ScriptBuf::new_op_return(PushBytesBuf::try_from(d.to_vec()).unwrap())
    }
    fn p2tr(byte: u8) -> ScriptBuf {
        ScriptBuf::from_hex(&format!("5120{}", format!("{byte:02x}").repeat(32))).unwrap()
    }

    struct Mock {
        blocks: Vec<ParentBlock>,
        unspent: BTreeMap<(Txid, u32), TxOutStatus>,
    }
    impl ParentRpc for Mock {
        fn block_count(&self) -> Result<u32> {
            Ok(self.blocks.last().map(|b| b.height).unwrap_or(0))
        }
        fn block_hash(&self, height: u32) -> Result<BlockHash> {
            self.blocks
                .iter()
                .find(|b| b.height == height)
                .map(|b| b.hash)
                .ok_or_else(|| Error::Parent("no block".into()))
        }
        fn block(&self, hash: &BlockHash) -> Result<ParentBlock> {
            self.blocks
                .iter()
                .find(|b| b.hash == *hash)
                .cloned()
                .ok_or_else(|| Error::Parent("no block".into()))
        }
        fn tx_out(&self, txid: &Txid, vout: u32) -> Result<Option<TxOutStatus>> {
            Ok(self.unspent.get(&(*txid, vout)).cloned())
        }
    }

    #[test]
    fn pegins_are_found_claimed_and_locked() {
        let me = p2tr(0xab);
        let peg = tx(vec![
            out(250_000, p2tr(0x7e)),
            out(0, data(&peg_marker_data("sidestr:trial", &me))),
        ]);
        let other_chain = tx(vec![
            out(1, p2tr(0x7e)),
            out(0, data(&peg_marker_data("sidestr:other", &me))),
        ]);
        let no_taproot = tx(vec![out(0, data(&peg_marker_data("sidestr:trial", &me)))]);
        let f = find_pegin(&peg, "sidestr:trial", 100, Some(Network::Testnet4), None).unwrap();
        assert_eq!(
            (f.vout, f.amount, &f.script, f.height),
            (0, 250_000, &me, 100)
        );
        assert!(f.parent_address.as_deref().unwrap().starts_with("tb1p"));
        assert!(find_pegin(&other_chain, "sidestr:trial", 100, None, None).is_none());
        assert!(find_pegin(&no_taproot, "sidestr:trial", 100, None, None).is_none());
        assert_eq!(find_payments(&peg, &p2tr(0x7e)), vec![(0, 250_000)]);
        assert!(find_payments(&peg, &me).is_empty());

        let mk = |h: u32, txs: Vec<Transaction>| ParentBlock {
            height: h,
            hash: BlockHash::from_byte_array([h as u8; 32]),
            time: 1_790_000_000 + h,
            txs,
            addresses: vec![],
        };
        let mock = Mock {
            blocks: vec![
                mk(10, vec![other_chain]),
                mk(11, vec![peg.clone()]),
                mk(12, vec![]),
            ],
            unspent: [(
                (peg.compute_txid(), 0),
                TxOutStatus {
                    confirmations: 2,
                    value: 250_000,
                    script_pubkey: p2tr(0x7e),
                },
            )]
            .into_iter()
            .collect(),
        };
        let mut seen = vec![];
        let found = scan_pegins(&mock, "sidestr:trial", 10, 12, None, None, |b| {
            seen.push(b.height)
        })
        .unwrap();
        assert_eq!(seen, vec![10, 11, 12]);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].txid, peg.compute_txid().to_string());
        assert_eq!(
            peg_status(&mock, &peg.compute_txid(), 0).unwrap(),
            PegStatus {
                unspent: true,
                confirmations: Some(2)
            }
        );
        assert_eq!(
            peg_status(&mock, &peg.compute_txid(), 1).unwrap(),
            PegStatus {
                unspent: false,
                confirmations: None
            }
        );
        // SPEC 6: claimable at pegConfirmations, and only once
        assert!(claimable(&found, 15, 6, |_, _| false).is_empty());
        let c = claimable(&found, 16, 6, |_, _| false);
        assert_eq!((c.len(), c[0].amount, &c[0].script), (1, 250_000, &me));
        assert!(claimable(&found, 16, 6, |_, _| true).is_empty());
        assert_eq!(outpoints_to_lock(&found, |_, _| false).len(), 1);
        assert!(outpoints_to_lock(&found, |_, _| true).is_empty());
        assert!(scan_pegins(&mock, "sidestr:trial", 10, 13, None, None, |_| {}).is_err());
    }

    /// A peg wallet that owns one parent address and answers nothing else.
    struct OneAddress(String);
    impl PegWallet for OneAddress {
        fn lock_outputs(&self, _: &[OutPoint], _: bool) -> Result<usize> {
            Ok(0)
        }
        fn send(&self, _: &[SendOutput]) -> Result<Txid> {
            Err(Error::Parent("read-only".into()))
        }
        fn sent_transactions(&self) -> Result<Vec<(Txid, Transaction)>> {
            Ok(vec![])
        }
        fn transaction_status(&self, _: &Txid) -> Result<WalletTxStatus> {
            Ok(WalletTxStatus::default())
        }
        fn owns_address(&self, address: &str) -> bool {
            address == self.0
        }
    }

    /// `parent.mjs scanPegins` at spec fa86dac (0.0.4, `pegScript`): the
    /// announced peg script is the peg wherever it sits, then the owner's,
    /// then (no owner) the first taproot output.
    #[test]
    fn the_announced_peg_script_is_taken_first() {
        let named = p2tr(0xee);
        // the wallet's change (0xaa) before the peg (0xbb)
        let t = tx(vec![
            out(20_000_000, p2tr(0xaa)),
            out(0, data(&peg_marker_data("sidestr:scan", &named))),
            out(50_000, p2tr(0xbb)),
        ]);
        let announced = p2tr(0xbb);
        // change before peg, with the announced script and no wallet: the peg
        let f = find_pegin_announced(&t, "sidestr:scan", 1, None, Some(&announced), None).unwrap();
        assert_eq!((f.vout, f.amount, &f.script), (2, 50_000, &named));
        // it wins over an owner that would say otherwise
        let owns_change = |s: &Script, _: Option<&str>| s == p2tr(0xaa).as_script();
        let f = find_pegin_announced(
            &t,
            "sidestr:scan",
            1,
            None,
            Some(&announced),
            Some(&owns_change),
        )
        .unwrap();
        assert_eq!(f.vout, 2);
        // a script no output pays: the ownership rule decides, as before
        let elsewhere = p2tr(0xcc);
        let owns_peg = |s: &Script, _: Option<&str>| s == p2tr(0xbb).as_script();
        let f = find_pegin_announced(
            &t,
            "sidestr:scan",
            1,
            None,
            Some(&elsewhere),
            Some(&owns_peg),
        )
        .unwrap();
        assert_eq!(f.vout, 2);
        let nobody = |_: &Script, _: Option<&str>| false;
        assert!(
            find_pegin_announced(&t, "sidestr:scan", 1, None, Some(&elsewhere), Some(&nobody))
                .is_none()
        );
        // a script no output pays and no owner to ask: the first taproot output
        let f = find_pegin_announced(&t, "sidestr:scan", 1, None, Some(&elsewhere), None).unwrap();
        assert_eq!(f.vout, 0);
        // a non-taproot output paying the announced script is not the peg (taproots only)
        let bare = ScriptBuf::from_hex("0014aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        let t2 = tx(vec![
            out(9_000, bare.clone()),
            out(0, data(&peg_marker_data("sidestr:scan", &named))),
            out(50_000, p2tr(0xbb)),
        ]);
        assert_eq!(
            find_pegin_announced(&t2, "sidestr:scan", 1, None, Some(&bare), None)
                .unwrap()
                .vout,
            2
        );
        // with no announced script, exactly find_pegin
        for owner in [None, Some(&owns_peg as PegOwner<'_>)] {
            assert_eq!(
                find_pegin_announced(&t, "sidestr:scan", 1, None, None, owner),
                find_pegin(&t, "sidestr:scan", 1, None, owner)
            );
        }
        // and the scanner over blocks
        let mock = Mock {
            blocks: vec![ParentBlock {
                height: 1,
                hash: BlockHash::from_byte_array([1; 32]),
                time: 0,
                txs: vec![tx(vec![]), t.clone()],
                addresses: vec![],
            }],
            unspent: BTreeMap::new(),
        };
        let found = scan_pegins_announced(
            &mock,
            "sidestr:scan",
            1,
            1,
            None,
            Some(&announced),
            None,
            |_| {},
        )
        .unwrap();
        assert_eq!((found.len(), found[0].vout), (1, 2));
    }

    /// `siding/test/txsign-test.mjs` (0.0.3), the scanner half: a marker
    /// transaction whose change (not the peg holders') comes before the peg.
    #[test]
    fn the_peg_is_the_output_the_peg_holders_own() {
        let named = p2tr(0xee);
        let t = tx(vec![
            out(20_000_000, p2tr(0xaa)),
            out(0, data(&peg_marker_data("sidestr:scan", &named))),
            out(50_000, p2tr(0xbb)),
        ]);
        let mock = Mock {
            blocks: vec![ParentBlock {
                height: 1,
                hash: BlockHash::from_byte_array([1; 32]),
                time: 0,
                txs: vec![tx(vec![]), t.clone()],
                addresses: vec![],
            }],
            unspent: BTreeMap::new(),
        };
        let net = Some(Network::Testnet4);
        let peg_addr = Address::from_script(&p2tr(0xbb), Network::Testnet4)
            .unwrap()
            .to_string();
        let wallet = OneAddress(peg_addr.clone());
        let owner = owned_by_peg_wallet(&wallet);
        let found = scan_pegins(&mock, "sidestr:scan", 1, 1, net, Some(&owner), |_| {}).unwrap();
        assert_eq!(found.len(), 1, "with a peg wallet, the owned output");
        assert_eq!(
            (found[0].vout, found[0].amount, &found[0].script),
            (2, 50_000, &named)
        );
        assert_eq!(found[0].parent_address.as_deref(), Some(peg_addr.as_str()));
        // a marker beside nothing the wallet owns is not a peg-in
        let nobody = OneAddress(String::new());
        let none = owned_by_peg_wallet(&nobody);
        assert!(
            scan_pegins(&mock, "sidestr:scan", 1, 1, net, Some(&none), |_| {})
                .unwrap()
                .is_empty()
        );
        // without a network no address can be asked about: nothing is owned
        assert!(find_pegin(&t, "sidestr:scan", 1, None, Some(&owner)).is_none());
        // the node's own addresses rule where it reported them: an output it gave
        // no address is not owned even though its script has one (`parent.mjs`)
        let mut unaddressed = mock.blocks[0].clone();
        unaddressed.addresses = vec![vec![], vec![None, None, None]];
        let quiet = Mock {
            blocks: vec![unaddressed.clone()],
            unspent: BTreeMap::new(),
        };
        assert!(
            scan_pegins(&quiet, "sidestr:scan", 1, 1, net, Some(&owner), |_| {})
                .unwrap()
                .is_empty()
        );
        unaddressed.addresses[1][2] = Some(peg_addr.clone());
        let told = Mock {
            blocks: vec![unaddressed],
            unspent: BTreeMap::new(),
        };
        let f = scan_pegins(&told, "sidestr:scan", 1, 1, None, Some(&owner), |_| {}).unwrap();
        assert_eq!((f.len(), f[0].vout), (1, 2));
        assert_eq!(f[0].parent_address.as_deref(), Some(peg_addr.as_str()));
        // without a peg wallet the first taproot output is taken (read-only producers)
        let legacy = scan_pegins(&mock, "sidestr:scan", 1, 1, net, None, |_| {}).unwrap();
        assert_eq!((legacy.len(), legacy[0].vout), (1, 0));
        // level 2: the challenge script is the owner
        let challenge = p2tr(0xbb);
        let level2 = |s: &Script, _: Option<&str>| s == challenge.as_script();
        assert_eq!(
            find_pegin(&t, "sidestr:scan", 1, None, Some(&level2))
                .unwrap()
                .vout,
            2
        );
    }

    #[test]
    fn payments_checkpoints_and_reconciliation() {
        let tbtc4 = resolve_parent("tbtc4").unwrap();
        let burn = Burn {
            txid: "c".repeat(64),
            vout: 1,
            script: format!("5120{}", "e9".repeat(32)),
            value: 50_000,
            height: 133,
        };
        let outs = pegout_payment("sidestr:trial", &burn, tbtc4).unwrap();
        let SendOutput::Pay { address, btc } = &outs[0] else {
            panic!()
        };
        assert!(address.starts_with("tb1p") && btc == "0.00050000");
        let SendOutput::Data(d) = &outs[1] else {
            panic!()
        };
        assert_eq!(
            parse_pegout_marker(&data(d), "sidestr:trial"),
            Some("c".repeat(64))
        );
        // a bare OP_RETURN is not an address
        let no_addr = Burn {
            script: "6a00".into(),
            ..burn.clone()
        };
        assert!(pegout_payment("sidestr:trial", &no_addr, tbtc4).is_err());
        assert!(
            pegout_payment("sidestr:trial", &burn, resolve_parent("btc").unwrap())
                .unwrap()
                .iter()
                .any(
                    |o| matches!(o, SendOutput::Pay { address, .. } if address.starts_with("bc1p"))
                )
        );
        let ck = checkpoint_payment("sidestr:trial", 70_000, &"d".repeat(64)).unwrap();
        let SendOutput::Data(d) = &ck[0] else {
            panic!()
        };
        assert_eq!(
            parse_checkpoint(&data(d), "sidestr:trial"),
            Some((70_000, "d".repeat(64)))
        );
        assert!(checkpoint_payment(&"x".repeat(60), 1, &"d".repeat(64)).is_err());
        // the wallet's history read back
        let paid_tx = tx(vec![
            out(50_000, p2tr(0xe9)),
            out(0, data(&outs_data(&outs))),
        ]);
        let ck_tx = tx(vec![out(0, data(d))]);
        let history = vec![
            (Txid::from_byte_array([1u8; 32]), paid_tx),
            (Txid::from_byte_array([2u8; 32]), ck_tx),
        ];
        let paid = paid_pegouts_in(&history, "sidestr:trial");
        assert_eq!(
            paid.get(&"c".repeat(64)),
            Some(&Txid::from_byte_array([1u8; 32]))
        );
        assert!(paid_pegouts_in(&history, "sidestr:other").is_empty());
        let sent = sent_checkpoints_in(&history, "sidestr:trial");
        assert_eq!(
            sent.get(&(70_000, "d".repeat(64))),
            Some(&Txid::from_byte_array([2u8; 32]))
        );
        let owed = Burn {
            txid: "e".repeat(64),
            height: 200,
            ..burn.clone()
        };
        let older = Burn {
            txid: "f".repeat(64),
            height: 150,
            ..burn.clone()
        };
        let r = reconcile(&[owed.clone(), burn.clone(), older.clone()], &paid);
        assert_eq!(r.paid, vec![(burn, Txid::from_byte_array([1u8; 32]))]);
        assert_eq!(r.outstanding, vec![older, owed]);
        assert_eq!(btc_string(100_000), "0.00100000");
        assert_eq!(parent_network(tbtc4), Some(Network::Testnet4));
        assert_eq!(
            parent_network(resolve_parent("xbt").unwrap()),
            Some(Network::Bitcoin)
        );
    }

    fn outs_data(outs: &[SendOutput]) -> Vec<u8> {
        outs.iter()
            .find_map(|o| match o {
                SendOutput::Data(d) => Some(d.clone()),
                _ => None,
            })
            .unwrap()
    }
}