ark-client 0.10.1

Main client library for interacting with Ark servers
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
use crate::Error;
use ark_core::contract::BoardingContract;
use ark_core::contract::ContractContext;
use ark_core::contract::ContractSpec;
use ark_core::contract::ContractState;
use ark_core::contract::ContractType;
use ark_core::contract::DefaultVtxoContract;
use ark_core::contract::DelegateVtxoContract;
use ark_core::contract::SpendSelection;
use ark_core::contract::StoredContract;
use ark_core::contract::VhtlcContract;
use ark_core::server;
use ark_core::server::VirtualTxOutPoint;
use ark_core::ArkAddress;
use ark_core::BoardingOutput;
use ark_core::Vtxo;
use bitcoin::Address;
use bitcoin::Amount;
use bitcoin::Network;
use bitcoin::Script;
use bitcoin::ScriptBuf;
use bitcoin::Sequence;
use bitcoin::XOnlyPublicKey;
use std::collections::HashMap;
use std::marker::PhantomData;
#[cfg(feature = "sqlite")]
use std::path::Path;
#[cfg(feature = "sqlite")]
use std::sync::Mutex;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

trait DynContractHandler: Send + Sync {
    fn contract_type(&self) -> ContractType;
    fn validate(&self, stored: &StoredContract, ctx: &ContractContext) -> Result<(), Error>;
    fn spendable_selections(
        &self,
        stored: &StoredContract,
        ctx: &ContractContext,
    ) -> Result<Vec<SpendSelection>, Error>;
}

struct ContractHandler<T> {
    _marker: PhantomData<T>,
}

impl<T> Default for ContractHandler<T> {
    fn default() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

impl<T: ContractSpec> DynContractHandler for ContractHandler<T> {
    fn contract_type(&self) -> ContractType {
        T::contract_type()
    }

    fn validate(&self, stored: &StoredContract, ctx: &ContractContext) -> Result<(), Error> {
        if stored.contract_type != T::contract_type() {
            return Err(Error::ad_hoc("unexpected contract type"));
        }
        if stored.contract_version != T::VERSION {
            return Err(Error::ad_hoc(format!(
                "unsupported contract version: {}",
                stored.contract_version
            )));
        }

        let data: T = serde_json::from_value(stored.data.clone())
            .map_err(|e| Error::ad_hoc(format!("failed to decode contract data: {e}")))?;
        let derived_script = data.script_pubkey(ctx)?;
        if derived_script != stored.script_pubkey {
            return Err(Error::ad_hoc("contract script mismatch"));
        }

        Ok(())
    }

    fn spendable_selections(
        &self,
        stored: &StoredContract,
        ctx: &ContractContext,
    ) -> Result<Vec<SpendSelection>, Error> {
        self.validate(stored, ctx)?;
        let data: T = serde_json::from_value(stored.data.clone())
            .map_err(|e| Error::ad_hoc(format!("failed to decode contract data: {e}")))?;
        data.spendable_selections(ctx).map_err(Into::into)
    }
}

#[derive(Default)]
pub struct ContractRegistry {
    handlers: HashMap<ContractType, Box<dyn DynContractHandler>>,
}

impl ContractRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register<T: ContractSpec>(&mut self) -> Result<(), Error> {
        let contract_type = T::contract_type();
        if self.handlers.contains_key(&contract_type) {
            return Err(Error::ad_hoc(format!(
                "contract handler already registered: {contract_type}"
            )));
        }
        let handler = Box::new(ContractHandler::<T>::default());
        debug_assert_eq!(handler.contract_type(), contract_type);
        self.handlers.insert(contract_type, handler);
        Ok(())
    }

    fn handler_for(&self, contract_type: &ContractType) -> Result<&dyn DynContractHandler, Error> {
        self.handlers
            .get(contract_type)
            .map(|handler| handler.as_ref())
            .ok_or_else(|| Error::ad_hoc(format!("unknown contract type: {contract_type}")))
    }
}

/// Persistence backend for validated [`StoredContract`] rows.
///
/// Stores are keyed by script pubkey. Higher-level compatibility for built-in same-script templates
/// is handled by [`ContractManager`], not by individual store implementations.
pub trait ContractStore: Send + Sync {
    fn insert(&mut self, contract: StoredContract) -> Result<(), Error>;
    fn get_by_script(&self, script_pubkey: &Script) -> Result<Option<StoredContract>, Error>;
    fn list(&self) -> Result<Vec<StoredContract>, Error>;
    fn update_state(&mut self, script_pubkey: &Script, state: ContractState) -> Result<(), Error>;
}

#[derive(Default)]
pub struct MemoryContractStore {
    contracts: HashMap<ScriptBuf, StoredContract>,
}

impl MemoryContractStore {
    pub fn new() -> Self {
        Self::default()
    }
}

impl ContractStore for MemoryContractStore {
    fn insert(&mut self, contract: StoredContract) -> Result<(), Error> {
        if self.contracts.contains_key(&contract.script_pubkey) {
            return Err(Error::ad_hoc("contract script already exists"));
        }
        self.contracts
            .insert(contract.script_pubkey.clone(), contract);
        Ok(())
    }

    fn get_by_script(&self, script_pubkey: &Script) -> Result<Option<StoredContract>, Error> {
        Ok(self.contracts.get(script_pubkey).cloned())
    }

    fn list(&self) -> Result<Vec<StoredContract>, Error> {
        Ok(self.contracts.values().cloned().collect())
    }

    fn update_state(&mut self, script_pubkey: &Script, state: ContractState) -> Result<(), Error> {
        let contract = self
            .contracts
            .get_mut(script_pubkey)
            .ok_or_else(|| Error::ad_hoc("unknown contract script"))?;
        contract.state = state;
        Ok(())
    }
}

#[cfg(feature = "sqlite")]
pub struct SqliteContractStore {
    connection: Mutex<rusqlite::Connection>,
}

#[cfg(feature = "sqlite")]
impl SqliteContractStore {
    pub fn new<P: AsRef<Path>>(db_path: P) -> Result<Self, Error> {
        let db_path = db_path.as_ref();
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                Error::consumer(format!("failed to create contract store directory: {e}"))
            })?;
        }

        let connection = rusqlite::Connection::open(db_path)
            .map_err(|e| Error::consumer(format!("failed to open contract store: {e}")))?;
        let store = Self {
            connection: Mutex::new(connection),
        };
        store.initialize()?;
        Ok(store)
    }

    pub fn new_default() -> Result<Self, Error> {
        Self::new("contracts.db")
    }

    fn initialize(&self) -> Result<(), Error> {
        let connection = self.connection()?;
        connection
            .execute_batch(
                "CREATE TABLE IF NOT EXISTS contracts (
                    script_pubkey BLOB PRIMARY KEY NOT NULL,
                    contract_type TEXT NOT NULL,
                    contract_version INTEGER NOT NULL,
                    state TEXT NOT NULL,
                    created_at INTEGER NOT NULL,
                    key_index INTEGER,
                    data TEXT NOT NULL
                );",
            )
            .map_err(|e| Error::consumer(format!("failed to initialize contract store: {e}")))?;
        Ok(())
    }

    fn connection(&self) -> Result<std::sync::MutexGuard<'_, rusqlite::Connection>, Error> {
        self.connection
            .lock()
            .map_err(|_| Error::ad_hoc("contract store connection lock poisoned"))
    }

    fn state_to_str(state: ContractState) -> &'static str {
        match state {
            ContractState::Active => "active",
            ContractState::Inactive => "inactive",
        }
    }

    fn state_from_str(value: &str) -> Result<ContractState, Error> {
        match value {
            "active" => Ok(ContractState::Active),
            "inactive" => Ok(ContractState::Inactive),
            _ => Err(Error::ad_hoc(format!("unknown contract state: {value}"))),
        }
    }

    fn row_to_contract(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredContract> {
        let script_pubkey: Vec<u8> = row.get("script_pubkey")?;
        let contract_type: String = row.get("contract_type")?;
        let contract_version: i64 = row.get("contract_version")?;
        let state: String = row.get("state")?;
        let created_at: i64 = row.get("created_at")?;
        let key_index: Option<i64> = row.get("key_index")?;
        let data: String = row.get("data")?;

        let contract_type = ContractType::new(contract_type).map_err(|e| {
            rusqlite::Error::FromSqlConversionFailure(1, rusqlite::types::Type::Text, Box::new(e))
        })?;
        let state = Self::state_from_str(&state).map_err(|e| {
            rusqlite::Error::FromSqlConversionFailure(3, rusqlite::types::Type::Text, Box::new(e))
        })?;
        let data = serde_json::from_str(&data).map_err(|e| {
            rusqlite::Error::FromSqlConversionFailure(6, rusqlite::types::Type::Text, Box::new(e))
        })?;

        Ok(StoredContract {
            contract_type,
            contract_version: u32::try_from(contract_version).map_err(|e| {
                rusqlite::Error::FromSqlConversionFailure(
                    2,
                    rusqlite::types::Type::Integer,
                    Box::new(e),
                )
            })?,
            script_pubkey: ScriptBuf::from_bytes(script_pubkey),
            state,
            created_at: u64::try_from(created_at).map_err(|e| {
                rusqlite::Error::FromSqlConversionFailure(
                    4,
                    rusqlite::types::Type::Integer,
                    Box::new(e),
                )
            })?,
            key_index: key_index
                .map(|value| {
                    u32::try_from(value).map_err(|e| {
                        rusqlite::Error::FromSqlConversionFailure(
                            5,
                            rusqlite::types::Type::Integer,
                            Box::new(e),
                        )
                    })
                })
                .transpose()?,
            data,
        })
    }
}

#[cfg(feature = "sqlite")]
impl ContractStore for SqliteContractStore {
    fn insert(&mut self, contract: StoredContract) -> Result<(), Error> {
        let data = serde_json::to_string(&contract.data)
            .map_err(|e| Error::ad_hoc(format!("failed to encode contract data: {e}")))?;
        let connection = self.connection()?;
        connection
            .execute(
                "INSERT INTO contracts (
                    script_pubkey,
                    contract_type,
                    contract_version,
                    state,
                    created_at,
                    key_index,
                    data
                ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                rusqlite::params![
                    contract.script_pubkey.as_bytes(),
                    contract.contract_type.as_str(),
                    i64::from(contract.contract_version),
                    Self::state_to_str(contract.state),
                    i64::try_from(contract.created_at).map_err(|e| Error::ad_hoc(format!(
                        "contract created_at does not fit sqlite integer: {e}"
                    )))?,
                    contract.key_index.map(i64::from),
                    data,
                ],
            )
            .map_err(|e| {
                if matches!(e, rusqlite::Error::SqliteFailure(ref err, _) if err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_PRIMARYKEY)
                {
                    Error::ad_hoc("contract script already exists")
                } else {
                    Error::consumer(format!("failed to insert contract: {e}"))
                }
            })?;
        Ok(())
    }

    fn get_by_script(&self, script_pubkey: &Script) -> Result<Option<StoredContract>, Error> {
        let connection = self.connection()?;
        let mut statement = connection
            .prepare(
                "SELECT script_pubkey, contract_type, contract_version, state, created_at, key_index, data
                 FROM contracts
                 WHERE script_pubkey = ?1",
            )
            .map_err(|e| Error::consumer(format!("failed to prepare contract lookup: {e}")))?;
        let mut rows = statement
            .query(rusqlite::params![script_pubkey.as_bytes()])
            .map_err(|e| Error::consumer(format!("failed to lookup contract: {e}")))?;
        let Some(row) = rows
            .next()
            .map_err(|e| Error::consumer(format!("failed to read contract: {e}")))?
        else {
            return Ok(None);
        };
        Self::row_to_contract(row)
            .map(Some)
            .map_err(|e| Error::consumer(format!("failed to decode contract: {e}")))
    }

    fn list(&self) -> Result<Vec<StoredContract>, Error> {
        let connection = self.connection()?;
        let mut statement = connection
            .prepare(
                "SELECT script_pubkey, contract_type, contract_version, state, created_at, key_index, data
                 FROM contracts
                 ORDER BY created_at, rowid",
            )
            .map_err(|e| Error::consumer(format!("failed to prepare contract list: {e}")))?;
        let rows = statement
            .query_map([], Self::row_to_contract)
            .map_err(|e| Error::consumer(format!("failed to list contracts: {e}")))?;
        rows.collect::<rusqlite::Result<Vec<_>>>()
            .map_err(|e| Error::consumer(format!("failed to decode contracts: {e}")))
    }

    fn update_state(&mut self, script_pubkey: &Script, state: ContractState) -> Result<(), Error> {
        let connection = self.connection()?;
        let updated = connection
            .execute(
                "UPDATE contracts SET state = ?1 WHERE script_pubkey = ?2",
                rusqlite::params![Self::state_to_str(state), script_pubkey.as_bytes()],
            )
            .map_err(|e| Error::consumer(format!("failed to update contract state: {e}")))?;
        if updated == 0 {
            return Err(Error::ad_hoc("unknown contract script"));
        }
        Ok(())
    }
}

/// A VTXO returned by wallet surfaces, enriched with its stored contract metadata.
///
/// Use [`Self::spend_selection`] to build transaction inputs. The underlying VTXO and contract are
/// exposed read-only for wallet UX and advanced integrations.
#[derive(Clone, Debug, PartialEq)]
pub struct AnnotatedVtxo {
    contract: StoredContract,
    vtxo: VirtualTxOutPoint,
    spend_selections: Vec<SpendSelection>,
}

impl AnnotatedVtxo {
    pub(crate) fn new(
        contract: StoredContract,
        vtxo: VirtualTxOutPoint,
        spend_selections: Vec<SpendSelection>,
    ) -> Self {
        Self {
            contract,
            vtxo,
            spend_selections,
        }
    }

    pub fn contract(&self) -> &StoredContract {
        &self.contract
    }

    pub fn vtxo(&self) -> &VirtualTxOutPoint {
        &self.vtxo
    }

    pub fn spend_selections(&self) -> &[SpendSelection] {
        &self.spend_selections
    }

    pub fn spend_selection(
        &self,
        kind: ark_core::contract::SpendPathKind,
    ) -> Result<SpendSelection, Error> {
        self.spend_selections
            .iter()
            .find(|selection| selection.path.kind == kind)
            .cloned()
            .ok_or_else(|| Error::ad_hoc(format!("missing {kind:?} spend path")))
    }

    pub fn tapscripts(&self) -> Vec<ScriptBuf> {
        self.spend_selections
            .iter()
            .map(|selection| selection.path.script.clone())
            .collect()
    }

    pub fn script_pubkey(&self) -> ScriptBuf {
        self.contract.script_pubkey.clone()
    }

    pub fn server_pk(&self) -> Result<XOnlyPublicKey, Error> {
        Ok(self.vtxo_contract_data()?.server)
    }

    pub fn owner_pk(&self) -> Result<XOnlyPublicKey, Error> {
        Ok(self.vtxo_contract_data()?.owner)
    }

    pub fn exit_delay(&self) -> Result<Sequence, Error> {
        Ok(self.vtxo_contract_data()?.exit_delay)
    }

    fn vtxo_contract_data(&self) -> Result<VtxoContractData, Error> {
        offchain_vtxo_data(&self.contract)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct VtxoContractData {
    server: XOnlyPublicKey,
    owner: XOnlyPublicKey,
    exit_delay: Sequence,
}

/// A boarding output returned by wallet surfaces, enriched with its stored contract metadata.
///
/// Use [`Self::spend_selection`] to build transaction inputs. The underlying output and contract
/// are exposed read-only for wallet UX and advanced integrations.
#[derive(Clone, Debug, PartialEq)]
pub struct AnnotatedBoardingOutput {
    contract: StoredContract,
    output: BoardingOutput,
    spend_selections: Vec<SpendSelection>,
}

impl AnnotatedBoardingOutput {
    pub(crate) fn new(
        contract: StoredContract,
        output: BoardingOutput,
        spend_selections: Vec<SpendSelection>,
    ) -> Self {
        Self {
            contract,
            output,
            spend_selections,
        }
    }

    pub fn contract(&self) -> &StoredContract {
        &self.contract
    }

    pub fn output(&self) -> &BoardingOutput {
        &self.output
    }

    pub fn spend_selections(&self) -> &[SpendSelection] {
        &self.spend_selections
    }

    pub fn spend_selection(
        &self,
        kind: ark_core::contract::SpendPathKind,
    ) -> Result<SpendSelection, Error> {
        self.spend_selections
            .iter()
            .find(|selection| selection.path.kind == kind)
            .cloned()
            .ok_or_else(|| Error::ad_hoc(format!("missing {kind:?} spend path")))
    }

    pub fn tapscripts(&self) -> Vec<ScriptBuf> {
        self.spend_selections
            .iter()
            .map(|selection| selection.path.script.clone())
            .collect()
    }

    pub fn address(&self) -> &Address {
        self.output.address()
    }

    pub fn script_pubkey(&self) -> ScriptBuf {
        self.contract.script_pubkey.clone()
    }

    pub fn server_pk(&self) -> XOnlyPublicKey {
        self.output.server_pk()
    }

    pub fn owner_pk(&self) -> XOnlyPublicKey {
        self.output.owner_pk()
    }

    pub fn exit_delay(&self) -> Sequence {
        self.output.exit_delay()
    }

    pub fn can_be_claimed_unilaterally_by_owner(
        &self,
        now: std::time::Duration,
        confirmation_blocktime: std::time::Duration,
        confirmations: u64,
    ) -> bool {
        self.output
            .can_be_claimed_unilaterally_by_owner(now, confirmation_blocktime, confirmations)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ActiveOffchainContract {
    pub address: ArkAddress,
    pub vtxo: Vtxo,
    pub spend_selections: Vec<SpendSelection>,
}

impl ActiveOffchainContract {
    pub fn spend_selection(
        &self,
        kind: ark_core::contract::SpendPathKind,
    ) -> Result<SpendSelection, Error> {
        self.spend_selections
            .iter()
            .find(|selection| selection.path.kind == kind)
            .cloned()
            .ok_or_else(|| Error::ad_hoc(format!("missing {kind:?} spend path")))
    }
}

#[derive(Clone, Debug)]
pub struct AnnotatedVtxoList {
    dust: Amount,
    vtxos: Vec<AnnotatedVtxo>,
}

impl AnnotatedVtxoList {
    pub fn new(dust: Amount, vtxos: Vec<AnnotatedVtxo>) -> Self {
        Self { dust, vtxos }
    }

    pub fn into_inner(self) -> Vec<AnnotatedVtxo> {
        self.vtxos
    }

    pub fn all(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        self.vtxos.iter()
    }

    pub fn all_unspent(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        let dust = self.dust;
        self.vtxos
            .iter()
            .filter(move |entry| entry.vtxo.is_unspent(dust))
    }

    pub fn spendable_offchain(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        let dust = self.dust;
        self.vtxos
            .iter()
            .filter(move |entry| entry.vtxo.is_spendable_offchain(dust))
    }

    pub fn spendable_offchain_at<'a>(
        &'a self,
        server_info: &'a server::Info,
        now_unix_secs: i64,
    ) -> impl Iterator<Item = &'a AnnotatedVtxo> + 'a {
        self.spendable_offchain().filter(move |entry| {
            !entry
                .server_pk()
                .map(|server_pk| server_info.signer_requires_recovery_at(server_pk, now_unix_secs))
                .unwrap_or(false)
        })
    }

    pub fn pending_recovery_due_to_signer_at<'a>(
        &'a self,
        server_info: &'a server::Info,
        now_unix_secs: i64,
    ) -> impl Iterator<Item = &'a AnnotatedVtxo> + 'a {
        self.spendable_offchain().filter(move |entry| {
            entry
                .server_pk()
                .map(|server_pk| server_info.signer_requires_recovery_at(server_pk, now_unix_secs))
                .unwrap_or(false)
        })
    }

    pub fn batch_settleable_at<'a>(
        &'a self,
        server_info: &'a server::Info,
        now_unix_secs: i64,
    ) -> impl Iterator<Item = &'a AnnotatedVtxo> + 'a {
        self.all_unspent().filter(move |entry| {
            entry.vtxo.is_recoverable(server_info.dust)
                || !entry
                    .server_pk()
                    .map(|server_pk| {
                        server_info.signer_requires_recovery_at(server_pk, now_unix_secs)
                    })
                    .unwrap_or(false)
        })
    }

    pub fn pre_confirmed(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        let dust = self.dust;
        self.vtxos
            .iter()
            .filter(move |entry| entry.vtxo.is_pre_confirmed_spendable(dust))
    }

    pub fn confirmed(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        let dust = self.dust;
        self.vtxos
            .iter()
            .filter(move |entry| entry.vtxo.is_confirmed_spendable(dust))
    }

    pub fn recoverable(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        self.vtxos
            .iter()
            .filter(move |entry| entry.vtxo.is_recoverable(self.dust))
    }

    pub fn could_exit_unilaterally(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        self.pre_confirmed().chain(self.confirmed())
    }

    pub fn spent(&self) -> impl Iterator<Item = &AnnotatedVtxo> {
        let dust = self.dust;
        self.vtxos
            .iter()
            .filter(move |entry| entry.vtxo.is_spent_status(dust))
    }
}

/// Registry and persistence layer for built-in and custom Ark contracts.
///
/// `ContractManager` is a public extension point: consumers can register custom
/// [`ContractSpec`] implementations while reusing the SDK's validation, persistence, and spend
/// selection plumbing. The low-level row APIs expose stored contracts keyed by script;
/// wallet-facing code should prefer semantic annotated outputs such as [`AnnotatedVtxo`] and
/// [`AnnotatedBoardingOutput`].
pub struct ContractManager {
    network: Network,
    registry: ContractRegistry,
    store: Box<dyn ContractStore>,
}

impl ContractManager {
    pub fn new(network: Network, store: Box<dyn ContractStore>) -> Self {
        Self {
            network,
            registry: ContractRegistry::new(),
            store,
        }
    }

    pub fn new_with_builtins(
        network: Network,
        store: Box<dyn ContractStore>,
    ) -> Result<Self, Error> {
        let mut manager = Self::new(network, store);
        manager.register_builtins()?;
        Ok(manager)
    }

    pub fn in_memory(network: Network) -> Self {
        Self::new(network, Box::new(MemoryContractStore::new()))
    }

    pub fn in_memory_with_builtins(network: Network) -> Result<Self, Error> {
        Self::new_with_builtins(network, Box::new(MemoryContractStore::new()))
    }

    pub fn network(&self) -> Network {
        self.network
    }

    pub fn register<T: ContractSpec>(&mut self) -> Result<(), Error> {
        self.registry.register::<T>()
    }

    pub fn register_builtins(&mut self) -> Result<(), Error> {
        self.register::<DefaultVtxoContract>()?;
        self.register::<DelegateVtxoContract>()?;
        self.register::<BoardingContract>()?;
        self.register::<VhtlcContract>()
    }

    pub fn insert<T: ContractSpec>(
        &mut self,
        contract: T,
        state: ContractState,
        key_index: Option<u32>,
    ) -> Result<StoredContract, Error> {
        let stored = self.stored_contract(contract, state, key_index)?;
        self.store.insert(stored.clone())?;
        Ok(stored)
    }

    pub fn insert_or_get<T: ContractSpec>(
        &mut self,
        contract: T,
        state: ContractState,
        key_index: Option<u32>,
    ) -> Result<StoredContract, Error> {
        let stored = self.stored_contract(contract, state, key_index)?;

        match self.store.get_by_script(&stored.script_pubkey)? {
            None => {
                self.store.insert(stored.clone())?;
                Ok(stored)
            }
            Some(existing) if same_stored_contract(&existing, &stored) => Ok(existing),
            Some(existing) if can_share_script_row(&existing, &stored)? => Ok(existing),
            Some(_) => Err(Error::ad_hoc(
                "contract script already exists with different data",
            )),
        }
    }

    fn stored_contract<T: ContractSpec>(
        &self,
        contract: T,
        state: ContractState,
        key_index: Option<u32>,
    ) -> Result<StoredContract, Error> {
        let ctx = ContractContext::new(self.network);
        let stored = StoredContract {
            contract_type: T::contract_type(),
            contract_version: T::VERSION,
            script_pubkey: contract.script_pubkey(&ctx)?,
            state,
            created_at: now_secs()?,
            key_index,
            data: serde_json::to_value(contract)
                .map_err(|e| Error::ad_hoc(format!("failed to encode contract data: {e}")))?,
        };

        let handler = self.registry.handler_for(&stored.contract_type)?;
        handler.validate(&stored, &ctx)?;
        Ok(stored)
    }

    pub fn insert_stored(&mut self, stored: StoredContract) -> Result<(), Error> {
        let ctx = ContractContext::new(self.network);
        let handler = self.registry.handler_for(&stored.contract_type)?;
        handler.validate(&stored, &ctx)?;
        self.store.insert(stored)
    }

    pub fn get(&self, script_pubkey: &Script) -> Result<Option<StoredContract>, Error> {
        self.store.get_by_script(script_pubkey)
    }

    pub fn get_typed<T: ContractSpec>(&self, script_pubkey: &Script) -> Result<Option<T>, Error> {
        let Some(stored) = self.store.get_by_script(script_pubkey)? else {
            return Ok(None);
        };

        if stored.contract_type != T::contract_type() {
            return Err(Error::ad_hoc("unexpected contract type"));
        }
        if stored.contract_version != T::VERSION {
            return Err(Error::ad_hoc(format!(
                "unsupported contract version: {}",
                stored.contract_version
            )));
        }

        serde_json::from_value(stored.data)
            .map(Some)
            .map_err(|e| Error::ad_hoc(format!("failed to decode contract data: {e}")))
    }

    pub fn list(&self) -> Result<Vec<StoredContract>, Error> {
        self.store.list()
    }

    pub fn list_by_type(&self, contract_type: ContractType) -> Result<Vec<StoredContract>, Error> {
        Ok(self
            .store
            .list()?
            .into_iter()
            .filter(|contract| contract.contract_type == contract_type)
            .collect())
    }

    pub fn list_active_by_type(
        &self,
        contract_type: ContractType,
    ) -> Result<Vec<StoredContract>, Error> {
        Ok(self
            .list_by_type(contract_type)?
            .into_iter()
            .filter(|contract| contract.state == ContractState::Active)
            .collect())
    }

    pub fn update_state(
        &mut self,
        script_pubkey: &Script,
        state: ContractState,
    ) -> Result<(), Error> {
        self.store.update_state(script_pubkey, state)
    }

    pub fn spendable_selections(
        &self,
        stored: &StoredContract,
    ) -> Result<Vec<SpendSelection>, Error> {
        let ctx = ContractContext::new(self.network);
        let handler = self.registry.handler_for(&stored.contract_type)?;
        handler.spendable_selections(stored, &ctx)
    }

    pub(crate) fn active_offchain_contracts(
        &self,
        unilateral_exit_delay_candidates: &[Sequence],
    ) -> Result<Vec<ActiveOffchainContract>, Error> {
        let ctx = ContractContext::new(self.network);
        self.store
            .list()?
            .into_iter()
            .filter(|stored| stored.state == ContractState::Active)
            .filter_map(|stored| {
                match active_offchain_contract_from_stored(
                    self,
                    &ctx,
                    stored,
                    unilateral_exit_delay_candidates,
                ) {
                    Ok(Some(contract)) => Some(Ok(contract)),
                    Ok(None) => None,
                    Err(e) => Some(Err(e)),
                }
            })
            .collect()
    }

    pub fn annotate_vtxos(
        &self,
        vtxos: Vec<VirtualTxOutPoint>,
    ) -> Result<Vec<AnnotatedVtxo>, Error> {
        vtxos
            .into_iter()
            .map(|vtxo| {
                let contract = self
                    .store
                    .get_by_script(&vtxo.script)?
                    .ok_or_else(|| Error::ad_hoc("unknown contract script"))?;
                let spend_selections = self.spendable_selections(&contract)?;
                Ok(AnnotatedVtxo::new(contract, vtxo, spend_selections))
            })
            .collect()
    }

    /// Return active boarding outputs, including compatible default VTXO rows.
    ///
    /// The store keeps one row per script. If a default VTXO row was stored before an equivalent
    /// boarding row, on-chain boarding discovery must still see it as a boarding output. Default
    /// VTXO rows are included only when their CSV delay is one of the caller's boarding delay
    /// candidates. Passing an empty slice means "strict boarding rows only".
    pub(crate) fn annotated_boarding_outputs_for_exit_delays(
        &self,
        compatible_default_exit_delays: &[Sequence],
    ) -> Result<Vec<AnnotatedBoardingOutput>, Error> {
        let ctx = ContractContext::new(self.network);
        self.store
            .list()?
            .into_iter()
            .filter(|stored| stored.state == ContractState::Active)
            .filter_map(|stored| {
                boarding_contract_from_stored(&stored, compatible_default_exit_delays)
                    .map(|contract| (stored, contract))
            })
            .map(|(stored, contract)| {
                let output = contract.boarding_output(&ctx)?;
                let spend_selections = self.spendable_selections(&stored)?;
                Ok(AnnotatedBoardingOutput::new(
                    stored,
                    output,
                    spend_selections,
                ))
            })
            .collect()
    }

    pub fn annotated_boarding_outputs(&self) -> Result<Vec<AnnotatedBoardingOutput>, Error> {
        self.annotated_boarding_outputs_for_exit_delays(&[])
    }
}

fn same_stored_contract(a: &StoredContract, b: &StoredContract) -> bool {
    a.contract_type == b.contract_type
        && a.contract_version == b.contract_version
        && a.data == b.data
}

/// Whether two same-script rows may use the row that was stored first.
///
/// This is intentionally limited to default VTXO/boarding rows that decode to the same two-leaf
/// server+owner/CSV template. Delegate and VHTLC scripts carry different leaves/semantics and a
/// same-script collision with them should remain a hard error.
fn can_share_script_row(a: &StoredContract, b: &StoredContract) -> Result<bool, Error> {
    let default_vtxo_boarding = a.contract_type == ContractType::default_vtxo()
        && b.contract_type == ContractType::boarding();
    let boarding_default_vtxo = a.contract_type == ContractType::boarding()
        && b.contract_type == ContractType::default_vtxo();
    if !default_vtxo_boarding && !boarding_default_vtxo {
        return Ok(false);
    }

    // Store only one row for a script. Allow default VTXO and boarding to share that row only
    // when the decoded script template is identical.
    Ok(two_leaf_vtxo_data(a)? == two_leaf_vtxo_data(b)?)
}

fn active_offchain_contract_from_stored(
    manager: &ContractManager,
    ctx: &ContractContext,
    stored: StoredContract,
    unilateral_exit_delay_candidates: &[Sequence],
) -> Result<Option<ActiveOffchainContract>, Error> {
    if stored.contract_type == ContractType::delegate_vtxo() {
        let contract: DelegateVtxoContract = serde_json::from_value(stored.data.clone())
            .map_err(|e| Error::ad_hoc(format!("failed to decode delegate vtxo contract: {e}")))?;
        return Ok(Some(active_offchain_contract(
            manager,
            &stored,
            contract.vtxo(ctx)?,
        )?));
    }

    if stored.contract_type != ContractType::default_vtxo()
        && stored.contract_type != ContractType::boarding()
    {
        return Ok(None);
    }

    let data = two_leaf_vtxo_data(&stored)?;

    // A boarding row can also represent an offchain default VTXO row for the same script, but only
    // when its CSV delay is one of the delays used for unilateral-exit VTXOs. Other boarding rows
    // must not be queried as Arkade receive addresses.
    if stored.contract_type == ContractType::boarding()
        && !unilateral_exit_delay_candidates.contains(&data.exit_delay)
    {
        return Ok(None);
    }

    let contract = DefaultVtxoContract {
        server: data.server,
        owner: data.owner,
        exit_delay: data.exit_delay,
    };
    Ok(Some(active_offchain_contract(
        manager,
        &stored,
        contract.vtxo(ctx)?,
    )?))
}

fn active_offchain_contract(
    manager: &ContractManager,
    stored: &StoredContract,
    vtxo: Vtxo,
) -> Result<ActiveOffchainContract, Error> {
    Ok(ActiveOffchainContract {
        address: vtxo.to_ark_address(),
        vtxo,
        spend_selections: manager.spendable_selections(stored)?,
    })
}

fn offchain_vtxo_data(stored: &StoredContract) -> Result<VtxoContractData, Error> {
    if stored.contract_type == ContractType::delegate_vtxo() {
        return delegate_vtxo_data(stored);
    }
    two_leaf_vtxo_data(stored)
}

fn delegate_vtxo_data(stored: &StoredContract) -> Result<VtxoContractData, Error> {
    if stored.contract_type != ContractType::delegate_vtxo() {
        return Err(Error::ad_hoc(format!(
            "contract type {} is not a delegate vtxo contract",
            stored.contract_type
        )));
    }
    let contract: DelegateVtxoContract = serde_json::from_value(stored.data.clone())
        .map_err(|e| Error::ad_hoc(format!("failed to decode delegate vtxo contract: {e}")))?;
    Ok(VtxoContractData {
        server: contract.server,
        owner: contract.owner,
        exit_delay: contract.exit_delay,
    })
}

/// Decode rows that use the shared two-leaf default VTXO/boarding template.
///
/// Both contract types produce the same spend paths when server, owner and CSV delay match. This
/// helper is the single place that treats them as the same template; callers decide whether that
/// template is being used as an offchain VTXO or as an on-chain boarding output.
fn two_leaf_vtxo_data(stored: &StoredContract) -> Result<VtxoContractData, Error> {
    if stored.contract_type == ContractType::default_vtxo() {
        let contract: DefaultVtxoContract = serde_json::from_value(stored.data.clone())
            .map_err(|e| Error::ad_hoc(format!("failed to decode default vtxo contract: {e}")))?;
        return Ok(VtxoContractData {
            server: contract.server,
            owner: contract.owner,
            exit_delay: contract.exit_delay,
        });
    }
    if stored.contract_type == ContractType::boarding() {
        let contract: BoardingContract = serde_json::from_value(stored.data.clone())
            .map_err(|e| Error::ad_hoc(format!("failed to decode boarding contract: {e}")))?;
        return Ok(VtxoContractData {
            server: contract.server,
            owner: contract.owner,
            exit_delay: contract.exit_delay,
        });
    }
    Err(Error::ad_hoc(format!(
        "contract type {} is not a two-leaf vtxo contract",
        stored.contract_type
    )))
}

/// Resolve a stored row into boarding semantics when safe.
///
/// Real boarding rows always qualify. Default VTXO rows qualify only as a script-sharing fallback
/// and only for the boarding exit-delay candidates supplied by the caller; otherwise every default
/// VTXO row would incorrectly appear as an on-chain boarding address.
fn boarding_contract_from_stored(
    stored: &StoredContract,
    compatible_default_vtxo_exit_delays: &[Sequence],
) -> Option<BoardingContract> {
    let data = two_leaf_vtxo_data(stored).ok()?;

    // A default VTXO row can also represent a boarding row for the same script, but only when the
    // caller is explicitly watching that CSV delay as a boarding delay.
    if stored.contract_type == ContractType::boarding()
        || compatible_default_vtxo_exit_delays.contains(&data.exit_delay)
    {
        return Some(BoardingContract {
            server: data.server,
            owner: data.owner,
            exit_delay: data.exit_delay,
        });
    }

    None
}

fn now_secs() -> Result<u64, Error> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .map_err(|e| Error::ad_hoc(format!("system clock before unix epoch: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use ark_core::contract::SpendPathKind;
    use bitcoin::Amount;
    use bitcoin::OutPoint;
    use bitcoin::Sequence;
    use bitcoin::XOnlyPublicKey;
    use std::str::FromStr;

    fn test_keys() -> (XOnlyPublicKey, XOnlyPublicKey, XOnlyPublicKey) {
        let server = XOnlyPublicKey::from_str(
            "18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166",
        )
        .unwrap();
        let owner = XOnlyPublicKey::from_str(
            "28845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166",
        )
        .unwrap();
        let delegator = XOnlyPublicKey::from_str(
            "38845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166",
        )
        .unwrap();
        (server, owner, delegator)
    }

    #[test]
    fn stores_and_dispatches_default_contract() {
        let (server, owner, _) = test_keys();
        let mut manager = ContractManager::in_memory(Network::Regtest);
        manager.register_builtins().unwrap();

        let contract = DefaultVtxoContract {
            server,
            owner,
            exit_delay: Sequence::from_seconds_ceil(86400).unwrap(),
        };
        let stored = manager
            .insert(contract.clone(), ContractState::Active, Some(7))
            .unwrap();

        assert_eq!(stored.contract_type, ContractType::default_vtxo());
        assert_eq!(stored.key_index, Some(7));
        assert_eq!(
            manager.get(&stored.script_pubkey).unwrap(),
            Some(stored.clone())
        );
        assert_eq!(
            manager
                .get_typed::<DefaultVtxoContract>(&stored.script_pubkey)
                .unwrap(),
            Some(contract)
        );

        let selections = manager.spendable_selections(&stored).unwrap();
        assert_eq!(selections.len(), 2);
        assert!(selections
            .iter()
            .all(|selection| !selection.path.script.is_empty()));
    }

    #[test]
    fn annotates_vtxos_with_contract_spend_paths() {
        let (server, owner, _) = test_keys();
        let mut manager = ContractManager::in_memory(Network::Regtest);
        manager.register_builtins().unwrap();

        let contract = DefaultVtxoContract {
            server,
            owner,
            exit_delay: Sequence::from_seconds_ceil(86400).unwrap(),
        };
        let stored = manager
            .insert(contract, ContractState::Active, Some(7))
            .unwrap();
        let vtxo = VirtualTxOutPoint {
            outpoint: OutPoint::null(),
            created_at: 0,
            expires_at: 0,
            amount: Amount::from_sat(42_000),
            script: stored.script_pubkey.clone(),
            is_preconfirmed: false,
            is_swept: false,
            is_unrolled: false,
            is_spent: false,
            spent_by: None,
            commitment_txids: Vec::new(),
            settled_by: None,
            ark_txid: None,
            assets: Vec::new(),
        };

        let annotated = manager.annotate_vtxos(vec![vtxo.clone()]).unwrap();

        assert_eq!(annotated.len(), 1);
        assert_eq!(annotated[0].contract, stored);
        assert_eq!(annotated[0].vtxo, vtxo);
        assert_eq!(annotated[0].spend_selections.len(), 2);
    }

    #[test]
    fn annotates_boarding_outputs_with_contract_spend_paths() {
        let (server, owner, _) = test_keys();
        let mut manager = ContractManager::in_memory(Network::Regtest);
        manager.register_builtins().unwrap();

        let contract = BoardingContract {
            server,
            owner,
            exit_delay: Sequence::from_seconds_ceil(86400).unwrap(),
        };
        let stored = manager
            .insert(contract, ContractState::Active, Some(7))
            .unwrap();

        let annotated = manager.annotated_boarding_outputs().unwrap();

        assert_eq!(annotated.len(), 1);
        assert_eq!(annotated[0].contract, stored);
        assert_eq!(annotated[0].script_pubkey(), stored.script_pubkey);
        assert_eq!(annotated[0].server_pk(), server);
        assert_eq!(annotated[0].owner_pk(), owner);
        assert_eq!(annotated[0].spend_selections.len(), 2);
        assert!(annotated[0].spend_selection(SpendPathKind::Forfeit).is_ok());
        assert!(annotated[0].spend_selection(SpendPathKind::Exit).is_ok());
    }

    #[test]
    fn default_vtxo_and_boarding_can_share_script_row() {
        let (server, owner, _) = test_keys();
        let mut manager = ContractManager::in_memory(Network::Regtest);
        manager.register_builtins().unwrap();
        let exit_delay = Sequence::from_seconds_ceil(86400).unwrap();

        let default = DefaultVtxoContract {
            server,
            owner,
            exit_delay,
        };
        let boarding = BoardingContract {
            server,
            owner,
            exit_delay,
        };

        let stored_default = manager
            .insert_or_get(default, ContractState::Active, Some(7))
            .unwrap();
        let stored_boarding = manager
            .insert_or_get(boarding, ContractState::Active, Some(7))
            .unwrap();

        assert_eq!(stored_boarding, stored_default);
        assert_eq!(stored_default.contract_type, ContractType::default_vtxo());
        assert_eq!(manager.list().unwrap().len(), 1);

        let boarding_outputs = manager
            .annotated_boarding_outputs_for_exit_delays(&[exit_delay])
            .unwrap();
        assert_eq!(boarding_outputs.len(), 1);
        assert_eq!(boarding_outputs[0].contract, stored_default);
        assert_eq!(boarding_outputs[0].server_pk(), server);
        assert_eq!(boarding_outputs[0].owner_pk(), owner);
    }

    #[test]
    fn malformed_builtin_contract_fails_vtxo_annotation() {
        let (server, owner, _) = test_keys();
        let ctx = ContractContext::new(Network::Regtest);
        let script_pubkey = DefaultVtxoContract {
            server,
            owner,
            exit_delay: Sequence::from_height(10),
        }
        .script_pubkey(&ctx)
        .unwrap();
        let mut store = MemoryContractStore::default();
        let stored = StoredContract {
            contract_type: ContractType::default_vtxo(),
            contract_version: DefaultVtxoContract::VERSION,
            script_pubkey,
            state: ContractState::Active,
            created_at: 0,
            key_index: None,
            data: serde_json::json!({"bad": "shape"}),
        };
        store.insert(stored.clone()).unwrap();
        let mut manager = ContractManager::new(Network::Regtest, Box::new(store));
        manager.register_builtins().unwrap();
        let vtxo = VirtualTxOutPoint {
            outpoint: OutPoint::null(),
            created_at: 0,
            expires_at: 0,
            amount: Amount::from_sat(42_000),
            script: stored.script_pubkey,
            is_preconfirmed: false,
            is_swept: false,
            is_unrolled: false,
            is_spent: false,
            spent_by: None,
            commitment_txids: Vec::new(),
            settled_by: None,
            ark_txid: None,
            assets: Vec::new(),
        };

        let err = manager.annotate_vtxos(vec![vtxo]).unwrap_err();

        assert!(
            format!("{err:?}").contains("failed to decode contract data"),
            "{err:?}"
        );
    }

    #[test]
    fn boarding_contract_can_annotate_offchain_vtxo() {
        let (server, owner, _) = test_keys();
        let mut manager = ContractManager::in_memory(Network::Regtest);
        manager.register_builtins().unwrap();
        let exit_delay = Sequence::from_seconds_ceil(86400).unwrap();

        let stored = manager
            .insert_or_get(
                BoardingContract {
                    server,
                    owner,
                    exit_delay,
                },
                ContractState::Active,
                Some(7),
            )
            .unwrap();
        let vtxo = VirtualTxOutPoint {
            outpoint: OutPoint::null(),
            created_at: 0,
            expires_at: 0,
            amount: Amount::from_sat(42_000),
            script: stored.script_pubkey.clone(),
            is_preconfirmed: false,
            is_swept: false,
            is_unrolled: false,
            is_spent: false,
            spent_by: None,
            commitment_txids: Vec::new(),
            settled_by: None,
            ark_txid: None,
            assets: Vec::new(),
        };

        let annotated = manager.annotate_vtxos(vec![vtxo]).unwrap();

        assert_eq!(annotated.len(), 1);
        assert_eq!(annotated[0].contract, stored);
        assert_eq!(annotated[0].server_pk().unwrap(), server);
        assert_eq!(annotated[0].owner_pk().unwrap(), owner);
        assert_eq!(annotated[0].exit_delay().unwrap(), exit_delay);
    }

    #[cfg(feature = "sqlite")]
    #[test]
    fn sqlite_store_persists_contracts() {
        let (server, owner, _) = test_keys();
        let tempdir = tempfile::tempdir().unwrap();
        let db_path = tempdir.path().join("contracts.db");
        let mut manager = ContractManager::new(
            Network::Regtest,
            Box::new(SqliteContractStore::new(&db_path).unwrap()),
        );
        manager.register_builtins().unwrap();

        let contract = DefaultVtxoContract {
            server,
            owner,
            exit_delay: Sequence::from_seconds_ceil(86400).unwrap(),
        };
        let stored = manager
            .insert(contract, ContractState::Active, Some(7))
            .unwrap();
        manager
            .update_state(&stored.script_pubkey, ContractState::Inactive)
            .unwrap();

        let mut reopened = ContractManager::new(
            Network::Regtest,
            Box::new(SqliteContractStore::new(&db_path).unwrap()),
        );
        reopened.register_builtins().unwrap();

        let persisted = reopened.get(&stored.script_pubkey).unwrap().unwrap();
        assert_eq!(persisted.state, ContractState::Inactive);
        assert_eq!(persisted.contract_type, ContractType::default_vtxo());
        assert_eq!(persisted.key_index, Some(7));
        assert_eq!(persisted.data, stored.data);
        assert_eq!(reopened.list().unwrap().len(), 1);
    }

    #[test]
    fn store_enforces_script_uniqueness() {
        let (server, owner, _) = test_keys();
        let mut manager = ContractManager::in_memory(Network::Regtest);
        manager.register_builtins().unwrap();
        let contract = DefaultVtxoContract {
            server,
            owner,
            exit_delay: Sequence::from_seconds_ceil(86400).unwrap(),
        };

        manager
            .insert(contract.clone(), ContractState::Active, None)
            .unwrap();
        assert!(manager
            .insert(contract, ContractState::Active, None)
            .is_err());
    }

    #[test]
    fn validates_script_mismatch() {
        let (server, owner, delegator) = test_keys();
        let mut manager = ContractManager::in_memory(Network::Regtest);
        manager.register_builtins().unwrap();
        let default = DefaultVtxoContract {
            server,
            owner,
            exit_delay: Sequence::from_seconds_ceil(86400).unwrap(),
        };
        let delegate = DelegateVtxoContract {
            server,
            owner,
            delegator,
            exit_delay: Sequence::from_seconds_ceil(86400).unwrap(),
        };
        let ctx = ContractContext::new(Network::Regtest);
        let stored = StoredContract {
            contract_type: ContractType::default_vtxo(),
            contract_version: DefaultVtxoContract::VERSION,
            script_pubkey: delegate.script_pubkey(&ctx).unwrap(),
            state: ContractState::Active,
            created_at: 0,
            key_index: None,
            data: serde_json::to_value(default).unwrap(),
        };

        assert!(manager.insert_stored(stored).is_err());
    }
}