ant-protocol 5.0.1

Wire protocol for the Autonomi decentralized network (WithAutonomi fork)
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
//! Pointers — paid mutable references with an immutable owner.
//!
//! A pointer is a mutable, owner-signed reference stored at an address derived
//! from its owner's public key. Unlike a
//! [`DataChunk`](crate::data_types::DataChunk) its address is **not** its
//! content hash: the address is fixed for the pointer's life while the bytes
//! under it change with every update.
//!
//! The owner *key* is fixed at creation. There is no lineage, no certificates
//! and no key rotation: a former owner keeps its key forever, so ownership
//! cannot be re-keyed by a local rule. An earlier draft of this module
//! implemented transfer through a genesis object and a chain of transfer
//! certificates; it was reviewed and withdrawn. See `ADR-0016` in `ant-node`.
//!
//! That choice is what lets the design be this small: the owner key is inlined
//! in the record, so validating a pointer needs nothing but the pointer — no
//! fetch, no cache, no second close group, nothing that can be missing.
//!
//! # Finality, and transfer by final redirection
//!
//! A record at `counter == u64::MAX` is **final**: no record replaces it, not
//! even another one at `u64::MAX`. That is what makes ownership transferable
//! without touching the record: the owner signs one last state, at the final
//! counter, pointing at a pointer the new owner holds the key to
//! ([`Pointer::transfer_to`]). A reader of the old address is redirected to the
//! new owner's pointer by every node that holds that final state, the address
//! never changes, and no node that holds the final state gives it up — a
//! larger counter does not exist, and an equal one does not replace.
//!
//! Two different final states can still exist, because only the owner decides
//! what it signs, and the rule only stops a node from changing its mind. A
//! node that holds no final state takes whichever one reaches it first. So the
//! former owner can fork the pointer by signing a second final state and
//! getting it to nodes the first has not reached: racing both at once, or
//! sending the second later. Nothing local can settle that. What the rule does
//! settle is that no node ever gives up a final state it holds, so a fork
//! cannot take a final state back from the nodes that hold it; it can only
//! split the nodes that held none. Finding a fork, and reading the state most of the
//! close group holds, is the client's job; not taking a rival of a final state
//! the close group already holds is the node's. See `ADR-0018` in `ant-node`.
//!
//! # Encoding
//!
//! Encoded by hand: canonical, fixed-width, big-endian, no length prefixes and
//! no `serde`. The signed payload must not depend on a serializer whose output
//! can change — 1.0's pointer called `rmp_serde` inside its signing routine and
//! silently signed nothing when it failed.
//!
//! ```text
//! format_version  1     byte
//! owner        1952     bytes   ML-DSA-65 public key
//! counter         8     bytes   big-endian u64
//! target         33     bytes   1-byte kind tag + 32-byte address, opaque here
//! signature    3309     bytes   ML-DSA-65 over the preceding 1994 bytes
//!             -----
//!              5303     bytes
//! ```
//!
//! # Identity
//!
//! ```text
//! A        = BLAKE3::derive_key("autonomi.pointer.address.v1", owner)
//! state_id = BLAKE3::derive_key("autonomi.pointer.state.v1",   body)
//! ```
//!
//! Derive-key, not a hash of a prefix and the input. A chunk is addressed by a
//! plain hash of its content, so a prefix would put both of these inside the
//! chunk address space for anyone who could write the preimage down: squatting
//! an owner's address before they used it, or buying a pointer and a chunk with
//! one payment. Both modes still produce 32 bytes, so the ranges overlap; what
//! changed is that crossing them is the preimage problem BLAKE3 is assumed to
//! resist.
//!
//! `A` routes and decides which nodes are responsible. `state_id` names the
//! authenticated state: it is what sync hints carry, what a fetch decision
//! compares, and **what a quote is paid against**. They are separate because
//! `A` must be stable for the pointer's life while the paid identifier must
//! change with every update, or updates after the first would be free — the
//! defect this design exists to fix.
//!
//! # What this module does not do
//!
//! Payment verification, storage and replication. Those are the node's job.

use saorsa_pqc::api::sig::{
    ml_dsa_65, MlDsaPublicKey, MlDsaSecretKey, MlDsaSignature, MlDsaVariant,
};

use crate::chunk::XORNAME_LEN;
use crate::data_types::XorName;

// =============================================================================
// Constants
// =============================================================================

/// Data type identifier for pointers, alongside
/// [`DATA_TYPE_CHUNK`](crate::chunk::DATA_TYPE_CHUNK).
pub const DATA_TYPE_POINTER: u32 = 1;

/// Wire format discriminator carried by every pointer.
///
/// Covered by the signature, so it cannot be downgraded, and part of the signed
/// body, so it reaches `state_id`: a record differing only in this byte is a
/// different state and is paid for separately.
pub const POINTER_FORMAT_VERSION: u8 = 1;

/// The final counter. A record signed at it is never replaced.
///
/// See [`PointerState::replaces`] for why, and [`Pointer::transfer_to`] for
/// what it is for.
pub const FINAL_COUNTER: u64 = u64::MAX;

/// Length of a raw ML-DSA-65 public key.
pub const ML_DSA_65_PUBLIC_KEY_LEN: usize = 1952;

/// Length of a raw ML-DSA-65 signature.
pub const ML_DSA_65_SIGNATURE_LEN: usize = 3309;

/// Length of an encoded [`PointerTarget`]: a kind tag plus an address.
pub const TARGET_WIRE_LEN: usize = 1 + XORNAME_LEN;

/// Byte offset of the owner key within an encoded pointer.
const OWNER_OFFSET: usize = 1;

/// Byte offset of the counter within an encoded pointer.
const COUNTER_OFFSET: usize = OWNER_OFFSET + ML_DSA_65_PUBLIC_KEY_LEN;

/// Byte offset of the target within an encoded pointer.
const TARGET_OFFSET: usize = COUNTER_OFFSET + 8;

/// Length of the signed body: everything before the signature.
pub const POINTER_BODY_LEN: usize = TARGET_OFFSET + TARGET_WIRE_LEN;

/// Total size of an encoded pointer.
pub const POINTER_WIRE_LEN: usize = POINTER_BODY_LEN + ML_DSA_65_SIGNATURE_LEN;

/// Key-derivation context for the pointer address.
///
/// Used with BLAKE3's `derive_key`, not as a hash prefix. A prefix separates
/// nothing: a chunk's address is `BLAKE3(content)`, so a chunk whose content is
/// the prefix followed by an owner key would land on exactly that owner's
/// pointer address, and an attacker could squat any address it could name.
/// `derive_key` runs BLAKE3 in a different mode. The two still share a 32-byte
/// range; what changes is that hitting a value from one mode with the other is
/// the preimage problem BLAKE3 is assumed to resist, rather than a string
/// anyone can write down.
const CONTEXT_ADDRESS: &str = "autonomi.pointer.address.v1";

/// Key-derivation context for the authenticated-state identifier.
///
/// Also `derive_key`, and for a sharper reason: `state_id` is what a pointer's
/// payment is quoted against. Were it a plain hash, one settled quote would pay
/// for both the pointer and a chunk sitting at the same address.
const CONTEXT_STATE: &str = "autonomi.pointer.state.v1";

/// ML-DSA signing context for a pointer.
///
/// Domain-separates a pointer signature from every other signature in the
/// system, so a signature lifted from elsewhere cannot authenticate a pointer
/// and vice versa.
const SIGNING_CONTEXT: &[u8] = b"autonomi.pointer.head.v1";

// =============================================================================
// Errors
// =============================================================================

/// Why a pointer was refused.
///
/// `Display` is written by hand rather than derived, because this crate is a
/// wire contract and does not take a macro dependency for it — the same reason
/// [`crate::error::Error`] is hand-written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PointerError {
    /// The encoding is not exactly [`POINTER_WIRE_LEN`] bytes.
    WrongLength(usize),
    /// The format version is not one this build understands.
    UnknownFormatVersion(u8),
    /// The owner key does not decode.
    InvalidOwnerKey(String),
    /// The signature does not decode.
    InvalidSignatureFormat(String),
    /// The signature does not verify under the owner key in the record.
    SignatureInvalid,
    /// Signing failed.
    SigningFailed(String),
    /// The counter is at [`FINAL_COUNTER`]: the pointer is final and no
    /// further state can replace it.
    CounterExhausted,
}

impl std::fmt::Display for PointerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WrongLength(len) => {
                write!(f, "pointer must be {POINTER_WIRE_LEN} bytes, got {len}")
            }
            Self::UnknownFormatVersion(version) => {
                write!(f, "unknown pointer format version {version}")
            }
            Self::InvalidOwnerKey(reason) => write!(f, "invalid pointer owner key: {reason}"),
            Self::InvalidSignatureFormat(reason) => {
                write!(f, "invalid pointer signature format: {reason}")
            }
            Self::SignatureInvalid => {
                write!(f, "pointer signature does not verify under its owner key")
            }
            Self::SigningFailed(reason) => write!(f, "pointer signing failed: {reason}"),
            Self::CounterExhausted => write!(
                f,
                "pointer is final: its counter is at u64::MAX, and no later state \
                 can replace it"
            ),
        }
    }
}

impl std::error::Error for PointerError {}

// =============================================================================
// Address derivation
// =============================================================================

/// Derive a pointer address from an owner key.
///
/// `BLAKE3::derive_key` rather than a hash of a prefix and the key. Chunk
/// addresses are `BLAKE3(content)` over the same 32-byte range, and derive-key
/// is a different mode of the same function: the ranges still overlap, but
/// putting content on one of these values is a preimage problem rather than a
/// string anyone can write down. The node still refuses an address the other
/// kind occupies; that guard now covers the cryptographic case only.
#[must_use]
pub fn pointer_address(owner: &MlDsaPublicKey) -> XorName {
    blake3::derive_key(CONTEXT_ADDRESS, &owner.to_bytes())
}

/// Derive the authenticated-state identifier from a signed body.
///
/// Derive-key for the same reason as the address, and one more: this is the
/// identifier a pointer's storage is paid against, so a chunk that could occupy
/// it would be a second record bought with one payment.
#[must_use]
pub fn state_id_for_body(body: &[u8]) -> XorName {
    blake3::derive_key(CONTEXT_STATE, body)
}

// =============================================================================
// Target
// =============================================================================

/// What a pointer points at, as clients interpret it.
///
/// A node never reads this. It stores the tag as an opaque byte, so a new kind
/// is a client-side change and not a network upgrade.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PointerTargetKind {
    /// An immutable content-addressed chunk.
    Chunk,
    /// Another pointer, which is how handover-by-indirection is expressed.
    Pointer,
}

impl PointerTargetKind {
    /// Wire tag for this kind.
    #[must_use]
    pub const fn tag(self) -> u8 {
        match self {
            Self::Chunk => 0,
            Self::Pointer => 1,
        }
    }

    /// Interpret a wire tag, if it names a kind this build knows.
    ///
    /// Returns `None` for anything else rather than an error: an unrecognised
    /// tag is a target this client cannot follow, not a malformed record.
    #[must_use]
    pub const fn from_tag(tag: u8) -> Option<Self> {
        match tag {
            0 => Some(Self::Chunk),
            1 => Some(Self::Pointer),
            _ => None,
        }
    }
}

/// A kind tag plus the address it refers to.
///
/// The tag is carried and signed but never interpreted by a storing node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PointerTarget {
    /// The raw kind tag, meaningful only to clients.
    kind_tag: u8,
    /// The address pointed at.
    pub address: XorName,
}

impl PointerTarget {
    /// Build a target of a known kind.
    #[must_use]
    pub const fn new(kind: PointerTargetKind, address: XorName) -> Self {
        Self {
            kind_tag: kind.tag(),
            address,
        }
    }

    /// Build a target from a raw tag, including one this build does not know.
    #[must_use]
    pub const fn from_raw_tag(kind_tag: u8, address: XorName) -> Self {
        Self { kind_tag, address }
    }

    /// The raw kind tag as carried on the wire.
    #[must_use]
    pub const fn kind_tag(&self) -> u8 {
        self.kind_tag
    }

    /// The kind, if this build recognises the tag.
    #[must_use]
    pub const fn kind(&self) -> Option<PointerTargetKind> {
        PointerTargetKind::from_tag(self.kind_tag)
    }

    /// Encode to its [`TARGET_WIRE_LEN`] wire bytes.
    #[must_use]
    pub fn to_bytes(&self) -> [u8; TARGET_WIRE_LEN] {
        let mut out = [0u8; TARGET_WIRE_LEN];
        if let Some((tag, address)) = out.split_first_mut() {
            *tag = self.kind_tag;
            address.copy_from_slice(&self.address);
        }
        out
    }

    /// Decode from wire bytes.
    ///
    /// Only the length can fail: every tag value is accepted, because a node
    /// stores the target without interpreting it.
    fn from_bytes(bytes: &[u8]) -> Option<Self> {
        let (tag, rest) = bytes.split_first()?;
        if rest.len() != XORNAME_LEN {
            return None;
        }
        let mut address = [0u8; XORNAME_LEN];
        address.copy_from_slice(rest);
        Some(Self {
            kind_tag: *tag,
            address,
        })
    }
}

// =============================================================================
// Merge order
// =============================================================================

/// The merge rule's comparison key: larger wins.
///
/// One type so that every comparison — an arriving record against a parsed one,
/// or against a store's index entry — is literally the same ordering. Deriving
/// `Ord` over the fields in declaration order is what encodes the rule:
/// `counter` first, then the target, inverted so that *smaller* target bytes
/// rank higher.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct MergeRank {
    /// The update counter. Larger wins.
    counter: u64,
    /// The encoded target, inverted: smaller bytes win.
    target: std::cmp::Reverse<[u8; TARGET_WIRE_LEN]>,
}

// =============================================================================
// State
// =============================================================================

/// The parts of a record that determine its authenticated state.
///
/// Parsed from the body alone, so obtaining one costs no signature
/// verification. That is what lets a node recognise a re-submission of what it
/// already holds and stop before doing expensive work.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PointerState {
    /// The authenticated-state identifier, derived from the signed body.
    pub state_id: XorName,
    /// The address the record belongs at.
    pub address: XorName,
    /// The update counter, the merge rule's first key.
    pub counter: u64,
    /// The target, whose bytes are the merge rule's second key.
    pub target: PointerTarget,
}

impl PointerState {
    /// Parse the state out of a record's bytes without verifying its signature.
    ///
    /// Checks length, format version and structure only. A `PointerState` says
    /// what a record *claims*; only [`Pointer::from_bytes`] establishes that
    /// the claim is signed.
    ///
    /// # Errors
    ///
    /// Returns [`PointerError`] for a record of the wrong length, an unknown
    /// format version, or an unparseable owner key.
    pub fn parse(bytes: &[u8]) -> Result<Self, PointerError> {
        Self::parse_with_owner(bytes).map(|(state, _)| state)
    }

    /// As [`Self::parse`], also returning the decoded owner key.
    fn parse_with_owner(bytes: &[u8]) -> Result<(Self, MlDsaPublicKey), PointerError> {
        if bytes.len() != POINTER_WIRE_LEN {
            return Err(PointerError::WrongLength(bytes.len()));
        }
        let version = bytes
            .first()
            .copied()
            .ok_or(PointerError::WrongLength(bytes.len()))?;
        if version != POINTER_FORMAT_VERSION {
            return Err(PointerError::UnknownFormatVersion(version));
        }

        let owner_bytes = bytes
            .get(OWNER_OFFSET..COUNTER_OFFSET)
            .ok_or(PointerError::WrongLength(bytes.len()))?;
        let owner = MlDsaPublicKey::from_bytes(MlDsaVariant::MlDsa65, owner_bytes)
            .map_err(|e| PointerError::InvalidOwnerKey(e.to_string()))?;

        let counter_bytes: [u8; 8] = bytes
            .get(COUNTER_OFFSET..TARGET_OFFSET)
            .and_then(|slice| slice.try_into().ok())
            .ok_or(PointerError::WrongLength(bytes.len()))?;

        let target = bytes
            .get(TARGET_OFFSET..POINTER_BODY_LEN)
            .and_then(PointerTarget::from_bytes)
            .ok_or(PointerError::WrongLength(bytes.len()))?;

        let body = bytes
            .get(..POINTER_BODY_LEN)
            .ok_or(PointerError::WrongLength(bytes.len()))?;

        Ok((
            Self {
                state_id: state_id_for_body(body),
                address: pointer_address(&owner),
                counter: u64::from_be_bytes(counter_bytes),
                target,
            },
            owner,
        ))
    }

    /// The comparison key for [`Self::replaces`].
    #[must_use]
    fn rank(&self) -> MergeRank {
        MergeRank {
            counter: self.counter,
            target: std::cmp::Reverse(self.target.to_bytes()),
        }
    }

    /// Whether this state is final: signed at [`FINAL_COUNTER`], and so
    /// replaced by nothing.
    #[must_use]
    pub const fn is_terminal(&self) -> bool {
        self.counter == FINAL_COUNTER
    }

    /// The pointer this state hands the address over to, if it is a transfer:
    /// a final state whose target is another pointer.
    ///
    /// A final state targeting anything else freezes the pointer rather than
    /// handing it on, and a pointer target below the final counter is a
    /// forwarding the owner can still take back. Neither is a transfer.
    #[must_use]
    pub const fn transferred_to(&self) -> Option<XorName> {
        transfer_target(self.counter, self.target)
    }

    /// Whether `self` replaces `other` under the merge rule.
    ///
    /// ```text
    /// 0. a final state (counter == u64::MAX) is replaced by nothing
    /// 1. larger counter
    /// 2. smaller target bytes
    /// ```
    ///
    /// Records of different owners are not comparable and neither replaces the
    /// other.
    ///
    /// Equal state never replaces, whatever the signature bytes: ML-DSA signing
    /// is randomized, so one authenticated state has unboundedly many valid
    /// encodings, and ordering records by their bytes would let an owner sign
    /// one paid state repeatedly, sort worst-first and have every submission
    /// win — unbounded storage, replication and audit work for a single
    /// payment.
    ///
    /// Rule 0 is what makes a pointer's last state final, and so what makes
    /// ownership transferable by redirection ([`Pointer::transfer_to`]). Under
    /// rules 1 and 2 alone a state at the final counter could still be
    /// displaced by another at the same counter with smaller target bytes, so
    /// a former owner could grind a target and take the address back after
    /// handing it on.
    ///
    /// The cost is that the order is total only below the final counter. Two
    /// different final states are incomparable: neither replaces the other, so
    /// whichever a node took first is the one it keeps. That is the only
    /// conflict this rule leaves unordered, and so the only fork no later
    /// state heals; a conflict at a lower counter is ordered by target bytes
    /// and replaced by any later counter. Only the owner can make it — by
    /// signing a second
    /// final state and getting it to nodes the first has not reached, at once
    /// or later. Once a node holds a final state no arrival can change it, so a
    /// second final state can never displace an established one; it can only
    /// land on a node that held no final state. A reader tells the two sides
    /// apart by how many of the close group hold each.
    ///
    /// Every other pair of distinct states is ordered, and the order is a
    /// strict partial order everywhere: never both ways round, and transitive.
    #[must_use]
    pub fn replaces(&self, other: &Self) -> bool {
        self.address == other.address && !other.is_terminal() && self.rank() > other.rank()
    }
}

/// The pointer a state at `counter` with `target` transfers to, if any.
///
/// One definition for [`PointerState::transferred_to`] and
/// [`Pointer::transferred_to`], so a record and its parsed state cannot
/// disagree about whether it is a transfer.
const fn transfer_target(counter: u64, target: PointerTarget) -> Option<XorName> {
    match target.kind() {
        Some(PointerTargetKind::Pointer) if counter == FINAL_COUNTER => Some(target.address),
        _ => None,
    }
}

// =============================================================================
// Parsed-but-unverified record
// =============================================================================

/// Bytes that have been structurally parsed but not yet verified.
///
/// The bytes travel with their parse, so a caller cannot pair one record's
/// bytes with another's state. Only [`Pointer::verify_parsed`] consumes it, and
/// only that step establishes that the bytes are signed.
pub struct ParsedPointer {
    /// The record's canonical encoding.
    bytes: Vec<u8>,
    /// What those bytes claim.
    state: PointerState,
    /// The owner key decoded from those bytes.
    owner: MlDsaPublicKey,
}

impl std::fmt::Debug for ParsedPointer {
    /// Shows what the unverified bytes claim, not the bytes themselves.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParsedPointer")
            .field("address", &hex::encode(self.state.address))
            .field("counter", &self.state.counter)
            .finish_non_exhaustive()
    }
}

impl ParsedPointer {
    /// Parse `bytes`, without verifying the signature.
    ///
    /// # Errors
    ///
    /// As [`PointerState::parse`].
    pub fn parse(bytes: Vec<u8>) -> Result<Self, PointerError> {
        let (state, owner) = PointerState::parse_with_owner(&bytes)?;
        Ok(Self {
            bytes,
            state,
            owner,
        })
    }

    /// What the unverified bytes claim.
    #[must_use]
    pub const fn state(&self) -> &PointerState {
        &self.state
    }
}

// =============================================================================
// The record
// =============================================================================

/// A paid, mutable, owner-signed reference.
///
/// A value of this type has been through [`Pointer::from_bytes`], so its
/// signature covers exactly its body and its address derives from its owner.
#[derive(Clone)]
pub struct Pointer {
    /// Wire format discriminator. Signed, so it cannot be downgraded.
    version: u8,
    /// The owner's public key — the pointer's identity.
    ///
    /// The address is derived from the owner key alone, so a pointer is public-key
    /// addressed, and the key that verifies it travels with it: ML-DSA has no
    /// key recovery and a 1,952-byte key cannot be a 32-byte address.
    owner: MlDsaPublicKey,
    /// The merge rule's first key: a larger counter wins.
    ///
    /// [`Self::create`] starts at 0 and [`Self::update`] adds one, but nothing
    /// requires the next state to be exactly one on. The counter orders states;
    /// it does not meter them. Every stored state is paid for once, whatever
    /// its number, so a number that is skipped is never stored and owes nothing.
    counter: u64,
    /// What this points at: a chunk or another pointer. Opaque to a node.
    target: PointerTarget,
    /// The owner's signature over every field above.
    sig: MlDsaSignature,
}

impl std::fmt::Debug for Pointer {
    /// Shows what identifies the record, not its 5 KB of key and signature.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Pointer")
            .field("address", &hex::encode(self.address()))
            .field("counter", &self.counter)
            .field("target_tag", &self.target.kind_tag())
            .field("target", &hex::encode(self.target.address))
            .field("state_id", &hex::encode(self.state_id()))
            .finish_non_exhaustive()
    }
}

impl Pointer {
    /// Build and sign a pointer.
    ///
    /// # Errors
    ///
    /// Returns [`PointerError::SigningFailed`] if signing fails, or a parse
    /// error if the resulting record does not parse, which would be a bug here
    /// rather than bad input.
    pub fn sign(
        secret_key: &MlDsaSecretKey,
        owner: &MlDsaPublicKey,
        counter: u64,
        target: PointerTarget,
    ) -> Result<Self, PointerError> {
        let body = encode_body(POINTER_FORMAT_VERSION, owner, counter, target)?;
        let signature = ml_dsa_65()
            .sign_with_context(secret_key, &body, SIGNING_CONTEXT)
            .map_err(|e| PointerError::SigningFailed(e.to_string()))?;
        let mut bytes = body;
        bytes.extend_from_slice(&signature.to_bytes());
        Self::from_bytes(&bytes)
    }

    /// Create a pointer at counter 0.
    ///
    /// # Errors
    ///
    /// As [`Self::sign`].
    pub fn create(
        secret_key: &MlDsaSecretKey,
        owner: &MlDsaPublicKey,
        target: PointerTarget,
    ) -> Result<Self, PointerError> {
        Self::sign(secret_key, owner, 0, target)
    }

    /// Sign the update that follows this one: `counter + 1`, new target.
    ///
    /// One past this record is the smallest counter that replaces it, and so
    /// the natural next state. A larger one would replace it just as well.
    ///
    /// # Errors
    ///
    /// Returns [`PointerError::CounterExhausted`] at `u64::MAX`, otherwise as
    /// [`Self::sign`].
    pub fn update(
        &self,
        secret_key: &MlDsaSecretKey,
        target: PointerTarget,
    ) -> Result<Self, PointerError> {
        Self::sign(secret_key, &self.owner, self.next_counter()?, target)
    }

    /// Sign this pointer's final state, pointing at `target`.
    ///
    /// Signed at [`FINAL_COUNTER`], so once a node holds it nothing replaces
    /// it — not a later update, which cannot exist, and not another final
    /// state, which does not replace. Use [`Self::transfer_to`] to hand the
    /// pointer to someone else; a final state pointing at a chunk freezes the
    /// pointer on that chunk at every node that holds it.
    ///
    /// Signing a second final state is the one way to fork a pointer for
    /// good: each node keeps whichever of the two it saw first, and no later
    /// state heals it, where a fork at a lower counter is. So this refuses to sign
    /// past a record that is already final, and a caller must read the
    /// network's state before finalizing rather than after. That refusal guards
    /// a caller against a mistake, not the network against the owner: an
    /// earlier record can be finalized again, and [`Self::sign`] signs any
    /// counter.
    ///
    /// # Errors
    ///
    /// Returns [`PointerError::CounterExhausted`] if this record is already
    /// final, otherwise as [`Self::sign`].
    pub fn finalize(
        &self,
        secret_key: &MlDsaSecretKey,
        target: PointerTarget,
    ) -> Result<Self, PointerError> {
        if self.is_terminal() {
            return Err(PointerError::CounterExhausted);
        }
        Self::sign(secret_key, &self.owner, FINAL_COUNTER, target)
    }

    /// Sign the final state that hands this pointer's address over to the
    /// pointer at `recipient`.
    ///
    /// The owner key cannot change, but what the address resolves to can be
    /// handed over: the final state points at a pointer the new owner holds
    /// the key to, so a reader of this address is redirected there by every
    /// node that holds this state, and from there only the new owner moves it
    /// on. It is not exclusive: the former owner can still finalize an earlier
    /// record towards someone else, and a node that holds neither takes
    /// whichever reaches it first (see [`Self::finalize`]). The address readers
    /// use does not change.
    ///
    /// `recipient` should be a pointer that exists, and one whose owner uses
    /// it only for this address: a pointer's address derives from its owner
    /// key, so every address handed to the same recipient pointer resolves to
    /// the same place.
    ///
    /// # Errors
    ///
    /// As [`Self::finalize`].
    pub fn transfer_to(
        &self,
        secret_key: &MlDsaSecretKey,
        recipient: XorName,
    ) -> Result<Self, PointerError> {
        self.finalize(
            secret_key,
            PointerTarget::new(PointerTargetKind::Pointer, recipient),
        )
    }

    /// Parse and fully validate a record.
    ///
    /// Checks, cheapest first: length, format version, structure, then the
    /// signature. A returned `Pointer` is structurally valid and correctly
    /// signed by the key it carries; it says nothing about payment, which is a
    /// separate external check.
    ///
    /// # Errors
    ///
    /// Returns [`PointerError`] for a malformed record or one whose signature
    /// does not verify.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, PointerError> {
        Self::verify_parsed(ParsedPointer::parse(bytes.to_vec())?)
    }

    /// Verify a record that has already been parsed.
    ///
    /// Decoding an ML-DSA public key is not free, and the request path parses
    /// before it decides whether verification is worth doing at all. This lets
    /// it hand over what it already has instead of decoding a second time.
    ///
    /// # Errors
    ///
    /// As [`Self::from_bytes`].
    pub fn verify_parsed(parsed: ParsedPointer) -> Result<Self, PointerError> {
        let ParsedPointer {
            bytes,
            state,
            owner,
        } = parsed;

        let body = bytes
            .get(..POINTER_BODY_LEN)
            .ok_or(PointerError::WrongLength(bytes.len()))?;
        let signature_bytes = bytes
            .get(POINTER_BODY_LEN..)
            .ok_or(PointerError::WrongLength(bytes.len()))?;
        let signature = MlDsaSignature::from_bytes(MlDsaVariant::MlDsa65, signature_bytes)
            .map_err(|e| PointerError::InvalidSignatureFormat(e.to_string()))?;

        let valid = ml_dsa_65()
            .verify_with_context(&owner, body, &signature, SIGNING_CONTEXT)
            .map_err(|e| PointerError::InvalidSignatureFormat(e.to_string()))?;
        if !valid {
            return Err(PointerError::SignatureInvalid);
        }

        Ok(Self {
            version: POINTER_FORMAT_VERSION,
            owner,
            counter: state.counter,
            target: state.target,
            sig: signature,
        })
    }

    /// The canonical encoding of this record.
    ///
    /// Re-encoded from the fields rather than cached. Every field is
    /// fixed-width with no optionality, so there is exactly one encoding and
    /// this is always byte-identical to what was signed.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = self.body();
        out.extend_from_slice(&self.sig.to_bytes());
        out
    }

    /// The signed body: every field the signature covers.
    fn body(&self) -> Vec<u8> {
        encode_body(self.version, &self.owner, self.counter, self.target)
            .unwrap_or_else(|_| Vec::with_capacity(POINTER_BODY_LEN))
    }

    /// The owner's public key. Fixed for the pointer's life.
    #[must_use]
    pub const fn owner(&self) -> &MlDsaPublicKey {
        &self.owner
    }

    /// The signed state this record carries.
    ///
    /// Derived, not stored: the identifiers are hashes of fields already here.
    #[must_use]
    pub fn state(&self) -> PointerState {
        PointerState {
            state_id: self.state_id(),
            address: self.address(),
            counter: self.counter,
            target: self.target,
        }
    }

    /// The update counter.
    #[must_use]
    pub const fn counter(&self) -> u64 {
        self.counter
    }

    /// What this pointer points at.
    #[must_use]
    pub const fn target(&self) -> PointerTarget {
        self.target
    }

    /// The address this record belongs at, derived from the owner key.
    #[must_use]
    pub fn address(&self) -> XorName {
        pointer_address(&self.owner)
    }

    /// The authenticated-state identifier, derived from the signed body.
    ///
    /// Names the state rather than the encoding, so two records carrying
    /// different valid signatures over one state share a `state_id`. This is
    /// what sync hints carry and what a quote is paid against.
    #[must_use]
    pub fn state_id(&self) -> XorName {
        state_id_for_body(&self.body())
    }

    /// The successor counter for an update to this pointer.
    ///
    /// # Errors
    ///
    /// Returns [`PointerError::CounterExhausted`] at [`FINAL_COUNTER`].
    ///
    /// A record at the final counter is replaced by nothing, so there is no
    /// update to sign past it. Migrating a pointer to a fresh one is exactly
    /// that final update: see [`Self::transfer_to`].
    pub fn next_counter(&self) -> Result<u64, PointerError> {
        self.counter
            .checked_add(1)
            .ok_or(PointerError::CounterExhausted)
    }

    /// Whether this record is final: signed at [`FINAL_COUNTER`].
    ///
    /// A node that holds a final record keeps it: neither a lower counter nor
    /// another final record replaces it. See [`PointerState::replaces`].
    #[must_use]
    pub const fn is_terminal(&self) -> bool {
        self.counter == FINAL_COUNTER
    }

    /// The pointer this record hands its address over to, if it is a transfer.
    ///
    /// As [`PointerState::transferred_to`].
    #[must_use]
    pub const fn transferred_to(&self) -> Option<XorName> {
        transfer_target(self.counter, self.target)
    }

    /// Whether `self` replaces `other` under the merge rule.
    ///
    /// See [`PointerState::replaces`], which is where the rule lives.
    #[must_use]
    pub fn replaces(&self, other: &Self) -> bool {
        self.state().replaces(&other.state())
    }
}

/// Encode the signed body of a pointer.
fn encode_body(
    version: u8,
    owner: &MlDsaPublicKey,
    counter: u64,
    target: PointerTarget,
) -> Result<Vec<u8>, PointerError> {
    let owner_bytes = owner.to_bytes();
    if owner_bytes.len() != ML_DSA_65_PUBLIC_KEY_LEN {
        return Err(PointerError::InvalidOwnerKey(format!(
            "owner key must be {ML_DSA_65_PUBLIC_KEY_LEN} bytes, got {}",
            owner_bytes.len()
        )));
    }
    let mut body = Vec::with_capacity(POINTER_BODY_LEN);
    // The record's own version, not this build's: a record is re-encoded as
    // what was signed. Only `POINTER_FORMAT_VERSION` parses today, so the two
    // coincide — but the encoder must not be the thing that assumes it.
    body.push(version);
    body.extend_from_slice(&owner_bytes);
    body.extend_from_slice(&counter.to_be_bytes());
    body.extend_from_slice(&target.to_bytes());
    Ok(body)
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "the crate guide allows these in tests"
)]
mod tests {
    use super::*;

    fn keypair(seed: u8) -> (MlDsaPublicKey, MlDsaSecretKey) {
        ml_dsa_65().generate_keypair_from_seed(&[seed; 32])
    }

    fn signed(seed: u8, counter: u64, target_byte: u8) -> Pointer {
        let (pk, sk) = keypair(seed);
        let target = PointerTarget::new(PointerTargetKind::Chunk, [target_byte; XORNAME_LEN]);
        Pointer::sign(&sk, &pk, counter, target).expect("sign")
    }

    #[test]
    fn sizes_match_the_design() {
        assert_eq!(POINTER_BODY_LEN, 1994);
        assert_eq!(POINTER_WIRE_LEN, 5303);
        assert_eq!(signed(1, 0, 0).to_bytes().len(), POINTER_WIRE_LEN);
    }

    #[test]
    fn roundtrips_and_validates() {
        let record = signed(1, 42, 7);
        let parsed = Pointer::from_bytes(&record.to_bytes()).expect("reparse");
        assert_eq!(parsed.counter(), 42);
        assert_eq!(parsed.address(), record.address());
        assert_eq!(parsed.state_id(), record.state_id());
    }

    #[test]
    fn a_tampered_record_does_not_verify() {
        let record = signed(1, 5, 5);
        let mut bytes = record.to_bytes();
        if let Some(byte) = bytes.get_mut(COUNTER_OFFSET + 7) {
            *byte ^= 1;
        }
        assert!(matches!(
            Pointer::from_bytes(&bytes),
            Err(PointerError::SignatureInvalid)
        ));
    }

    #[test]
    fn an_unknown_format_version_is_refused() {
        let record = signed(1, 1, 1);
        let mut bytes = record.to_bytes();
        if let Some(byte) = bytes.first_mut() {
            *byte = 2;
        }
        assert!(matches!(
            Pointer::from_bytes(&bytes),
            Err(PointerError::UnknownFormatVersion(2))
        ));
    }

    #[test]
    fn the_format_version_reaches_the_paid_identifier() {
        // A record differing only in its version byte is a different state and
        // must be paid for separately. Without this a future version could
        // reuse a receipt bought for version 1.
        let record = signed(1, 3, 3);
        let mut body = record
            .to_bytes()
            .get(..POINTER_BODY_LEN)
            .expect("body")
            .to_vec();
        let baseline = state_id_for_body(&body);
        assert_eq!(baseline, record.state_id());

        for version in 0u8..=255 {
            if version == POINTER_FORMAT_VERSION {
                continue;
            }
            if let Some(byte) = body.first_mut() {
                *byte = version;
            }
            assert_ne!(
                state_id_for_body(&body),
                baseline,
                "version {version} must not share version 1's paid identifier"
            );
        }
    }

    #[test]
    fn different_owners_are_not_comparable() {
        let mine = signed(1, 1, 9);
        let theirs = signed(2, 500, 0);
        assert!(!mine.replaces(&theirs));
        assert!(!theirs.replaces(&mine));
    }

    #[test]
    fn the_counter_is_terminal_at_its_maximum() {
        let ordinary = signed(1, 0, 0);
        assert!(!ordinary.is_terminal());
        assert_eq!(ordinary.next_counter().expect("next"), 1);

        let terminal = signed(1, u64::MAX, 0);
        assert!(terminal.is_terminal());
        assert_eq!(terminal.next_counter(), Err(PointerError::CounterExhausted));
        assert!(terminal.next_counter().is_err());
    }

    #[test]
    fn nothing_out_ranks_a_terminal_counter() {
        // No lower counter replaces a final state, and a final state replaces
        // every lower one.
        let terminal = signed(1, u64::MAX, 5);
        for counter in [0u64, 1, 42, u64::MAX - 1] {
            let earlier = signed(1, counter, 0);
            assert!(
                !earlier.replaces(&terminal),
                "counter {counter} must not replace a terminal pointer"
            );
            assert!(terminal.replaces(&earlier));
        }
    }

    #[test]
    fn a_final_state_is_replaced_by_nothing_not_even_a_smaller_target() {
        // Below the final counter, equal counters resolve by target bytes. At
        // it they do not: a former owner who handed the address on could
        // otherwise grind a smaller target and take it back. So two final
        // states are incomparable, and a node keeps whichever it took first.
        let first = signed(1, FINAL_COUNTER, 9);
        let smaller_target = signed(1, FINAL_COUNTER, 1);
        assert!(
            !smaller_target.replaces(&first),
            "a smaller target no longer wins"
        );
        assert!(!first.replaces(&smaller_target));

        // Below the final counter nothing changed.
        let low = signed(1, 7, 1);
        let high = signed(1, 7, 9);
        assert!(
            low.replaces(&high),
            "smaller target still wins below the end"
        );
    }

    #[test]
    fn a_state_at_the_final_counter_is_final_whatever_it_targets() {
        let (pk, sk) = keypair(40);
        let chunk = PointerTarget::new(PointerTargetKind::Chunk, [4; XORNAME_LEN]);
        let pointer = PointerTarget::new(PointerTargetKind::Pointer, [5; XORNAME_LEN]);
        let unknown = PointerTarget::from_raw_tag(200, [6; XORNAME_LEN]);
        for target in [chunk, pointer, unknown] {
            let held = Pointer::sign(&sk, &pk, FINAL_COUNTER, target).expect("sign");
            assert!(held.is_terminal());
            assert!(held.state().is_terminal());
            for other in [chunk, pointer, unknown] {
                for counter in [0, 1, FINAL_COUNTER - 1, FINAL_COUNTER] {
                    let arrival = Pointer::sign(&sk, &pk, counter, other).expect("sign");
                    assert!(
                        !arrival.replaces(&held),
                        "counter {counter} must not replace a final state"
                    );
                }
            }
        }
    }

    #[test]
    fn a_transfer_is_a_final_state_that_targets_the_recipient_pointer() {
        let (pk, sk) = keypair(41);
        let recipient = [0x42; XORNAME_LEN];
        let current = Pointer::create(
            &sk,
            &pk,
            PointerTarget::new(PointerTargetKind::Chunk, [1; XORNAME_LEN]),
        )
        .expect("create");
        assert_eq!(current.transferred_to(), None);

        let transfer = current.transfer_to(&sk, recipient).expect("transfer");
        assert_eq!(transfer.counter(), FINAL_COUNTER);
        assert_eq!(transfer.address(), current.address(), "the address stays");
        assert_eq!(
            transfer.target(),
            PointerTarget::new(PointerTargetKind::Pointer, recipient)
        );
        assert_eq!(transfer.transferred_to(), Some(recipient));
        assert_eq!(transfer.state().transferred_to(), Some(recipient));
        assert!(transfer.replaces(&current));

        // Nothing replaces the final state: no later counter exists, and a
        // second final state, however its target sorts, does not replace it.
        assert!(matches!(
            transfer.update(&sk, current.target()),
            Err(PointerError::CounterExhausted)
        ));
        assert!(
            matches!(
                transfer.transfer_to(&sk, [0; XORNAME_LEN]),
                Err(PointerError::CounterExhausted)
            ),
            "finalizing twice is refused rather than signed into a fork"
        );
        let grinded = Pointer::sign(
            &sk,
            &pk,
            FINAL_COUNTER,
            PointerTarget::new(PointerTargetKind::Pointer, [0; XORNAME_LEN]),
        )
        .expect("sign");
        assert!(!grinded.replaces(&transfer));
    }

    #[test]
    fn an_earlier_record_can_be_finalized_twice_and_neither_replaces_the_other() {
        // The refusal to finalize a final record is a guard for the caller
        // that holds it. The owner still holds the earlier record and its key,
        // so it can sign a second, different final state. The merge rule does
        // not order the two: a node keeps whichever it took first.
        let (pk, sk) = keypair(44);
        let current = Pointer::create(
            &sk,
            &pk,
            PointerTarget::new(PointerTargetKind::Chunk, [1; XORNAME_LEN]),
        )
        .expect("create");
        let to_a = current.transfer_to(&sk, [0xA; XORNAME_LEN]).expect("first");
        let to_b = current
            .transfer_to(&sk, [0xB; XORNAME_LEN])
            .expect("second");
        assert_ne!(to_a.state().state_id, to_b.state().state_id);
        assert!(to_a.replaces(&current) && to_b.replaces(&current));
        assert!(
            !to_a.replaces(&to_b),
            "neither final state replaces the other"
        );
        assert!(!to_b.replaces(&to_a));
    }

    #[test]
    fn only_a_final_pointer_target_is_a_transfer() {
        let (pk, sk) = keypair(43);
        let forward = PointerTarget::new(PointerTargetKind::Pointer, [7; XORNAME_LEN]);
        let chunk = PointerTarget::new(PointerTargetKind::Chunk, [7; XORNAME_LEN]);

        // A pointer target below the final counter is a forwarding the owner
        // can still take back, not a transfer.
        let forwarding = Pointer::sign(&sk, &pk, FINAL_COUNTER - 1, forward).expect("sign");
        assert_eq!(forwarding.transferred_to(), None);

        // A final chunk target freezes the pointer at the nodes that hold it;
        // nobody receives it.
        let frozen = Pointer::sign(&sk, &pk, FINAL_COUNTER, chunk).expect("sign");
        assert_eq!(frozen.transferred_to(), None);

        let handed_on = Pointer::sign(&sk, &pk, FINAL_COUNTER, forward).expect("sign");
        assert_eq!(handed_on.transferred_to(), Some([7; XORNAME_LEN]));
    }

    #[test]
    fn with_final_states_a_fold_keeps_the_first_final_it_meets() {
        // A node folds `replaces` over arrivals in arrival order. Below the
        // final counter the order is total, so the fold ends in one place
        // whatever the order; two final states are the one pair it does not
        // order, so the fold keeps whichever came first. That is the
        // first-come rule, and the only place arrival order matters.
        let fold = |arrivals: &[&Pointer]| -> XorName {
            let mut held: Option<&Pointer> = None;
            for arrival in arrivals {
                if held.is_none_or(|h| arrival.replaces(h)) {
                    held = Some(arrival);
                }
            }
            held.expect("something arrived").state_id()
        };
        let early = signed(44, 3, 1);
        let final_a = signed(44, FINAL_COUNTER, 9);
        let final_b = signed(44, FINAL_COUNTER, 1);

        assert_eq!(fold(&[&early, &final_a, &final_b]), final_a.state_id());
        assert_eq!(fold(&[&final_b, &early, &final_a]), final_b.state_id());
        assert_eq!(fold(&[&final_a, &final_b, &early]), final_a.state_id());
        assert_eq!(fold(&[&early, &final_b]), final_b.state_id());
    }

    #[test]
    fn create_starts_at_zero_and_update_adds_one() {
        let (pk, sk) = keypair(20);
        let target = |b: u8| PointerTarget::new(PointerTargetKind::Chunk, [b; XORNAME_LEN]);

        let created = Pointer::create(&sk, &pk, target(1)).expect("create");
        assert_eq!(created.counter(), 0);

        let first = created.update(&sk, target(2)).expect("update");
        assert_eq!(first.counter(), 1);
        assert!(first.replaces(&created));

        let second = first.update(&sk, target(3)).expect("update");
        assert_eq!(second.counter(), 2);
        assert!(second.replaces(&first));
    }

    #[test]
    fn any_larger_counter_replaces_so_counters_may_skip() {
        // The counter orders states; it does not meter them. Each stored state
        // is paid for once whatever its number, so a skipped number is never
        // stored and owes nothing.
        let held = signed(21, 5, 7);
        for later in [6u64, 7, 99, u64::MAX] {
            assert!(
                signed(21, later, 7).replaces(&held),
                "counter {later} must replace counter 5"
            );
        }
        for earlier in [0u64, 4] {
            assert!(
                !signed(21, earlier, 7).replaces(&held),
                "counter {earlier} must not replace counter 5"
            );
        }
    }

    #[test]
    fn a_fork_at_one_counter_resolves_by_target_and_any_later_counter_heals_it() {
        // Two records at one counter are a fork. Every node that sees both
        // keeps the smaller target, and a record at any later counter replaces
        // whichever side a node was left holding.
        let smaller = signed(25, 5, 1);
        let larger = signed(25, 5, 9);
        assert!(smaller.replaces(&larger), "smaller target bytes win");
        assert!(!larger.replaces(&smaller));

        for later in [6u64, 50] {
            let healed = signed(25, later, 9);
            assert!(healed.replaces(&smaller));
            assert!(healed.replaces(&larger));
        }
    }

    #[test]
    fn a_terminal_pointer_cannot_be_updated() {
        let (pk, sk) = keypair(24);
        let target = PointerTarget::new(PointerTargetKind::Chunk, [1; XORNAME_LEN]);
        let terminal = Pointer::sign(&sk, &pk, u64::MAX, target).expect("sign");
        assert!(
            terminal.update(&sk, target).is_err(),
            "the counter must not wrap around into a fresh-looking pointer"
        );
    }

    /// Re-encoding must be byte-identical to what was signed.
    ///
    /// This is what lets the record hold its five fields and nothing else: the
    /// encoding is fixed-width with no optionality, so there is exactly one
    /// byte sequence for a given record and caching it would buy nothing. If
    /// this ever fails, the cache has to come back.
    #[test]
    fn re_encoding_is_byte_identical() {
        let (pk, sk) = keypair(30);
        for counter in [0u64, 1, 42, u64::MAX] {
            for tag in [0u8, 1, 200] {
                let target = PointerTarget::from_raw_tag(tag, [tag; XORNAME_LEN]);
                let signed = Pointer::sign(&sk, &pk, counter, target).expect("sign");
                let wire = signed.to_bytes();

                // Parsed from the wire, re-encoded, identical.
                let parsed = Pointer::from_bytes(&wire).expect("parse");
                assert_eq!(parsed.to_bytes(), wire, "counter {counter}, tag {tag}");

                // And still verifies, which is the property that actually matters.
                assert!(Pointer::from_bytes(&parsed.to_bytes()).is_ok());
            }
        }
    }

    #[test]
    fn equal_state_never_replaces() {
        let variants: Vec<Pointer> = (0..8).map(|_| signed(1, 7, 3)).collect();
        for a in &variants {
            for b in &variants {
                assert!(!a.replaces(b));
                assert_eq!(a.state_id(), b.state_id());
            }
        }
    }

    #[test]
    fn the_obvious_chunk_preimages_miss_both_pointer_identities() {
        // A chunk's address is BLAKE3 over its content, so a hash of a prefix
        // and a key was reachable by anyone who could write that prefix as a
        // chunk: they could squat an owner's address before it was created, or
        // buy a pointer and a chunk with one payment. These are the preimages
        // that construction handed out. Nothing here proves no content exists —
        // that is a preimage assumption, not a test.
        let (pk, sk) = keypair(77);
        let record = Pointer::create(
            &sk,
            &pk,
            PointerTarget::new(PointerTargetKind::Chunk, [3; XORNAME_LEN]),
        )
        .expect("create");

        let address_preimage = [b"autonomi.pointer.address.v1".as_slice(), &pk.to_bytes()].concat();
        assert_ne!(
            *blake3::hash(&address_preimage).as_bytes(),
            record.address(),
            "a chunk holding this content must not land on the pointer's address"
        );

        let body = record.to_bytes();
        let body = body.get(..POINTER_BODY_LEN).expect("body");
        let state_preimage = [b"autonomi.pointer.state.v1".as_slice(), body].concat();
        assert_ne!(
            *blake3::hash(&state_preimage).as_bytes(),
            record.state_id(),
            "a chunk holding this content must not land on the paid identifier"
        );

        // Nor does the bare key, the bare body, or the context alone.
        for content in [
            pk.to_bytes().as_slice(),
            body,
            b"autonomi.pointer.address.v1",
        ] {
            let address = *blake3::hash(content).as_bytes();
            assert_ne!(address, record.address());
            assert_ne!(address, record.state_id());
        }
    }

    #[test]
    fn the_rule_is_a_strict_order_so_only_final_states_depend_on_arrival_order() {
        // Nodes and clients both pick a winner by folding `replaces` over
        // whatever arrives. That fold gives the same answer whatever the order
        // exactly when the rule is a strict total order on one address: never
        // both ways round, always one way for distinct states, and transitive.
        // It is, for every pair but two different final states — the pair the
        // first-come rule leaves unordered on purpose.
        let records = [
            signed(1, 0, 9),
            signed(1, 2, 1),
            signed(1, 5, 1),
            signed(1, 5, 2),
            signed(1, FINAL_COUNTER, 3),
            signed(1, FINAL_COUNTER, 4),
        ];
        for a in &records {
            assert!(!a.replaces(a), "an equal state never replaces");
            for b in &records {
                assert!(
                    !(a.replaces(b) && b.replaces(a)),
                    "two records cannot each replace the other"
                );
                let both_final = a.is_terminal() && b.is_terminal();
                assert!(
                    a.replaces(b) || b.replaces(a) || a.state_id() == b.state_id() || both_final,
                    "distinct states are always ordered unless both are final"
                );
                for c in &records {
                    assert!(
                        !(a.replaces(b) && b.replaces(c)) || a.replaces(c),
                        "the order is transitive"
                    );
                }
            }
        }
    }
}