freenet-stdlib 0.11.0

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

use blake3::{traits::digest::Digest, Hasher as Blake3};
use serde::{Deserialize, Deserializer, Serialize};
use serde_with::serde_as;

use crate::generated::client_request::{
    DelegateKey as FbsDelegateKey, InboundDelegateMsg as FbsInboundDelegateMsg,
    InboundDelegateMsgType,
};

use crate::common_generated::common::SecretsId as FbsSecretsId;

use crate::client_api::{fixed_size_field, unknown_union_discriminant, TryFromFbs, WsApiError};
use crate::contract_interface::{RelatedContracts, UpdateData, CONTRACT_KEY_SIZE};
use crate::prelude::{ContractInstanceId, WrappedState};
use crate::versioning::ContractContainer;
use crate::{code_hash::CodeHash, prelude::Parameters};

const DELEGATE_HASH_LENGTH: usize = 32;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delegate<'a> {
    #[serde(borrow)]
    parameters: Parameters<'a>,
    #[serde(borrow)]
    pub data: DelegateCode<'a>,
    key: DelegateKey,
}

impl Delegate<'_> {
    pub fn key(&self) -> &DelegateKey {
        &self.key
    }

    pub fn code(&self) -> &DelegateCode<'_> {
        &self.data
    }

    pub fn code_hash(&self) -> &CodeHash {
        &self.data.code_hash
    }

    pub fn params(&self) -> &Parameters<'_> {
        &self.parameters
    }

    pub fn into_owned(self) -> Delegate<'static> {
        Delegate {
            parameters: self.parameters.into_owned(),
            data: self.data.into_owned(),
            key: self.key,
        }
    }

    pub fn size(&self) -> usize {
        self.parameters.size() + self.data.size()
    }

    pub(crate) fn deserialize_delegate<'de, D>(deser: D) -> Result<Delegate<'static>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let data: Delegate<'de> = Deserialize::deserialize(deser)?;
        Ok(data.into_owned())
    }
}

impl PartialEq for Delegate<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

impl Eq for Delegate<'_> {}

impl<'a> From<(&DelegateCode<'a>, &Parameters<'a>)> for Delegate<'a> {
    fn from((data, parameters): (&DelegateCode<'a>, &Parameters<'a>)) -> Self {
        Self {
            key: DelegateKey::from_params_and_code(parameters, data),
            parameters: parameters.clone(),
            data: data.clone(),
        }
    }
}

/// Executable delegate
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde_as]
pub struct DelegateCode<'a> {
    #[serde_as(as = "serde_with::Bytes")]
    #[serde(borrow)]
    pub(crate) data: Cow<'a, [u8]>,
    // todo: skip serializing and instead compute it
    pub(crate) code_hash: CodeHash,
}

impl DelegateCode<'static> {
    /// Loads the contract raw wasm module, without any version.
    pub fn load_raw(path: &Path) -> Result<Self, std::io::Error> {
        let contract_data = Self::load_bytes(path)?;
        Ok(DelegateCode::from(contract_data))
    }

    pub(crate) fn load_bytes(path: &Path) -> Result<Vec<u8>, std::io::Error> {
        let mut contract_file = File::open(path)?;
        let mut contract_data = if let Ok(md) = contract_file.metadata() {
            Vec::with_capacity(md.len() as usize)
        } else {
            Vec::new()
        };
        contract_file.read_to_end(&mut contract_data)?;
        Ok(contract_data)
    }
}

impl DelegateCode<'_> {
    /// Delegate code hash.
    pub fn hash(&self) -> &CodeHash {
        &self.code_hash
    }

    /// Returns the `Base58` string representation of the delegate key.
    pub fn hash_str(&self) -> String {
        Self::encode_hash(&self.code_hash.0)
    }

    /// Reference to delegate code.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Returns the `Base58` string representation of a hash.
    pub fn encode_hash(hash: &[u8; DELEGATE_HASH_LENGTH]) -> String {
        bs58::encode(hash)
            .with_alphabet(bs58::Alphabet::BITCOIN)
            .into_string()
    }

    pub fn into_owned(self) -> DelegateCode<'static> {
        DelegateCode {
            code_hash: self.code_hash,
            data: Cow::from(self.data.into_owned()),
        }
    }

    pub fn size(&self) -> usize {
        self.data.len()
    }
}

impl PartialEq for DelegateCode<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.code_hash == other.code_hash
    }
}

impl Eq for DelegateCode<'_> {}

impl AsRef<[u8]> for DelegateCode<'_> {
    fn as_ref(&self) -> &[u8] {
        self.data.borrow()
    }
}

impl From<Vec<u8>> for DelegateCode<'static> {
    fn from(data: Vec<u8>) -> Self {
        let key = CodeHash::from_code(data.as_slice());
        DelegateCode {
            data: Cow::from(data),
            code_hash: key,
        }
    }
}

impl<'a> From<&'a [u8]> for DelegateCode<'a> {
    fn from(code: &'a [u8]) -> Self {
        let key = CodeHash::from_code(code);
        DelegateCode {
            data: Cow::from(code),
            code_hash: key,
        }
    }
}

#[serde_as]
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub struct DelegateKey {
    #[serde_as(as = "[_; DELEGATE_HASH_LENGTH]")]
    key: [u8; DELEGATE_HASH_LENGTH],
    code_hash: CodeHash,
}

impl From<DelegateKey> for SecretsId {
    fn from(key: DelegateKey) -> SecretsId {
        SecretsId {
            hash: key.key,
            key: vec![],
        }
    }
}

impl DelegateKey {
    pub const fn new(key: [u8; DELEGATE_HASH_LENGTH], code_hash: CodeHash) -> Self {
        Self { key, code_hash }
    }

    fn from_params_and_code<'a>(
        params: impl Borrow<Parameters<'a>>,
        wasm_code: impl Borrow<DelegateCode<'a>>,
    ) -> Self {
        let code = wasm_code.borrow();
        let key = generate_id(params.borrow(), code);
        Self {
            key,
            code_hash: *code.hash(),
        }
    }

    pub fn encode(&self) -> String {
        bs58::encode(self.key)
            .with_alphabet(bs58::Alphabet::BITCOIN)
            .into_string()
    }

    pub fn code_hash(&self) -> &CodeHash {
        &self.code_hash
    }

    pub fn bytes(&self) -> &[u8] {
        self.key.as_ref()
    }

    pub fn from_params(
        code_hash: impl Into<String>,
        parameters: &Parameters,
    ) -> Result<Self, bs58::decode::Error> {
        let mut code_key = [0; DELEGATE_HASH_LENGTH];
        bs58::decode(code_hash.into())
            .with_alphabet(bs58::Alphabet::BITCOIN)
            .onto(&mut code_key)?;
        let mut hasher = Blake3::new();
        hasher.update(code_key.as_slice());
        hasher.update(parameters.as_ref());
        let full_key_arr = hasher.finalize();

        debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
        let mut key = [0; DELEGATE_HASH_LENGTH];
        key.copy_from_slice(&full_key_arr);

        Ok(Self {
            key,
            code_hash: CodeHash(code_key),
        })
    }
}

impl Deref for DelegateKey {
    type Target = [u8; DELEGATE_HASH_LENGTH];

    fn deref(&self) -> &Self::Target {
        &self.key
    }
}

impl Display for DelegateKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.encode())
    }
}

impl<'a> TryFromFbs<&FbsDelegateKey<'a>> for DelegateKey {
    fn try_decode_fbs(key: &FbsDelegateKey<'a>) -> Result<Self, WsApiError> {
        // Both fields are `(required)` in the schema and BOTH need an explicit
        // length check, because the verifier only guarantees presence. `key`
        // used to be a bare `copy_from_slice` into a `[0; 32]`, which panics on
        // a length mismatch, while `code_hash` one line below was already
        // length-checked inside `CodeHash::try_from`. Keep them symmetric: a
        // future field added here needs the same treatment.
        let key_bytes =
            fixed_size_field::<DELEGATE_HASH_LENGTH>("DelegateKey.key", key.key().bytes())?;
        // `CodeHash::try_from` DOES length-check, so this field never panicked —
        // but its error stringifies to "invalid data", naming neither the field
        // nor the length. Symmetric treatment means the same message shape, not
        // merely the same safety, so it goes through the same helper.
        let code_hash = CodeHash::new(fixed_size_field::<CONTRACT_KEY_SIZE>(
            "DelegateKey.code_hash",
            key.code_hash().bytes(),
        )?);
        Ok(DelegateKey {
            key: key_bytes,
            code_hash,
        })
    }
}

/// Type of errors during interaction with a delegate.
///
/// Marked `#[non_exhaustive]` so future error variants can be added without a
/// source-level break. Downstream `match` sites must include a wildcard arm.
#[non_exhaustive]
#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
pub enum DelegateError {
    #[error("de/serialization error: {0}")]
    Deser(String),
    #[error("{0}")]
    Other(String),
}

fn generate_id<'a>(
    parameters: &Parameters<'a>,
    code_data: &DelegateCode<'a>,
) -> [u8; DELEGATE_HASH_LENGTH] {
    let contract_hash = code_data.hash();

    let mut hasher = Blake3::new();
    hasher.update(contract_hash.0.as_slice());
    hasher.update(parameters.as_ref());
    let full_key_arr = hasher.finalize();

    debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
    let mut key = [0; DELEGATE_HASH_LENGTH];
    key.copy_from_slice(&full_key_arr);
    key
}

#[serde_as]
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct SecretsId {
    #[serde_as(as = "serde_with::Bytes")]
    key: Vec<u8>,
    #[serde_as(as = "[_; 32]")]
    hash: [u8; 32],
}

impl SecretsId {
    pub fn new(key: Vec<u8>) -> Self {
        let mut hasher = Blake3::new();
        hasher.update(&key);
        let hashed = hasher.finalize();
        let mut hash = [0; 32];
        hash.copy_from_slice(&hashed);
        Self { key, hash }
    }

    pub fn encode(&self) -> String {
        bs58::encode(self.hash)
            .with_alphabet(bs58::Alphabet::BITCOIN)
            .into_string()
    }

    pub fn hash(&self) -> &[u8; 32] {
        &self.hash
    }
    pub fn key(&self) -> &[u8] {
        self.key.as_slice()
    }
}

impl Display for SecretsId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.encode())
    }
}

impl<'a> TryFromFbs<&FbsSecretsId<'a>> for SecretsId {
    fn try_decode_fbs(key: &FbsSecretsId<'a>) -> Result<Self, WsApiError> {
        // No production caller reaches this decoder today — `common.SecretsId`
        // appears in no client-request table. It is fixed anyway because the
        // `copy_from_slice` it replaces is a loaded gun for whoever wires it up:
        // `hash` is `(required)`, which the verifier reads as "present", not
        // "32 bytes", so the first client to send a short one would have
        // panicked the connection task.
        let key_hash = fixed_size_field::<32>("SecretsId.hash", key.hash().bytes())?;
        Ok(SecretsId {
            key: key.key().bytes().to_vec(),
            hash: key_hash,
        })
    }
}

/// Identifies where an inbound application message originated from.
///
/// When a web app sends a message to a delegate through the WebSocket API with
/// an authentication token, the runtime resolves the token to the originating
/// contract and wraps it in `MessageOrigin::WebApp`. When one delegate sends a
/// message to another via [`OutboundDelegateMsg::SendDelegateMessage`], the
/// runtime attests the caller's identity in `MessageOrigin::Delegate`.
/// Delegates receive this as the `origin` parameter of
/// [`DelegateInterface::process`].
///
/// This enum is `#[non_exhaustive]`: downstream code matching on it must
/// include a wildcard arm so future variants can be added without a
/// source-level breaking change.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum MessageOrigin {
    /// The message was sent by a web application backed by the given contract.
    WebApp(ContractInstanceId),
    /// The message was sent by another delegate via
    /// [`OutboundDelegateMsg::SendDelegateMessage`]. The carried key is the
    /// runtime-attested identity of the calling delegate; the receiver can
    /// trust it to make authorization decisions.
    ///
    /// Note: an inter-delegate message **replaces** rather than composes with
    /// any inherited `WebApp` origin the calling delegate may itself hold.
    /// The receiver sees only `Delegate(caller_key)` for the duration of the
    /// call, and does not gain contract access on behalf of any web app the
    /// caller was acting for. Authorization should be made on the calling
    /// delegate's identity alone.
    Delegate(DelegateKey),
}

/// A Delegate is a webassembly code designed to act as an agent for the user on
/// Freenet. Delegates can:
///
///  * Store private data on behalf of the user
///  * Create, read, and modify contracts
///  * Create other delegates
///  * Send and receive messages from other delegates and user interfaces
///  * Ask the user questions and receive answers
///
/// Example use cases:
///
///  * A delegate stores a private key for the user, other components can ask
///    the delegate to sign messages, it will ask the user for permission
///  * A delegate monitors an inbox contract and downloads new messages when
///    they arrive
///
/// # Example
///
/// ```ignore
/// use freenet_stdlib::prelude::*;
///
/// struct MyDelegate;
///
/// #[delegate]
/// impl DelegateInterface for MyDelegate {
///     fn process(
///         ctx: &mut DelegateCtx,
///         _params: Parameters<'static>,
///         _origin: Option<MessageOrigin>,
///         message: InboundDelegateMsg,
///     ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
///         // Access secrets synchronously - no round-trip needed!
///         if let Some(key) = ctx.get_secret(b"private_key") {
///             // use key...
///         }
///         ctx.set_secret(b"new_key", b"value");
///
///         // Read/write context for temporary state within a batch
///         ctx.write(b"some state");
///
///         Ok(vec![])
///     }
/// }
/// ```
pub trait DelegateInterface {
    /// Process inbound message, producing zero or more outbound messages in response.
    ///
    /// # Arguments
    /// - `ctx`: Mutable handle to the delegate's execution environment. Provides:
    ///   - **Context** (temporary): `read()`, `write()`, `len()`, `clear()` - state within a batch
    ///   - **Secrets** (persistent): `get_secret()`, `set_secret()`, `has_secret()`, `remove_secret()`
    /// - `parameters`: The delegate's initialization parameters.
    /// - `origin`: An optional [`MessageOrigin`] identifying where the message came from.
    ///   For messages sent by web applications, this is `MessageOrigin::WebApp(contract_id)`.
    /// - `message`: The inbound message to process.
    fn process(
        ctx: &mut crate::delegate_host::DelegateCtx,
        parameters: Parameters<'static>,
        origin: Option<MessageOrigin>,
        message: InboundDelegateMsg,
    ) -> Result<Vec<OutboundDelegateMsg>, DelegateError>;
}

#[serde_as]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DelegateContext(#[serde_as(as = "serde_with::Bytes")] Vec<u8>);

impl DelegateContext {
    pub const MAX_SIZE: usize = 4096 * 10 * 10;

    pub fn new(bytes: Vec<u8>) -> Self {
        assert!(bytes.len() < Self::MAX_SIZE);
        Self(bytes)
    }

    pub fn append(&mut self, bytes: &mut Vec<u8>) {
        assert!(self.0.len() + bytes.len() < Self::MAX_SIZE);
        self.0.append(bytes)
    }

    pub fn replace(&mut self, bytes: Vec<u8>) {
        assert!(bytes.len() < Self::MAX_SIZE);
        let _ = std::mem::replace(&mut self.0, bytes);
    }
}

impl AsRef<[u8]> for DelegateContext {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

/// Messages delivered **into** a delegate's `process()` function.
///
/// This is the inbound counterpart of [`OutboundDelegateMsg`] and sits on the
/// host↔delegate wire boundary.
///
/// Marked `#[non_exhaustive]` so future variants can be added without a
/// source-level break; downstream `match` sites must include a wildcard arm.
/// [`OutboundDelegateMsg`] is deliberately **not** marked, and the asymmetry is
/// the point — see the rationale on that enum. (An earlier version of this
/// comment asserted that `OutboundDelegateMsg` already carried the attribute.
/// It never has.)
///
/// # Wire format and compatibility
///
/// bincode, variant index 0..=N in **declaration order**. Two rules follow, and
/// the compiler enforces neither:
///
/// - **Never insert or reorder a variant.** That silently reassigns every later
///   tag, so delegate WASM compiled against an older stdlib decodes the same
///   bytes into a *different* variant — no error, just a message quietly
///   reinterpreted as another one. `delegate_msg_variant_tags_are_pinned` pins
///   the tag of every variant of both enums so a reorder fails CI instead.
/// - **Appending is compatible in exactly one direction.** An old sender's old
///   variant always decodes on a new receiver. A **new** sender's **new**
///   variant does **not** decode on an old receiver: bincode rejects the
///   unknown tag — as `ErrorKind::Custom("invalid value: integer `N`, expected
///   variant index 0 <= i < M")`, since bincode hands the index to serde's
///   derived visitor rather than validating it itself. (Not
///   `InvalidTagEncoding`, which bincode only ever produces for a bad `Option`
///   discriminant.) `#[non_exhaustive]` does
///   not change this — it is a source-level attribute with no effect on the
///   encoding, and serde has no unknown-variant fallback to fall back to.
///
/// For this enum the incompatible direction is a **new host → old delegate**,
/// and it is mostly unreachable in practice: the host emits a response variant
/// only in reply to the matching request variant, so a delegate that never
/// emits a request added in stdlib version X never receives the response added
/// in X. Deployed delegate WASM therefore keeps working against an upgraded
/// node. The genuinely constrained direction is delegate → host; see
/// [`OutboundDelegateMsg`].
///
/// The compatibility claims above are asserted, not merely asserted-in-prose,
/// by the `delegate_wire_compat` test module at the bottom of this file.
#[non_exhaustive]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum InboundDelegateMsg<'a> {
    ApplicationMessage(ApplicationMessage),
    UserResponse(#[serde(borrow)] UserInputResponse<'a>),
    GetContractResponse(GetContractResponse),
    PutContractResponse(PutContractResponse),
    UpdateContractResponse(UpdateContractResponse),
    SubscribeContractResponse(SubscribeContractResponse),
    ContractNotification(ContractNotification),
    DelegateMessage(DelegateMessage),
    // Appended in 0.10.0 at tag 8. New variants go at the END, never inserted —
    // see the wire-format note on this enum.
    UnsubscribeContractResponse(UnsubscribeContractResponse),
    /// Delivered by the host when a wakeup previously requested via
    /// `DelegateCtx::schedule_wakeup` fires. `tag` is the opaque
    /// value the delegate supplied when scheduling, echoed back verbatim so
    /// the delegate can identify which wakeup fired. Owned (`'static`).
    ///
    /// # Currently unreachable, and deliberately kept — do not delete it
    ///
    /// This is the *delivery* half of scheduled wakeup. Its *request* half,
    /// `DelegateCtx::schedule_wakeup`, was removed in 0.11.0 because no
    /// released freenet-core ever registered the
    /// `__frnt__delegate__schedule_wakeup` host import it called. Nothing can
    /// ask for a wakeup today, so this variant never arrives.
    ///
    /// That makes it an orphan, and an orphan invites tidying. Three reasons
    /// not to:
    ///
    /// - **Unreachable is not harmful.** The removed externs were removed
    ///   because a delegate calling one compiles and then fails at module
    ///   instantiation, leaving a healthy-looking node running a broken app.
    ///   A variant that never arrives does none of that. Only the first
    ///   problem justifies a breaking change.
    /// - **This one is on the wire.** Deleting it is a wire-format change on a
    ///   pinned enum, which is a much heavier act than deleting an unused
    ///   `extern` declaration — and the tag-pinning test below exists to stop
    ///   it happening casually.
    /// - **The feature is expected back.** freenet-core's host-side
    ///   implementation exists on the unmerged branch
    ///   `feat/3972-delegate-wakeup-core`. Removing the delivery half now buys
    ///   nothing and costs a second wire change when it lands.
    ///
    /// Restoring the feature means landing **both halves together**: the host
    /// registration in freenet-core and the stdlib extern plus its
    /// `host_imports::DECLARED_HOST_IMPORTS` entry. See freenet-core#5717 for
    /// the check that makes that ordering visible.
    ///
    /// # What the context cache holds during a wakeup
    ///
    /// Nothing the delegate should read. freenet-core's delegate context cache
    /// is keyed **per delegate**, not per conversation, and entries are pruned
    /// after `DELEGATE_CONTEXT_TTL` (10 minutes). Two consequences, both
    /// arguing the same way:
    ///
    /// - Any wakeup worth scheduling is far longer than 10 minutes, so whatever
    ///   context existed when it was scheduled is **gone** by the time it fires.
    /// - If the delegate happens to have a live context from some *other*
    ///   in-flight exchange inside that window, it belongs to that exchange.
    ///   Reading it during a wakeup would be reading another conversation's
    ///   working state.
    ///
    /// This is why the variant carries no `DelegateContext`: there is no
    /// coherent value to put in it. A delegate needing state across a wakeup
    /// reads it from its secrets, which is what core's own cache doc
    /// recommends for exactly this case.
    ///
    /// Appended at tag **9**, after `UnsubscribeContractResponse` at tag 8.
    WakeupFired {
        tag: Vec<u8>,
    },
}

impl InboundDelegateMsg<'_> {
    pub fn into_owned(self) -> InboundDelegateMsg<'static> {
        match self {
            InboundDelegateMsg::ApplicationMessage(r) => InboundDelegateMsg::ApplicationMessage(r),
            InboundDelegateMsg::UserResponse(r) => InboundDelegateMsg::UserResponse(r.into_owned()),
            InboundDelegateMsg::GetContractResponse(r) => {
                InboundDelegateMsg::GetContractResponse(r)
            }
            InboundDelegateMsg::PutContractResponse(r) => {
                InboundDelegateMsg::PutContractResponse(r)
            }
            InboundDelegateMsg::UpdateContractResponse(r) => {
                InboundDelegateMsg::UpdateContractResponse(r)
            }
            InboundDelegateMsg::SubscribeContractResponse(r) => {
                InboundDelegateMsg::SubscribeContractResponse(r)
            }
            InboundDelegateMsg::ContractNotification(r) => {
                InboundDelegateMsg::ContractNotification(r)
            }
            InboundDelegateMsg::DelegateMessage(r) => InboundDelegateMsg::DelegateMessage(r),
            InboundDelegateMsg::UnsubscribeContractResponse(r) => {
                InboundDelegateMsg::UnsubscribeContractResponse(r)
            }
            InboundDelegateMsg::WakeupFired { tag } => InboundDelegateMsg::WakeupFired { tag },
        }
    }

    pub fn get_context(&self) -> Option<&DelegateContext> {
        match self {
            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
                Some(context)
            }
            // UserResponse carries a context too. It was missing from both
            // accessors, so this returned None for it — the `_ => None`
            // wildcard below swallowed the omission silently. Found in review.
            InboundDelegateMsg::UserResponse(UserInputResponse { context, .. }) => Some(context),
            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
                Some(context)
            }
            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
                Some(context)
            }
            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
                context, ..
            }) => Some(context),
            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
                context,
                ..
            }) => Some(context),
            InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
                Some(context)
            }
            InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
                context,
                ..
            }) => Some(context),
            // `WakeupFired` carries no `DelegateContext`, so `None` here is
            // the honest answer rather than a missing arm. The reasoning lives
            // on the variant itself -- see `InboundDelegateMsg::WakeupFired`,
            // which explains both why a wakeup is not a reply and why the
            // context cache could not supply a coherent value anyway. Kept in
            // one place deliberately: a maintainer editing this accessor should
            // not meet a second, older version of the argument.
            InboundDelegateMsg::WakeupFired { .. } => None,
            // No wildcard, deliberately. The `_ => None` that used to sit here
            // is what let UserResponse go unhandled and silently report "no
            // context". Exhaustive means a new variant is a compile error here
            // instead — which is how `WakeupFired` above came to be considered
            // explicitly rather than defaulting into the wildcard.
            //
            // Correcting a premise this crate briefly asserted: "every variant
            // carries a context" was already false before `WakeupFired`, and
            // false about *this accessor* rather than about the structs. In
            // 0.8.5 this match listed seven variants, omitted `UserResponse`
            // — which does have a context field — and ended in `_ => None`. So
            // the claim was true of the types and wrong about the code. That
            // is why the `WakeupFired` exemption in the test asserts
            // `get_context()` is `None`: it pins what this function does, not
            // what the struct definitions look like.
        }
    }

    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
        match self {
            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
                Some(context)
            }
            // UserResponse carries a context too. It was missing from both
            // accessors, so this returned None for it — the `_ => None`
            // wildcard below swallowed the omission silently. Found in review.
            InboundDelegateMsg::UserResponse(UserInputResponse { context, .. }) => Some(context),
            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
                Some(context)
            }
            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
                Some(context)
            }
            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
                context, ..
            }) => Some(context),
            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
                context,
                ..
            }) => Some(context),
            InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
                Some(context)
            }
            InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
                context,
                ..
            }) => Some(context),
            // `WakeupFired` carries no context; see `get_context`.
            InboundDelegateMsg::WakeupFired { .. } => None,
            // No wildcard, deliberately. The `_ => None` that used to sit here
            // is what let UserResponse go unhandled and silently report "no
            // context". Exhaustive means a new variant is a compile error here
            // instead.
        }
    }
}

impl From<ApplicationMessage> for InboundDelegateMsg<'_> {
    fn from(value: ApplicationMessage) -> Self {
        Self::ApplicationMessage(value)
    }
}

impl<'a> TryFromFbs<&FbsInboundDelegateMsg<'a>> for InboundDelegateMsg<'a> {
    fn try_decode_fbs(msg: &FbsInboundDelegateMsg<'a>) -> Result<Self, WsApiError> {
        match msg.inbound_type() {
            InboundDelegateMsgType::common_ApplicationMessage => {
                let app_msg = msg.inbound_as_common_application_message().unwrap();
                let app_msg = ApplicationMessage {
                    payload: app_msg.payload().bytes().to_vec(),
                    context: DelegateContext::new(app_msg.context().bytes().to_vec()),
                    processed: app_msg.processed(),
                };
                Ok(InboundDelegateMsg::ApplicationMessage(app_msg))
            }
            InboundDelegateMsgType::UserInputResponse => {
                let user_response = msg.inbound_as_user_input_response().unwrap();
                let user_response = UserInputResponse {
                    request_id: user_response.request_id(),
                    response: ClientResponse::new(user_response.response().data().bytes().to_vec()),
                    context: DelegateContext::new(
                        user_response.delegate_context().bytes().to_vec(),
                    ),
                };
                Ok(InboundDelegateMsg::UserResponse(user_response))
            }
            // Reachable, not `unreachable!()`: the generated verifier for this
            // union ends in `_ => Ok(())`, so any discriminant a client sets —
            // including `NONE` — arrives here. See `unknown_union_discriminant`.
            other => Err(unknown_union_discriminant(
                "InboundDelegateMsgType",
                other.0,
            )),
        }
    }
}

#[non_exhaustive]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ApplicationMessage {
    pub payload: Vec<u8>,
    pub context: DelegateContext,
    pub processed: bool,
}

impl ApplicationMessage {
    pub fn new(payload: Vec<u8>) -> Self {
        Self {
            payload,
            context: DelegateContext::default(),
            processed: false,
        }
    }

    pub fn with_context(mut self, context: DelegateContext) -> Self {
        self.context = context;
        self
    }

    pub fn processed(mut self, p: bool) -> Self {
        self.processed = p;
        self
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserInputResponse<'a> {
    pub request_id: u32,
    #[serde(borrow)]
    pub response: ClientResponse<'a>,
    pub context: DelegateContext,
}

impl UserInputResponse<'_> {
    pub fn into_owned(self) -> UserInputResponse<'static> {
        UserInputResponse {
            request_id: self.request_id,
            response: self.response.into_owned(),
            context: self.context,
        }
    }
}

/// Messages emitted **out of** a delegate's `process()` function.
///
/// This is the outbound counterpart of [`InboundDelegateMsg`] and sits on the
/// same host↔delegate wire boundary.
///
/// # Deliberately not `#[non_exhaustive]`
///
/// Adding a variant here is a source-level break for any downstream crate that
/// matches on it exhaustively. That is the intended behaviour and it should not
/// be "fixed" by marking the enum.
///
/// Every variant of this enum is a **request the host must act on**. There is
/// one host — freenet-core — and it dispatches these in exhaustive matches with
/// no wildcard (`crates/core/src/contract.rs`, in the request loop and again in
/// the app-message filter). Marking this enum `#[non_exhaustive]` would force
/// those matches to grow `_ =>` arms, and a newly added variant would then
/// compile against the host with **no arm of its own**: the delegate's request
/// would fall into the wildcard, the call would appear to succeed, and nothing
/// would report that it did nothing.
///
/// The compile error is what stops that, and it is the only mechanism that
/// does. Keep it.
///
/// Two honest limits on this argument, because it is easy to claim more:
///
/// - **It forces an arm to exist, not a handler to be correct.** This crate's
///   own FlatBuffers encoder (`client_api::client_events`) has explicit arms
///   for six outbound variants that log an error and drop the message. The
///   compile error made someone write those arms deliberately; it could not
///   make them do anything useful.
/// - **It is not the bug behind this workstream.** A delegate
///   `SubscribeContractRequest` *is* handled by the host today. Its defect is
///   different and subtler: it registers no demand in the network, so the
///   subscription does not pin the contract (freenet-core#4669). Do not read
///   the compile-error argument as a fix for that; it is a guard against a
///   different failure that has not happened yet, which is the point of a
///   guard.
///
/// [`InboundDelegateMsg`] carries the opposite trade-off, and is marked: its
/// consumers are third-party delegate WASM, which can reasonably ignore a
/// variant it does not know about.
///
/// # Wire format and compatibility
///
/// bincode, variant index 0..=N in **declaration order**. Never insert or
/// reorder a variant: that silently reassigns every later tag, and deployed
/// delegate WASM built against an older stdlib would encode into what the host
/// now reads as a different variant. `delegate_msg_variant_tags_are_pinned`
/// pins every tag so a reorder fails CI rather than production.
///
/// Appending is compatible in one direction only, and this enum is the
/// direction that bites:
///
/// - **Old delegate → new host: fine, for appended VARIANTS.** The host
///   understands every tag an older delegate can emit, so deployed delegate
///   WASM keeps working against an upgraded node with no rebuild. This does
///   **not** extend to appending a FIELD to an existing variant's payload
///   struct, because a field breaks in the opposite direction. See
///   `struct_field_wire_compat` in `client_api::client_events`.
///   (`ApplicationMessage` is `#[non_exhaustive]`, which invites precisely that
///   edit. It is the only payload struct here that is.)
/// - **New delegate → old host: fails, and fails loudly.** bincode rejects the
///   unknown variant tag — as `ErrorKind::Custom("invalid value: integer `N`,
///   expected variant index 0 <= i < M")`, since it hands the index to serde's
///   derived visitor rather than validating it itself — so the host surfaces a
///   decode error on that message rather than misreading it.
///
/// There is deliberately **no feature-detection handshake**. A delegate cannot
/// ask the host which variants it understands, and adding a probe would itself
/// be a wire change with the same bootstrapping problem. The rule is therefore
/// the blunt one: **a delegate that emits a variant introduced in stdlib
/// version X requires a host built against stdlib >= X.**
///
/// Where a host function exists for the same capability, it is the better
/// choice against older hosts. Host functions are resolved **by name at module
/// instantiation**, so an import an old host does not provide fails at load
/// time with a named missing-import error, instead of mid-protocol on a decode.
///
/// That said, the `freenet_delegate_contracts` namespace holds only
/// `get_contract_state(_len)` — a local read. There is no host function for
/// writing or subscribing, so `PutContractRequest`, `UpdateContractRequest` and
/// `SubscribeContractRequest` below are the only route for those, and the
/// variant rule above governs them.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum OutboundDelegateMsg {
    // for the apps
    ApplicationMessage(ApplicationMessage),
    RequestUserInput(
        #[serde(deserialize_with = "OutboundDelegateMsg::deser_user_input_req")]
        UserInputRequest<'static>,
    ),
    // todo: remove when context can be accessed from the delegate environment and we pass it as reference
    ContextUpdated(DelegateContext),
    GetContractRequest(GetContractRequest),
    PutContractRequest(PutContractRequest),
    UpdateContractRequest(UpdateContractRequest),
    SubscribeContractRequest(SubscribeContractRequest),
    SendDelegateMessage(DelegateMessage),
    // Appended in 0.10.0 at tag 8. New variants go at the END, never inserted —
    // see the wire-format note on this enum.
    UnsubscribeContractRequest(UnsubscribeContractRequest),
}

impl From<ApplicationMessage> for OutboundDelegateMsg {
    fn from(req: ApplicationMessage) -> Self {
        Self::ApplicationMessage(req)
    }
}

impl From<GetContractRequest> for OutboundDelegateMsg {
    fn from(req: GetContractRequest) -> Self {
        Self::GetContractRequest(req)
    }
}

impl From<PutContractRequest> for OutboundDelegateMsg {
    fn from(req: PutContractRequest) -> Self {
        Self::PutContractRequest(req)
    }
}

impl From<UpdateContractRequest> for OutboundDelegateMsg {
    fn from(req: UpdateContractRequest) -> Self {
        Self::UpdateContractRequest(req)
    }
}

impl From<SubscribeContractRequest> for OutboundDelegateMsg {
    fn from(req: SubscribeContractRequest) -> Self {
        Self::SubscribeContractRequest(req)
    }
}

impl From<UnsubscribeContractRequest> for OutboundDelegateMsg {
    fn from(req: UnsubscribeContractRequest) -> Self {
        Self::UnsubscribeContractRequest(req)
    }
}

impl From<DelegateMessage> for OutboundDelegateMsg {
    fn from(msg: DelegateMessage) -> Self {
        Self::SendDelegateMessage(msg)
    }
}

impl OutboundDelegateMsg {
    fn deser_user_input_req<'de, D>(deser: D) -> Result<UserInputRequest<'static>, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <UserInputRequest<'de> as Deserialize>::deserialize(deser)?;
        Ok(value.into_owned())
    }

    pub fn processed(&self) -> bool {
        match self {
            OutboundDelegateMsg::ApplicationMessage(msg) => msg.processed,
            OutboundDelegateMsg::GetContractRequest(msg) => msg.processed,
            OutboundDelegateMsg::PutContractRequest(msg) => msg.processed,
            OutboundDelegateMsg::UpdateContractRequest(msg) => msg.processed,
            OutboundDelegateMsg::SubscribeContractRequest(msg) => msg.processed,
            OutboundDelegateMsg::UnsubscribeContractRequest(msg) => msg.processed,
            OutboundDelegateMsg::SendDelegateMessage(msg) => msg.processed,
            OutboundDelegateMsg::RequestUserInput(_) => true,
            OutboundDelegateMsg::ContextUpdated(_) => true,
        }
    }

    pub fn get_context(&self) -> Option<&DelegateContext> {
        match self {
            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
                Some(context)
            }
            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
                Some(context)
            }
            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
                Some(context)
            }
            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
                context, ..
            }) => Some(context),
            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
                context,
                ..
            }) => Some(context),
            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest {
                context,
                ..
            }) => Some(context),
            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
                Some(context)
            }
            _ => None,
        }
    }

    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
        match self {
            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
                Some(context)
            }
            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
                Some(context)
            }
            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
                Some(context)
            }
            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
                context, ..
            }) => Some(context),
            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
                context,
                ..
            }) => Some(context),
            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest {
                context,
                ..
            }) => Some(context),
            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
                Some(context)
            }
            _ => None,
        }
    }
}

/// Request to get contract state from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GetContractRequest {
    pub contract_id: ContractInstanceId,
    pub context: DelegateContext,
    pub processed: bool,
}

impl GetContractRequest {
    pub fn new(contract_id: ContractInstanceId) -> Self {
        Self {
            contract_id,
            context: Default::default(),
            processed: false,
        }
    }
}

/// Response containing contract state for a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GetContractResponse {
    pub contract_id: ContractInstanceId,
    /// The contract state, or None if the contract was not found locally.
    pub state: Option<WrappedState>,
    pub context: DelegateContext,
}

/// Request to store a new contract from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PutContractRequest {
    /// The contract code and parameters.
    pub contract: ContractContainer,
    /// The initial state for the contract.
    pub state: WrappedState,
    /// Related contracts that this contract depends on.
    #[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
    pub related_contracts: RelatedContracts<'static>,
    /// Context for the delegate.
    pub context: DelegateContext,
    /// Whether this request has been processed.
    pub processed: bool,
}

impl PutContractRequest {
    pub fn new(
        contract: ContractContainer,
        state: WrappedState,
        related_contracts: RelatedContracts<'static>,
    ) -> Self {
        Self {
            contract,
            state,
            related_contracts,
            context: Default::default(),
            processed: false,
        }
    }
}

/// Response after attempting to store a contract from a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PutContractResponse {
    /// The ID of the contract that was (attempted to be) stored.
    pub contract_id: ContractInstanceId,
    /// Success (Ok) or error message (Err).
    pub result: Result<(), String>,
    /// Context for the delegate.
    pub context: DelegateContext,
}

/// Request to update an existing contract's state from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UpdateContractRequest {
    /// The contract to update.
    pub contract_id: ContractInstanceId,
    /// The update to apply (full state or delta).
    #[serde(deserialize_with = "UpdateContractRequest::deser_update_data")]
    pub update: UpdateData<'static>,
    /// Context for the delegate.
    pub context: DelegateContext,
    /// Whether this request has been processed.
    pub processed: bool,
}

impl UpdateContractRequest {
    pub fn new(contract_id: ContractInstanceId, update: UpdateData<'static>) -> Self {
        Self {
            contract_id,
            update,
            context: Default::default(),
            processed: false,
        }
    }

    fn deser_update_data<'de, D>(deser: D) -> Result<UpdateData<'static>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = <UpdateData<'de> as Deserialize>::deserialize(deser)?;
        Ok(value.into_owned())
    }
}

/// Response after attempting to update a contract from a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UpdateContractResponse {
    /// The contract that was updated.
    pub contract_id: ContractInstanceId,
    /// Success (Ok) or error message (Err).
    pub result: Result<(), String>,
    /// Context for the delegate.
    pub context: DelegateContext,
}

/// Request to subscribe to a contract's state changes from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SubscribeContractRequest {
    /// The contract to subscribe to.
    pub contract_id: ContractInstanceId,
    /// Context for the delegate.
    pub context: DelegateContext,
    /// Whether this request has been processed.
    pub processed: bool,
}

impl SubscribeContractRequest {
    pub fn new(contract_id: ContractInstanceId) -> Self {
        Self {
            contract_id,
            context: Default::default(),
            processed: false,
        }
    }
}

/// Response after attempting to subscribe to a contract from a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SubscribeContractResponse {
    /// The contract subscribed to.
    pub contract_id: ContractInstanceId,
    /// Success (Ok) or error message (Err).
    pub result: Result<(), String>,
    /// Context for the delegate.
    pub context: DelegateContext,
}

/// Request to stop receiving a contract's state changes, from within a delegate.
///
/// The counterpart of [`SubscribeContractRequest`]. Before 0.10.0 a delegate had
/// no way to drop a subscription it had taken: the only release path was the
/// implicit cleanup when the delegate itself was unregistered, so a delegate
/// that had finished with a contract went on holding interest in it for as long
/// as the delegate existed. Specified in freenet-core#2830 alongside subscribe;
/// only subscribe was built.
///
/// Answered with [`InboundDelegateMsg::UnsubscribeContractResponse`].
///
/// Field order is the wire format. Do not reorder.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UnsubscribeContractRequest {
    /// The contract to stop receiving notifications for.
    pub contract_id: ContractInstanceId,
    /// Context for the delegate.
    pub context: DelegateContext,
    /// Whether this request has been processed.
    pub processed: bool,
}

impl UnsubscribeContractRequest {
    pub fn new(contract_id: ContractInstanceId) -> Self {
        Self {
            contract_id,
            context: Default::default(),
            processed: false,
        }
    }
}

/// Response after attempting to unsubscribe from a contract from a delegate.
///
/// **Unsubscribing a contract the delegate is not subscribed to reports
/// `Ok(())`, not an error.** That is not a convenience: it is what the host
/// actually does. Teardown goes through the same removal path that a
/// no-longer-present client id already takes as a no-op, so returning an error
/// would have the host inventing a failure it did not have. It also matches the
/// subscribe side, where a repeat subscribe is a set insert.
///
/// Field order is the wire format. Do not reorder.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UnsubscribeContractResponse {
    /// The contract unsubscribed from.
    pub contract_id: ContractInstanceId,
    /// Success (Ok) or error message (Err). Unsubscribing a contract the
    /// delegate was not subscribed to reports `Ok(())`.
    pub result: Result<(), String>,
    /// Context for the delegate.
    pub context: DelegateContext,
}

/// A message sent from one delegate to another.
///
/// Delegates can communicate with each other by emitting
/// `OutboundDelegateMsg::SendDelegateMessage` with a `DelegateMessage` targeting
/// another delegate. The runtime delivers it as `InboundDelegateMsg::DelegateMessage`
/// to the target delegate's `process()` function.
///
/// The `sender` field is overwritten by the runtime with the actual sender's key
/// (sender attestation), so delegates cannot spoof their identity.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DelegateMessage {
    /// The delegate to deliver this message to.
    pub target: DelegateKey,
    /// The delegate that sent this message (overwritten by runtime for attestation).
    pub sender: DelegateKey,
    /// Arbitrary message payload.
    pub payload: Vec<u8>,
    /// Delegate context, carried through the processing pipeline.
    pub context: DelegateContext,
    /// Runtime protocol flag indicating whether this message has been delivered.
    pub processed: bool,
}

impl DelegateMessage {
    pub fn new(target: DelegateKey, sender: DelegateKey, payload: Vec<u8>) -> Self {
        Self {
            target,
            sender,
            payload,
            context: DelegateContext::default(),
            processed: false,
        }
    }
}

/// Notification delivered to a delegate when a subscribed contract's state changes.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ContractNotification {
    /// The contract whose state changed.
    pub contract_id: ContractInstanceId,
    /// The new state of the contract.
    pub new_state: WrappedState,
    /// Context for the delegate.
    pub context: DelegateContext,
}

#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NotificationMessage<'a>(
    #[serde_as(as = "serde_with::Bytes")]
    #[serde(borrow)]
    Cow<'a, [u8]>,
);

impl TryFrom<&serde_json::Value> for NotificationMessage<'static> {
    type Error = ();

    fn try_from(json: &serde_json::Value) -> Result<NotificationMessage<'static>, ()> {
        // todo: validate format when we have a better idea of what we want here
        let bytes = serde_json::to_vec(json).unwrap();
        Ok(Self(Cow::Owned(bytes)))
    }
}

impl NotificationMessage<'_> {
    pub fn into_owned(self) -> NotificationMessage<'static> {
        NotificationMessage(self.0.into_owned().into())
    }
    pub fn bytes(&self) -> &[u8] {
        self.0.as_ref()
    }
}

#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClientResponse<'a>(
    #[serde_as(as = "serde_with::Bytes")]
    #[serde(borrow)]
    Cow<'a, [u8]>,
);

impl Deref for ClientResponse<'_> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl ClientResponse<'_> {
    pub fn new(response: Vec<u8>) -> Self {
        Self(response.into())
    }
    pub fn into_owned(self) -> ClientResponse<'static> {
        ClientResponse(self.0.into_owned().into())
    }
    pub fn bytes(&self) -> &[u8] {
        self.0.as_ref()
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserInputRequest<'a> {
    pub request_id: u32,
    #[serde(borrow)]
    /// An interpretable message by the notification system.
    pub message: NotificationMessage<'a>,
    /// If a response is required from the user they can be chosen from this list.
    pub responses: Vec<ClientResponse<'a>>,
}

impl UserInputRequest<'_> {
    pub fn into_owned(self) -> UserInputRequest<'static> {
        UserInputRequest {
            request_id: self.request_id,
            message: self.message.into_owned(),
            responses: self.responses.into_iter().map(|r| r.into_owned()).collect(),
        }
    }
}

#[doc(hidden)]
pub(crate) mod wasm_interface {
    //! Contains all the types to interface between the host environment and
    //! the wasm module execution.
    use super::*;
    use crate::memory::WasmLinearMem;

    #[repr(C)]
    #[derive(Debug, Clone, Copy)]
    pub struct DelegateInterfaceResult {
        ptr: i64,
        size: u32,
    }

    impl DelegateInterfaceResult {
        pub unsafe fn from_raw(ptr: i64, mem: &WasmLinearMem) -> Self {
            let result = Box::leak(Box::from_raw(crate::memory::buf::compute_ptr(
                ptr as *mut Self,
                mem,
            )));
            #[cfg(feature = "trace")]
            {
                tracing::trace!(
                    "got FFI result @ {ptr} ({:p}) -> {result:?}",
                    ptr as *mut Self
                );
            }
            *result
        }

        #[cfg(feature = "contract")]
        pub fn into_raw(self) -> i64 {
            #[cfg(feature = "trace")]
            {
                tracing::trace!("returning FFI -> {self:?}");
            }
            let ptr = Box::into_raw(Box::new(self));
            #[cfg(feature = "trace")]
            {
                tracing::trace!("FFI result ptr: {ptr:p} ({}i64)", ptr as i64);
            }
            ptr as _
        }

        pub unsafe fn unwrap(
            self,
            mem: WasmLinearMem,
        ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
            let ptr = crate::memory::buf::compute_ptr(self.ptr as *mut u8, &mem);
            let serialized = std::slice::from_raw_parts(ptr as *const u8, self.size as _);
            let value: Result<Vec<OutboundDelegateMsg>, DelegateError> =
                bincode::deserialize(serialized)
                    .map_err(|e| DelegateError::Other(format!("{e}")))?;
            #[cfg(feature = "trace")]
            {
                tracing::trace!(
                    "got result through FFI; addr: {:p} ({}i64, mapped: {ptr:p})
                     serialized: {serialized:?}
                     value: {value:?}",
                    self.ptr as *mut u8,
                    self.ptr
                );
            }
            value
        }
    }

    impl From<Result<Vec<OutboundDelegateMsg>, DelegateError>> for DelegateInterfaceResult {
        fn from(value: Result<Vec<OutboundDelegateMsg>, DelegateError>) -> Self {
            let serialized = bincode::serialize(&value).unwrap();
            let size = serialized.len() as _;
            let ptr = serialized.as_ptr();
            #[cfg(feature = "trace")]
            {
                tracing::trace!(
                    "sending result through FFI; addr: {ptr:p} ({}),\n  serialized: {serialized:?}\n  value: {value:?}",
                    ptr as i64
                );
            }
            std::mem::forget(serialized);
            Self {
                ptr: ptr as i64,
                size,
            }
        }
    }
}

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

    /// Wire-format pin: bincode encoding of `MessageOrigin::WebApp(..)` must
    /// stay byte-identical across stdlib releases. Deployed delegate WASM
    /// compiled against an older stdlib will receive these bytes from a
    /// host running the new stdlib and must continue to deserialize them.
    /// If this test ever fails, it is a wire-format break and is NOT
    /// publishable as a non-major bump.
    #[test]
    fn webapp_origin_wire_format_is_stable() {
        let id = ContractInstanceId::new([0xABu8; 32]);
        let origin = MessageOrigin::WebApp(id);
        let encoded = bincode::serialize(&origin).unwrap();

        // Variant tag 0 (4-byte LE u32 in default bincode config) followed by
        // the 32 raw bytes of the ContractInstanceId.
        let mut expected = vec![0u8, 0, 0, 0];
        expected.extend_from_slice(&[0xABu8; 32]);
        assert_eq!(encoded, expected);
    }

    /// Wire-format pin for the `Delegate` variant. Locks the full byte
    /// layout (variant tag + serde repr of `DelegateKey`) so that any future
    /// change to either `DelegateKey`'s serde or the workspace bincode
    /// config is caught loudly. If `DelegateKey`'s on-the-wire encoding
    /// changes, deployed delegates compiled against a previous stdlib will
    /// silently fail to deserialize inter-delegate origins — which is
    /// exactly the failure mode this test exists to prevent.
    #[test]
    fn delegate_origin_wire_format_is_stable() {
        let key = DelegateKey::new([0x11u8; 32], crate::code_hash::CodeHash::new([0x22u8; 32]));
        let origin = MessageOrigin::Delegate(key);
        let encoded = bincode::serialize(&origin).unwrap();

        // Variant tag 1 (4-byte LE u32 in default bincode config), followed
        // by the 32-byte `key` field, followed by the 32-byte `code_hash`
        // field of `DelegateKey`.
        let mut expected = vec![1u8, 0, 0, 0];
        expected.extend_from_slice(&[0x11u8; 32]);
        expected.extend_from_slice(&[0x22u8; 32]);
        assert_eq!(encoded, expected);

        // And it must still round-trip.
        let decoded: MessageOrigin = bincode::deserialize(&encoded).unwrap();
        assert!(matches!(decoded, MessageOrigin::Delegate(_)));
    }

    /// Wire-format pin for the first variant of [`InboundDelegateMsg`]. Pins
    /// the tag so that reordering the enum cannot silently shift existing
    /// deployed delegate WASM off the correct variant. Only tag+payload
    /// prefix is asserted (not the full ApplicationMessage byte layout),
    /// since ApplicationMessage's internal fields have their own stability
    /// expectations handled at a different layer. What matters here is that
    /// variant 0 stays `ApplicationMessage` on the wire.
    #[test]
    fn inbound_delegate_msg_wire_format_is_stable() {
        let msg = InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(vec![0xCC]));
        let encoded = bincode::serialize(&msg).unwrap();
        assert_eq!(
            encoded[..4],
            [0, 0, 0, 0],
            "ApplicationMessage must stay at variant tag 0 on the wire; \
             reordering InboundDelegateMsg variants is a wire-format break"
        );
        // And it must still round-trip into the same variant.
        let decoded: InboundDelegateMsg<'_> = bincode::deserialize(&encoded).unwrap();
        assert!(matches!(decoded, InboundDelegateMsg::ApplicationMessage(_)));
    }

    /// Wire-format pin for [`InboundDelegateMsg::WakeupFired`]. It is the 10th
    /// variant (declaration index 9), so its bincode tag must be `9` (4-byte
    /// LE) — it sits behind `UnsubscribeContractResponse` at tag 8. Once
    /// shipped this tag is frozen: reordering or inserting a variant ahead of
    /// it would silently redirect a host's wakeup delivery to the wrong variant
    /// on a delegate compiled against this stdlib.
    #[test]
    fn inbound_wakeup_fired_wire_format_is_stable() {
        let msg = InboundDelegateMsg::WakeupFired {
            tag: vec![0xAA, 0xBB],
        };
        let encoded = bincode::serialize(&msg).unwrap();

        // tag 9 (u32 LE) + Vec<u8> len (u64 LE = 2) + the two tag bytes.
        let mut expected = vec![9u8, 0, 0, 0];
        expected.extend_from_slice(&[2, 0, 0, 0, 0, 0, 0, 0]);
        expected.extend_from_slice(&[0xAA, 0xBB]);
        assert_eq!(
            encoded, expected,
            "WakeupFired must stay at variant tag 9 with a stable payload layout"
        );

        let decoded: InboundDelegateMsg<'_> = bincode::deserialize(&encoded).unwrap();
        assert!(matches!(
            decoded,
            InboundDelegateMsg::WakeupFired { tag } if tag == vec![0xAA, 0xBB]
        ));
    }
}

/// Executable evidence for the wire-compatibility rules documented on
/// [`InboundDelegateMsg`] and [`OutboundDelegateMsg`].
///
/// The claims those doc comments make about bincode's behaviour are asserted
/// here rather than believed, because every one of them is the kind of claim
/// that is easy to state, easy to get backwards, and impossible to notice being
/// wrong until deployed delegate WASM misreads a message in production.
#[cfg(test)]
mod delegate_wire_compat {
    use super::*;
    use crate::contract_interface::WrappedContract;
    use crate::prelude::ContractCode;
    use crate::versioning::ContractWasmAPIVersion;
    use std::sync::Arc;

    /// The number of variants each enum has **today**. These are not free
    /// parameters: see `an_unpinned_variant_fails_this_test`, which is what
    /// makes them fail closed rather than drift.
    const INBOUND_VARIANT_COUNT: u32 = 10;
    const OUTBOUND_VARIANT_COUNT: u32 = 9;

    fn instance_id() -> ContractInstanceId {
        ContractInstanceId::new([0x5Au8; 32])
    }

    fn delegate_key() -> DelegateKey {
        DelegateKey::new([0x11u8; 32], CodeHash::new([0x22u8; 32]))
    }

    fn contract_container() -> ContractContainer {
        ContractContainer::Wasm(ContractWasmAPIVersion::V1(WrappedContract::new(
            Arc::new(ContractCode::from(vec![1u8, 2, 3])),
            Parameters::from(vec![9u8, 8, 7]),
        )))
    }

    /// The bincode variant tag actually on the wire: a 4-byte little-endian
    /// u32 prefix (this workspace's bincode config uses fixint encoding).
    fn wire_tag(encoded: &[u8]) -> u32 {
        u32::from_le_bytes(
            encoded[..4]
                .try_into()
                .expect("a bincode enum encoding starts with a 4-byte tag"),
        )
    }

    /// The tag each [`InboundDelegateMsg`] variant is frozen at, forever.
    ///
    /// This match is **exhaustive on purpose**. `#[non_exhaustive]` has no
    /// effect inside the crate that defines the enum, so adding a variant
    /// without adding an arm here is a **compile error** — which is the point.
    /// A new variant cannot slip in unpinned.
    ///
    /// If you are here because you added a variant: give it the next unused
    /// number, append it at the END of the enum, add it to `every_inbound`
    /// below, and bump `INBOUND_VARIANT_COUNT`. Do not renumber anything.
    fn pinned_inbound_tag(msg: &InboundDelegateMsg<'_>) -> u32 {
        match msg {
            InboundDelegateMsg::ApplicationMessage(_) => 0,
            InboundDelegateMsg::UserResponse(_) => 1,
            InboundDelegateMsg::GetContractResponse(_) => 2,
            InboundDelegateMsg::PutContractResponse(_) => 3,
            InboundDelegateMsg::UpdateContractResponse(_) => 4,
            InboundDelegateMsg::SubscribeContractResponse(_) => 5,
            InboundDelegateMsg::ContractNotification(_) => 6,
            InboundDelegateMsg::DelegateMessage(_) => 7,
            InboundDelegateMsg::UnsubscribeContractResponse(_) => 8,
            InboundDelegateMsg::WakeupFired { .. } => 9,
        }
    }

    /// The tag each [`OutboundDelegateMsg`] variant is frozen at, forever.
    /// Exhaustive for the same reason as [`pinned_inbound_tag`].
    fn pinned_outbound_tag(msg: &OutboundDelegateMsg) -> u32 {
        match msg {
            OutboundDelegateMsg::ApplicationMessage(_) => 0,
            OutboundDelegateMsg::RequestUserInput(_) => 1,
            OutboundDelegateMsg::ContextUpdated(_) => 2,
            OutboundDelegateMsg::GetContractRequest(_) => 3,
            OutboundDelegateMsg::PutContractRequest(_) => 4,
            OutboundDelegateMsg::UpdateContractRequest(_) => 5,
            OutboundDelegateMsg::SubscribeContractRequest(_) => 6,
            OutboundDelegateMsg::SendDelegateMessage(_) => 7,
            OutboundDelegateMsg::UnsubscribeContractRequest(_) => 8,
        }
    }

    /// One value of every [`InboundDelegateMsg`] variant.
    fn every_inbound() -> Vec<InboundDelegateMsg<'static>> {
        let id = instance_id();
        let ctx = DelegateContext::default();
        vec![
            InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(vec![0xCC])),
            InboundDelegateMsg::UserResponse(UserInputResponse {
                request_id: 7,
                response: ClientResponse::new(vec![0x01]),
                context: ctx.clone(),
            }),
            InboundDelegateMsg::GetContractResponse(GetContractResponse {
                contract_id: id,
                state: None,
                context: ctx.clone(),
            }),
            InboundDelegateMsg::PutContractResponse(PutContractResponse {
                contract_id: id,
                result: Ok(()),
                context: ctx.clone(),
            }),
            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
                contract_id: id,
                result: Ok(()),
                context: ctx.clone(),
            }),
            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
                contract_id: id,
                result: Ok(()),
                context: ctx.clone(),
            }),
            InboundDelegateMsg::ContractNotification(ContractNotification {
                contract_id: id,
                new_state: WrappedState::new(vec![0xAB]),
                context: ctx.clone(),
            }),
            InboundDelegateMsg::DelegateMessage(DelegateMessage::new(
                delegate_key(),
                delegate_key(),
                vec![0xEE],
            )),
            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
                contract_id: id,
                result: Ok(()),
                context: ctx.clone(),
            }),
            InboundDelegateMsg::WakeupFired {
                tag: vec![0xAA, 0xBB],
            },
        ]
    }

    /// One value of every [`OutboundDelegateMsg`] variant.
    ///
    /// Every variant is covered, `PutContractRequest` included: building a
    /// `ContractContainer` is four lines (see `contract_container`), and a pin
    /// test with a hole in it is exactly the shape of guard that reads as
    /// coverage while providing none.
    fn every_outbound() -> Vec<OutboundDelegateMsg> {
        let id = instance_id();
        vec![
            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(vec![0xCC])),
            OutboundDelegateMsg::RequestUserInput(UserInputRequest {
                request_id: 7,
                message: NotificationMessage(Cow::Owned(vec![0x02])),
                responses: vec![],
            }),
            OutboundDelegateMsg::ContextUpdated(DelegateContext::default()),
            OutboundDelegateMsg::GetContractRequest(GetContractRequest::new(id)),
            OutboundDelegateMsg::PutContractRequest(PutContractRequest::new(
                contract_container(),
                WrappedState::new(vec![0xAB]),
                RelatedContracts::default(),
            )),
            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest::new(
                id,
                UpdateData::State(vec![0xAB].into()),
            )),
            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest::new(id)),
            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage::new(
                delegate_key(),
                delegate_key(),
                vec![0xEE],
            )),
            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest::new(id)),
        ]
    }

    /// Pins the bincode variant tag of **every** variant of both delegate
    /// message enums.
    ///
    /// The pin this replaces covered `InboundDelegateMsg`'s variant 0 alone, so
    /// any reorder that happened to leave `ApplicationMessage` first — swapping
    /// `UserResponse` and `GetContractResponse`, say — went undetected. That is
    /// not a theoretical gap: exactly that swap was written, and staged, during
    /// the work that produced this test.
    ///
    /// A reorder is the dangerous edit precisely because it is silent. The
    /// bytes still decode. They decode into the wrong variant, and the failure
    /// surfaces as a delegate acting on a message it was never sent.
    ///
    /// **If this test fails, do not update the expected numbers.** Either a
    /// variant was inserted or reordered (revert it; append instead), or one
    /// was removed — which reassigns every later tag and is a wire break
    /// needing a deliberate release decision. See the
    /// `RegisterDelegateWithPredecessors` removal in 0.9.0 for the shape of
    /// that decision: it was appended last specifically so that removing it
    /// renumbered nothing.
    #[test]
    fn delegate_msg_variant_tags_are_pinned() {
        for msg in every_inbound() {
            let expected = pinned_inbound_tag(&msg);
            let encoded = bincode::serialize(&msg).expect("inbound must serialize");
            assert_eq!(
                wire_tag(&encoded),
                expected,
                "InboundDelegateMsg::{msg:?} moved off wire tag {expected}; inserting, \
                 reordering or removing variants breaks deployed delegate WASM"
            );
        }

        for msg in every_outbound() {
            let expected = pinned_outbound_tag(&msg);
            let encoded = bincode::serialize(&msg).expect("outbound must serialize");
            assert_eq!(
                wire_tag(&encoded),
                expected,
                "OutboundDelegateMsg::{msg:?} moved off wire tag {expected}; inserting, \
                 reordering or removing variants breaks deployed delegate WASM"
            );
        }
    }

    /// Every variant is actually exercised by the pin above.
    ///
    /// [`pinned_inbound_tag`] is exhaustive, so a new variant cannot be left
    /// unpinned without a compile error — but it *could* be left out of
    /// `every_inbound`, and then the pin would silently stop covering it.
    /// Asserting that the sampled tags are exactly `0..COUNT`, with no gaps and
    /// no repeats, closes that.
    #[test]
    fn every_variant_is_covered_by_the_pin() {
        let mut inbound: Vec<u32> = every_inbound().iter().map(pinned_inbound_tag).collect();
        inbound.sort_unstable();
        assert_eq!(
            inbound,
            (0..INBOUND_VARIANT_COUNT).collect::<Vec<_>>(),
            "every_inbound must contain each InboundDelegateMsg variant exactly once"
        );

        let mut outbound: Vec<u32> = every_outbound().iter().map(pinned_outbound_tag).collect();
        outbound.sort_unstable();
        assert_eq!(
            outbound,
            (0..OUTBOUND_VARIANT_COUNT).collect::<Vec<_>>(),
            "every_outbound must contain each OutboundDelegateMsg variant exactly once"
        );
    }

    /// The count constants above cannot be allowed to drift, so this probes the
    /// enums themselves: a payload whose tag is one past the last known variant
    /// must fail to decode.
    ///
    /// This is the test that fails **closed**. Add a variant and forget
    /// everything else here, and the tag that was previously undecodable
    /// becomes decodable, and this fails. Without it, `INBOUND_VARIANT_COUNT`
    /// would be a number asserted only against a list written by the same hand
    /// in the same commit — which is not a check, it is a restatement.
    ///
    /// The payload is a run of zero bytes after the tag, which decodes as
    /// empty vectors, `None`, `Ok`, `false` and zeroed arrays, so it satisfies
    /// essentially any variant shape a new variant is likely to have. Trailing
    /// bytes are ignored: `bincode::deserialize` configures
    /// `allow_trailing_bytes()` (bincode-1.3.3 `src/lib.rs`), which is also why
    /// a fixed-size probe is safe here.
    #[test]
    fn an_unpinned_variant_fails_this_test() {
        // The probe must fail because the TAG is unknown, not because a
        // payload of zeros happened not to parse. Asserting only `is_err()`
        // would let a new variant whose first field rejects zeros (a
        // `DateTime`, a `NonZero*`, a validating `deserialize_with`) go
        // undetected: the tag would be valid, the decode would still fail, and
        // this test would stay green while the counts drifted.
        //
        // bincode hands an out-of-range variant index to serde's derived
        // visitor, which rejects it as `invalid value: integer `N`, expected
        // variant index 0 <= i < M` — an `ErrorKind::Custom`. Match on that
        // wording rather than on `InvalidTagEncoding`, which bincode produces
        // only for a bad `Option` discriminant.
        fn assert_rejected_as_unknown_variant(err: &bincode::Error, tag: u32, which: &str) {
            let msg = err.to_string();
            assert!(
                msg.contains("variant index"),
                "tag {tag} on {which} failed for the wrong reason ({msg}); the tag itself must \
                 still be unknown, otherwise a variant was added without updating the count, \
                 the pinned_*_tag match and the every_* list"
            );
        }

        let mut probe = INBOUND_VARIANT_COUNT.to_le_bytes().to_vec();
        probe.extend_from_slice(&[0u8; 256]);
        let err = match bincode::deserialize::<InboundDelegateMsg<'_>>(&probe) {
            Ok(v) => panic!(
                "tag {INBOUND_VARIANT_COUNT} must not decode as an InboundDelegateMsg, got {v:?}"
            ),
            Err(e) => e,
        };
        assert_rejected_as_unknown_variant(&err, INBOUND_VARIANT_COUNT, "InboundDelegateMsg");

        let mut probe = OUTBOUND_VARIANT_COUNT.to_le_bytes().to_vec();
        probe.extend_from_slice(&[0u8; 256]);
        let err = match bincode::deserialize::<OutboundDelegateMsg>(&probe) {
            Ok(v) => panic!(
                "tag {OUTBOUND_VARIANT_COUNT} must not decode as an OutboundDelegateMsg, got {v:?}"
            ),
            Err(e) => e,
        };
        assert_rejected_as_unknown_variant(&err, OUTBOUND_VARIANT_COUNT, "OutboundDelegateMsg");

        // Control, so the probe cannot pass vacuously from the other end: the
        // LAST known tag must still decode from the same all-zero payload. If
        // this ever fails, the zero payload has stopped being a valid encoding
        // for the final variant, and the probes above are no longer testing
        // what they claim.
        let mut control = (INBOUND_VARIANT_COUNT - 1).to_le_bytes().to_vec();
        control.extend_from_slice(&[0u8; 256]);
        bincode::deserialize::<InboundDelegateMsg<'_>>(&control).expect(
            "the LAST inbound variant's payload must be decodable from zeros, or this probe can \
             no longer tell an unknown tag from an unparseable payload. If a variant whose \
             payload rejects zeros was just appended, do not delete this — point the control at \
             a variant that still decodes from zeros",
        );

        let mut control = (OUTBOUND_VARIANT_COUNT - 1).to_le_bytes().to_vec();
        control.extend_from_slice(&[0u8; 256]);
        bincode::deserialize::<OutboundDelegateMsg>(&control).expect(
            "the LAST outbound variant's payload must be decodable from zeros — see the inbound \
             control above for what to do if that stops being true",
        );
    }

    /// Direction 1 of the append rule: **old sender to new receiver works.**
    ///
    /// The payload is hand-built rather than produced by this crate's own
    /// encoder, so it stands in for bytes emitted by a delegate compiled
    /// against an older stdlib; an encoder-produced value would only prove the
    /// code agrees with itself.
    ///
    /// Named for what it actually pins. Nothing here appends a variant — the
    /// test cannot fail *because of* an append, only because a tag moved or a
    /// payload layout changed, which `delegate_msg_variant_tags_are_pinned`
    /// also covers. Its distinct value is that the expected bytes are written
    /// out by hand, so a change to `ContractNotification`'s field order or to
    /// the bincode config fails here with a concrete byte string to compare
    /// against. Direction 2, which genuinely models an old receiver, is
    /// `a_new_variant_does_not_decode_on_an_old_receiver` below.
    #[test]
    fn a_hand_built_old_encoder_payload_decodes_into_the_same_variant() {
        // InboundDelegateMsg tag 6 = ContractNotification { contract_id,
        // new_state: WrappedState (empty), context: DelegateContext (empty) }.
        let mut old_payload = vec![6u8, 0, 0, 0];
        old_payload.extend_from_slice(&[0x5Au8; 32]);
        old_payload.extend_from_slice(&0u64.to_le_bytes()); // new_state: len 0
        old_payload.extend_from_slice(&0u64.to_le_bytes()); // context: len 0

        let decoded: InboundDelegateMsg<'_> = bincode::deserialize(&old_payload)
            .expect("a payload predating any appended variant must still decode");
        match decoded {
            InboundDelegateMsg::ContractNotification(n) => {
                assert_eq!(n.contract_id, instance_id());
            }
            other => panic!("an old ContractNotification decoded as {other:?}"),
        }
    }

    /// Direction 2 of the append rule: **new sender to old receiver fails, and
    /// fails loudly.** This is the direction the docs warn about, so it is
    /// asserted rather than assumed.
    ///
    /// An old receiver is modelled by an enum with a truncated tag space,
    /// which is exactly what an older stdlib's version of these types is. The
    /// point is that the failure is an `Err` — not a silent mis-decode into
    /// whatever variant happens to sit at that index.
    #[test]
    fn a_new_variant_does_not_decode_on_an_old_receiver() {
        // An "old" OutboundDelegateMsg that knows tags 0..=6 only, i.e. one
        // built before `SendDelegateMessage` was appended at 7.
        // Variants are only ever produced by deserialization, never
        // constructed here — which is the whole point of the test.
        #[allow(dead_code)]
        #[derive(serde::Deserialize, Debug)]
        enum OldOutboundTagSpace {
            V0,
            V1,
            V2,
            V3,
            V4,
            V5,
            V6,
        }

        let new_msg = bincode::serialize(&OutboundDelegateMsg::SendDelegateMessage(
            DelegateMessage::new(delegate_key(), delegate_key(), vec![0xEE]),
        ))
        .expect("outbound must serialize");
        assert_eq!(wire_tag(&new_msg), 7);

        let decoded = bincode::deserialize::<OldOutboundTagSpace>(&new_msg);
        assert!(
            decoded.is_err(),
            "a receiver that predates a variant must REJECT it, not mis-decode it; \
             if this ever passes, the compatibility rule documented on \
             OutboundDelegateMsg is wrong and delegates are silently misreading messages"
        );
    }

    /// The unsubscribe pair added in 0.10.0 round-trips, and adding it did not
    /// disturb any payload that predates it.
    ///
    /// The pre-0.10.0 byte string is hand-built rather than produced by this
    /// crate, so it stands in for bytes from a delegate compiled before the
    /// pair existed. Both halves matter: the new variant must work, and the old
    /// ones must be untouched by its arrival.
    #[test]
    fn the_unsubscribe_pair_round_trips_and_disturbs_nothing_older() {
        let id = instance_id();

        let req =
            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest::new(id));
        let encoded = bincode::serialize(&req).expect("request must serialize");
        assert_eq!(wire_tag(&encoded), 8, "unsubscribe request is frozen at 8");
        match bincode::deserialize::<OutboundDelegateMsg>(&encoded).expect("must round-trip") {
            OutboundDelegateMsg::UnsubscribeContractRequest(r) => {
                assert_eq!(r.contract_id, id);
                assert!(!r.processed);
            }
            other => panic!("round-tripped into {other:?}"),
        }

        let resp = InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
            contract_id: id,
            result: Ok(()),
            context: DelegateContext::default(),
        });
        let encoded = bincode::serialize(&resp).expect("response must serialize");
        assert_eq!(wire_tag(&encoded), 8, "unsubscribe response is frozen at 8");
        match bincode::deserialize::<InboundDelegateMsg<'_>>(&encoded).expect("must round-trip") {
            InboundDelegateMsg::UnsubscribeContractResponse(r) => {
                // Assert the VALUES, not merely the variant. Checking only
                // `matches!` is what lets a field reorder through: the encoder
                // and decoder would still agree with each other.
                assert_eq!(r.contract_id, id);
                assert!(r.result.is_ok());
            }
            other => panic!("round-tripped into {other:?}"),
        }

        // Both structs' doc comments say the field ORDER is the wire format.
        // A round-trip through this crate's own encoder cannot establish that —
        // it proves the code agrees with itself, and a swap of `contract_id`
        // and `result` would round-trip just as happily. So the layout is
        // frozen as hand-written bytes, the same way ContractNotification is.
        let mut expected_resp = vec![8u8, 0, 0, 0];
        expected_resp.extend_from_slice(&[0x5Au8; 32]); // contract_id
        expected_resp.extend_from_slice(&0u32.to_le_bytes()); // result: Ok variant tag
        expected_resp.extend_from_slice(&0u64.to_le_bytes()); // context: empty
        assert_eq!(
            encoded, expected_resp,
            "UnsubscribeContractResponse layout is frozen: tag, contract_id, result, context"
        );

        let expected_req = {
            let mut v = vec![8u8, 0, 0, 0];
            v.extend_from_slice(&[0x5Au8; 32]); // contract_id
            v.extend_from_slice(&0u64.to_le_bytes()); // context: empty
            v.push(0u8); // processed: false
            v
        };
        assert_eq!(
            bincode::serialize(&req).expect("request must serialize"),
            expected_req,
            "UnsubscribeContractRequest layout is frozen: tag, contract_id, context, processed"
        );

        // The error path has a different bincode shape from Ok and is part of
        // the same frozen layout, so it is exercised rather than assumed.
        let err_resp =
            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
                contract_id: id,
                result: Err("nope".to_string()),
                context: DelegateContext::default(),
            });
        match bincode::deserialize::<InboundDelegateMsg<'_>>(
            &bincode::serialize(&err_resp).expect("must serialize"),
        )
        .expect("must round-trip")
        {
            InboundDelegateMsg::UnsubscribeContractResponse(r) => {
                assert_eq!(r.result.unwrap_err(), "nope");
            }
            other => panic!("error response round-tripped into {other:?}"),
        }

        // A ContractNotification encoded before 0.10.0 existed: tag 6, the 32
        // raw id bytes, an empty state and an empty context. Appending at 8
        // must leave it decoding exactly as it always did.
        let mut pre_0_9_0 = vec![6u8, 0, 0, 0];
        pre_0_9_0.extend_from_slice(&[0x5Au8; 32]);
        pre_0_9_0.extend_from_slice(&0u64.to_le_bytes());
        pre_0_9_0.extend_from_slice(&0u64.to_le_bytes());
        match bincode::deserialize::<InboundDelegateMsg<'_>>(&pre_0_9_0)
            .expect("a pre-0.10.0 payload must still decode")
        {
            InboundDelegateMsg::ContractNotification(n) => assert_eq!(n.contract_id, id),
            other => panic!("a pre-0.10.0 ContractNotification decoded as {other:?}"),
        }
    }

    /// Every inbound variant whose payload carries a `context` must return it.
    ///
    /// Both `get_context` and `get_mut_context` end in `_ => None`, so a
    /// missing arm is not a compile error — it silently reports "no context".
    /// That wildcard had already swallowed one: `UserResponse` carries a
    /// context and returned `None` for it, undetected, because nothing in the
    /// crate called either accessor.
    ///
    /// Driven off `every_inbound`, so a newly appended variant is covered the
    /// moment it is added to that list — which the tag pin already forces.
    #[test]
    fn every_inbound_variant_with_a_context_exposes_it() {
        for mut msg in every_inbound() {
            let tag = pinned_inbound_tag(&msg);

            // `WakeupFired` is the one inbound variant with no context field,
            // and it is named here rather than skipped by a wildcard, matching
            // the outbound test below. See `get_context` for why it has none:
            // a context is per-conversation working state handed back on a
            // reply, and a wakeup opens a conversation rather than continuing
            // one. Carrying one would commit the host to persisting delegate
            // context across arbitrary wall-clock time, which is #5467 Phase 3.
            //
            // This asserts the accessor returns `None`, not that the struct
            // lacks a field. That distinction is the point: the claim "every
            // variant carries a context" was already false of this accessor in
            // 0.8.5, where it omitted `UserResponse` behind a `_ => None`
            // wildcard. Pin the behaviour, not the shape.
            if matches!(msg, InboundDelegateMsg::WakeupFired { .. }) {
                assert!(
                    msg.get_context().is_none() && msg.get_mut_context().is_none(),
                    "WakeupFired is documented as carrying no context; if it grew one,                      remove this exemption rather than widening it"
                );
                continue;
            }

            assert!(
                msg.get_context().is_some(),
                "InboundDelegateMsg tag {tag} has a context field but get_context returned None; \
                 the `_ => None` wildcard hides a missing arm"
            );
            assert!(
                msg.get_mut_context().is_some(),
                "InboundDelegateMsg tag {tag} has a context field but get_mut_context returned \
                 None; the two accessors must agree"
            );
        }
    }

    /// The same, for the outbound side.
    ///
    /// `RequestUserInput` and `ContextUpdated` genuinely have no context field
    /// to return, so they are the two exceptions and are named explicitly
    /// rather than skipped by a wildcard.
    #[test]
    fn every_outbound_variant_with_a_context_exposes_it() {
        for mut msg in every_outbound() {
            let tag = pinned_outbound_tag(&msg);
            let has_no_context = matches!(
                msg,
                OutboundDelegateMsg::RequestUserInput(_) | OutboundDelegateMsg::ContextUpdated(_)
            );
            if has_no_context {
                continue;
            }
            assert!(
                msg.get_context().is_some(),
                "OutboundDelegateMsg tag {tag} has a context field but get_context returned None"
            );
            assert!(
                msg.get_mut_context().is_some(),
                "OutboundDelegateMsg tag {tag} has a context field but get_mut_context returned \
                 None; the two accessors must agree"
            );
        }
    }

    // ---------------------------------------------------------------------
    // `#[serde(other)]` — the one rule in WIRE-FORMAT.md that contradicts the
    // common advice, so it is the one a future reader will doubt and re-derive.
    // These three tests are that derivation, kept where it cannot rot.
    //
    // Mock types, deliberately: the real enums must never grow a catch-all, so
    // the property has to be demonstrated on stand-ins.
    // ---------------------------------------------------------------------

    // The appended variants sit at tag 2, and `OldMsgWithCatchAll` declares
    // only 0 and 1. That gap is load-bearing: at tag 1 the catch-all's own
    // declared index, a plain unit variant decodes identically and the
    // attribute does no work at all — so mocks aligned that way pass with
    // `#[serde(other)]` deleted, testing nothing. Verified: they did.
    //
    // Both cases occur on a real append. The FIRST new variant lands exactly at
    // the catch-all's index, where the attribute is unnecessary; the SECOND is
    // out of range, where it is the only thing between a hard error and silent
    // corruption. The out-of-range case is the one the rule depends on, so it
    // is the one the mocks must produce.
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    enum NewMsgWithPayload {
        First(u32),
        Second(bool),
        Appended(String),
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    enum OldMsgWithCatchAll {
        First(u32),
        // Deliberately stops here: real variants 0 only, catch-all at 1. The
        // appended variants above are at tag 2, which is OUT OF RANGE for this
        // enum — that gap is what the attribute has to bridge.
        #[serde(other)]
        Unknown,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    enum NewMsgUnitAppended {
        First(u32),
        Second(bool),
        AppendedUnit,
    }

    /// The mocks' tag gap is asserted, not merely commented — and asserted
    /// against **the two enums whose alignment actually matters**.
    ///
    /// The vacuity condition is precisely: the tag `Appended` encodes to is the
    /// same as the index `OldMsgWithCatchAll` absorbs into `Unknown`. At that
    /// index a plain unit variant behaves identically and `#[serde(other)]`
    /// does no work, so the three tests below stop testing the attribute while
    /// still passing.
    ///
    /// Both numbers are measured from the types rather than written down, so
    /// this fires whichever side moves — adding a variant to the old enum, or
    /// removing the filler from the new ones. An earlier version of this guard
    /// compared against a separate no-attribute copy of the old enum and
    /// **missed the first case entirely**, because that copy did not move when
    /// the real one did. A control that can drift from what it controls is not
    /// a control.
    ///
    /// This exists because the alignment has broken **three times** in this
    /// file, twice at the hands of someone actively fixing it. A comment cannot
    /// catch the fourth.
    #[test]
    fn the_attribute_is_what_bridges_the_gap() {
        fn tag_of(bytes: &[u8]) -> u32 {
            u32::from_le_bytes(
                bytes[..4]
                    .try_into()
                    .expect("a bincode enum tag is 4 bytes"),
            )
        }

        let appended =
            tag_of(&bincode::serialize(&NewMsgWithPayload::Appended("x".into())).unwrap());

        // The lowest tag `OldMsgWithCatchAll` absorbs into `Unknown` is its
        // catch-all index; below it, real variants decode as themselves.
        let absorbed_from = (0u32..16)
            .find(|t| {
                let mut probe = t.to_le_bytes().to_vec();
                probe.extend_from_slice(&[0u8; 32]);
                matches!(
                    bincode::deserialize::<OldMsgWithCatchAll>(&probe),
                    Ok(OldMsgWithCatchAll::Unknown)
                )
            })
            .expect("OldMsgWithCatchAll must absorb some tag; it has #[serde(other)]");

        assert!(
            appended > absorbed_from,
            "`Appended` is at tag {appended} and OldMsgWithCatchAll absorbs from tag \
             {absorbed_from}: the mocks have re-aligned, so the serde(other) tests below \
             are vacuous and pass with the attribute deleted. Move `Appended` above the \
             catch-all index again rather than adjusting this test."
        );
    }

    /// Contradicts the usual "self-describing formats only" claim: bincode 1.x
    /// **does** let `#[serde(other)]` absorb an unknown variant tag.
    ///
    /// That is the trap, not a feature — see the next test for why.
    #[test]
    fn serde_other_does_absorb_an_unknown_tag_in_bincode() {
        let encoded = bincode::serialize(&NewMsgWithPayload::Appended("x".into())).unwrap();
        let decoded: OldMsgWithCatchAll =
            bincode::deserialize(&encoded).expect("serde(other) absorbs the unknown tag");
        assert_eq!(decoded, OldMsgWithCatchAll::Unknown);
    }

    /// The absorption consumes the **tag only**, never the unknown variant's
    /// payload, so everything after it in the buffer is silently misread.
    ///
    /// A hard decode error would have been strictly better: this turns a loud,
    /// immediate failure into a wrong value with no error anywhere.
    #[test]
    fn the_catch_all_silently_corrupts_trailing_data() {
        let encoded =
            bincode::serialize(&(NewMsgWithPayload::Appended("hello-future".into()), 4242u32))
                .unwrap();

        let (variant, trailing): (OldMsgWithCatchAll, u32) =
            bincode::deserialize(&encoded).expect("decodes, which is the problem");

        assert_eq!(variant, OldMsgWithCatchAll::Unknown);
        assert_ne!(
            trailing, 4242,
            "if this ever equals 4242, serde(other) stopped eating the payload \
             and this section of WIRE-FORMAT.md needs revisiting"
        );
    }

    /// And the reason the trap works: against a **unit** unknown variant there
    /// is no payload to leave behind, nothing after it is misread, and the
    /// decode really is clean.
    ///
    /// So a developer who tries `#[serde(other)]` on a unit variant sees it
    /// work and concludes the warning is overstated. The corruption is
    /// conditional on a property of a variant that does not exist yet — you are
    /// betting nobody ever gives a future variant a field.
    #[test]
    fn the_catch_all_is_clean_for_a_unit_variant() {
        let encoded = bincode::serialize(&(NewMsgUnitAppended::AppendedUnit, 4242u32)).unwrap();

        let (variant, trailing): (OldMsgWithCatchAll, u32) =
            bincode::deserialize(&encoded).expect("unit variant leaves nothing behind");

        assert_eq!(variant, OldMsgWithCatchAll::Unknown);
        assert_eq!(
            trailing, 4242,
            "a unit unknown variant must NOT corrupt what follows — this is the \
             case that misleads, and it is why the rule is unconditional"
        );
    }
}