zinc-core 0.4.0

Core Rust library for Zinc Bitcoin + Ordinals wallet
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
//! Signed pairing and intent protocol primitives for decentralized agent approval flows.
//!
//! Phase 0 scope:
//! - Canonical serde models
//! - Deterministic domain-separated ids
//! - Schnorr signature helpers
//! - Structural validation for local fixtures and adapters

use crate::ZincError;
use base64::Engine;
use bdk_wallet::bitcoin::hashes::{sha256, Hash};
use bdk_wallet::bitcoin::psbt::{Input as PsbtInput, Psbt};
use bdk_wallet::bitcoin::secp256k1::XOnlyPublicKey;
use bdk_wallet::bitcoin::secp256k1::{schnorr::Signature, Keypair, Message, Secp256k1, SecretKey};
use bdk_wallet::bitcoin::OutPoint;
use getrandom::getrandom;
use nostr::nips::nip44;
use nostr::{PublicKey as NostrPublicKey, SecretKey as NostrSecretKey};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::str::FromStr;

const VERSION_V1: u8 = 1;
const DOMAIN_PAIRING_REQUEST: &str = "zinc-pairing-request-v1";
const DOMAIN_PAIRING_ACK: &str = "zinc-pairing-ack-v1";
const DOMAIN_PAIRING_ACK_ENVELOPE: &str = "zinc-pairing-ack-envelope-v1";
const DOMAIN_PAIRING_TAG_HASH: &str = "zinc-pairing-tag-hash-v1";
const DOMAIN_PAIRING_COMPLETE_RECEIPT: &str = "zinc-pairing-complete-receipt-v1";
const DOMAIN_SIGN_INTENT: &str = "zinc-sign-intent-v1";
const DOMAIN_SIGN_INTENT_RECEIPT: &str = "zinc-sign-intent-receipt-v1";

pub const NOSTR_SIGN_INTENT_APP_TAG_VALUE: &str = "zinc-sign-intent-v1";
pub const NOSTR_PAIRING_ACK_TYPE_TAG_VALUE: &str = "pairing-ack-v1";
pub const NOSTR_PAIRING_COMPLETE_RECEIPT_TYPE_TAG_VALUE: &str = "pairing-complete-receipt-v1";
pub const NOSTR_SIGN_INTENT_TYPE_TAG_VALUE: &str = "sign-intent-v1";
pub const NOSTR_SIGN_INTENT_RECEIPT_TYPE_TAG_VALUE: &str = "sign-intent-receipt-v1";
pub const PAIRING_TRANSPORT_EVENT_KIND: u64 = 1_059;
pub const NOSTR_TAG_APP_KEY: &str = "z";
pub const NOSTR_TAG_TYPE_KEY: &str = "t";
pub const NOSTR_TAG_PAIRING_HASH_KEY: &str = "x";
pub const NOSTR_TAG_RECIPIENT_PUBKEY_KEY: &str = "p";

const PAIRING_TRANSPORT_SEAL_EVENT_KIND: u64 = 13;
const PAIRING_TRANSPORT_RUMOR_EVENT_KIND: u64 = PAIRING_TRANSPORT_EVENT_KIND;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SignIntentActionV1 {
    BuildBuyerOffer,
    SignSellerInput,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CapabilityPolicyV1 {
    pub allowed_actions: Vec<SignIntentActionV1>,
    pub max_sats_per_intent: Option<u64>,
    pub daily_spend_limit_sats: Option<u64>,
    pub max_fee_rate_sat_vb: Option<u64>,
    pub allowed_networks: Vec<String>,
}

impl CapabilityPolicyV1 {
    fn validate(&self) -> Result<(), ZincError> {
        if self.allowed_actions.is_empty() {
            return Err(ZincError::OfferError(
                "capability policy must include at least one allowed action".to_string(),
            ));
        }

        let mut action_set = HashSet::new();
        for action in &self.allowed_actions {
            if !action_set.insert(*action) {
                return Err(ZincError::OfferError(
                    "capability policy contains duplicate allowed actions".to_string(),
                ));
            }
        }

        if self.allowed_networks.is_empty() {
            return Err(ZincError::OfferError(
                "capability policy must include at least one allowed network".to_string(),
            ));
        }

        let mut network_set = HashSet::new();
        for network in &self.allowed_networks {
            ensure_non_empty("capability network", network)?;
            let normalized = normalize_network(network);
            if !is_supported_network(&normalized) {
                return Err(ZincError::OfferError(format!(
                    "unsupported capability network `{network}`"
                )));
            }
            if !network_set.insert(normalized) {
                return Err(ZincError::OfferError(
                    "capability policy contains duplicate networks".to_string(),
                ));
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingRequestV1 {
    pub version: u8,
    pub agent_pubkey_hex: String,
    pub challenge_nonce: String,
    pub created_at_unix: i64,
    pub expires_at_unix: i64,
    #[serde(default)]
    pub relays: Vec<String>,
    pub requested_capabilities: CapabilityPolicyV1,
}

impl PairingRequestV1 {
    fn validate(&self) -> Result<(), ZincError> {
        validate_version(self.version)?;
        validate_pubkey_hex("pairing request agent_pubkey_hex", &self.agent_pubkey_hex)?;
        validate_nonce("pairing request challenge_nonce", &self.challenge_nonce)?;
        validate_expiry_window(self.created_at_unix, self.expires_at_unix)?;
        validate_unique_relays(&self.relays)?;
        self.requested_capabilities.validate()
    }

    pub fn canonical_json(&self) -> Result<Vec<u8>, ZincError> {
        self.validate()?;
        serde_json::to_vec(self).map_err(|e| ZincError::SerializationError(e.to_string()))
    }

    pub fn pairing_id_digest(&self) -> Result<[u8; 32], ZincError> {
        domain_separated_digest(DOMAIN_PAIRING_REQUEST, &self.canonical_json()?)
    }

    pub fn pairing_id_hex(&self) -> Result<String, ZincError> {
        Ok(digest_hex(&self.pairing_id_digest()?))
    }

    pub fn sign_schnorr_hex(&self, secret_key_hex: &str) -> Result<String, ZincError> {
        sign_payload_with_expected_pubkey(
            secret_key_hex,
            &self.agent_pubkey_hex,
            DOMAIN_PAIRING_REQUEST,
            &self.canonical_json()?,
        )
    }

    pub fn verify_schnorr_hex(&self, signature_hex: &str) -> Result<(), ZincError> {
        verify_payload_signature(
            &self.agent_pubkey_hex,
            signature_hex,
            DOMAIN_PAIRING_REQUEST,
            &self.canonical_json()?,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PairingAckDecisionV1 {
    Approved,
    Rejected,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingAckV1 {
    pub version: u8,
    pub pairing_id: String,
    pub challenge_nonce: String,
    pub agent_pubkey_hex: String,
    pub wallet_pubkey_hex: String,
    pub created_at_unix: i64,
    pub expires_at_unix: i64,
    pub decision: PairingAckDecisionV1,
    pub granted_capabilities: Option<CapabilityPolicyV1>,
    pub rejection_reason: Option<String>,
}

impl PairingAckV1 {
    fn validate(&self) -> Result<(), ZincError> {
        validate_version(self.version)?;
        validate_hex64("pairing ack pairing_id", &self.pairing_id)?;
        validate_nonce("pairing ack challenge_nonce", &self.challenge_nonce)?;
        validate_pubkey_hex("pairing ack agent_pubkey_hex", &self.agent_pubkey_hex)?;
        validate_pubkey_hex("pairing ack wallet_pubkey_hex", &self.wallet_pubkey_hex)?;
        validate_expiry_window(self.created_at_unix, self.expires_at_unix)?;

        match self.decision {
            PairingAckDecisionV1::Approved => {
                if self.granted_capabilities.is_none() {
                    return Err(ZincError::OfferError(
                        "approved pairing ack must include granted_capabilities".to_string(),
                    ));
                }
                if self.rejection_reason.is_some() {
                    return Err(ZincError::OfferError(
                        "approved pairing ack must not include rejection_reason".to_string(),
                    ));
                }
            }
            PairingAckDecisionV1::Rejected => {
                if self.granted_capabilities.is_some() {
                    return Err(ZincError::OfferError(
                        "rejected pairing ack must not include granted_capabilities".to_string(),
                    ));
                }
            }
        }

        if let Some(capabilities) = &self.granted_capabilities {
            capabilities.validate()?;
        }

        if let Some(reason) = &self.rejection_reason {
            ensure_non_empty("pairing ack rejection_reason", reason)?;
        }

        Ok(())
    }

    pub fn canonical_json(&self) -> Result<Vec<u8>, ZincError> {
        self.validate()?;
        serde_json::to_vec(self).map_err(|e| ZincError::SerializationError(e.to_string()))
    }

    pub fn ack_id_digest(&self) -> Result<[u8; 32], ZincError> {
        domain_separated_digest(DOMAIN_PAIRING_ACK, &self.canonical_json()?)
    }

    pub fn ack_id_hex(&self) -> Result<String, ZincError> {
        Ok(digest_hex(&self.ack_id_digest()?))
    }

    pub fn sign_schnorr_hex(&self, secret_key_hex: &str) -> Result<String, ZincError> {
        sign_payload_with_expected_pubkey(
            secret_key_hex,
            &self.wallet_pubkey_hex,
            DOMAIN_PAIRING_ACK,
            &self.canonical_json()?,
        )
    }

    pub fn verify_schnorr_hex(&self, signature_hex: &str) -> Result<(), ZincError> {
        verify_payload_signature(
            &self.wallet_pubkey_hex,
            signature_hex,
            DOMAIN_PAIRING_ACK,
            &self.canonical_json()?,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildBuyerOfferIntentV1 {
    pub inscription_id: String,
    pub seller_outpoint: String,
    pub ask_sats: u64,
    pub fee_rate_sat_vb: u64,
}

impl BuildBuyerOfferIntentV1 {
    fn validate(&self) -> Result<(), ZincError> {
        ensure_non_empty("build buyer offer inscription_id", &self.inscription_id)?;
        ensure_non_empty("build buyer offer seller_outpoint", &self.seller_outpoint)?;
        if self.ask_sats == 0 {
            return Err(ZincError::OfferError(
                "build buyer offer ask_sats must be > 0".to_string(),
            ));
        }
        if self.fee_rate_sat_vb == 0 {
            return Err(ZincError::OfferError(
                "build buyer offer fee_rate_sat_vb must be > 0".to_string(),
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignSellerInputIntentV1 {
    pub offer_id: String,
    pub offer_psbt_base64: String,
    pub expected_seller_outpoint: String,
    pub expected_ask_sats: u64,
}

impl SignSellerInputIntentV1 {
    fn validate(&self) -> Result<(), ZincError> {
        validate_hex64("sign seller input offer_id", &self.offer_id)?;
        ensure_non_empty(
            "sign seller input offer_psbt_base64",
            &self.offer_psbt_base64,
        )?;
        ensure_non_empty(
            "sign seller input expected_seller_outpoint",
            &self.expected_seller_outpoint,
        )?;
        if self.expected_ask_sats == 0 {
            return Err(ZincError::OfferError(
                "sign seller input expected_ask_sats must be > 0".to_string(),
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "action", content = "params", rename_all = "camelCase")]
pub enum SignIntentPayloadV1 {
    BuildBuyerOffer(BuildBuyerOfferIntentV1),
    SignSellerInput(SignSellerInputIntentV1),
}

impl SignIntentPayloadV1 {
    fn validate(&self) -> Result<(), ZincError> {
        match self {
            Self::BuildBuyerOffer(payload) => payload.validate(),
            Self::SignSellerInput(payload) => payload.validate(),
        }
    }

    pub fn action(&self) -> SignIntentActionV1 {
        match self {
            Self::BuildBuyerOffer(_) => SignIntentActionV1::BuildBuyerOffer,
            Self::SignSellerInput(_) => SignIntentActionV1::SignSellerInput,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignIntentV1 {
    pub version: u8,
    pub pairing_id: String,
    pub agent_pubkey_hex: String,
    pub wallet_pubkey_hex: String,
    pub network: String,
    pub created_at_unix: i64,
    pub expires_at_unix: i64,
    pub nonce: u64,
    pub payload: SignIntentPayloadV1,
}

impl SignIntentV1 {
    fn validate(&self) -> Result<(), ZincError> {
        validate_version(self.version)?;
        validate_hex64("sign intent pairing_id", &self.pairing_id)?;
        validate_pubkey_hex("sign intent agent_pubkey_hex", &self.agent_pubkey_hex)?;
        validate_pubkey_hex("sign intent wallet_pubkey_hex", &self.wallet_pubkey_hex)?;
        ensure_non_empty("sign intent network", &self.network)?;

        let normalized_network = normalize_network(&self.network);
        if !is_supported_network(&normalized_network) {
            return Err(ZincError::OfferError(format!(
                "unsupported sign intent network `{}`",
                self.network
            )));
        }

        validate_expiry_window(self.created_at_unix, self.expires_at_unix)?;
        self.payload.validate()
    }

    pub fn canonical_json(&self) -> Result<Vec<u8>, ZincError> {
        self.validate()?;
        serde_json::to_vec(self).map_err(|e| ZincError::SerializationError(e.to_string()))
    }

    pub fn intent_id_digest(&self) -> Result<[u8; 32], ZincError> {
        domain_separated_digest(DOMAIN_SIGN_INTENT, &self.canonical_json()?)
    }

    pub fn intent_id_hex(&self) -> Result<String, ZincError> {
        Ok(digest_hex(&self.intent_id_digest()?))
    }

    pub fn sign_schnorr_hex(&self, secret_key_hex: &str) -> Result<String, ZincError> {
        sign_payload_with_expected_pubkey(
            secret_key_hex,
            &self.agent_pubkey_hex,
            DOMAIN_SIGN_INTENT,
            &self.canonical_json()?,
        )
    }

    pub fn verify_schnorr_hex(&self, signature_hex: &str) -> Result<(), ZincError> {
        verify_payload_signature(
            &self.agent_pubkey_hex,
            signature_hex,
            DOMAIN_SIGN_INTENT,
            &self.canonical_json()?,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SignIntentReceiptStatusV1 {
    Approved,
    Rejected,
    Expired,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignIntentReceiptV1 {
    pub version: u8,
    pub intent_id: String,
    pub pairing_id: String,
    pub signer_pubkey_hex: String,
    pub created_at_unix: i64,
    pub status: SignIntentReceiptStatusV1,
    pub signed_psbt_base64: Option<String>,
    pub artifact_json: Option<String>,
    pub error_message: Option<String>,
}

impl SignIntentReceiptV1 {
    fn validate(&self) -> Result<(), ZincError> {
        validate_version(self.version)?;
        validate_hex64("sign intent receipt intent_id", &self.intent_id)?;
        validate_hex64("sign intent receipt pairing_id", &self.pairing_id)?;
        validate_pubkey_hex(
            "sign intent receipt signer_pubkey_hex",
            &self.signer_pubkey_hex,
        )?;

        match self.status {
            SignIntentReceiptStatusV1::Approved => {
                if self.signed_psbt_base64.is_none() && self.artifact_json.is_none() {
                    return Err(ZincError::OfferError(
                        "approved sign intent receipt must include signed_psbt_base64 or artifact_json"
                            .to_string(),
                    ));
                }
            }
            SignIntentReceiptStatusV1::Rejected
            | SignIntentReceiptStatusV1::Expired
            | SignIntentReceiptStatusV1::Failed => {}
        }

        if let Some(psbt) = &self.signed_psbt_base64 {
            ensure_non_empty("sign intent receipt signed_psbt_base64", psbt)?;
        }
        if let Some(artifact) = &self.artifact_json {
            ensure_non_empty("sign intent receipt artifact_json", artifact)?;
        }
        if let Some(message) = &self.error_message {
            ensure_non_empty("sign intent receipt error_message", message)?;
        }

        Ok(())
    }

    pub fn canonical_json(&self) -> Result<Vec<u8>, ZincError> {
        self.validate()?;
        serde_json::to_vec(self).map_err(|e| ZincError::SerializationError(e.to_string()))
    }

    pub fn receipt_id_digest(&self) -> Result<[u8; 32], ZincError> {
        domain_separated_digest(DOMAIN_SIGN_INTENT_RECEIPT, &self.canonical_json()?)
    }

    pub fn receipt_id_hex(&self) -> Result<String, ZincError> {
        Ok(digest_hex(&self.receipt_id_digest()?))
    }

    pub fn sign_schnorr_hex(&self, secret_key_hex: &str) -> Result<String, ZincError> {
        sign_payload_with_expected_pubkey(
            secret_key_hex,
            &self.signer_pubkey_hex,
            DOMAIN_SIGN_INTENT_RECEIPT,
            &self.canonical_json()?,
        )
    }

    pub fn verify_schnorr_hex(&self, signature_hex: &str) -> Result<(), ZincError> {
        verify_payload_signature(
            &self.signer_pubkey_hex,
            signature_hex,
            DOMAIN_SIGN_INTENT_RECEIPT,
            &self.canonical_json()?,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedPairingRequestV1 {
    pub request: PairingRequestV1,
    pub signature_hex: String,
}

impl SignedPairingRequestV1 {
    pub fn new(request: PairingRequestV1, secret_key_hex: &str) -> Result<Self, ZincError> {
        let signature_hex = request.sign_schnorr_hex(secret_key_hex)?;
        Ok(Self {
            request,
            signature_hex,
        })
    }

    pub fn verify(&self) -> Result<(), ZincError> {
        self.request.verify_schnorr_hex(&self.signature_hex)
    }

    pub fn pairing_id_hex(&self) -> Result<String, ZincError> {
        self.request.pairing_id_hex()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedPairingAckV1 {
    pub ack: PairingAckV1,
    pub signature_hex: String,
}

impl SignedPairingAckV1 {
    pub fn new(ack: PairingAckV1, secret_key_hex: &str) -> Result<Self, ZincError> {
        let signature_hex = ack.sign_schnorr_hex(secret_key_hex)?;
        Ok(Self { ack, signature_hex })
    }

    pub fn verify(&self) -> Result<(), ZincError> {
        self.ack.verify_schnorr_hex(&self.signature_hex)
    }

    pub fn ack_id_hex(&self) -> Result<String, ZincError> {
        self.ack.ack_id_hex()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingAckEnvelopeV1 {
    pub version: u8,
    pub app_tag: String,
    pub type_tag: String,
    pub pairing_tag_hash_hex: String,
    pub created_at_unix: i64,
    pub signed_ack: SignedPairingAckV1,
}

impl PairingAckEnvelopeV1 {
    pub fn new(signed_ack: SignedPairingAckV1, created_at_unix: i64) -> Result<Self, ZincError> {
        signed_ack.verify()?;
        let pairing_tag_hash_hex = pairing_tag_hash_hex(&signed_ack.ack.pairing_id)?;
        let envelope = Self {
            version: VERSION_V1,
            app_tag: NOSTR_SIGN_INTENT_APP_TAG_VALUE.to_string(),
            type_tag: NOSTR_PAIRING_ACK_TYPE_TAG_VALUE.to_string(),
            pairing_tag_hash_hex,
            created_at_unix,
            signed_ack,
        };
        envelope.validate()?;
        Ok(envelope)
    }

    fn validate(&self) -> Result<(), ZincError> {
        validate_version(self.version)?;
        if self.app_tag != NOSTR_SIGN_INTENT_APP_TAG_VALUE {
            return Err(ZincError::OfferError(format!(
                "pairing ack envelope app_tag must be `{NOSTR_SIGN_INTENT_APP_TAG_VALUE}`"
            )));
        }
        if self.type_tag != NOSTR_PAIRING_ACK_TYPE_TAG_VALUE {
            return Err(ZincError::OfferError(format!(
                "pairing ack envelope type_tag must be `{NOSTR_PAIRING_ACK_TYPE_TAG_VALUE}`"
            )));
        }
        validate_hex64(
            "pairing ack envelope pairing_tag_hash_hex",
            &self.pairing_tag_hash_hex,
        )?;
        self.signed_ack.verify()?;

        let expected_hash = pairing_tag_hash_hex(&self.signed_ack.ack.pairing_id)?;
        if self.pairing_tag_hash_hex != expected_hash {
            return Err(ZincError::OfferError(
                "pairing ack envelope pairing_tag_hash_hex does not match embedded pairing_id"
                    .to_string(),
            ));
        }
        Ok(())
    }

    pub fn canonical_json(&self) -> Result<Vec<u8>, ZincError> {
        self.validate()?;
        serde_json::to_vec(self).map_err(|e| ZincError::SerializationError(e.to_string()))
    }

    pub fn envelope_id_digest(&self) -> Result<[u8; 32], ZincError> {
        domain_separated_digest(DOMAIN_PAIRING_ACK_ENVELOPE, &self.canonical_json()?)
    }

    pub fn envelope_id_hex(&self) -> Result<String, ZincError> {
        Ok(digest_hex(&self.envelope_id_digest()?))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NostrTransportEventV1 {
    pub id: String,
    pub pubkey: String,
    #[serde(rename = "created_at", alias = "createdAt")]
    pub created_at: u64,
    pub kind: u64,
    pub tags: Vec<Vec<String>>,
    pub content: String,
    pub sig: String,
}

impl NostrTransportEventV1 {
    pub fn new(
        kind: u64,
        tags: Vec<Vec<String>>,
        content: String,
        created_at_unix: u64,
        secret_key_hex: &str,
    ) -> Result<Self, ZincError> {
        let secret_key = SecretKey::from_str(secret_key_hex)
            .map_err(|e| ZincError::OfferError(format!("invalid secret key: {e}")))?;
        let secp = Secp256k1::new();
        let keypair = Keypair::from_secret_key(&secp, &secret_key);
        let (pubkey, _) = XOnlyPublicKey::from_keypair(&keypair);
        let pubkey_hex = pubkey.to_string();

        let id = compute_nostr_event_id_hex(&pubkey_hex, created_at_unix, kind, &tags, &content)?;
        let sig = sign_nostr_event_id_hex(&id, &secret_key)?;

        let event = Self {
            id,
            pubkey: pubkey_hex,
            created_at: created_at_unix,
            kind,
            tags,
            content,
            sig,
        };
        event.verify()?;
        Ok(event)
    }

    pub fn verify(&self) -> Result<(), ZincError> {
        validate_hex64("nostr event id", &self.id)?;
        validate_pubkey_hex("nostr event pubkey", &self.pubkey)?;
        let expected_id = compute_nostr_event_id_hex(
            &self.pubkey,
            self.created_at,
            self.kind,
            &self.tags,
            &self.content,
        )?;
        if expected_id != self.id {
            return Err(ZincError::OfferError("nostr event id mismatch".to_string()));
        }

        let signature = Signature::from_str(&self.sig)
            .map_err(|e| ZincError::OfferError(format!("invalid nostr event signature: {e}")))?;
        let digest = hex_to_digest32(&self.id)?;
        let message = Message::from_digest(digest);
        let pubkey = XOnlyPublicKey::from_str(&self.pubkey)
            .map_err(|e| ZincError::OfferError(format!("invalid nostr event pubkey: {e}")))?;
        let secp = Secp256k1::verification_only();
        secp.verify_schnorr(&signature, &message, &pubkey)
            .map_err(|e| {
                ZincError::OfferError(format!("nostr event signature verification failed: {e}"))
            })
    }

    pub fn tag_value(&self, key: &str) -> Option<&str> {
        self.tags.iter().find_map(|tag| {
            if tag.len() >= 2 && tag[0] == key {
                Some(tag[1].as_str())
            } else {
                None
            }
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NostrTransportRumorV1 {
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<String>,
    pubkey: String,
    #[serde(rename = "created_at", alias = "createdAt")]
    created_at: u64,
    kind: u64,
    tags: Vec<Vec<String>>,
    content: String,
}

impl NostrTransportRumorV1 {
    fn verify(&self) -> Result<(), ZincError> {
        validate_pubkey_hex("nostr rumor pubkey", &self.pubkey)?;
        if self.kind != PAIRING_TRANSPORT_RUMOR_EVENT_KIND {
            return Err(ZincError::OfferError(format!(
                "unexpected nostr rumor kind {}, expected {}",
                self.kind, PAIRING_TRANSPORT_RUMOR_EVENT_KIND
            )));
        }
        if let Some(id) = &self.id {
            validate_hex64("nostr rumor id", id)?;
            let expected_id = compute_nostr_event_id_hex(
                &self.pubkey,
                self.created_at,
                self.kind,
                &self.tags,
                &self.content,
            )?;
            if expected_id != *id {
                return Err(ZincError::OfferError("nostr rumor id mismatch".to_string()));
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PairingCompleteReceiptStatusV1 {
    Confirmed,
    Rejected,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingCompleteReceiptV1 {
    pub version: u8,
    pub pairing_id: String,
    pub ack_id: String,
    pub challenge_nonce: String,
    pub agent_pubkey_hex: String,
    pub wallet_pubkey_hex: String,
    pub created_at_unix: i64,
    pub status: PairingCompleteReceiptStatusV1,
    pub error_message: Option<String>,
}

impl PairingCompleteReceiptV1 {
    fn validate(&self) -> Result<(), ZincError> {
        validate_version(self.version)?;
        validate_hex64("pairing complete receipt pairing_id", &self.pairing_id)?;
        validate_hex64("pairing complete receipt ack_id", &self.ack_id)?;
        validate_nonce(
            "pairing complete receipt challenge_nonce",
            &self.challenge_nonce,
        )?;
        validate_pubkey_hex(
            "pairing complete receipt agent_pubkey_hex",
            &self.agent_pubkey_hex,
        )?;
        validate_pubkey_hex(
            "pairing complete receipt wallet_pubkey_hex",
            &self.wallet_pubkey_hex,
        )?;
        if let Some(message) = &self.error_message {
            ensure_non_empty("pairing complete receipt error_message", message)?;
        }

        match self.status {
            PairingCompleteReceiptStatusV1::Confirmed => {
                if self.error_message.is_some() {
                    return Err(ZincError::OfferError(
                        "confirmed pairing complete receipt must not include error_message"
                            .to_string(),
                    ));
                }
            }
            PairingCompleteReceiptStatusV1::Rejected => {
                if self.error_message.is_none() {
                    return Err(ZincError::OfferError(
                        "rejected pairing complete receipt must include error_message".to_string(),
                    ));
                }
            }
        }

        Ok(())
    }

    pub fn canonical_json(&self) -> Result<Vec<u8>, ZincError> {
        self.validate()?;
        serde_json::to_vec(self).map_err(|e| ZincError::SerializationError(e.to_string()))
    }

    pub fn receipt_id_digest(&self) -> Result<[u8; 32], ZincError> {
        domain_separated_digest(DOMAIN_PAIRING_COMPLETE_RECEIPT, &self.canonical_json()?)
    }

    pub fn receipt_id_hex(&self) -> Result<String, ZincError> {
        Ok(digest_hex(&self.receipt_id_digest()?))
    }

    pub fn sign_schnorr_hex(&self, secret_key_hex: &str) -> Result<String, ZincError> {
        sign_payload_with_expected_pubkey(
            secret_key_hex,
            &self.agent_pubkey_hex,
            DOMAIN_PAIRING_COMPLETE_RECEIPT,
            &self.canonical_json()?,
        )
    }

    pub fn verify_schnorr_hex(&self, signature_hex: &str) -> Result<(), ZincError> {
        verify_payload_signature(
            &self.agent_pubkey_hex,
            signature_hex,
            DOMAIN_PAIRING_COMPLETE_RECEIPT,
            &self.canonical_json()?,
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedPairingCompleteReceiptV1 {
    pub receipt: PairingCompleteReceiptV1,
    pub signature_hex: String,
}

impl SignedPairingCompleteReceiptV1 {
    pub fn new(receipt: PairingCompleteReceiptV1, secret_key_hex: &str) -> Result<Self, ZincError> {
        let signature_hex = receipt.sign_schnorr_hex(secret_key_hex)?;
        Ok(Self {
            receipt,
            signature_hex,
        })
    }

    pub fn verify(&self) -> Result<(), ZincError> {
        self.receipt.verify_schnorr_hex(&self.signature_hex)
    }

    pub fn receipt_id_hex(&self) -> Result<String, ZincError> {
        self.receipt.receipt_id_hex()
    }
}

pub fn build_signed_pairing_complete_receipt(
    signed_request: &SignedPairingRequestV1,
    signed_ack: &SignedPairingAckV1,
    agent_secret_key_hex: &str,
    now_unix: i64,
) -> Result<SignedPairingCompleteReceiptV1, ZincError> {
    let approval = verify_pairing_approval(signed_request, signed_ack, now_unix)?;
    let receipt = PairingCompleteReceiptV1 {
        version: VERSION_V1,
        pairing_id: approval.pairing_id,
        ack_id: signed_ack.ack_id_hex()?,
        challenge_nonce: signed_request.request.challenge_nonce.clone(),
        agent_pubkey_hex: approval.agent_pubkey_hex,
        wallet_pubkey_hex: approval.wallet_pubkey_hex,
        created_at_unix: now_unix,
        status: PairingCompleteReceiptStatusV1::Confirmed,
        error_message: None,
    };
    let signed = SignedPairingCompleteReceiptV1::new(receipt, agent_secret_key_hex)?;
    signed.verify()?;
    Ok(signed)
}

pub fn build_signed_pairing_ack(
    signed_request: &SignedPairingRequestV1,
    wallet_secret_key_hex: &str,
    now_unix: i64,
    ack_ttl_secs: i64,
) -> Result<SignedPairingAckV1, ZincError> {
    build_signed_pairing_ack_with_granted(
        signed_request,
        wallet_secret_key_hex,
        now_unix,
        ack_ttl_secs,
        None,
    )
}

pub fn build_signed_pairing_ack_with_granted(
    signed_request: &SignedPairingRequestV1,
    wallet_secret_key_hex: &str,
    now_unix: i64,
    ack_ttl_secs: i64,
    granted_capabilities: Option<CapabilityPolicyV1>,
) -> Result<SignedPairingAckV1, ZincError> {
    if ack_ttl_secs <= 0 {
        return Err(ZincError::OfferError(
            "pairing ack ttl must be greater than zero seconds".to_string(),
        ));
    }

    signed_request.verify()?;
    let request = &signed_request.request;
    if now_unix > request.expires_at_unix {
        return Err(ZincError::OfferError(
            "pairing request expired before ack creation".to_string(),
        ));
    }

    let created_at_unix = now_unix;
    let ttl_expires_at_unix = created_at_unix.checked_add(ack_ttl_secs).ok_or_else(|| {
        ZincError::OfferError("pairing ack expiry overflowed unix range".to_string())
    })?;
    let expires_at_unix = ttl_expires_at_unix.min(request.expires_at_unix);
    if expires_at_unix <= created_at_unix {
        return Err(ZincError::OfferError(
            "pairing ack expires_at_unix must be greater than created_at_unix".to_string(),
        ));
    }

    let pairing_id = signed_request.pairing_id_hex()?;
    let wallet_pubkey_hex = pubkey_hex_from_secret_key(wallet_secret_key_hex)?;
    let granted_capabilities =
        granted_capabilities.unwrap_or_else(|| request.requested_capabilities.clone());

    let ack = PairingAckV1 {
        version: VERSION_V1,
        pairing_id,
        challenge_nonce: request.challenge_nonce.clone(),
        agent_pubkey_hex: request.agent_pubkey_hex.clone(),
        wallet_pubkey_hex,
        created_at_unix,
        expires_at_unix,
        decision: PairingAckDecisionV1::Approved,
        granted_capabilities: Some(granted_capabilities),
        rejection_reason: None,
    };

    let signed_ack = SignedPairingAckV1::new(ack, wallet_secret_key_hex)?;
    verify_pairing_approval(signed_request, &signed_ack, now_unix)?;
    Ok(signed_ack)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedSignIntentV1 {
    pub intent: SignIntentV1,
    pub signature_hex: String,
}

impl SignedSignIntentV1 {
    pub fn new(intent: SignIntentV1, secret_key_hex: &str) -> Result<Self, ZincError> {
        let signature_hex = intent.sign_schnorr_hex(secret_key_hex)?;
        Ok(Self {
            intent,
            signature_hex,
        })
    }

    pub fn verify(&self) -> Result<(), ZincError> {
        self.intent.verify_schnorr_hex(&self.signature_hex)
    }

    pub fn intent_id_hex(&self) -> Result<String, ZincError> {
        self.intent.intent_id_hex()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignSellerInputScopeV1 {
    pub intent_id: String,
    pub offer_id: String,
    pub seller_input_index: usize,
    pub input_count: usize,
    pub expected_seller_outpoint: String,
    pub expected_ask_sats: u64,
}

pub fn verify_sign_seller_input_scope(
    signed_intent: &SignedSignIntentV1,
    now_unix: i64,
) -> Result<SignSellerInputScopeV1, ZincError> {
    signed_intent.verify()?;
    if now_unix > signed_intent.intent.expires_at_unix {
        return Err(ZincError::OfferError(format!(
            "sign seller input intent expired at {}",
            signed_intent.intent.expires_at_unix
        )));
    }

    let details = match &signed_intent.intent.payload {
        SignIntentPayloadV1::SignSellerInput(details) => details,
        _ => {
            return Err(ZincError::OfferError(
                "sign intent payload action must be SignSellerInput".to_string(),
            ))
        }
    };
    details.validate()?;

    let expected_seller_outpoint = details
        .expected_seller_outpoint
        .parse::<OutPoint>()
        .map_err(|e| {
            ZincError::OfferError(format!(
                "invalid sign seller input expected_seller_outpoint `{}`: {e}",
                details.expected_seller_outpoint
            ))
        })?;
    let psbt = decode_sign_seller_input_psbt(&details.offer_psbt_base64)?;
    let seller_input_index = locate_expected_seller_input(&psbt, expected_seller_outpoint)?;
    enforce_sign_seller_input_scope_constraints(
        &psbt,
        seller_input_index,
        expected_seller_outpoint,
        details.expected_ask_sats,
    )?;

    Ok(SignSellerInputScopeV1 {
        intent_id: signed_intent.intent_id_hex()?,
        offer_id: details.offer_id.clone(),
        seller_input_index,
        input_count: psbt.inputs.len(),
        expected_seller_outpoint: details.expected_seller_outpoint.clone(),
        expected_ask_sats: details.expected_ask_sats,
    })
}

pub fn verify_sign_seller_input_scope_json(
    signed_intent_json: &str,
    now_unix: i64,
) -> Result<SignSellerInputScopeV1, ZincError> {
    let signed_intent: SignedSignIntentV1 =
        serde_json::from_str(signed_intent_json).map_err(|e| {
            ZincError::SerializationError(format!("invalid signed sign intent json: {e}"))
        })?;
    verify_sign_seller_input_scope(&signed_intent, now_unix)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedSignIntentReceiptV1 {
    pub receipt: SignIntentReceiptV1,
    pub signature_hex: String,
}

impl SignedSignIntentReceiptV1 {
    pub fn new(receipt: SignIntentReceiptV1, secret_key_hex: &str) -> Result<Self, ZincError> {
        let signature_hex = receipt.sign_schnorr_hex(secret_key_hex)?;
        Ok(Self {
            receipt,
            signature_hex,
        })
    }

    pub fn verify(&self) -> Result<(), ZincError> {
        self.receipt.verify_schnorr_hex(&self.signature_hex)
    }

    pub fn receipt_id_hex(&self) -> Result<String, ZincError> {
        self.receipt.receipt_id_hex()
    }
}

pub fn build_signed_sign_intent_rejection_receipt(
    signed_intent: &SignedSignIntentV1,
    wallet_secret_key_hex: &str,
    now_unix: i64,
    rejection_reason: &str,
) -> Result<SignedSignIntentReceiptV1, ZincError> {
    signed_intent.verify()?;
    ensure_non_empty("sign intent rejection reason", rejection_reason)?;
    let signer_pubkey_hex = pubkey_hex_from_secret_key(wallet_secret_key_hex)?;
    let receipt = SignIntentReceiptV1 {
        version: VERSION_V1,
        intent_id: signed_intent.intent_id_hex()?,
        pairing_id: signed_intent.intent.pairing_id.clone(),
        signer_pubkey_hex,
        created_at_unix: now_unix,
        status: SignIntentReceiptStatusV1::Rejected,
        signed_psbt_base64: None,
        artifact_json: None,
        error_message: Some(rejection_reason.to_string()),
    };
    let signed_receipt = SignedSignIntentReceiptV1::new(receipt, wallet_secret_key_hex)?;
    signed_receipt.verify()?;
    Ok(signed_receipt)
}

pub fn build_signed_sign_intent_approved_receipt(
    signed_intent: &SignedSignIntentV1,
    wallet_secret_key_hex: &str,
    now_unix: i64,
    signed_psbt_base64: Option<&str>,
    artifact_json: Option<&str>,
) -> Result<SignedSignIntentReceiptV1, ZincError> {
    signed_intent.verify()?;
    if now_unix > signed_intent.intent.expires_at_unix {
        return Err(ZincError::OfferError(format!(
            "sign intent expired at {}",
            signed_intent.intent.expires_at_unix
        )));
    }
    if signed_psbt_base64.is_none() && artifact_json.is_none() {
        return Err(ZincError::OfferError(
            "approved sign intent receipt must include signed_psbt_base64 or artifact_json"
                .to_string(),
        ));
    }

    if matches!(
        signed_intent.intent.payload,
        SignIntentPayloadV1::SignSellerInput(_)
    ) {
        verify_sign_seller_input_scope(signed_intent, now_unix)?;
        if signed_psbt_base64.is_none() {
            return Err(ZincError::OfferError(
                "approved SignSellerInput receipt must include signed_psbt_base64".to_string(),
            ));
        }
    }

    let signer_pubkey_hex = pubkey_hex_from_secret_key(wallet_secret_key_hex)?;
    let receipt = SignIntentReceiptV1 {
        version: VERSION_V1,
        intent_id: signed_intent.intent_id_hex()?,
        pairing_id: signed_intent.intent.pairing_id.clone(),
        signer_pubkey_hex,
        created_at_unix: now_unix,
        status: SignIntentReceiptStatusV1::Approved,
        signed_psbt_base64: signed_psbt_base64.map(str::to_string),
        artifact_json: artifact_json.map(str::to_string),
        error_message: None,
    };
    let signed_receipt = SignedSignIntentReceiptV1::new(receipt, wallet_secret_key_hex)?;
    signed_receipt.verify()?;
    Ok(signed_receipt)
}

fn decode_sign_seller_input_psbt(offer_psbt_base64: &str) -> Result<Psbt, ZincError> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(offer_psbt_base64.as_bytes())
        .map_err(|e| {
            ZincError::OfferError(format!("invalid sign seller input psbt base64: {e}"))
        })?;
    Psbt::deserialize(&bytes)
        .map_err(|e| ZincError::OfferError(format!("invalid sign seller input psbt: {e}")))
}

fn locate_expected_seller_input(
    psbt: &Psbt,
    expected_seller_outpoint: OutPoint,
) -> Result<usize, ZincError> {
    let seller_indices: Vec<usize> = psbt
        .unsigned_tx
        .input
        .iter()
        .enumerate()
        .filter_map(|(index, input)| {
            (input.previous_output == expected_seller_outpoint).then_some(index)
        })
        .collect();
    match seller_indices.len() {
        0 => Err(ZincError::OfferError(format!(
            "sign seller input psbt contains no expected seller input `{expected_seller_outpoint}`"
        ))),
        1 => Ok(seller_indices[0]),
        count => Err(ZincError::OfferError(format!(
            "sign seller input psbt contains {count} expected seller inputs `{expected_seller_outpoint}`"
        ))),
    }
}

fn enforce_sign_seller_input_scope_constraints(
    psbt: &Psbt,
    seller_input_index: usize,
    expected_seller_outpoint: OutPoint,
    expected_ask_sats: u64,
) -> Result<(), ZincError> {
    if seller_input_index != 0 {
        return Err(ZincError::OfferError(format!(
            "expected seller input `{expected_seller_outpoint}` must be first input (index 0), found index {seller_input_index}"
        )));
    }
    if psbt
        .inputs
        .get(seller_input_index)
        .is_some_and(psbt_input_has_signature)
    {
        return Err(ZincError::OfferError(format!(
            "expected seller input `{expected_seller_outpoint}` must be unsigned"
        )));
    }

    for (index, input) in psbt.inputs.iter().enumerate() {
        if index == seller_input_index {
            continue;
        }
        if !psbt_input_has_signature(input) {
            let outpoint = psbt.unsigned_tx.input[index].previous_output;
            return Err(ZincError::OfferError(format!(
                "buyer input `{outpoint}` must be signed before seller approval"
            )));
        }
    }

    let seller_postage_sats =
        seller_input_prevout_sats(psbt, seller_input_index, expected_seller_outpoint)?;
    if psbt.unsigned_tx.output.len() < 2 {
        return Err(ZincError::OfferError(
            "sign seller input psbt must include buyer postage and seller payout outputs"
                .to_string(),
        ));
    }

    let buyer_postage_out = &psbt.unsigned_tx.output[0];
    if buyer_postage_out.value.to_sat() != seller_postage_sats {
        return Err(ZincError::OfferError(format!(
            "expected buyer postage output at index 0 to equal seller postage {} sats; found {} sats",
            seller_postage_sats,
            buyer_postage_out.value.to_sat()
        )));
    }

    let expected_seller_payout = seller_postage_sats
        .checked_add(expected_ask_sats)
        .ok_or_else(|| {
            ZincError::OfferError(
                "sign seller input expected_ask_sats + postage overflows u64".to_string(),
            )
        })?;
    let seller_payout_out = &psbt.unsigned_tx.output[1];
    if seller_payout_out.value.to_sat() != expected_seller_payout {
        return Err(ZincError::OfferError(format!(
            "expected seller payout output at index 1 to equal ask+postage {} sats; found {} sats",
            expected_seller_payout,
            seller_payout_out.value.to_sat()
        )));
    }

    Ok(())
}

fn seller_input_prevout_sats(
    psbt: &Psbt,
    seller_input_index: usize,
    expected_seller_outpoint: OutPoint,
) -> Result<u64, ZincError> {
    let seller_input = psbt.inputs.get(seller_input_index).ok_or_else(|| {
        ZincError::OfferError("expected seller input metadata is missing".to_string())
    })?;
    let seller_txin = psbt
        .unsigned_tx
        .input
        .get(seller_input_index)
        .ok_or_else(|| ZincError::OfferError("expected seller tx input is missing".to_string()))?;

    seller_input
        .witness_utxo
        .as_ref()
        .map(|txout| txout.value.to_sat())
        .or_else(|| {
            seller_input.non_witness_utxo.as_ref().and_then(|prev_tx| {
                prev_tx
                    .output
                    .get(seller_txin.previous_output.vout as usize)
                    .map(|txout| txout.value.to_sat())
            })
        })
        .ok_or_else(|| {
            ZincError::OfferError(format!(
                "expected seller input `{expected_seller_outpoint}` is missing prevout value metadata"
            ))
        })
}

fn psbt_input_has_signature(input: &PsbtInput) -> bool {
    input.final_script_sig.is_some()
        || input.final_script_witness.is_some()
        || !input.partial_sigs.is_empty()
        || input.tap_key_sig.is_some()
        || !input.tap_script_sigs.is_empty()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PairingLinkApprovalV1 {
    pub pairing_id: String,
    pub agent_pubkey_hex: String,
    pub wallet_pubkey_hex: String,
    pub granted_capabilities: CapabilityPolicyV1,
    pub request_expires_at_unix: i64,
    pub ack_expires_at_unix: i64,
}

pub fn verify_pairing_approval(
    signed_request: &SignedPairingRequestV1,
    signed_ack: &SignedPairingAckV1,
    now_unix: i64,
) -> Result<PairingLinkApprovalV1, ZincError> {
    signed_request.verify()?;
    signed_ack.verify()?;

    let request = &signed_request.request;
    let ack = &signed_ack.ack;

    let pairing_id = signed_request.pairing_id_hex()?;
    if ack.pairing_id != pairing_id {
        return Err(ZincError::OfferError(
            "pairing ack pairing_id does not match pairing request".to_string(),
        ));
    }

    if ack.challenge_nonce != request.challenge_nonce {
        return Err(ZincError::OfferError(
            "pairing ack challenge_nonce does not match pairing request".to_string(),
        ));
    }

    if ack.agent_pubkey_hex != request.agent_pubkey_hex {
        return Err(ZincError::OfferError(
            "pairing ack agent_pubkey_hex does not match pairing request".to_string(),
        ));
    }

    if now_unix > request.expires_at_unix {
        return Err(ZincError::OfferError(
            "pairing request expired before ack verification".to_string(),
        ));
    }

    if now_unix > ack.expires_at_unix {
        return Err(ZincError::OfferError(
            "pairing ack expired before verification".to_string(),
        ));
    }

    if !matches!(ack.decision, PairingAckDecisionV1::Approved) {
        return Err(ZincError::OfferError(
            "pairing ack decision is not approved".to_string(),
        ));
    }

    let granted = ack.granted_capabilities.clone().ok_or_else(|| {
        ZincError::OfferError("approved pairing ack missing granted_capabilities".to_string())
    })?;
    validate_granted_capabilities_subset(&request.requested_capabilities, &granted)?;

    Ok(PairingLinkApprovalV1 {
        pairing_id,
        agent_pubkey_hex: request.agent_pubkey_hex.clone(),
        wallet_pubkey_hex: ack.wallet_pubkey_hex.clone(),
        granted_capabilities: granted,
        request_expires_at_unix: request.expires_at_unix,
        ack_expires_at_unix: ack.expires_at_unix,
    })
}

pub fn verify_pairing_approval_json(
    signed_request_json: &str,
    signed_ack_json: &str,
    now_unix: i64,
) -> Result<PairingLinkApprovalV1, ZincError> {
    let signed_request: SignedPairingRequestV1 = serde_json::from_str(signed_request_json)
        .map_err(|e| {
            ZincError::SerializationError(format!("invalid signed pairing request json: {e}"))
        })?;
    let signed_ack: SignedPairingAckV1 = serde_json::from_str(signed_ack_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid signed pairing ack json: {e}"))
    })?;
    verify_pairing_approval(&signed_request, &signed_ack, now_unix)
}

pub fn validate_signed_pairing_request_json(payload_json: &str) -> Result<String, ZincError> {
    let signed: SignedPairingRequestV1 = serde_json::from_str(payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid signed pairing request json: {e}"))
    })?;
    signed.verify()?;
    signed.pairing_id_hex()
}

pub fn validate_signed_pairing_ack_json(payload_json: &str) -> Result<String, ZincError> {
    let signed: SignedPairingAckV1 = serde_json::from_str(payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid signed pairing ack json: {e}"))
    })?;
    signed.verify()?;
    signed.ack_id_hex()
}

pub fn validate_pairing_ack_envelope_json(payload_json: &str) -> Result<String, ZincError> {
    let envelope: PairingAckEnvelopeV1 = serde_json::from_str(payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid pairing ack envelope json: {e}"))
    })?;
    envelope.validate()?;
    envelope.envelope_id_hex()
}

pub fn validate_signed_pairing_complete_receipt_json(
    payload_json: &str,
) -> Result<String, ZincError> {
    let signed: SignedPairingCompleteReceiptV1 =
        serde_json::from_str(payload_json).map_err(|e| {
            ZincError::SerializationError(format!(
                "invalid signed pairing complete receipt json: {e}"
            ))
        })?;
    signed.verify()?;
    signed.receipt_id_hex()
}

pub fn pairing_transport_tags(
    type_tag: &str,
    pairing_id: &str,
    recipient_pubkey_hex: &str,
) -> Result<Vec<Vec<String>>, ZincError> {
    if type_tag != NOSTR_PAIRING_ACK_TYPE_TAG_VALUE
        && type_tag != NOSTR_PAIRING_COMPLETE_RECEIPT_TYPE_TAG_VALUE
        && type_tag != NOSTR_SIGN_INTENT_TYPE_TAG_VALUE
        && type_tag != NOSTR_SIGN_INTENT_RECEIPT_TYPE_TAG_VALUE
    {
        return Err(ZincError::OfferError(format!(
            "unsupported pairing transport type tag `{type_tag}`"
        )));
    }
    validate_hex64("pairing id", pairing_id)?;
    validate_pubkey_hex("recipient pubkey", recipient_pubkey_hex)?;
    let pairing_hash = pairing_tag_hash_hex(pairing_id)?;
    Ok(vec![
        vec![
            NOSTR_TAG_APP_KEY.to_string(),
            NOSTR_SIGN_INTENT_APP_TAG_VALUE.to_string(),
        ],
        vec![NOSTR_TAG_TYPE_KEY.to_string(), type_tag.to_string()],
        vec![NOSTR_TAG_PAIRING_HASH_KEY.to_string(), pairing_hash],
        vec![
            NOSTR_TAG_RECIPIENT_PUBKEY_KEY.to_string(),
            recipient_pubkey_hex.to_string(),
        ],
    ])
}

pub fn build_pairing_transport_event(
    payload_json: &str,
    type_tag: &str,
    pairing_id: &str,
    recipient_pubkey_hex: &str,
    created_at_unix: u64,
    sender_secret_key_hex: &str,
) -> Result<NostrTransportEventV1, ZincError> {
    ensure_non_empty("pairing transport payload_json", payload_json)?;
    let tags = pairing_transport_tags(type_tag, pairing_id, recipient_pubkey_hex)?;
    let sender_pubkey_hex = pubkey_hex_from_secret_key(sender_secret_key_hex)?;

    let rumor = NostrTransportRumorV1 {
        id: None,
        pubkey: sender_pubkey_hex,
        created_at: created_at_unix,
        kind: PAIRING_TRANSPORT_RUMOR_EVENT_KIND,
        tags: tags.clone(),
        content: payload_json.to_string(),
    };
    rumor.verify()?;

    let rumor_json = serde_json::to_string(&rumor)
        .map_err(|e| ZincError::SerializationError(format!("failed to serialize rumor: {e}")))?;
    let seal_content = encrypt_pairing_transport_content(
        &rumor_json,
        sender_secret_key_hex,
        recipient_pubkey_hex,
    )?;
    let seal_event = NostrTransportEventV1::new(
        PAIRING_TRANSPORT_SEAL_EVENT_KIND,
        Vec::new(),
        seal_content,
        created_at_unix,
        sender_secret_key_hex,
    )?;

    let ephemeral_secret_key_hex = generate_secret_key_hex()?;
    let seal_event_json = serde_json::to_string(&seal_event).map_err(|e| {
        ZincError::SerializationError(format!("failed to serialize pairing transport seal: {e}"))
    })?;
    let wrapped_content = encrypt_pairing_transport_content(
        &seal_event_json,
        &ephemeral_secret_key_hex,
        recipient_pubkey_hex,
    )?;

    NostrTransportEventV1::new(
        PAIRING_TRANSPORT_EVENT_KIND,
        tags,
        wrapped_content,
        created_at_unix,
        &ephemeral_secret_key_hex,
    )
}

pub fn decode_pairing_transport_event_content_with_secret(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: &str,
) -> Result<String, ZincError> {
    event.verify()?;
    ensure_supported_pairing_transport_event_kind(event.kind)?;
    ensure_event_recipient_tag_matches_secret(event, recipient_secret_key_hex)?;
    decrypt_pairing_transport_gift_wrap_content(event, recipient_secret_key_hex)
}

pub fn encrypt_pairing_transport_content(
    payload_json: &str,
    sender_secret_key_hex: &str,
    recipient_pubkey_hex: &str,
) -> Result<String, ZincError> {
    ensure_non_empty("pairing transport payload_json", payload_json)?;
    validate_pubkey_hex(
        "pairing transport recipient_pubkey_hex",
        recipient_pubkey_hex,
    )?;
    let sender_secret_key = parse_nostr_secret_key_hex(sender_secret_key_hex)?;
    let recipient_pubkey = parse_nostr_pubkey_hex(recipient_pubkey_hex)?;
    nip44::encrypt(
        &sender_secret_key,
        &recipient_pubkey,
        payload_json,
        nip44::Version::V2,
    )
    .map_err(|e| ZincError::OfferError(format!("failed to encrypt pairing transport payload: {e}")))
}

pub fn decrypt_pairing_transport_content(
    payload_ciphertext: &str,
    recipient_secret_key_hex: &str,
    sender_pubkey_hex: &str,
) -> Result<String, ZincError> {
    ensure_non_empty("pairing transport payload_ciphertext", payload_ciphertext)?;
    validate_pubkey_hex("pairing transport sender_pubkey_hex", sender_pubkey_hex)?;
    let recipient_secret_key = parse_nostr_secret_key_hex(recipient_secret_key_hex)?;
    let sender_pubkey = parse_nostr_pubkey_hex(sender_pubkey_hex)?;
    nip44::decrypt(&recipient_secret_key, &sender_pubkey, payload_ciphertext).map_err(|e| {
        ZincError::OfferError(format!("failed to decrypt pairing transport payload: {e}"))
    })
}

pub fn validate_nostr_transport_event_json(payload_json: &str) -> Result<String, ZincError> {
    let event: NostrTransportEventV1 = serde_json::from_str(payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid nostr transport event json: {e}"))
    })?;
    event.verify()?;
    Ok(event.id)
}

pub fn decode_pairing_ack_envelope_event(
    event: &NostrTransportEventV1,
) -> Result<PairingAckEnvelopeV1, ZincError> {
    decode_pairing_ack_envelope_event_internal(event, None)
}

pub fn decode_pairing_ack_envelope_event_with_secret(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: &str,
) -> Result<PairingAckEnvelopeV1, ZincError> {
    decode_pairing_ack_envelope_event_internal(event, Some(recipient_secret_key_hex))
}

fn decode_pairing_ack_envelope_event_internal(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: Option<&str>,
) -> Result<PairingAckEnvelopeV1, ZincError> {
    event.verify()?;
    ensure_supported_pairing_transport_event_kind(event.kind)?;
    let payload_json = decode_pairing_transport_payload_json(
        event,
        NOSTR_PAIRING_ACK_TYPE_TAG_VALUE,
        recipient_secret_key_hex,
    )?;
    let envelope: PairingAckEnvelopeV1 = serde_json::from_str(&payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid pairing ack envelope json: {e}"))
    })?;
    envelope.validate()?;
    ensure_event_pairing_hash_matches(event, &envelope.signed_ack.ack.pairing_id)?;
    Ok(envelope)
}

pub fn decode_signed_pairing_complete_receipt_event(
    event: &NostrTransportEventV1,
) -> Result<SignedPairingCompleteReceiptV1, ZincError> {
    decode_signed_pairing_complete_receipt_event_internal(event, None)
}

pub fn decode_signed_pairing_complete_receipt_event_with_secret(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: &str,
) -> Result<SignedPairingCompleteReceiptV1, ZincError> {
    decode_signed_pairing_complete_receipt_event_internal(event, Some(recipient_secret_key_hex))
}

fn decode_signed_pairing_complete_receipt_event_internal(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: Option<&str>,
) -> Result<SignedPairingCompleteReceiptV1, ZincError> {
    event.verify()?;
    ensure_supported_pairing_transport_event_kind(event.kind)?;
    let payload_json = decode_pairing_transport_payload_json(
        event,
        NOSTR_PAIRING_COMPLETE_RECEIPT_TYPE_TAG_VALUE,
        recipient_secret_key_hex,
    )?;
    let signed: SignedPairingCompleteReceiptV1 =
        serde_json::from_str(&payload_json).map_err(|e| {
            ZincError::SerializationError(format!(
                "invalid signed pairing complete receipt json: {e}"
            ))
        })?;
    signed.verify()?;
    ensure_event_pairing_hash_matches(event, &signed.receipt.pairing_id)?;
    Ok(signed)
}

pub fn decode_signed_sign_intent_event(
    event: &NostrTransportEventV1,
) -> Result<SignedSignIntentV1, ZincError> {
    decode_signed_sign_intent_event_internal(event, None)
}

pub fn decode_signed_sign_intent_event_with_secret(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: &str,
) -> Result<SignedSignIntentV1, ZincError> {
    decode_signed_sign_intent_event_internal(event, Some(recipient_secret_key_hex))
}

fn decode_signed_sign_intent_event_internal(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: Option<&str>,
) -> Result<SignedSignIntentV1, ZincError> {
    event.verify()?;
    ensure_supported_pairing_transport_event_kind(event.kind)?;
    let payload_json = decode_pairing_transport_payload_json(
        event,
        NOSTR_SIGN_INTENT_TYPE_TAG_VALUE,
        recipient_secret_key_hex,
    )?;
    let signed: SignedSignIntentV1 = serde_json::from_str(&payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid signed sign intent json: {e}"))
    })?;
    signed.verify()?;
    ensure_event_pairing_hash_matches(event, &signed.intent.pairing_id)?;
    Ok(signed)
}

pub fn decode_signed_sign_intent_receipt_event(
    event: &NostrTransportEventV1,
) -> Result<SignedSignIntentReceiptV1, ZincError> {
    decode_signed_sign_intent_receipt_event_internal(event, None)
}

pub fn decode_signed_sign_intent_receipt_event_with_secret(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: &str,
) -> Result<SignedSignIntentReceiptV1, ZincError> {
    decode_signed_sign_intent_receipt_event_internal(event, Some(recipient_secret_key_hex))
}

fn decode_signed_sign_intent_receipt_event_internal(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: Option<&str>,
) -> Result<SignedSignIntentReceiptV1, ZincError> {
    event.verify()?;
    ensure_supported_pairing_transport_event_kind(event.kind)?;
    let payload_json = decode_pairing_transport_payload_json(
        event,
        NOSTR_SIGN_INTENT_RECEIPT_TYPE_TAG_VALUE,
        recipient_secret_key_hex,
    )?;
    let signed: SignedSignIntentReceiptV1 = serde_json::from_str(&payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid signed sign intent receipt json: {e}"))
    })?;
    signed.verify()?;
    ensure_event_pairing_hash_matches(event, &signed.receipt.pairing_id)?;
    Ok(signed)
}

pub fn validate_signed_sign_intent_json(payload_json: &str) -> Result<String, ZincError> {
    let signed: SignedSignIntentV1 = serde_json::from_str(payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid signed sign intent json: {e}"))
    })?;
    signed.verify()?;
    signed.intent_id_hex()
}

pub fn validate_signed_sign_intent_receipt_json(payload_json: &str) -> Result<String, ZincError> {
    let signed: SignedSignIntentReceiptV1 = serde_json::from_str(payload_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid signed sign intent receipt json: {e}"))
    })?;
    signed.verify()?;
    signed.receipt_id_hex()
}

pub fn pubkey_hex_from_secret_key(secret_key_hex: &str) -> Result<String, ZincError> {
    let secret_key = SecretKey::from_str(secret_key_hex)
        .map_err(|e| ZincError::OfferError(format!("invalid secret key: {e}")))?;
    Ok(pubkey_hex_from_secret(&secret_key))
}

pub fn generate_secret_key_hex() -> Result<String, ZincError> {
    let mut candidate = [0u8; 32];
    loop {
        getrandom(&mut candidate)
            .map_err(|e| ZincError::OfferError(format!("failed to generate secret key: {e}")))?;
        if let Ok(secret_key) = SecretKey::from_slice(&candidate) {
            return Ok(bytes_to_hex_lower(&secret_key.secret_bytes()));
        }
    }
}

pub fn pairing_tag_hash_hex(pairing_id: &str) -> Result<String, ZincError> {
    validate_hex64("pairing id", pairing_id)?;
    let digest = domain_separated_digest(DOMAIN_PAIRING_TAG_HASH, pairing_id.as_bytes())?;
    Ok(digest_hex(&digest))
}

fn ensure_event_tags_match(
    event: &NostrTransportEventV1,
    expected_type_tag: &str,
) -> Result<(), ZincError> {
    let app_tag = event.tag_value(NOSTR_TAG_APP_KEY).ok_or_else(|| {
        ZincError::OfferError(format!(
            "nostr transport event missing `{NOSTR_TAG_APP_KEY}` tag"
        ))
    })?;
    if app_tag != NOSTR_SIGN_INTENT_APP_TAG_VALUE {
        return Err(ZincError::OfferError(format!(
            "nostr transport app tag must be `{NOSTR_SIGN_INTENT_APP_TAG_VALUE}`"
        )));
    }

    let type_tag = event.tag_value(NOSTR_TAG_TYPE_KEY).ok_or_else(|| {
        ZincError::OfferError(format!(
            "nostr transport event missing `{NOSTR_TAG_TYPE_KEY}` tag"
        ))
    })?;
    if type_tag != expected_type_tag {
        return Err(ZincError::OfferError(format!(
            "nostr transport type tag mismatch (expected `{expected_type_tag}`, got `{type_tag}`)"
        )));
    }

    let pairing_hash = event.tag_value(NOSTR_TAG_PAIRING_HASH_KEY).ok_or_else(|| {
        ZincError::OfferError(format!(
            "nostr transport event missing `{NOSTR_TAG_PAIRING_HASH_KEY}` tag"
        ))
    })?;
    validate_hex64("nostr transport pairing hash tag", pairing_hash)?;
    Ok(())
}

fn bytes_to_hex_lower(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(nibble_to_hex(byte >> 4));
        out.push(nibble_to_hex(byte & 0x0f));
    }
    out
}

fn nibble_to_hex(nibble: u8) -> char {
    match nibble {
        0..=9 => (b'0' + nibble) as char,
        10..=15 => (b'a' + (nibble - 10)) as char,
        _ => '0',
    }
}

fn ensure_event_pairing_hash_matches(
    event: &NostrTransportEventV1,
    pairing_id: &str,
) -> Result<(), ZincError> {
    let expected = pairing_tag_hash_hex(pairing_id)?;
    let actual = event.tag_value(NOSTR_TAG_PAIRING_HASH_KEY).ok_or_else(|| {
        ZincError::OfferError(format!(
            "nostr transport event missing `{NOSTR_TAG_PAIRING_HASH_KEY}` tag"
        ))
    })?;
    if actual != expected {
        return Err(ZincError::OfferError(
            "nostr transport pairing hash tag does not match payload pairing id".to_string(),
        ));
    }
    Ok(())
}

fn ensure_supported_pairing_transport_event_kind(kind: u64) -> Result<(), ZincError> {
    if kind == PAIRING_TRANSPORT_EVENT_KIND {
        return Ok(());
    }
    Err(ZincError::OfferError(format!(
        "unexpected nostr event kind {kind}, expected {PAIRING_TRANSPORT_EVENT_KIND}"
    )))
}

fn decrypt_pairing_transport_gift_wrap_content(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: &str,
) -> Result<String, ZincError> {
    let seal_json =
        decrypt_pairing_transport_content(&event.content, recipient_secret_key_hex, &event.pubkey)?;
    let seal_event: NostrTransportEventV1 = serde_json::from_str(&seal_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid pairing transport seal json: {e}"))
    })?;
    seal_event.verify()?;
    if seal_event.kind != PAIRING_TRANSPORT_SEAL_EVENT_KIND {
        return Err(ZincError::OfferError(format!(
            "unexpected pairing transport seal kind {}, expected {}",
            seal_event.kind, PAIRING_TRANSPORT_SEAL_EVENT_KIND
        )));
    }

    let rumor_json = decrypt_pairing_transport_content(
        &seal_event.content,
        recipient_secret_key_hex,
        &seal_event.pubkey,
    )?;
    let rumor: NostrTransportRumorV1 = serde_json::from_str(&rumor_json).map_err(|e| {
        ZincError::SerializationError(format!("invalid pairing transport rumor json: {e}"))
    })?;
    rumor.verify()?;
    if !rumor.pubkey.eq_ignore_ascii_case(&seal_event.pubkey) {
        return Err(ZincError::OfferError(
            "pairing transport rumor sender pubkey mismatch".to_string(),
        ));
    }
    Ok(rumor.content)
}

fn decode_pairing_transport_payload_json(
    event: &NostrTransportEventV1,
    expected_type_tag: &str,
    recipient_secret_key_hex: Option<&str>,
) -> Result<String, ZincError> {
    ensure_event_tags_match(event, expected_type_tag)?;
    if let Some(secret_key_hex) = recipient_secret_key_hex {
        return decode_pairing_transport_event_content_with_secret(event, secret_key_hex);
    }
    Ok(event.content.clone())
}

fn ensure_event_recipient_tag_matches_secret(
    event: &NostrTransportEventV1,
    recipient_secret_key_hex: &str,
) -> Result<(), ZincError> {
    let recipient_pubkey_hex = pubkey_hex_from_secret_key(recipient_secret_key_hex)?;
    let actual = event
        .tag_value(NOSTR_TAG_RECIPIENT_PUBKEY_KEY)
        .ok_or_else(|| {
            ZincError::OfferError(format!(
                "nostr transport event missing `{NOSTR_TAG_RECIPIENT_PUBKEY_KEY}` tag"
            ))
        })?;
    if actual != recipient_pubkey_hex {
        return Err(ZincError::OfferError(
            "nostr transport recipient pubkey tag does not match recipient secret key".to_string(),
        ));
    }
    Ok(())
}

fn parse_nostr_secret_key_hex(secret_key_hex: &str) -> Result<NostrSecretKey, ZincError> {
    NostrSecretKey::from_str(secret_key_hex)
        .map_err(|e| ZincError::OfferError(format!("invalid secret key: {e}")))
}

fn parse_nostr_pubkey_hex(pubkey_hex: &str) -> Result<NostrPublicKey, ZincError> {
    NostrPublicKey::from_hex(pubkey_hex)
        .map_err(|e| ZincError::OfferError(format!("invalid pubkey hex: {e}")))
}

fn compute_nostr_event_id_hex(
    pubkey_hex: &str,
    created_at: u64,
    kind: u64,
    tags: &[Vec<String>],
    content: &str,
) -> Result<String, ZincError> {
    let payload = serde_json::json!([0, pubkey_hex, created_at, kind, tags, content]);
    let serialized = serde_json::to_vec(&payload).map_err(|e| {
        ZincError::SerializationError(format!("failed to serialize nostr event payload: {e}"))
    })?;
    let digest = sha256::Hash::hash(&serialized);
    Ok(digest.to_string())
}

fn sign_nostr_event_id_hex(
    event_id_hex: &str,
    secret_key: &SecretKey,
) -> Result<String, ZincError> {
    let digest = hex_to_digest32(event_id_hex)?;
    let message = Message::from_digest(digest);
    let secp = Secp256k1::new();
    let keypair = Keypair::from_secret_key(&secp, secret_key);
    let signature = secp.sign_schnorr_no_aux_rand(&message, &keypair);
    Ok(signature.to_string())
}

fn hex_to_digest32(hex: &str) -> Result<[u8; 32], ZincError> {
    validate_hex64("digest", hex)?;
    let mut bytes = [0u8; 32];
    for (idx, chunk) in hex.as_bytes().chunks_exact(2).enumerate() {
        let part = std::str::from_utf8(chunk)
            .map_err(|e| ZincError::OfferError(format!("invalid digest hex utf8: {e}")))?;
        bytes[idx] = u8::from_str_radix(part, 16)
            .map_err(|e| ZincError::OfferError(format!("invalid digest hex byte: {e}")))?;
    }
    Ok(bytes)
}

fn validate_version(version: u8) -> Result<(), ZincError> {
    if version != VERSION_V1 {
        return Err(ZincError::OfferError(format!(
            "unsupported protocol version {version}"
        )));
    }
    Ok(())
}

fn ensure_non_empty(label: &str, value: &str) -> Result<(), ZincError> {
    if value.trim().is_empty() {
        return Err(ZincError::OfferError(format!("{label} must not be empty")));
    }
    Ok(())
}

fn validate_nonce(label: &str, nonce: &str) -> Result<(), ZincError> {
    ensure_non_empty(label, nonce)?;
    if nonce.len() > 256 {
        return Err(ZincError::OfferError(format!(
            "{label} is too long (max 256 chars)"
        )));
    }
    Ok(())
}

fn validate_expiry_window(created_at_unix: i64, expires_at_unix: i64) -> Result<(), ZincError> {
    if expires_at_unix <= created_at_unix {
        return Err(ZincError::OfferError(
            "expires_at_unix must be greater than created_at_unix".to_string(),
        ));
    }
    Ok(())
}

fn validate_unique_relays(relays: &[String]) -> Result<(), ZincError> {
    let mut seen = HashSet::new();
    for relay in relays {
        ensure_non_empty("relay url", relay)?;
        if !seen.insert(relay.to_ascii_lowercase()) {
            return Err(ZincError::OfferError(
                "duplicate relay url in pairing request".to_string(),
            ));
        }
    }
    Ok(())
}

fn validate_granted_capabilities_subset(
    requested: &CapabilityPolicyV1,
    granted: &CapabilityPolicyV1,
) -> Result<(), ZincError> {
    requested.validate()?;
    granted.validate()?;

    let requested_actions: HashSet<SignIntentActionV1> =
        requested.allowed_actions.iter().copied().collect();
    for action in &granted.allowed_actions {
        if !requested_actions.contains(action) {
            return Err(ZincError::OfferError(format!(
                "granted capability action `{action:?}` was not requested"
            )));
        }
    }

    let requested_networks: HashSet<String> = requested
        .allowed_networks
        .iter()
        .map(|network| normalize_network(network))
        .collect();
    for network in &granted.allowed_networks {
        let normalized = normalize_network(network);
        if !requested_networks.contains(&normalized) {
            return Err(ZincError::OfferError(format!(
                "granted capability network `{network}` was not requested"
            )));
        }
    }

    validate_capability_limit(
        "max_sats_per_intent",
        requested.max_sats_per_intent,
        granted.max_sats_per_intent,
    )?;
    validate_capability_limit(
        "daily_spend_limit_sats",
        requested.daily_spend_limit_sats,
        granted.daily_spend_limit_sats,
    )?;
    validate_capability_limit(
        "max_fee_rate_sat_vb",
        requested.max_fee_rate_sat_vb,
        granted.max_fee_rate_sat_vb,
    )?;

    Ok(())
}

fn validate_capability_limit(
    label: &str,
    requested: Option<u64>,
    granted: Option<u64>,
) -> Result<(), ZincError> {
    match (requested, granted) {
        (Some(requested_limit), Some(granted_limit)) if granted_limit <= requested_limit => Ok(()),
        (Some(requested_limit), Some(granted_limit)) => Err(ZincError::OfferError(format!(
            "granted {label}={granted_limit} exceeds requested limit {requested_limit}"
        ))),
        (Some(_), None) => Err(ZincError::OfferError(format!(
            "granted {label} must be set because request set a limit"
        ))),
        (None, _) => Ok(()),
    }
}

fn validate_hex64(label: &str, value: &str) -> Result<(), ZincError> {
    if value.len() != 64 {
        return Err(ZincError::OfferError(format!(
            "{label} must be 64 hex characters"
        )));
    }
    if !value.chars().all(|ch| ch.is_ascii_hexdigit()) {
        return Err(ZincError::OfferError(format!("{label} must be valid hex")));
    }
    Ok(())
}

fn validate_pubkey_hex(label: &str, value: &str) -> Result<(), ZincError> {
    ensure_non_empty(label, value)?;
    XOnlyPublicKey::from_str(value)
        .map_err(|e| ZincError::OfferError(format!("{label} is invalid: {e}")))?;
    Ok(())
}

fn normalize_network(network: &str) -> String {
    let lower = network.trim().to_ascii_lowercase();
    if lower == "bitcoin" {
        "mainnet".to_string()
    } else {
        lower
    }
}

fn is_supported_network(network: &str) -> bool {
    matches!(network, "mainnet" | "signet" | "testnet" | "regtest")
}

fn domain_separated_digest(domain: &str, canonical_payload: &[u8]) -> Result<[u8; 32], ZincError> {
    let mut bytes = Vec::with_capacity(domain.len() + 1 + canonical_payload.len());
    bytes.extend_from_slice(domain.as_bytes());
    bytes.push(0u8);
    bytes.extend_from_slice(canonical_payload);
    let digest = sha256::Hash::hash(&bytes);
    Ok(digest.to_byte_array())
}

fn digest_hex(digest: &[u8; 32]) -> String {
    digest.iter().map(|b| format!("{b:02x}")).collect()
}

fn pubkey_hex_from_secret(secret_key: &SecretKey) -> String {
    let secp = Secp256k1::new();
    let keypair = Keypair::from_secret_key(&secp, secret_key);
    let (xonly, _) = XOnlyPublicKey::from_keypair(&keypair);
    xonly.to_string()
}

fn sign_payload_with_expected_pubkey(
    secret_key_hex: &str,
    expected_pubkey_hex: &str,
    domain: &str,
    canonical_payload: &[u8],
) -> Result<String, ZincError> {
    let secret_key = SecretKey::from_str(secret_key_hex)
        .map_err(|e| ZincError::OfferError(format!("invalid secret key: {e}")))?;

    let actual_pubkey_hex = pubkey_hex_from_secret(&secret_key);
    if actual_pubkey_hex != expected_pubkey_hex {
        return Err(ZincError::OfferError(format!(
            "secret key does not match expected pubkey {expected_pubkey_hex}"
        )));
    }

    let digest = domain_separated_digest(domain, canonical_payload)?;
    let message = Message::from_digest(digest);
    let secp = Secp256k1::new();
    let keypair = Keypair::from_secret_key(&secp, &secret_key);
    let signature = secp.sign_schnorr_no_aux_rand(&message, &keypair);
    Ok(signature.to_string())
}

fn verify_payload_signature(
    pubkey_hex: &str,
    signature_hex: &str,
    domain: &str,
    canonical_payload: &[u8],
) -> Result<(), ZincError> {
    let pubkey = XOnlyPublicKey::from_str(pubkey_hex)
        .map_err(|e| ZincError::OfferError(format!("invalid signature pubkey: {e}")))?;
    let signature = Signature::from_str(signature_hex)
        .map_err(|e| ZincError::OfferError(format!("invalid schnorr signature: {e}")))?;
    let digest = domain_separated_digest(domain, canonical_payload)?;
    let message = Message::from_digest(digest);

    let secp = Secp256k1::verification_only();
    secp.verify_schnorr(&signature, &message, &pubkey)
        .map_err(|e| ZincError::OfferError(format!("signature verification failed: {e}")))
}