bsv-wallet-toolbox 0.2.23

Pure Rust BSV wallet-toolbox implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
//! Wallet struct implementing the full WalletInterface trait.
//!
//! This is the core deliverable of Phase 5: a complete WalletInterface implementation
//! that wires together the signer, storage, and ProtoWallet subsystems. Every method
//! follows the validate-delegate-postprocess pattern from the TS reference.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;

use bsv::primitives::public_key::PublicKey;
use bsv::services::overlay_tools::LookupResolver;
use bsv::transaction::beef_party::BeefParty;
use bsv::wallet::cached_key_deriver::CachedKeyDeriver;
use bsv::wallet::error::WalletError as SdkWalletError;
use bsv::wallet::interfaces::{
    AbortActionArgs, AbortActionResult, AcquireCertificateArgs, AcquisitionProtocol,
    AuthenticatedResult, Certificate, CreateActionArgs, CreateActionOptions, CreateActionResult,
    CreateHmacArgs, CreateHmacResult, CreateSignatureArgs, CreateSignatureResult, DecryptArgs,
    DecryptResult, DiscoverByAttributesArgs, DiscoverByIdentityKeyArgs, DiscoverCertificatesResult,
    EncryptArgs, EncryptResult, GetHeaderArgs, GetHeaderResult, GetHeightResult, GetNetworkResult,
    GetPublicKeyArgs, GetPublicKeyResult, GetVersionResult, InternalizeActionArgs,
    InternalizeActionResult, ListActionsArgs, ListActionsResult, ListCertificatesArgs,
    ListCertificatesResult, ListOutputsArgs, ListOutputsResult, Network, ProveCertificateArgs,
    ProveCertificateResult, RelinquishCertificateArgs, RelinquishCertificateResult,
    RelinquishOutputArgs, RelinquishOutputResult, RevealCounterpartyKeyLinkageArgs,
    RevealCounterpartyKeyLinkageResult, RevealSpecificKeyLinkageArgs,
    RevealSpecificKeyLinkageResult, SignActionArgs, SignActionResult, TrustSelf, VerifyHmacArgs,
    VerifyHmacResult, VerifySignatureArgs, VerifySignatureResult, WalletInterface,
};
use bsv::wallet::proto_wallet::ProtoWallet;

use crate::wallet::discovery::OverlayCache;

use crate::error::WalletError;
use crate::services::traits::WalletServices;
use crate::signer::default_signer::DefaultWalletSigner;
use crate::signer::traits::WalletSigner;
use crate::storage::manager::WalletStorageManager;
use crate::types::Chain;
use crate::wallet::privileged::PrivilegedKeyManager;
use crate::wallet::settings::WalletSettingsManager;
use crate::wallet::types::{
    AdminStatsResult, AuthId, KeyPair, PendingSignAction, StorageIdentity, UtxoInfo, WalletArgs,
    WalletBalance, SPEC_OP_FAILED_ACTIONS, SPEC_OP_INVALID_CHANGE, SPEC_OP_NO_SEND_ACTIONS,
    SPEC_OP_SET_WALLET_CHANGE_PARAMS, SPEC_OP_WALLET_BALANCE,
};
use crate::wallet::validation::validate_originator;

// ---------------------------------------------------------------------------
// Wallet struct
// ---------------------------------------------------------------------------

/// The core Wallet implementing all 28 WalletInterface methods.
///
/// Delegates crypto operations to ProtoWallet (or PrivilegedKeyManager),
/// action operations to DefaultWalletSigner, and query operations to
/// WalletStorageManager.
///
/// # Example
///
/// ```no_run
/// use bsv::primitives::private_key::PrivateKey;
/// use bsv_wallet_toolbox::wallet::setup::WalletBuilder;
/// use bsv_wallet_toolbox::types::Chain;
///
/// # async fn example() -> bsv_wallet_toolbox::WalletResult<()> {
/// let root_key = PrivateKey::from_hex("aa").unwrap();
/// let setup = WalletBuilder::new()
///     .chain(Chain::Test)
///     .root_key(root_key)
///     .with_sqlite_memory()
///     .build()
///     .await?;
///
/// // Use the wallet for operations
/// let wallet = setup.wallet;
/// # Ok(())
/// # }
/// ```
pub struct Wallet {
    /// BSV network chain this wallet operates on.
    pub chain: Chain,
    /// Key deriver for BRC-42/BRC-43 child key derivation.
    pub key_deriver: Arc<CachedKeyDeriver>,
    /// Storage manager providing persistence operations.
    pub storage: Arc<WalletStorageManager>,
    /// Optional network services (broadcasting, chain lookups, etc.).
    pub services: Option<Arc<dyn WalletServices>>,
    /// Optional background monitor for transaction lifecycle.
    pub monitor: Option<Arc<crate::monitor::Monitor>>,
    /// Optional privileged key manager for sensitive crypto operations.
    pub privileged_key_manager: Option<Arc<dyn PrivilegedKeyManager>>,
    /// Settings manager with cached TTL for wallet configuration.
    pub settings_manager: WalletSettingsManager,
    /// Public identity key derived from the root private key.
    pub identity_key: PublicKey,
    /// Protocol wallet providing default WalletInterface implementations.
    pub proto: ProtoWallet,

    // BeefParty state
    beef: tokio::sync::Mutex<BeefParty>,
    /// Whether to include all source transactions in BEEF output.
    pub include_all_source_transactions: bool,
    /// Whether to automatically add known txids from storage.
    pub auto_known_txids: bool,
    /// Whether to return only the txid without full BEEF data.
    pub return_txid_only: bool,
    /// Self-trust configuration for signed operations.
    pub trust_self: Option<TrustSelf>,
    // Stored for future BEEF-party operations; currently only referenced at
    // construction time via `BeefParty::new(...)`. Kept to preserve the
    // identity used to construct `beef` so later operations can rebind it.
    #[allow(dead_code)]
    user_party: String,

    /// In-memory pending sign actions awaiting deferred signing.
    pub pending_sign_actions: tokio::sync::Mutex<HashMap<String, PendingSignAction>>,

    // Overlay discovery cache
    overlay_cache: OverlayCache,
    /// Optional overlay lookup resolver for identity certificate discovery.
    pub lookup_resolver: Option<Arc<LookupResolver>>,

    /// Test hook: pre-determined random values for deterministic testing.
    pub random_vals: Option<Vec<f64>>,

    // Internal signer
    signer: DefaultWalletSigner,
}

// ---------------------------------------------------------------------------
// Constructor and helpers
// ---------------------------------------------------------------------------

impl Wallet {
    /// Create a new Wallet from WalletArgs.
    ///
    /// Validates that the key deriver's identity key matches the storage auth ID.
    pub fn new(args: WalletArgs) -> Result<Self, WalletError> {
        // Validate identity key match
        let identity_key = args.key_deriver.identity_key();
        let identity_key_hex = identity_key.to_der_hex();
        let storage_auth_id = args.storage.auth_id().to_string();
        if identity_key_hex != storage_auth_id {
            return Err(WalletError::InvalidParameter {
                parameter: "key_deriver".to_string(),
                must_be: format!(
                    "consistent with storage auth_id. key_deriver identity_key={} but storage auth_id={}",
                    identity_key_hex, storage_auth_id
                ),
            });
        }

        // Create ProtoWallet from key_deriver's root key
        let root_key = args.key_deriver.root_key().clone();
        let proto = ProtoWallet::new(root_key);

        // Derive user_party
        let root_pub_hex = args.key_deriver.root_key().to_public_key().to_der_hex();
        let user_party = format!("user {}", root_pub_hex);

        // Initialize BeefParty
        let beef = BeefParty::new([user_party.clone()]);

        // Wire services into signer
        let services_for_signer = args.services.clone().ok_or_else(|| {
            WalletError::InvalidOperation(
                "WalletServices required for Wallet construction".to_string(),
            )
        })?;

        // Signer shares the same Arc<WalletStorageManager> as the wallet
        let signer = DefaultWalletSigner::new(
            args.storage.clone(),
            services_for_signer,
            args.key_deriver.clone(),
            args.chain.clone(),
            identity_key.clone(),
        );

        // Settings manager: use provided or create default
        let settings_manager = args.settings_manager.unwrap_or_else(|| {
            // Use the initial active provider for the settings cache.
            // The wallet always requires at least one provider.
            let active_provider = args
                .storage
                .active()
                .cloned()
                .expect("WalletStorageManager must have at least one storage provider");
            WalletSettingsManager::new(active_provider)
        });

        Ok(Wallet {
            chain: args.chain,
            key_deriver: args.key_deriver,
            storage: args.storage,
            services: args.services,
            monitor: args.monitor,
            privileged_key_manager: args.privileged_key_manager,
            settings_manager,
            identity_key,
            proto,
            beef: tokio::sync::Mutex::new(beef),
            include_all_source_transactions: true,
            auto_known_txids: false,
            return_txid_only: false,
            trust_self: Some(TrustSelf::Known),
            user_party,
            pending_sign_actions: tokio::sync::Mutex::new(HashMap::new()),
            overlay_cache: OverlayCache::new(),
            lookup_resolver: args.lookup_resolver,
            random_vals: None,
            signer,
        })
    }

    /// Returns the AuthId for this wallet.
    fn auth_id(&self) -> AuthId {
        AuthId {
            identity_key: self.identity_key.to_der_hex(),
            user_id: None,
            is_active: None,
        }
    }

    /// Validates the originator parameter.
    fn validate_originator(&self, originator: Option<&str>) -> Result<(), WalletError> {
        validate_originator(originator)
    }

    /// Returns a reference to the wallet services, or an error if not configured.
    fn get_services(&self) -> Result<&Arc<dyn WalletServices>, WalletError> {
        self.services.as_ref().ok_or_else(|| {
            WalletError::InvalidOperation("Wallet services not configured".to_string())
        })
    }

    /// Returns the client change key pair (root private + public key).
    pub fn get_client_change_key_pair(&self) -> KeyPair {
        let root = self.key_deriver.root_key();
        KeyPair {
            private_key: root.to_hex(),
            public_key: root.to_public_key().to_der_hex(),
        }
    }

    /// Returns the storage identity for this wallet.
    ///
    /// Returns the active store's storage_identity_key if available (after
    /// make_available), otherwise falls back to the wallet's identity key.
    pub async fn get_storage_identity(&self) -> StorageIdentity {
        let key = self
            .storage
            .get_storage_identity_key()
            .await
            .unwrap_or_else(|_| self.identity_key.to_der_hex());
        StorageIdentity {
            storage_identity_key: key,
            storage_name: "default".to_string(),
        }
    }

    /// Returns the storage party string.
    pub async fn storage_party(&self) -> String {
        let si = self.get_storage_identity().await;
        format!("storage {}", si.storage_identity_key)
    }

    /// Returns the identity key as a hex string.
    pub async fn get_identity_key(&self) -> Result<String, SdkWalletError> {
        let result = self
            .get_public_key(
                GetPublicKeyArgs {
                    identity_key: true,
                    protocol_id: None,
                    key_id: None,
                    counterparty: None,
                    privileged: false,
                    privileged_reason: None,
                    for_self: None,
                    seek_permission: None,
                },
                None,
            )
            .await?;
        Ok(result.public_key.to_der_hex())
    }

    /// Destroy the wallet: destroys storage and privileged key manager if present.
    pub async fn destroy(&self) -> Result<(), WalletError> {
        self.storage.destroy().await?;
        if let Some(ref pkm) = self.privileged_key_manager {
            pkm.destroy_key().await.map_err(|e| {
                WalletError::Internal(format!("Failed to destroy privileged key: {}", e))
            })?;
        }
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Convenience methods (Phase 7)
    // -----------------------------------------------------------------------

    /// Returns the total spendable balance in satoshis.
    ///
    /// Routes through the specOp WalletBalance basket to sum all spendable
    /// outputs. If `args` is provided with a non-specOp basket, the specOp
    /// constant is pushed to tags to combine basket filtering with balance.
    pub async fn balance(&self, args: Option<ListOutputsArgs>) -> Result<u64, WalletError> {
        let args = match args {
            Some(mut a) => {
                if a.basket != SPEC_OP_WALLET_BALANCE {
                    a.tags.push(SPEC_OP_WALLET_BALANCE.to_string());
                }
                a
            }
            None => ListOutputsArgs {
                basket: SPEC_OP_WALLET_BALANCE.to_string(),
                tags: vec![],
                tag_query_mode: None,
                include: None,
                include_custom_instructions: Default::default(),
                include_tags: Default::default(),
                include_labels: Default::default(),
                limit: None,
                offset: None,
                seek_permission: Default::default(),
            },
        };

        let r = self
            .list_outputs(args, None)
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))?;
        Ok(r.total_outputs as u64)
    }

    /// Returns the total spendable balance plus individual UTXO details.
    ///
    /// Similar to `balance()` but also collects per-output information.
    pub async fn balance_and_utxos(
        &self,
        args: Option<ListOutputsArgs>,
    ) -> Result<WalletBalance, WalletError> {
        let args = match args {
            Some(mut a) => {
                if a.basket != SPEC_OP_WALLET_BALANCE {
                    a.tags.push(SPEC_OP_WALLET_BALANCE.to_string());
                }
                a
            }
            None => ListOutputsArgs {
                basket: SPEC_OP_WALLET_BALANCE.to_string(),
                tags: vec![],
                tag_query_mode: None,
                include: None,
                include_custom_instructions: Default::default(),
                include_tags: Default::default(),
                include_labels: Default::default(),
                limit: None,
                offset: None,
                seek_permission: Default::default(),
            },
        };

        let r = self
            .list_outputs(args, None)
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))?;

        let utxos: Vec<UtxoInfo> = r
            .outputs
            .iter()
            .map(|o| UtxoInfo {
                satoshis: o.satoshis,
                outpoint: o.outpoint.clone(),
            })
            .collect();

        Ok(WalletBalance {
            total: r.total_outputs as u64,
            utxos,
        })
    }

    /// Transfer all wallet funds to another wallet using BRC-29 payment.
    ///
    /// Creates a sweep transaction sending MAX_POSSIBLE_SATOSHIS to the
    /// receiving wallet via createAction + internalizeAction.
    pub async fn sweep_to(&self, to_wallet: &Wallet) -> Result<(), WalletError> {
        use crate::storage::methods::generate_change::MAX_POSSIBLE_SATOSHIS;
        use crate::utility::script_template_brc29::ScriptTemplateBRC29;

        // Generate random derivation prefix and suffix
        let derivation_prefix = random_base64(8);
        let derivation_suffix = random_base64(8);

        let template =
            ScriptTemplateBRC29::new(derivation_prefix.clone(), derivation_suffix.clone());

        // Lock with sender's private key to receiver's public key
        let sender_priv = self.key_deriver.root_key().clone();
        let receiver_pub = to_wallet.identity_key.clone();
        let lock_script = template.lock(&sender_priv, &receiver_pub)?;

        let custom_instructions = serde_json::json!({
            "derivationPrefix": derivation_prefix,
            "derivationSuffix": derivation_suffix,
            "type": "BRC29"
        })
        .to_string();

        let car = self
            .create_action(
                CreateActionArgs {
                    description: "sweep".to_string(),
                    input_beef: None,
                    inputs: vec![],
                    outputs: vec![bsv::wallet::interfaces::CreateActionOutput {
                        locking_script: Some(lock_script),
                        satoshis: MAX_POSSIBLE_SATOSHIS,
                        output_description: "sweep".to_string(),
                        basket: None,
                        custom_instructions: Some(custom_instructions),
                        tags: vec!["relinquish".to_string()],
                    }],
                    lock_time: None,
                    version: None,
                    labels: vec!["sweep".to_string()],
                    options: Some(CreateActionOptions {
                        randomize_outputs: bsv::wallet::types::BooleanDefaultTrue(Some(false)),
                        accept_delayed_broadcast: bsv::wallet::types::BooleanDefaultTrue(Some(
                            false,
                        )),
                        ..Default::default()
                    }),
                    reference: None,
                },
                None,
            )
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))?;

        let tx = car.tx.ok_or_else(|| {
            WalletError::Internal("sweep createAction returned no tx".to_string())
        })?;

        // Internalize on receiving wallet
        to_wallet
            .internalize_action(
                InternalizeActionArgs {
                    tx,
                    description: "sweep".to_string(),
                    labels: vec!["sweep".to_string()],
                    seek_permission: bsv::wallet::types::BooleanDefaultTrue(Some(false)),
                    outputs: vec![bsv::wallet::interfaces::InternalizeOutput::WalletPayment {
                        output_index: 0,
                        payment: bsv::wallet::interfaces::Payment {
                            derivation_prefix: derivation_prefix.into_bytes(),
                            derivation_suffix: derivation_suffix.into_bytes(),
                            sender_identity_key: self.identity_key.clone(),
                        },
                    }],
                },
                None,
            )
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))?;

        Ok(())
    }

    /// Check UTXOs against the network and identify invalid/unspendable outputs.
    ///
    /// If `release` is true, locked invalid outputs are released.
    /// If `all` is true, all outputs are checked (not just change).
    pub async fn review_spendable_outputs(
        &self,
        release: bool,
        all: bool,
    ) -> Result<ListOutputsResult, WalletError> {
        let mut tags = Vec::new();
        if release {
            tags.push("release".to_string());
        }
        if all {
            tags.push("all".to_string());
        }

        let args = ListOutputsArgs {
            basket: SPEC_OP_INVALID_CHANGE.to_string(),
            tags,
            tag_query_mode: None,
            include: None,
            include_custom_instructions: Default::default(),
            include_tags: Default::default(),
            include_labels: Default::default(),
            limit: None,
            offset: None,
            seek_permission: Default::default(),
        };

        self.list_outputs(args, None)
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))
    }

    /// Configure the number and size of change outputs for the default basket.
    ///
    /// Parameters are passed via specOp tags to list_outputs.
    pub async fn set_wallet_change_params(
        &self,
        count: u32,
        satoshis: u64,
    ) -> Result<(), WalletError> {
        let args = ListOutputsArgs {
            basket: SPEC_OP_SET_WALLET_CHANGE_PARAMS.to_string(),
            tags: vec![count.to_string(), satoshis.to_string()],
            tag_query_mode: None,
            include: None,
            include_custom_instructions: Default::default(),
            include_tags: Default::default(),
            include_labels: Default::default(),
            limit: None,
            offset: None,
            seek_permission: Default::default(),
        };

        let _ = self
            .list_outputs(args, None)
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))?;
        Ok(())
    }

    /// List all no-send (un-broadcast) actions.
    ///
    /// If `abort` is true, each matched action is aborted after querying.
    pub async fn list_no_send_actions(
        &self,
        abort: bool,
    ) -> Result<ListActionsResult, WalletError> {
        let mut labels = vec![SPEC_OP_NO_SEND_ACTIONS.to_string()];
        if abort {
            labels.push("abort".to_string());
        }

        let args = ListActionsArgs {
            labels,
            label_query_mode: None,
            include_labels: Default::default(),
            include_inputs: Default::default(),
            include_input_source_locking_scripts: Default::default(),
            include_input_unlocking_scripts: Default::default(),
            include_outputs: Default::default(),
            include_output_locking_scripts: Default::default(),
            limit: None,
            offset: None,
            seek_permission: Default::default(),
        };

        self.list_actions(args, None)
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))
    }

    /// List all failed actions.
    ///
    /// If `unfail` is true, each matched action is reset to unprocessed for retry.
    pub async fn list_failed_actions(
        &self,
        unfail: bool,
    ) -> Result<ListActionsResult, WalletError> {
        let mut labels = vec![SPEC_OP_FAILED_ACTIONS.to_string()];
        if unfail {
            labels.push("unfail".to_string());
        }

        let args = ListActionsArgs {
            labels,
            label_query_mode: None,
            include_labels: Default::default(),
            include_inputs: Default::default(),
            include_input_source_locking_scripts: Default::default(),
            include_input_unlocking_scripts: Default::default(),
            include_outputs: Default::default(),
            include_output_locking_scripts: Default::default(),
            limit: None,
            offset: None,
            seek_permission: Default::default(),
        };

        self.list_actions(args, None)
            .await
            .map_err(|e| WalletError::Internal(e.to_string()))
    }

    /// Returns aggregate deployment statistics from storage.
    ///
    /// Delegates to the storage manager's admin_stats method.
    pub async fn admin_stats(&self) -> Result<AdminStatsResult, WalletError> {
        let identity_key_hex = self.identity_key.to_der_hex();
        self.storage.admin_stats(&identity_key_hex).await
    }
}

/// Generate a random base64-encoded string from `n` random bytes.
fn random_base64(n: usize) -> String {
    use base64::Engine;
    use rand::RngCore;
    let mut buf = vec![0u8; n];
    rand::thread_rng().fill_bytes(&mut buf);
    base64::engine::general_purpose::STANDARD.encode(&buf)
}

// ---------------------------------------------------------------------------
// Error conversion: crate::error::WalletError -> bsv::wallet::error::WalletError
// ---------------------------------------------------------------------------

fn to_sdk_error(e: WalletError) -> SdkWalletError {
    match e {
        WalletError::InvalidParameter { parameter, must_be } => SdkWalletError::InvalidParameter(
            format!("The {} parameter must be {}", parameter, must_be),
        ),
        WalletError::NotImplemented(msg) => SdkWalletError::NotImplemented(msg),
        WalletError::InvalidOperation(msg) => SdkWalletError::Internal(msg),
        _ => SdkWalletError::Internal(e.to_string()),
    }
}

// ---------------------------------------------------------------------------
// WalletInterface implementation
// ---------------------------------------------------------------------------

#[async_trait]
impl WalletInterface for Wallet {
    // -----------------------------------------------------------------------
    // CRYPTO methods (9) -- delegate to ProtoWallet or PrivilegedKeyManager
    // -----------------------------------------------------------------------

    async fn get_public_key(
        &self,
        args: GetPublicKeyArgs,
        originator: Option<&str>,
    ) -> Result<GetPublicKeyResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_get_public_key_args(&args)?;

        if args.privileged {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.get_public_key(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto.get_public_key(args, originator).await
    }

    async fn encrypt(
        &self,
        args: EncryptArgs,
        originator: Option<&str>,
    ) -> Result<EncryptResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_encrypt_args(&args)?;

        if args.privileged {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.encrypt(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto.encrypt(args, originator).await
    }

    async fn decrypt(
        &self,
        args: DecryptArgs,
        originator: Option<&str>,
    ) -> Result<DecryptResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_decrypt_args(&args)?;

        if args.privileged {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.decrypt(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto.decrypt(args, originator).await
    }

    async fn create_hmac(
        &self,
        args: CreateHmacArgs,
        originator: Option<&str>,
    ) -> Result<CreateHmacResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_create_hmac_args(&args)?;

        if args.privileged {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.create_hmac(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto.create_hmac(args, originator).await
    }

    async fn verify_hmac(
        &self,
        args: VerifyHmacArgs,
        originator: Option<&str>,
    ) -> Result<VerifyHmacResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_verify_hmac_args(&args)?;

        if args.privileged {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.verify_hmac(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto.verify_hmac(args, originator).await
    }

    async fn create_signature(
        &self,
        args: CreateSignatureArgs,
        originator: Option<&str>,
    ) -> Result<CreateSignatureResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_create_signature_args(&args)?;

        if args.privileged {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.create_signature(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto.create_signature(args, originator).await
    }

    async fn verify_signature(
        &self,
        args: VerifySignatureArgs,
        originator: Option<&str>,
    ) -> Result<VerifySignatureResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_verify_signature_args(&args)?;

        if args.privileged {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.verify_signature(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto.verify_signature(args, originator).await
    }

    async fn reveal_counterparty_key_linkage(
        &self,
        args: RevealCounterpartyKeyLinkageArgs,
        originator: Option<&str>,
    ) -> Result<RevealCounterpartyKeyLinkageResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_reveal_counterparty_key_linkage_args(&args)?;

        if args.privileged.unwrap_or(false) {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.reveal_counterparty_key_linkage(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto
            .reveal_counterparty_key_linkage(args, originator)
            .await
    }

    async fn reveal_specific_key_linkage(
        &self,
        args: RevealSpecificKeyLinkageArgs,
        originator: Option<&str>,
    ) -> Result<RevealSpecificKeyLinkageResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_reveal_specific_key_linkage_args(&args)?;

        if args.privileged.unwrap_or(false) {
            if let Some(ref pkm) = self.privileged_key_manager {
                return pkm.reveal_specific_key_linkage(args).await;
            }
            return Err(SdkWalletError::Internal(
                "No privileged key manager configured".to_string(),
            ));
        }
        self.proto
            .reveal_specific_key_linkage(args, originator)
            .await
    }

    // -----------------------------------------------------------------------
    // INFO methods (6)
    // -----------------------------------------------------------------------

    async fn is_authenticated(
        &self,
        originator: Option<&str>,
    ) -> Result<AuthenticatedResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        Ok(AuthenticatedResult {
            authenticated: true,
        })
    }

    async fn wait_for_authentication(
        &self,
        originator: Option<&str>,
    ) -> Result<AuthenticatedResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        Ok(AuthenticatedResult {
            authenticated: true,
        })
    }

    async fn get_height(
        &self,
        originator: Option<&str>,
    ) -> Result<GetHeightResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        let services = self.get_services().map_err(to_sdk_error)?;
        let height = services
            .get_height()
            .await
            .map_err(|e| SdkWalletError::Internal(e.to_string()))?;
        Ok(GetHeightResult { height })
    }

    async fn get_header_for_height(
        &self,
        args: GetHeaderArgs,
        originator: Option<&str>,
    ) -> Result<GetHeaderResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_get_header_args(&args)?;
        let services = self.get_services().map_err(to_sdk_error)?;
        let header = services
            .get_header_for_height(args.height)
            .await
            .map_err(|e| SdkWalletError::Internal(e.to_string()))?;
        Ok(GetHeaderResult { header })
    }

    async fn get_network(
        &self,
        originator: Option<&str>,
    ) -> Result<GetNetworkResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        let network = match self.chain {
            Chain::Main => Network::Mainnet,
            Chain::Test => Network::Testnet,
        };
        Ok(GetNetworkResult { network })
    }

    async fn get_version(
        &self,
        originator: Option<&str>,
    ) -> Result<GetVersionResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        Ok(GetVersionResult {
            version: "wallet-brc100-1.0.0".to_string(),
        })
    }

    // -----------------------------------------------------------------------
    // ACTION methods (4) -- delegate to signer
    // -----------------------------------------------------------------------

    async fn create_action(
        &self,
        args: CreateActionArgs,
        originator: Option<&str>,
    ) -> Result<CreateActionResult, SdkWalletError> {
        let _spend_guard = self
            .storage
            .acquire_spend_lock()
            .await
            .map_err(to_sdk_error)?;
        tracing::debug!(description = %args.description, "createAction starting");
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_create_action_args(&args)?;

        // Merge wallet defaults into options
        let mut options = args.options.clone().unwrap_or_default();

        // Merge trust_self from wallet defaults if not set
        if options.trust_self.is_none() {
            options.trust_self = self.trust_self.clone();
        }

        // Merge auto_known_txids: add wallet's BeefParty known txids
        if self.auto_known_txids {
            let mut beef_lock = self.beef.lock().await;
            let known = crate::wallet::beef_helpers::get_known_txids(
                &mut beef_lock,
                Some(&options.known_txids),
            );
            options.known_txids = known;
        }

        // Build validated args for signer
        let sign_and_process = *options.sign_and_process;
        let no_send = *options.no_send;
        let accept_delayed = *options.accept_delayed_broadcast;

        let valid_args = crate::signer::types::ValidCreateActionArgs {
            description: args.description,
            inputs: args
                .inputs
                .iter()
                .map(|input| {
                    let parts: Vec<&str> = input.outpoint.rsplitn(2, '.').collect();
                    let (vout_str, txid_str) = if parts.len() == 2 {
                        (parts[0], parts[1])
                    } else {
                        ("0", input.outpoint.as_str())
                    };
                    crate::signer::types::ValidCreateActionInput {
                        outpoint: crate::signer::types::OutpointInfo {
                            txid: txid_str.to_string(),
                            vout: vout_str.parse().unwrap_or(0),
                        },
                        input_description: input.input_description.clone(),
                        unlocking_script: input.unlocking_script.clone(),
                        unlocking_script_length: input.unlocking_script_length.unwrap_or(0)
                            as usize,
                        sequence_number: input.sequence_number.unwrap_or(0xffffffff),
                    }
                })
                .collect(),
            outputs: args.outputs,
            lock_time: args.lock_time.unwrap_or(0),
            version: args.version.unwrap_or(1),
            labels: args.labels,
            options: options.clone(),
            input_beef: args.input_beef,
            is_new_tx: true,
            is_sign_action: !sign_and_process,
            is_no_send: no_send,
            is_delayed: accept_delayed,
            is_send_with: !options.send_with.is_empty(),
        };

        let signer_result = self
            .signer
            .create_action(valid_args)
            .await
            .map_err(to_sdk_error)?;

        // Convert signer result to SDK result
        let mut result = CreateActionResult {
            txid: signer_result.txid,
            tx: signer_result.tx,
            no_send_change: signer_result.no_send_change,
            send_with_results: signer_result.send_with_results,
            signable_transaction: signer_result.signable_transaction.map(|st| {
                bsv::wallet::interfaces::SignableTransaction {
                    reference: st.reference.into_bytes(),
                    tx: st.tx,
                }
            }),
        };

        // Merge result beef into BeefParty
        if let Some(ref tx_bytes) = result.tx {
            let mut beef_lock = self.beef.lock().await;
            if let Ok(beef) =
                bsv::transaction::beef::Beef::from_binary(&mut std::io::Cursor::new(tx_bytes))
            {
                if let Err(e) = beef_lock.beef.merge_beef(&beef) {
                    tracing::warn!("BeefParty merge failed: {e}");
                }
            }
        }

        // Verify returned txid-only if applicable
        if let Some(ref mut tx_bytes) = result.tx {
            let beef_lock = self.beef.lock().await;
            let verified = crate::wallet::beef_helpers::verify_returned_txid_only_atomic_beef(
                tx_bytes,
                &beef_lock,
                self.return_txid_only,
                None,
            )?;
            *tx_bytes = verified;
        }

        // Check for unsuccessful results
        crate::wallet::error_helpers::throw_if_any_unsuccessful_create_actions(&result)?;

        tracing::info!(txid = ?result.txid, "createAction completed");
        Ok(result)
    }

    async fn sign_action(
        &self,
        args: SignActionArgs,
        originator: Option<&str>,
    ) -> Result<SignActionResult, SdkWalletError> {
        let _spend_guard = self
            .storage
            .acquire_spend_lock()
            .await
            .map_err(to_sdk_error)?;
        tracing::debug!("signAction starting");
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_sign_action_args(&args)?;

        let reference = String::from_utf8_lossy(&args.reference).to_string();
        let raw_options = &args.options;
        let options = raw_options.clone().unwrap_or_default();

        // Derive Option<bool> flags from raw options, preserving None when the
        // caller didn't specify a value.  This enables mergePriorOptions in
        // sign_action.rs: None means "inherit from createAction", Some(v) means
        // "caller explicitly set this".
        let (is_no_send, is_delayed, is_send_with) = match raw_options {
            Some(opts) => (
                opts.no_send.0,
                opts.accept_delayed_broadcast.0.map(|abd| !abd),
                if opts.send_with.is_empty() {
                    None
                } else {
                    Some(true)
                },
            ),
            None => (None, None, None),
        };

        let valid_args = crate::signer::types::ValidSignActionArgs {
            reference: reference.clone(),
            spends: args.spends,
            options,
            is_new_tx: true,
            is_no_send,
            is_delayed,
            is_send_with,
        };

        let signer_result = self
            .signer
            .sign_action(valid_args)
            .await
            .map_err(to_sdk_error)?;

        let mut result = SignActionResult {
            txid: signer_result.txid,
            tx: signer_result.tx,
            send_with_results: signer_result.send_with_results,
        };

        // Verify returned txid-only if applicable
        if let Some(ref mut tx_bytes) = result.tx {
            let beef_lock = self.beef.lock().await;
            let verified = crate::wallet::beef_helpers::verify_returned_txid_only_atomic_beef(
                tx_bytes,
                &beef_lock,
                self.return_txid_only,
                None,
            )?;
            *tx_bytes = verified;
        }

        // Check for unsuccessful results
        crate::wallet::error_helpers::throw_if_any_unsuccessful_sign_actions(&result)?;

        tracing::info!(txid = ?result.txid, "signAction completed");
        Ok(result)
    }

    async fn internalize_action(
        &self,
        args: InternalizeActionArgs,
        originator: Option<&str>,
    ) -> Result<InternalizeActionResult, SdkWalletError> {
        let _spend_guard = self
            .storage
            .acquire_spend_lock()
            .await
            .map_err(to_sdk_error)?;
        tracing::debug!(description = %args.description, "internalizeAction starting");
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_internalize_action_args(&args)?;

        // Check specOp throw review actions label
        for label in &args.labels {
            if crate::wallet::types::is_spec_op_throw_label(label) {
                return Err(SdkWalletError::Internal(
                    "WERR_REVIEW_ACTIONS: internalizeAction specOp throw review actions"
                        .to_string(),
                ));
            }
        }

        // Pass SDK InternalizeOutput enum directly through to signer
        let valid_args = crate::signer::types::ValidInternalizeActionArgs {
            tx: args.tx,
            description: args.description,
            labels: args.labels,
            outputs: args.outputs,
        };

        let signer_result = self
            .signer
            .internalize_action(valid_args)
            .await
            .map_err(to_sdk_error)?;

        let result = InternalizeActionResult {
            accepted: signer_result.accepted,
        };

        crate::wallet::error_helpers::throw_if_unsuccessful_internalize_action(&result)?;

        tracing::info!(accepted = result.accepted, "internalizeAction completed");
        Ok(result)
    }

    async fn abort_action(
        &self,
        args: AbortActionArgs,
        originator: Option<&str>,
    ) -> Result<AbortActionResult, SdkWalletError> {
        let _spend_guard = self
            .storage
            .acquire_spend_lock()
            .await
            .map_err(to_sdk_error)?;
        tracing::debug!(reference = %String::from_utf8_lossy(&args.reference), "abortAction starting");
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_abort_action_args(&args)?;

        let auth = self.auth_id();
        let result = self
            .storage
            .abort_action(&auth, &args)
            .await
            .map_err(to_sdk_error)?;
        tracing::info!("abortAction completed");
        Ok(result)
    }

    // -----------------------------------------------------------------------
    // QUERY methods (3) -- delegate to storage
    // -----------------------------------------------------------------------

    async fn list_actions(
        &self,
        args: ListActionsArgs,
        originator: Option<&str>,
    ) -> Result<ListActionsResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_list_actions_args(&args)?;

        let auth = self.auth_id();
        let mut result = self
            .storage
            .list_actions(&auth, &args)
            .await
            .map_err(to_sdk_error)?;

        // Strip customInstructions from outputs (security policy)
        for action in &mut result.actions {
            for output in &mut action.outputs {
                output.custom_instructions = None;
            }
        }

        Ok(result)
    }

    async fn list_outputs(
        &self,
        args: ListOutputsArgs,
        originator: Option<&str>,
    ) -> Result<ListOutputsResult, SdkWalletError> {
        use bsv::transaction::beef::{Beef, BEEF_V2};
        use bsv::wallet::interfaces::OutputInclude;
        use std::collections::HashSet;
        use std::io::Cursor;

        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_list_outputs_args(&args)?;

        let auth = self.auth_id();
        let mut result = self
            .storage
            .list_outputs(&auth, &args)
            .await
            .map_err(to_sdk_error)?;

        // BEEF assembly at the wallet layer for EntireTransactions requests.
        // The storage layer returns beef = None (stub); we build it here where
        // we have access to StorageProvider (required by get_valid_beef_for_txid).
        if matches!(args.include, Some(OutputInclude::EntireTransactions)) && result.beef.is_none()
        {
            // Collect unique txids from outpoints (format: "txid.vout")
            let mut unique_txids: Vec<String> = Vec::new();
            let mut seen: HashSet<String> = HashSet::new();
            for output in &result.outputs {
                if let Some(dot_pos) = output.outpoint.find('.') {
                    let txid = output.outpoint[..dot_pos].to_string();
                    if seen.insert(txid.clone()) {
                        unique_txids.push(txid);
                    }
                }
            }

            if !unique_txids.is_empty() {
                // Map SDK TrustSelf to local beef TrustSelf
                let beef_trust_self = match &self.trust_self {
                    Some(TrustSelf::Known) => crate::storage::beef::TrustSelf::Known,
                    None => crate::storage::beef::TrustSelf::No,
                };
                let known_txids: HashSet<String> = HashSet::new();
                let storage_provider = self.storage.get_active().await.map_err(to_sdk_error)?;

                // Build a single merged BEEF from all txids
                let mut merged_beef = Beef::new(BEEF_V2);
                for txid in &unique_txids {
                    let beef_bytes_opt = crate::storage::beef::get_valid_beef_for_txid(
                        storage_provider.as_ref(),
                        txid,
                        beef_trust_self,
                        &known_txids,
                    )
                    .await
                    .map_err(to_sdk_error)?;

                    if let Some(beef_bytes) = beef_bytes_opt {
                        // Parse the returned BEEF and merge bumps and txs
                        let mut cursor = Cursor::new(&beef_bytes);
                        let parsed = Beef::from_binary(&mut cursor).map_err(|e| {
                            to_sdk_error(crate::error::WalletError::Internal(format!(
                                "Failed to parse BEEF for {}: {}",
                                txid, e
                            )))
                        })?;
                        // Merge bumps
                        let bump_offset = merged_beef.bumps.len();
                        merged_beef.bumps.extend(parsed.bumps);
                        // Merge txs, adjusting bump_index offsets
                        for mut beef_tx in parsed.txs {
                            if let Some(ref mut idx) = beef_tx.bump_index {
                                *idx += bump_offset;
                            }
                            // Only add if not already present (dedup by txid)
                            let tx_txid = beef_tx.txid.clone();
                            if !merged_beef.txs.iter().any(|t| t.txid == tx_txid) {
                                merged_beef.txs.push(beef_tx);
                            }
                        }
                    }
                }

                if !merged_beef.txs.is_empty() {
                    let mut buf = Vec::new();
                    merged_beef.to_binary(&mut buf).map_err(|e| {
                        to_sdk_error(crate::error::WalletError::Internal(format!(
                            "Failed to serialize merged BEEF: {}",
                            e
                        )))
                    })?;
                    result.beef = Some(buf);
                }
            }
        }

        // Merge BEEF into BeefParty and verify returned txid-only
        if let Some(ref mut beef_bytes) = result.beef {
            let beef_lock = self.beef.lock().await;
            let verified = crate::wallet::beef_helpers::verify_returned_txid_only_beef(
                beef_bytes,
                &beef_lock,
                self.return_txid_only,
            )?;
            *beef_bytes = verified;
        }

        Ok(result)
    }

    async fn list_certificates(
        &self,
        args: ListCertificatesArgs,
        originator: Option<&str>,
    ) -> Result<ListCertificatesResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_list_certificates_args(&args)?;

        let auth = self.auth_id();
        self.storage
            .list_certificates(&auth, &args)
            .await
            .map_err(to_sdk_error)
    }

    // -----------------------------------------------------------------------
    // RELINQUISH methods (2) -- delegate to storage
    // -----------------------------------------------------------------------

    async fn relinquish_output(
        &self,
        args: RelinquishOutputArgs,
        originator: Option<&str>,
    ) -> Result<RelinquishOutputResult, SdkWalletError> {
        let _spend_guard = self
            .storage
            .acquire_spend_lock()
            .await
            .map_err(to_sdk_error)?;
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_relinquish_output_args(&args)?;

        let auth = self.auth_id();
        self.storage
            .relinquish_output(&auth, &args)
            .await
            .map(|_| bsv::wallet::interfaces::RelinquishOutputResult { relinquished: true })
            .map_err(to_sdk_error)
    }

    async fn relinquish_certificate(
        &self,
        args: RelinquishCertificateArgs,
        originator: Option<&str>,
    ) -> Result<RelinquishCertificateResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_relinquish_certificate_args(&args)?;

        let auth = self.auth_id();
        self.storage
            .relinquish_certificate(&auth, &args)
            .await
            .map(|_| bsv::wallet::interfaces::RelinquishCertificateResult { relinquished: true })
            .map_err(to_sdk_error)
    }

    // -----------------------------------------------------------------------
    // CERTIFICATE methods (4) -- Plans 04/05
    // -----------------------------------------------------------------------

    async fn acquire_certificate(
        &self,
        args: AcquireCertificateArgs,
        originator: Option<&str>,
    ) -> Result<Certificate, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_acquire_certificate_args(&args)?;

        let auth = self.auth_id();

        let result = match args.acquisition_protocol {
            AcquisitionProtocol::Direct => crate::wallet::certificates::acquire_direct_certificate(
                &self.storage,
                self,
                &auth,
                &args,
            )
            .await
            .map_err(to_sdk_error)?,
            AcquisitionProtocol::Issuance => {
                crate::wallet::certificates::acquire_issuance_certificate(
                    &self.storage,
                    self,
                    &auth,
                    &args,
                )
                .await
                .map_err(to_sdk_error)?
            }
        };

        // Convert AcquireCertificateResult to SDK Certificate
        let subject_pk = PublicKey::from_string(&result.subject)
            .map_err(|e| SdkWalletError::Internal(format!("Invalid subject key: {}", e)))?;
        let certifier_pk = PublicKey::from_string(&result.certifier)
            .map_err(|e| SdkWalletError::Internal(format!("Invalid certifier key: {}", e)))?;

        Ok(Certificate {
            cert_type: args.cert_type,
            serial_number: args
                .serial_number
                .unwrap_or(bsv::wallet::interfaces::SerialNumber([0u8; 32])),
            subject: subject_pk,
            certifier: certifier_pk,
            revocation_outpoint: Some(result.revocation_outpoint),
            fields: Some(result.fields),
            signature: args.signature,
        })
    }

    async fn prove_certificate(
        &self,
        args: ProveCertificateArgs,
        originator: Option<&str>,
    ) -> Result<ProveCertificateResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_prove_certificate_args(&args)?;

        let auth = self.auth_id();
        crate::wallet::certificates::prove_certificate(&self.storage, self, &auth, &args)
            .await
            .map_err(to_sdk_error)
    }

    async fn discover_by_identity_key(
        &self,
        args: DiscoverByIdentityKeyArgs,
        originator: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_discover_by_identity_key_args(&args)?;

        let resolver = self
            .lookup_resolver
            .as_ref()
            .ok_or_else(|| SdkWalletError::Internal("No lookup resolver configured".to_string()))?;

        crate::wallet::discovery::discover_by_identity_key(
            &self.settings_manager,
            resolver,
            &self.overlay_cache,
            &args,
        )
        .await
        .map_err(to_sdk_error)
    }

    async fn discover_by_attributes(
        &self,
        args: DiscoverByAttributesArgs,
        originator: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, SdkWalletError> {
        self.validate_originator(originator).map_err(to_sdk_error)?;
        bsv::wallet::validation::validate_discover_by_attributes_args(&args)?;

        let resolver = self
            .lookup_resolver
            .as_ref()
            .ok_or_else(|| SdkWalletError::Internal("No lookup resolver configured".to_string()))?;

        crate::wallet::discovery::discover_by_attributes(
            &self.settings_manager,
            resolver,
            &self.overlay_cache,
            &args,
        )
        .await
        .map_err(to_sdk_error)
    }
}

// ---------------------------------------------------------------------------
// WalletArc -- Clone-able newtype for Wallet
// ---------------------------------------------------------------------------
//
// AuthMiddlewareFactory requires W: Clone, but Wallet cannot implement Clone
// (WalletStorageManager contains Mutex). We use a newtype around Arc<Wallet>
// that is Clone and implements WalletInterface by delegating to the inner Wallet.
// This satisfies orphan rules (WalletArc is a local type).

/// Clone-able wrapper around `Arc<Wallet>` implementing `WalletInterface`.
///
/// Needed because `Wallet` cannot implement `Clone` (contains `Mutex`),
/// but `AuthMiddlewareFactory` requires `W: WalletInterface + Clone`.
#[derive(Clone)]
pub struct WalletArc(pub Arc<Wallet>);

impl WalletArc {
    /// Create a new WalletArc from an existing `Arc<Wallet>`.
    pub fn new(wallet: Arc<Wallet>) -> Self {
        Self(wallet)
    }
}

#[async_trait]
impl WalletInterface for WalletArc {
    async fn get_public_key(
        &self,
        args: GetPublicKeyArgs,
        originator: Option<&str>,
    ) -> Result<GetPublicKeyResult, SdkWalletError> {
        self.0.as_ref().get_public_key(args, originator).await
    }

    async fn encrypt(
        &self,
        args: EncryptArgs,
        originator: Option<&str>,
    ) -> Result<EncryptResult, SdkWalletError> {
        self.0.as_ref().encrypt(args, originator).await
    }

    async fn decrypt(
        &self,
        args: DecryptArgs,
        originator: Option<&str>,
    ) -> Result<DecryptResult, SdkWalletError> {
        self.0.as_ref().decrypt(args, originator).await
    }

    async fn create_hmac(
        &self,
        args: CreateHmacArgs,
        originator: Option<&str>,
    ) -> Result<CreateHmacResult, SdkWalletError> {
        self.0.as_ref().create_hmac(args, originator).await
    }

    async fn verify_hmac(
        &self,
        args: VerifyHmacArgs,
        originator: Option<&str>,
    ) -> Result<VerifyHmacResult, SdkWalletError> {
        self.0.as_ref().verify_hmac(args, originator).await
    }

    async fn create_signature(
        &self,
        args: CreateSignatureArgs,
        originator: Option<&str>,
    ) -> Result<CreateSignatureResult, SdkWalletError> {
        self.0.as_ref().create_signature(args, originator).await
    }

    async fn verify_signature(
        &self,
        args: VerifySignatureArgs,
        originator: Option<&str>,
    ) -> Result<VerifySignatureResult, SdkWalletError> {
        self.0.as_ref().verify_signature(args, originator).await
    }

    async fn reveal_counterparty_key_linkage(
        &self,
        args: RevealCounterpartyKeyLinkageArgs,
        originator: Option<&str>,
    ) -> Result<RevealCounterpartyKeyLinkageResult, SdkWalletError> {
        self.0
            .as_ref()
            .reveal_counterparty_key_linkage(args, originator)
            .await
    }

    async fn reveal_specific_key_linkage(
        &self,
        args: RevealSpecificKeyLinkageArgs,
        originator: Option<&str>,
    ) -> Result<RevealSpecificKeyLinkageResult, SdkWalletError> {
        self.0
            .as_ref()
            .reveal_specific_key_linkage(args, originator)
            .await
    }

    async fn is_authenticated(
        &self,
        originator: Option<&str>,
    ) -> Result<AuthenticatedResult, SdkWalletError> {
        self.0.as_ref().is_authenticated(originator).await
    }

    async fn wait_for_authentication(
        &self,
        originator: Option<&str>,
    ) -> Result<AuthenticatedResult, SdkWalletError> {
        self.0.as_ref().wait_for_authentication(originator).await
    }

    async fn get_height(
        &self,
        originator: Option<&str>,
    ) -> Result<GetHeightResult, SdkWalletError> {
        self.0.as_ref().get_height(originator).await
    }

    async fn get_header_for_height(
        &self,
        args: GetHeaderArgs,
        originator: Option<&str>,
    ) -> Result<GetHeaderResult, SdkWalletError> {
        self.0
            .as_ref()
            .get_header_for_height(args, originator)
            .await
    }

    async fn get_network(
        &self,
        originator: Option<&str>,
    ) -> Result<GetNetworkResult, SdkWalletError> {
        self.0.as_ref().get_network(originator).await
    }

    async fn get_version(
        &self,
        originator: Option<&str>,
    ) -> Result<GetVersionResult, SdkWalletError> {
        self.0.as_ref().get_version(originator).await
    }

    async fn create_action(
        &self,
        args: CreateActionArgs,
        originator: Option<&str>,
    ) -> Result<CreateActionResult, SdkWalletError> {
        self.0.as_ref().create_action(args, originator).await
    }

    async fn sign_action(
        &self,
        args: SignActionArgs,
        originator: Option<&str>,
    ) -> Result<SignActionResult, SdkWalletError> {
        self.0.as_ref().sign_action(args, originator).await
    }

    async fn internalize_action(
        &self,
        args: InternalizeActionArgs,
        originator: Option<&str>,
    ) -> Result<InternalizeActionResult, SdkWalletError> {
        self.0.as_ref().internalize_action(args, originator).await
    }

    async fn abort_action(
        &self,
        args: AbortActionArgs,
        originator: Option<&str>,
    ) -> Result<AbortActionResult, SdkWalletError> {
        self.0.as_ref().abort_action(args, originator).await
    }

    async fn list_actions(
        &self,
        args: ListActionsArgs,
        originator: Option<&str>,
    ) -> Result<ListActionsResult, SdkWalletError> {
        self.0.as_ref().list_actions(args, originator).await
    }

    async fn list_outputs(
        &self,
        args: ListOutputsArgs,
        originator: Option<&str>,
    ) -> Result<ListOutputsResult, SdkWalletError> {
        self.0.as_ref().list_outputs(args, originator).await
    }

    async fn list_certificates(
        &self,
        args: ListCertificatesArgs,
        originator: Option<&str>,
    ) -> Result<ListCertificatesResult, SdkWalletError> {
        self.0.as_ref().list_certificates(args, originator).await
    }

    async fn relinquish_output(
        &self,
        args: RelinquishOutputArgs,
        originator: Option<&str>,
    ) -> Result<RelinquishOutputResult, SdkWalletError> {
        self.0.as_ref().relinquish_output(args, originator).await
    }

    async fn relinquish_certificate(
        &self,
        args: RelinquishCertificateArgs,
        originator: Option<&str>,
    ) -> Result<RelinquishCertificateResult, SdkWalletError> {
        self.0
            .as_ref()
            .relinquish_certificate(args, originator)
            .await
    }

    async fn acquire_certificate(
        &self,
        args: AcquireCertificateArgs,
        originator: Option<&str>,
    ) -> Result<Certificate, SdkWalletError> {
        self.0.as_ref().acquire_certificate(args, originator).await
    }

    async fn prove_certificate(
        &self,
        args: ProveCertificateArgs,
        originator: Option<&str>,
    ) -> Result<ProveCertificateResult, SdkWalletError> {
        self.0.as_ref().prove_certificate(args, originator).await
    }

    async fn discover_by_identity_key(
        &self,
        args: DiscoverByIdentityKeyArgs,
        originator: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, SdkWalletError> {
        self.0
            .as_ref()
            .discover_by_identity_key(args, originator)
            .await
    }

    async fn discover_by_attributes(
        &self,
        args: DiscoverByAttributesArgs,
        originator: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, SdkWalletError> {
        self.0
            .as_ref()
            .discover_by_attributes(args, originator)
            .await
    }
}