Skip to main content

ant_node/pointer/
service.rs

1//! The node's pointer request handler.
2//!
3//! Sits between the wire messages in [`ant_protocol::chunk`] and the
4//! [`PointerStore`], and owns the three things a pointer PUT needs that a chunk
5//! PUT does not:
6//!
7//! 1. **Payment at `state_id`, not at the address.** A pointer's address is
8//!    stable for its life, so quoting against it would make every update after
9//!    the first free — 1.0's defect. The quote's content is the state
10//!    identifier; the close group that answers is still the one around the
11//!    address.
12//! 2. **Merge instead of "already exists".** The chunk path answers
13//!    `AlreadyExists` and stops, which for a mutable record silently drops
14//!    every update.
15//! 3. **Cross-kind collision refusal.** A pointer address and a chunk address
16//!    are both 32 bytes from the same range; the domain separator makes a
17//!    collision infeasible, not impossible. A node that holds one kind at an
18//!    address refuses the other rather than silently choosing.
19//! 4. **A look before a final state.** A state at the final counter is
20//!    replaced by nothing, so a node that takes one can never be corrected.
21//!    Before taking one it neither holds nor lost, the node asks its close
22//!    group whether a *different* final state is already held there, and
23//!    refuses if a peer proves one with the signed record (ADR-0018). That is
24//!    what keeps a former owner from handing an address over a second time to
25//!    a node that had not heard of the first, whenever a peer can prove the
26//!    first in time. A proven loser is remembered and refused again before its
27//!    signature is checked.
28//!
29//! # Order of work
30//!
31//! ```text
32//! parse → compare with what is held → (final state only) a proven loser?
33//!       → verify signature → check payment
34//!       → (final state only) ask the close group → commit
35//! ```
36//!
37//! The comparison precedes the signature check, so re-submitting a state the
38//! node already holds costs a parse and a map lookup rather than an ML-DSA
39//! verification. The payment check sits between validation and commit, and the
40//! commit re-checks, because a newer state can land while payment is verified.
41
42use std::sync::Arc;
43
44use ant_protocol::chunk::{
45    PointerGetRequest, PointerGetResponse, PointerPutRequest, PointerPutResponse, ProtocolError,
46    XorName,
47};
48use bytes::Bytes;
49use futures::future::BoxFuture;
50use parking_lot::RwLock;
51use saorsa_core::P2PNode;
52use tokio::sync::mpsc;
53
54use crate::error::{Error, Result};
55use crate::logging::{debug, info, warn};
56use crate::payment::PaymentVerifier;
57use crate::pointer::store::{Inspected, PointerStore, PutOutcome};
58use crate::replication::admission;
59use crate::replication::pointer::PointerFreshWrite;
60use crate::storage::{ChunkStore, SELF_CLOSENESS_GATE_WIDTH};
61use ant_protocol::pointer::{PointerState, POINTER_WIRE_LEN};
62
63/// Where a node looks, before it takes a final state, for a different final
64/// state its close group already holds (ADR-0018).
65///
66/// A trait rather than the replication engine itself, because the engine is
67/// built after this service and needs a running P2P node, and because what the
68/// service decides from the answer is worth testing without one.
69pub trait FinalStateWitness: Send + Sync {
70    /// Ask the close group whether a final state other than `state` is
71    /// already held at `state.address`.
72    fn check_final<'a>(&'a self, state: &'a PointerState) -> BoxFuture<'a, FinalityCheck>;
73
74    /// A final state at `state.address`, other than `state`, that an earlier
75    /// check already proved, without asking anyone.
76    ///
77    /// Cheap enough to consult ahead of the signature check, so a final state
78    /// that lost once is refused again for nothing, however often the same
79    /// paid record is replayed.
80    fn proven_conflict(&self, state: &PointerState) -> Option<PointerState>;
81
82    /// Forget that a look found `state` clear: the write it cleared did not
83    /// land, so a retry must look again rather than reuse the answer.
84    fn forget_clear(&self, state: &PointerState);
85}
86
87/// What a close group said about a final state a node is about to take.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum FinalityCheck {
90    /// No peer proved a different final state. Also the answer when the group
91    /// could not be asked in time: silence is not evidence, so it never
92    /// refuses a write.
93    Clear,
94    /// A different final state a peer holds, proven by the signed record,
95    /// which only the owner could have made.
96    Conflict(PointerState),
97    /// Too many checks were running to start this one in time. The state is
98    /// neither taken nor refused for good, and the sender may try again.
99    Busy,
100}
101
102/// Handles pointer requests against a [`PointerStore`].
103#[derive(Clone)]
104pub struct PointerService {
105    /// Where pointers are kept.
106    store: PointerStore,
107    /// Consulted so an address held as a chunk is never overwritten by a
108    /// pointer.
109    chunks: Option<Arc<ChunkStore>>,
110    /// Confirms a state was paid for. `None` in tests that exercise the merge
111    /// rather than the payment.
112    payments: Option<Arc<PaymentVerifier>>,
113    /// Where a newly stored paid state goes to be offered to the rest of its
114    /// close group (ADR-0016 replication). Attached once the replication
115    /// engine exists, which is after this service is built; empty where
116    /// nothing replicates, as in unit tests and the devnet.
117    fresh_writes: Arc<RwLock<Option<mpsc::UnboundedSender<PointerFreshWrite>>>>,
118    /// The node's P2P handle, for the self-closeness gate.
119    ///
120    /// Attached after construction, because the node builds its protocol
121    /// handler before it has a running P2P node. `None` in unit tests that
122    /// never attach one, exactly as the chunk path does.
123    p2p_node: Arc<RwLock<Option<Arc<P2PNode>>>>,
124    /// Asked before a final state is taken (ADR-0018). Attached with the
125    /// replication engine; `None` where nothing replicates, and then a final
126    /// state is taken on the merge rule alone.
127    final_witness: Arc<RwLock<Option<Arc<dyn FinalStateWitness>>>>,
128}
129
130impl std::fmt::Debug for PointerService {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        f.debug_struct("PointerService")
133            .field("records", &self.store.len())
134            .field("checks_chunk_collisions", &self.chunks.is_some())
135            .field("verifies_payment", &self.payments.is_some())
136            .finish_non_exhaustive()
137    }
138}
139
140impl PointerService {
141    /// Build a service over `store`.
142    #[must_use]
143    pub fn new(store: PointerStore) -> Self {
144        Self {
145            store,
146            chunks: None,
147            payments: None,
148            fresh_writes: Arc::new(RwLock::new(None)),
149            p2p_node: Arc::new(RwLock::new(None)),
150            final_witness: Arc::new(RwLock::new(None)),
151        }
152    }
153
154    /// Apply the self-closeness gate, so a pointer PUT is admitted only where
155    /// the node is actually responsible.
156    ///
157    /// Without it one valid proof can be replayed to every node on the network,
158    /// each of which would store the record and trigger replication for an
159    /// address it has no business holding.
160    pub fn attach_p2p_node(&self, p2p_node: Arc<P2PNode>) {
161        *self.p2p_node.write() = Some(p2p_node);
162    }
163
164    /// Consult `chunks` before storing, so a cross-kind address collision is
165    /// refused rather than resolved by whichever kind arrived last.
166    #[must_use]
167    pub fn with_chunk_store(mut self, chunks: Arc<ChunkStore>) -> Self {
168        self.chunks = Some(chunks);
169        self
170    }
171
172    /// Require payment, verified against each record's `state_id`.
173    #[must_use]
174    pub fn with_payments(mut self, payments: Arc<PaymentVerifier>) -> Self {
175        self.payments = Some(payments);
176        self
177    }
178
179    /// Hand every newly stored paid state to replication on `writes`.
180    pub fn attach_fresh_writes(&self, writes: mpsc::UnboundedSender<PointerFreshWrite>) {
181        *self.fresh_writes.write() = Some(writes);
182    }
183
184    /// Ask `witness` before taking a final state this node does not hold.
185    pub fn attach_final_state_witness(&self, witness: Arc<dyn FinalStateWitness>) {
186        *self.final_witness.write() = Some(witness);
187    }
188
189    /// The store this service fronts.
190    #[must_use]
191    pub const fn store(&self) -> &PointerStore {
192        &self.store
193    }
194
195    /// Handle a pointer PUT.
196    ///
197    /// Never returns `Err`: a rejection is a response the peer should see, so
198    /// every failure is mapped onto [`PointerPutResponse`].
199    pub async fn handle_put(&self, request: PointerPutRequest) -> PointerPutResponse {
200        // Cheap first: parse and compare against what is held. No signature is
201        // checked yet, so a forged record for an address this node does not
202        // serve is rejected by the gates below without buying an ML-DSA
203        // verification.
204        let parsed = match self.store.inspect(&request.record).await {
205            Ok(Inspected::Unchanged(state)) => {
206                return PointerPutResponse::Unchanged {
207                    address: state.address,
208                    state_id: state.state_id,
209                };
210            }
211            Ok(Inspected::Stale(state)) => {
212                // The state named is the one this node keeps, not the one that
213                // arrived: it is what the sender needs in order to catch up.
214                return PointerPutResponse::Stale {
215                    address: state.address,
216                    state_id: self.store.state_id(&state.address).unwrap_or_default(),
217                };
218            }
219            Ok(Inspected::Candidate(parsed)) => parsed,
220            Err(e) => {
221                debug!("Pointer PUT refused: {e}");
222                return PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
223            }
224        };
225
226        let state = *parsed.state();
227        let address = state.address;
228        let state_id = state.state_id;
229
230        if let Some(refusal) = self.admit(&state).await {
231            return refusal;
232        }
233
234        // Only now is the record worth a signature check.
235        let record = match self.store.verify(parsed).await {
236            Ok(record) => record,
237            Err(e) => {
238                debug!("Pointer PUT refused: {e}");
239                return PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
240            }
241        };
242
243        // Payment is checked against the state, not the address: the address
244        // never changes, so paying against it would buy every future update.
245        if let Some(payments) = &self.payments {
246            if let Err(e) =
247                Self::verify_payment(payments, address, state_id, request.payment_proof.as_ref())
248                    .await
249            {
250                return PointerPutResponse::PaymentRequired {
251                    message: e.to_string(),
252                };
253            }
254        }
255
256        // Last, because it costs the close group a round trip, and only for a
257        // paid final state: if a peer proves a different final state is
258        // already held, this one lost the race to it everywhere that matters.
259        if let Some(refusal) = self.final_refusal(&state).await {
260            return refusal;
261        }
262
263        // Charge the bytes this write will take, and hold the charge until it
264        // lands. Checking capacity and then writing is the race the file store
265        // exists to close: concurrent writers all pass one cached measurement
266        // before any of them has written a byte, and cross the reserve
267        // together. A record is a fixed `POINTER_WIRE_LEN`, so that is the
268        // whole charge.
269        let reservation = match &self.chunks {
270            Some(chunks) => match chunks.reserve(POINTER_WIRE_LEN as u64) {
271                Ok(reservation) => Some(reservation),
272                Err(e) => {
273                    debug!("Rejecting pointer PUT for {}: {e}", hex::encode(address));
274                    self.forget_clear(&state);
275                    return PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
276                }
277            },
278            None => None,
279        };
280        // The charge travels with the write. Settling it here instead would
281        // release it the moment this future is dropped, while the blocking
282        // transaction it started runs on and publishes the file.
283        let record_bytes = request.record.to_vec();
284        let response = match self.store.commit(record, reservation).await {
285            Ok(PutOutcome::Changed) => {
286                // Offer it to the rest of the close group, proof included, so
287                // every member holds it whichever of them the client reached.
288                let writes = self.fresh_writes.read().clone();
289                if let (Some(writes), Some(proof)) = (writes, request.payment_proof) {
290                    if writes
291                        .send(PointerFreshWrite {
292                            record: record_bytes,
293                            payment_proof: proof,
294                        })
295                        .is_err()
296                    {
297                        debug!(
298                            "Replication is not running; pointer {} is not offered on",
299                            hex::encode(address)
300                        );
301                    }
302                }
303                PointerPutResponse::Success { address, state_id }
304            }
305            // The re-check under the commit lock found a newer state. The
306            // client paid for a state that lost a race; say so plainly.
307            Ok(PutOutcome::Unchanged) => PointerPutResponse::Unchanged { address, state_id },
308            Ok(PutOutcome::Stale) => PointerPutResponse::Stale {
309                address,
310                state_id: self.store.state_id(&address).unwrap_or(state_id),
311            },
312            Err(e) => {
313                warn!("Pointer commit failed for {}: {e}", hex::encode(address));
314                PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()))
315            }
316        };
317        // A look that cleared a final state is reused briefly for replays of
318        // it; a write that did not land must not leave that answer behind.
319        if !matches!(
320            response,
321            PointerPutResponse::Success { .. } | PointerPutResponse::Unchanged { .. }
322        ) {
323            self.forget_clear(&state);
324        }
325        response
326    }
327
328    /// Forget a clear look for `state`, if a witness took one.
329    fn forget_clear(&self, state: &PointerState) {
330        if state.is_terminal() {
331            if let Some(witness) = self.final_witness.read().as_ref() {
332                witness.forget_clear(state);
333            }
334        }
335    }
336
337    /// Everything that must hold before a record is worth verifying.
338    ///
339    /// `Some(response)` means refuse. Ordered cheapest first, and all of it
340    /// ahead of the signature check, so a forged record for an address this
341    /// node does not serve buys no cryptography.
342    async fn admit(&self, state: &PointerState) -> Option<PointerPutResponse> {
343        let address = state.address;
344
345        // Any state the merge rule prefers to what this node knows, whatever
346        // its counter: a node that missed updates, or joined the group after
347        // them, must take the next one or it never catches up. An arrival that
348        // loses to what is held was already answered as stale; this also
349        // covers a record the node lost, which that comparison cannot see, so
350        // a replay cannot roll it back.
351        if !self.store.admits(state) {
352            info!(
353                "Rejecting pointer PUT for {}: counter {} does not beat the state this node knows",
354                hex::encode(address),
355                state.counter
356            );
357            // Named as the state this node knows, even one whose file it
358            // lost, so the sender can see what it must catch up to.
359            return Some(PointerPutResponse::Stale {
360                address,
361                state_id: self
362                    .store
363                    .remembered(&address)
364                    .map(|known| known.state_id)
365                    .unwrap_or_default(),
366            });
367        }
368
369        if let Some(chunks) = &self.chunks {
370            // A chunk already here means the two kinds collided. Refuse rather
371            // than pick: whichever we chose, someone's data would vanish.
372            if let Some(refusal) = cross_kind_refusal(address, chunks.exists(&address)) {
373                return Some(refusal);
374            }
375            // Capacity before payment, as the chunk path does, and for the
376            // size a record actually is rather than for nothing. The binding
377            // charge is taken at the commit; this only avoids paying to find
378            // out the disk is full.
379            if let Err(e) = chunks.check_capacity_for(POINTER_WIRE_LEN as u64) {
380                let addr = hex::encode(address);
381                info!(
382                    target: "ant_node::storage::disk_precheck",
383                    addr = %addr,
384                    kind = "pointer",
385                    "Rejecting pointer PUT before payment verification: {e}"
386                );
387                return Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
388                    e.to_string(),
389                )));
390            }
391        }
392
393        // Self-closeness gate (ADR-0003), judged at the pointer's address
394        // because that is what the network routes on. Bind the handle out of
395        // the lock first: no guard may be held across an await.
396        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
397        if let Some(p2p) = attached {
398            let self_id = *p2p.peer_id();
399            if !admission::is_responsible(&self_id, &address, &p2p, SELF_CLOSENESS_GATE_WIDTH).await
400            {
401                debug!(
402                    "Rejecting pointer PUT for {}: not within local closest peers",
403                    hex::encode(address)
404                );
405                return Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
406                    "node is not within its local closest peers for this address".to_string(),
407                )));
408            }
409        }
410
411        // A final state an earlier check proved lost to another is refused
412        // again here, before it buys a signature check or a round trip.
413        if self.needs_final_check(state) {
414            let proven = self
415                .final_witness
416                .read()
417                .as_ref()
418                .and_then(|witness| witness.proven_conflict(state));
419            if let Some(conflict) = proven {
420                return Some(PointerPutResponse::Stale {
421                    address,
422                    state_id: conflict.state_id,
423                });
424            }
425        }
426        None
427    }
428
429    /// Whether `state` needs the close group's word before this node takes
430    /// it: it is final, and this node neither holds nor remembers a final
431    /// state at its address.
432    ///
433    /// Nothing else is asked about. A lower counter can be replaced, so taking
434    /// one blind costs nothing a later state cannot fix. A node that holds a
435    /// final state has had its answer from the merge rule before this runs:
436    /// the same state is unchanged and any other is stale. And a node that
437    /// lost the file of a final state it held is admitted only that state
438    /// again ([`PointerStore::admits`]), which restores what it already took
439    /// rather than taking a new one. Asking there would let any peer on the
440    /// other side of a fork keep it from restoring its own copy.
441    fn needs_final_check(&self, state: &PointerState) -> bool {
442        state.is_terminal()
443            && !self
444                .store
445                .remembered(&state.address)
446                .is_some_and(|known| known.is_terminal())
447    }
448
449    /// The answer to a paid final state the close group proves already lost,
450    /// or that could not be checked in time; `None` to take it.
451    async fn final_refusal(&self, state: &PointerState) -> Option<PointerPutResponse> {
452        if !self.needs_final_check(state) {
453            return None;
454        }
455        let witness = self.final_witness.read().as_ref().map(Arc::clone)?;
456        match witness.check_final(state).await {
457            FinalityCheck::Clear => None,
458            // Named as the state the group proved, as for any stale arrival.
459            FinalityCheck::Conflict(conflict) => {
460                info!(
461                    "Refusing final pointer state {} at {}: the close group already holds \
462                     final state {}, so the owner has finalized it before",
463                    hex::encode(state.state_id),
464                    hex::encode(state.address),
465                    hex::encode(conflict.state_id)
466                );
467                Some(PointerPutResponse::Stale {
468                    address: state.address,
469                    state_id: conflict.state_id,
470                })
471            }
472            FinalityCheck::Busy => {
473                debug!(
474                    "Deferring final pointer state {} at {}: too many finality checks running",
475                    hex::encode(state.state_id),
476                    hex::encode(state.address)
477                );
478                Some(PointerPutResponse::Error(ProtocolError::Internal(
479                    "too many finality checks running; try again".to_string(),
480                )))
481            }
482        }
483    }
484
485    /// Handle a pointer GET.
486    pub async fn handle_get(&self, request: PointerGetRequest) -> PointerGetResponse {
487        match self.store.get(&request.address).await {
488            Ok(Some(record)) => PointerGetResponse::Success {
489                record: Bytes::from(record.to_bytes()),
490            },
491            Ok(None) => PointerGetResponse::NotFound {
492                address: request.address,
493            },
494            Err(e) => PointerGetResponse::Error(ProtocolError::StorageFailed(e.to_string())),
495        }
496    }
497
498    /// Confirm the submitted state was paid for.
499    ///
500    /// `routing_address` selects the close group whose quotes count;
501    /// `paid_content` is what the quote must name. They are different values
502    /// here, which is the whole point — the existing chunk path passes one
503    /// address for both jobs.
504    async fn verify_payment(
505        payments: &PaymentVerifier,
506        routing_address: XorName,
507        paid_content: XorName,
508        proof: Option<&Vec<u8>>,
509    ) -> Result<()> {
510        let Some(proof) = proof else {
511            return Err(Error::Payment(format!(
512                "a pointer update must be paid for; no proof supplied for state {}",
513                hex::encode(paid_content)
514            )));
515        };
516        payments
517            .verify_pointer_payment(&routing_address, &paid_content, proof)
518            .await
519    }
520}
521
522/// Decide whether a chunk already at `address` blocks this pointer.
523///
524/// Separated from the handler because the branch cannot be reached in a test
525/// any other way: a pointer address comes out of BLAKE3's derive-key mode and a
526/// chunk address out of a plain hash, so occupying both with real data would
527/// take a collision across the two. The decision is what matters, so the
528/// decision is what is tested.
529///
530/// `Some(response)` means refuse. Refusing is the only safe answer: whichever
531/// kind were chosen, the other's data would be destroyed, and the node cannot
532/// know which one the network expects.
533fn cross_kind_refusal(address: XorName, chunk_present: Result<bool>) -> Option<PointerPutResponse> {
534    match chunk_present {
535        Ok(true) => {
536            warn!(
537                "Refusing pointer at {}: a chunk already occupies that address",
538                hex::encode(address)
539            );
540            Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
541                format!(
542                    "address {} is already occupied by a chunk; refusing to store a \
543                     pointer over it",
544                    hex::encode(address)
545                ),
546            )))
547        }
548        Ok(false) => None,
549        Err(e) => Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
550            format!("cannot check the chunk store for a collision: {e}"),
551        ))),
552    }
553}
554
555#[cfg(test)]
556#[allow(
557    clippy::unwrap_used,
558    clippy::expect_used,
559    clippy::panic,
560    reason = "test assertions"
561)]
562mod tests {
563    use super::*;
564    use crate::payment::{EvmVerifierConfig, PriceFloorConfig};
565    use ant_protocol::pointer::{Pointer, PointerTarget, PointerTargetKind, FINAL_COUNTER};
566    use saorsa_pqc::api::sig::{ml_dsa_65, MlDsaPublicKey, MlDsaSecretKey};
567    use std::sync::atomic::{AtomicUsize, Ordering};
568
569    fn keypair(seed: u8) -> (MlDsaPublicKey, MlDsaSecretKey) {
570        ml_dsa_65().generate_keypair_from_seed(&[seed; 32])
571    }
572
573    fn signed(seed: u8, counter: u64, target_byte: u8) -> Pointer {
574        let (pk, sk) = keypair(seed);
575        let target = PointerTarget::new(PointerTargetKind::Chunk, [target_byte; 32]);
576        Pointer::sign(&sk, &pk, counter, target).expect("sign")
577    }
578
579    async fn service() -> (PointerService, tempfile::TempDir) {
580        let dir = tempfile::tempdir().expect("tempdir");
581        let store = PointerStore::new(dir.path()).await.expect("store");
582        (PointerService::new(store), dir)
583    }
584
585    /// A service whose chunk store guards a disk that cannot take another byte.
586    async fn service_with_full_disk() -> (PointerService, tempfile::TempDir) {
587        let dir = tempfile::tempdir().expect("tempdir");
588        let store = PointerStore::new(dir.path()).await.expect("store");
589        let chunks = ChunkStore::new(crate::storage::ChunkStoreConfig {
590            root_dir: dir.path().to_path_buf(),
591            verify_on_read: false,
592            // Larger than any disk, so every capacity question answers "full".
593            disk_reserve: u64::MAX,
594        })
595        .await
596        .expect("chunk store");
597        (
598            PointerService::new(store).with_chunk_store(Arc::new(chunks)),
599            dir,
600        )
601    }
602
603    #[tokio::test]
604    async fn a_full_disk_refuses_a_pointer_before_it_is_written() {
605        // A disk with no room refuses at the admission check, before payment,
606        // so a client is not charged to find out. This does not reach the
607        // reservation — the store-level tests cover that — it covers the early
608        // refusal and that nothing is stored when it fires.
609        let (service, _dir) = service_with_full_disk().await;
610        let record = signed(1, 0, 1);
611
612        match service.handle_put(put(&record)).await {
613            PointerPutResponse::Error(ProtocolError::StorageFailed(message)) => {
614                assert!(
615                    message.contains("disk space") || message.contains("reserve"),
616                    "a full disk should say so, got: {message}"
617                );
618            }
619            other => panic!("a full disk must refuse the write, got {other:?}"),
620        }
621
622        assert!(
623            matches!(
624                service
625                    .handle_get(PointerGetRequest::new(record.address()))
626                    .await,
627                PointerGetResponse::NotFound { .. }
628            ),
629            "nothing may be stored when the disk had no room for it"
630        );
631    }
632
633    #[tokio::test]
634    async fn concurrent_creations_are_each_charged_against_the_disk() {
635        // Every one of these would pass a bare capacity *check* against one
636        // cached measurement. What stops them collectively crossing the
637        // reserve is that each holds a charge until its write lands.
638        let (service, dir) = service().await;
639        let chunks = ChunkStore::new(crate::storage::ChunkStoreConfig {
640            root_dir: dir.path().to_path_buf(),
641            verify_on_read: false,
642            disk_reserve: 0,
643        })
644        .await
645        .expect("chunk store");
646        let service = service.with_chunk_store(Arc::new(chunks));
647
648        let chunks = service.chunks.clone().expect("chunk store");
649        let (written_before, in_flight_before) = chunks.capacity_counters();
650
651        let mut writes = Vec::new();
652        for seed in 1..=8u8 {
653            let record = signed(seed, 0, 1);
654            let service = service.clone();
655            writes.push(tokio::spawn(async move {
656                (record.address(), service.handle_put(put(&record)).await)
657            }));
658        }
659
660        for write in writes {
661            let (address, response) = write.await.expect("join");
662            assert!(
663                matches!(response, PointerPutResponse::Success { .. }),
664                "a disk with room must take the write, got {response:?}"
665            );
666            assert!(matches!(
667                service.handle_get(PointerGetRequest::new(address)).await,
668                PointerGetResponse::Success { .. }
669            ));
670        }
671        assert_eq!(service.store().len(), 8);
672
673        // Each of the eight was charged, and none of the charges was left
674        // hanging. Without the counters this would pass just as well against a
675        // bare capacity check that charges nothing.
676        // Exactly eight allocation charges. An inequality against the raw
677        // record size would accept four: a record rounds up to the allocation
678        // unit, and four of those already exceed eight record sizes.
679        let one = ChunkStore::capacity_charge_for(POINTER_WIRE_LEN as u64);
680        assert_eq!(
681            chunks.capacity_counters(),
682            (written_before + 8 * one, in_flight_before),
683            "eight writes, eight charges, none left in flight"
684        );
685    }
686
687    fn put(record: &Pointer) -> PointerPutRequest {
688        PointerPutRequest::new(Bytes::from(record.to_bytes()))
689    }
690
691    #[tokio::test]
692    async fn a_put_then_a_get_round_trips_the_record() {
693        let (service, _dir) = service().await;
694        let record = signed(1, 0, 1);
695
696        match service.handle_put(put(&record)).await {
697            PointerPutResponse::Success { address, state_id } => {
698                assert_eq!(address, record.address());
699                assert_eq!(state_id, record.state_id());
700            }
701            other => panic!("expected Success, got {other:?}"),
702        }
703
704        match service
705            .handle_get(PointerGetRequest::new(record.address()))
706            .await
707        {
708            PointerGetResponse::Success { record: bytes } => {
709                assert_eq!(bytes.as_ref(), record.to_bytes());
710            }
711            other => panic!("expected Success, got {other:?}"),
712        }
713    }
714
715    #[tokio::test]
716    async fn an_update_replaces_and_a_stale_one_is_told_so() {
717        let (service, _dir) = service().await;
718        let first = signed(1, 0, 1);
719        let second = signed(1, 1, 1);
720        service.handle_put(put(&first)).await;
721
722        assert!(matches!(
723            service.handle_put(put(&second)).await,
724            PointerPutResponse::Success { .. }
725        ));
726
727        match service.handle_put(put(&first)).await {
728            PointerPutResponse::Stale { address, state_id } => {
729                assert_eq!(address, first.address());
730                assert_eq!(state_id, second.state_id(), "the newer state is reported");
731            }
732            other => panic!("expected Stale, got {other:?}"),
733        }
734    }
735
736    #[tokio::test]
737    async fn two_nodes_given_the_same_states_in_opposite_orders_agree() {
738        // The convergence property, driven through the request handler rather
739        // than the store. The gate in front of the merge rule is part of the
740        // production path, and a gate that admits records by arrival order
741        // would leave these two nodes holding different records for ever --
742        // which is the fork the merge rule exists to prevent.
743        let (first_node, _a) = service().await;
744        let (second_node, _b) = service().await;
745
746        // Two separately paid states at one counter. The merge rule says the
747        // smaller target wins, whichever arrives first.
748        let loser = signed(1, 0, 9);
749        let winner = signed(1, 0, 1);
750        assert!(winner.replaces(&loser));
751
752        for record in [&loser, &winner] {
753            first_node.handle_put(put(record)).await;
754        }
755        for record in [&winner, &loser] {
756            second_node.handle_put(put(record)).await;
757        }
758
759        for (name, node) in [("first", &first_node), ("second", &second_node)] {
760            match node
761                .handle_get(PointerGetRequest::new(winner.address()))
762                .await
763            {
764                PointerGetResponse::Success { record: bytes } => assert_eq!(
765                    Pointer::from_bytes(&bytes).expect("parse").state_id(),
766                    winner.state_id(),
767                    "the {name} node kept the wrong record"
768                ),
769                other => panic!("expected the winner, got {other:?}"),
770            }
771        }
772
773        // And the node that already had the winner refused to go back.
774        assert!(matches!(
775            second_node.handle_put(put(&loser)).await,
776            PointerPutResponse::Stale { .. }
777        ));
778    }
779
780    #[tokio::test]
781    async fn a_fork_between_two_nodes_is_healed_by_any_later_counter() {
782        // Two paid states at one counter, each reaching a different node: a
783        // fork no read can settle for them. The next update, at any later
784        // counter, lands on both and leaves them holding the same record.
785        let (first_node, _a) = service().await;
786        let (second_node, _b) = service().await;
787        let one_side = signed(1, 1, 9);
788        let other_side = signed(1, 1, 1);
789        assert!(matches!(
790            first_node.handle_put(put(&one_side)).await,
791            PointerPutResponse::Success { .. }
792        ));
793        assert!(matches!(
794            second_node.handle_put(put(&other_side)).await,
795            PointerPutResponse::Success { .. }
796        ));
797
798        let healed = signed(1, 5, 4);
799        for (name, node) in [("first", &first_node), ("second", &second_node)] {
800            match node.handle_put(put(&healed)).await {
801                PointerPutResponse::Success { address, state_id } => {
802                    assert_eq!(address, healed.address());
803                    assert_eq!(state_id, healed.state_id());
804                }
805                other => panic!("the {name} node refused the healing update: {other:?}"),
806            }
807            let held = node
808                .store()
809                .get(&healed.address())
810                .await
811                .expect("get")
812                .expect("present");
813            assert_eq!(held.state_id(), healed.state_id(), "the {name} node");
814        }
815    }
816
817    #[tokio::test]
818    async fn re_submitting_a_held_state_is_unchanged_not_success() {
819        // A client that retries must be able to tell "your update landed" from
820        // "you paid for something already stored".
821        let (service, _dir) = service().await;
822        let record = signed(1, 0, 4);
823        service.handle_put(put(&record)).await;
824
825        let variant = signed(1, 0, 4);
826        assert_ne!(variant.to_bytes(), record.to_bytes());
827        match service.handle_put(put(&variant)).await {
828            PointerPutResponse::Unchanged { address, state_id } => {
829                assert_eq!(address, record.address());
830                assert_eq!(state_id, record.state_id());
831            }
832            other => panic!("expected Unchanged, got {other:?}"),
833        }
834    }
835
836    #[tokio::test]
837    async fn an_absent_pointer_is_not_found() {
838        let (service, _dir) = service().await;
839        match service.handle_get(PointerGetRequest::new([7u8; 32])).await {
840            PointerGetResponse::NotFound { address } => assert_eq!(address, [7u8; 32]),
841            other => panic!("expected NotFound, got {other:?}"),
842        }
843    }
844
845    #[tokio::test]
846    async fn junk_is_refused_rather_than_stored() {
847        let (service, _dir) = service().await;
848        assert!(matches!(
849            service
850                .handle_put(PointerPutRequest::new(Bytes::from_static(b"not a pointer")))
851                .await,
852            PointerPutResponse::Error(_)
853        ));
854        assert!(service.store().is_empty());
855    }
856
857    #[tokio::test]
858    async fn a_forged_signature_is_refused() {
859        let (service, _dir) = service().await;
860        let record = signed(1, 0, 1);
861        let mut bytes = record.to_bytes();
862        if let Some(byte) = bytes.get_mut(ant_protocol::pointer::POINTER_BODY_LEN + 3) {
863            *byte ^= 0xff;
864        }
865        assert!(matches!(
866            service
867                .handle_put(PointerPutRequest::new(Bytes::from(bytes)))
868                .await,
869            PointerPutResponse::Error(_)
870        ));
871        assert!(service.store().is_empty());
872    }
873
874    #[tokio::test]
875    async fn payment_is_required_when_a_verifier_is_attached() {
876        use crate::payment::{PaymentVerifier, PaymentVerifierConfig};
877
878        let dir = tempfile::tempdir().expect("tempdir");
879        let store = PointerStore::new(dir.path()).await.expect("store");
880        let verifier = Arc::new(PaymentVerifier::new(PaymentVerifierConfig {
881            evm: EvmVerifierConfig::default(),
882            cache_capacity: 16,
883            close_group_size: ant_protocol::chunk::CLOSE_GROUP_SIZE,
884            local_rewards_address: evmlib::common::Address::new([1u8; 20]),
885            price_floor: PriceFloorConfig::default(),
886        }));
887        let service = PointerService::new(store).with_payments(verifier);
888
889        // No proof at all: refused as PaymentRequired, not stored.
890        match service.handle_put(put(&signed(1, 0, 1))).await {
891            PointerPutResponse::PaymentRequired { message } => {
892                assert!(message.contains("must be paid for"), "got: {message}");
893            }
894            other => panic!("expected PaymentRequired, got {other:?}"),
895        }
896        assert!(
897            service.store().is_empty(),
898            "an unpaid update must not be stored"
899        );
900    }
901
902    #[tokio::test]
903    async fn any_counter_that_beats_what_is_held_is_taken() {
904        let (service, _dir) = service().await;
905
906        // A node that joined after the pointer was created holds nothing, so
907        // the first record it sees need not be counter 0.
908        let first_seen = signed(1, 5, 1);
909        assert!(matches!(
910            service.handle_put(put(&first_seen)).await,
911            PointerPutResponse::Success { .. }
912        ));
913
914        // Anything older is stale, whatever else it says.
915        for older in [0u64, 4] {
916            assert!(
917                matches!(
918                    service.handle_put(put(&signed(1, older, 2))).await,
919                    PointerPutResponse::Stale { .. }
920                ),
921                "counter {older} must not replace counter 5"
922            );
923        }
924
925        // Anything newer lands, however far it skips.
926        for newer in [6u64, 99, u64::MAX] {
927            let record = signed(1, newer, 2);
928            match service.handle_put(put(&record)).await {
929                PointerPutResponse::Success { state_id, .. } => {
930                    assert_eq!(state_id, record.state_id());
931                }
932                other => panic!("counter {newer} was refused: {other:?}"),
933            }
934        }
935        let held = service
936            .store()
937            .get(&first_seen.address())
938            .await
939            .expect("get")
940            .expect("present");
941        assert_eq!(held.counter(), u64::MAX);
942    }
943
944    /// A close group whose answer to the finality question is fixed, and
945    /// which counts how often it was asked.
946    struct StubWitness {
947        answer: FinalityCheck,
948        proven: Option<PointerState>,
949        asked: AtomicUsize,
950        forgotten: AtomicUsize,
951    }
952
953    impl StubWitness {
954        fn answering(answer: FinalityCheck) -> Arc<Self> {
955            Arc::new(Self {
956                answer,
957                proven: None,
958                asked: AtomicUsize::new(0),
959                forgotten: AtomicUsize::new(0),
960            })
961        }
962
963        /// One that already proved `conflict` in an earlier check.
964        fn having_proven(conflict: PointerState) -> Arc<Self> {
965            Arc::new(Self {
966                answer: FinalityCheck::Clear,
967                proven: Some(conflict),
968                asked: AtomicUsize::new(0),
969                forgotten: AtomicUsize::new(0),
970            })
971        }
972
973        fn asked(&self) -> usize {
974            self.asked.load(Ordering::SeqCst)
975        }
976    }
977
978    impl FinalStateWitness for StubWitness {
979        fn check_final<'a>(&'a self, _state: &'a PointerState) -> BoxFuture<'a, FinalityCheck> {
980            self.asked.fetch_add(1, Ordering::SeqCst);
981            let answer = self.answer;
982            Box::pin(async move { answer })
983        }
984
985        fn proven_conflict(&self, state: &PointerState) -> Option<PointerState> {
986            self.proven
987                .filter(|proven| proven.state_id != state.state_id)
988        }
989
990        fn forget_clear(&self, _state: &PointerState) {
991            self.forgotten.fetch_add(1, Ordering::SeqCst);
992        }
993    }
994
995    fn final_state(seed: u8, target_byte: u8) -> Pointer {
996        let (pk, sk) = keypair(seed);
997        let target = PointerTarget::new(PointerTargetKind::Pointer, [target_byte; 32]);
998        Pointer::sign(&sk, &pk, FINAL_COUNTER, target).expect("sign")
999    }
1000
1001    #[tokio::test]
1002    async fn a_final_state_the_group_proves_is_already_superseded_is_refused() {
1003        // The node has the pointer's ordinary state and has never seen a final
1004        // one, so the merge rule alone would take this. The group proves the
1005        // owner already finalized it elsewhere, so it is refused, named as the
1006        // state that got there first, and nothing is written.
1007        let (service, _dir) = service().await;
1008        let current = signed(1, 3, 1);
1009        service.handle_put(put(&current)).await;
1010
1011        let established = final_state(1, 0xAA);
1012        let late = final_state(1, 0x01);
1013        let witness = StubWitness::answering(FinalityCheck::Conflict(established.state()));
1014        service.attach_final_state_witness(witness.clone());
1015
1016        match service.handle_put(put(&late)).await {
1017            PointerPutResponse::Stale { address, state_id } => {
1018                assert_eq!(address, late.address());
1019                assert_eq!(
1020                    state_id,
1021                    established.state_id(),
1022                    "the first final state is named"
1023                );
1024            }
1025            other => panic!("a second final state must be refused, got {other:?}"),
1026        }
1027        assert_eq!(witness.asked(), 1);
1028        assert_eq!(
1029            service.store().state_id(&late.address()),
1030            Some(current.state_id()),
1031            "nothing was written"
1032        );
1033    }
1034
1035    #[tokio::test]
1036    async fn a_final_state_nobody_contradicts_is_taken() {
1037        // Silence is not evidence: a group that proves nothing lets the final
1038        // state through on the merge rule.
1039        let (service, _dir) = service().await;
1040        let witness = StubWitness::answering(FinalityCheck::Clear);
1041        service.attach_final_state_witness(witness.clone());
1042
1043        let transfer = final_state(2, 0x42);
1044        assert!(matches!(
1045            service.handle_put(put(&transfer)).await,
1046            PointerPutResponse::Success { .. }
1047        ));
1048        assert_eq!(witness.asked(), 1);
1049        assert_eq!(
1050            service.store().state_id(&transfer.address()),
1051            Some(transfer.state_id())
1052        );
1053    }
1054
1055    #[tokio::test]
1056    async fn the_group_is_asked_only_about_a_final_state_the_node_lacks() {
1057        // A lower counter can always be replaced later, so it is taken without
1058        // a round trip. A node already holding a final state has its answer
1059        // from the merge rule before any round trip: the same state is
1060        // unchanged, and any other is stale.
1061        let (service, _dir) = service().await;
1062        let witness = StubWitness::answering(FinalityCheck::Clear);
1063        service.attach_final_state_witness(witness.clone());
1064
1065        for counter in [0u64, 1, u64::MAX - 1] {
1066            assert!(matches!(
1067                service.handle_put(put(&signed(3, counter, 1))).await,
1068                PointerPutResponse::Success { .. }
1069            ));
1070        }
1071        assert_eq!(witness.asked(), 0, "no final state yet, no question");
1072
1073        let first = final_state(3, 0x10);
1074        assert!(matches!(
1075            service.handle_put(put(&first)).await,
1076            PointerPutResponse::Success { .. }
1077        ));
1078        assert_eq!(witness.asked(), 1);
1079
1080        let second = final_state(3, 0x01);
1081        match service.handle_put(put(&second)).await {
1082            PointerPutResponse::Stale { state_id, .. } => {
1083                assert_eq!(state_id, first.state_id());
1084            }
1085            other => panic!("a second final state must be stale, got {other:?}"),
1086        }
1087        assert!(matches!(
1088            service.handle_put(put(&final_state(3, 0x10))).await,
1089            PointerPutResponse::Unchanged { .. }
1090        ));
1091        assert_eq!(witness.asked(), 1, "a held final state answers for itself");
1092    }
1093
1094    #[tokio::test]
1095    async fn a_node_restores_its_own_lost_final_state_without_asking() {
1096        // The node took a final state, then lost the file. The group holds
1097        // the other side of a fork, which a check would prove. Asking would
1098        // keep the node from restoring what it already took, for good; the
1099        // lost state itself is the one thing it is admitted, so nobody is
1100        // asked, and the rival is still refused.
1101        let (service, _dir) = service().await;
1102        let own = final_state(5, 0x10);
1103        let rival = final_state(5, 0x01);
1104        assert!(matches!(
1105            service.handle_put(put(&own)).await,
1106            PointerPutResponse::Success { .. }
1107        ));
1108        std::fs::remove_file(service.store().file_for(&own.address())).expect("remove");
1109        assert!(service
1110            .store()
1111            .get(&own.address())
1112            .await
1113            .expect("get")
1114            .is_none());
1115
1116        let witness = StubWitness::answering(FinalityCheck::Conflict(rival.state()));
1117        service.attach_final_state_witness(witness.clone());
1118        assert!(matches!(
1119            service.handle_put(put(&own)).await,
1120            PointerPutResponse::Success { .. }
1121        ));
1122        assert_eq!(witness.asked(), 0, "restoring its own state asks nobody");
1123        assert_eq!(
1124            service.store().state_id(&own.address()),
1125            Some(own.state_id())
1126        );
1127        std::fs::remove_file(service.store().file_for(&own.address())).expect("remove");
1128        assert!(service
1129            .store()
1130            .get(&own.address())
1131            .await
1132            .expect("get")
1133            .is_none());
1134        match service.handle_put(put(&rival)).await {
1135            PointerPutResponse::Stale { state_id, .. } => {
1136                assert_eq!(
1137                    state_id,
1138                    own.state_id(),
1139                    "the rival is told which state won"
1140                );
1141            }
1142            other => panic!("the rival must be stale, got {other:?}"),
1143        }
1144    }
1145
1146    /// A group that answers clear while, meanwhile, a rival final state
1147    /// lands on this node: the race a clear look can lose.
1148    struct RacingWitness {
1149        store: PointerStore,
1150        rival: Pointer,
1151        forgotten: AtomicUsize,
1152    }
1153
1154    impl FinalStateWitness for RacingWitness {
1155        fn check_final<'a>(&'a self, _state: &'a PointerState) -> BoxFuture<'a, FinalityCheck> {
1156            Box::pin(async move {
1157                self.store
1158                    .put_bytes(&self.rival.to_bytes())
1159                    .await
1160                    .expect("the rival lands");
1161                FinalityCheck::Clear
1162            })
1163        }
1164
1165        fn proven_conflict(&self, _state: &PointerState) -> Option<PointerState> {
1166            None
1167        }
1168
1169        fn forget_clear(&self, _state: &PointerState) {
1170            self.forgotten.fetch_add(1, Ordering::SeqCst);
1171        }
1172    }
1173
1174    #[tokio::test]
1175    async fn a_cleared_final_state_whose_write_fails_is_looked_for_again() {
1176        // The look found nothing, but a rival final state landed while it
1177        // looked, so the write it cleared comes back stale. The clear answer
1178        // must not outlive that write: a retry has to look again.
1179        let (landing, _other) = service().await;
1180        let (service, _dir) = service().await;
1181        let witness = Arc::new(RacingWitness {
1182            store: service.store().clone(),
1183            rival: final_state(8, 0x01),
1184            forgotten: AtomicUsize::new(0),
1185        });
1186        service.attach_final_state_witness(witness.clone());
1187        assert!(matches!(
1188            service.handle_put(put(&final_state(8, 0x42))).await,
1189            PointerPutResponse::Stale { .. }
1190        ));
1191        assert_eq!(witness.forgotten.load(Ordering::SeqCst), 1);
1192
1193        // A write that lands keeps its answer.
1194        let witness = StubWitness::answering(FinalityCheck::Clear);
1195        landing.attach_final_state_witness(witness.clone());
1196        assert!(matches!(
1197            landing.handle_put(put(&final_state(9, 0x42))).await,
1198            PointerPutResponse::Success { .. }
1199        ));
1200        assert_eq!(witness.forgotten.load(Ordering::SeqCst), 0);
1201    }
1202
1203    #[tokio::test]
1204    async fn a_busy_check_neither_takes_nor_refuses_a_final_state_for_good() {
1205        let (service, _dir) = service().await;
1206        let current = signed(6, 3, 1);
1207        service.handle_put(put(&current)).await;
1208        let witness = StubWitness::answering(FinalityCheck::Busy);
1209        service.attach_final_state_witness(witness.clone());
1210
1211        let transfer = final_state(6, 0x42);
1212        assert!(matches!(
1213            service.handle_put(put(&transfer)).await,
1214            PointerPutResponse::Error(ProtocolError::Internal(_))
1215        ));
1216        assert_eq!(witness.asked(), 1);
1217        assert_eq!(
1218            service.store().state_id(&transfer.address()),
1219            Some(current.state_id()),
1220            "nothing was written"
1221        );
1222        assert!(
1223            service.store().admits(&transfer.state()),
1224            "and the state can still be taken later"
1225        );
1226    }
1227
1228    #[tokio::test]
1229    async fn a_proven_conflict_is_refused_again_before_any_signature_check() {
1230        // Replaying a paid final state that already lost costs a node
1231        // nothing: the refusal comes from what an earlier check proved, ahead
1232        // of the signature check and without asking the group. A record
1233        // whose signature does not even verify shows the order.
1234        let (unwitnessed, _other) = service().await;
1235        let (service, _dir) = service().await;
1236        let established = final_state(7, 0xAA);
1237        let late = final_state(7, 0x01);
1238        let witness = StubWitness::having_proven(established.state());
1239        service.attach_final_state_witness(witness.clone());
1240
1241        let mut forged = late.to_bytes();
1242        if let Some(last) = forged.last_mut() {
1243            *last ^= 0xFF;
1244        }
1245        match service
1246            .handle_put(PointerPutRequest::new(Bytes::from(forged.clone())))
1247            .await
1248        {
1249            PointerPutResponse::Stale { state_id, .. } => {
1250                assert_eq!(state_id, established.state_id());
1251            }
1252            other => panic!("a proven loser must be refused as stale, got {other:?}"),
1253        }
1254        assert_eq!(witness.asked(), 0, "and nobody is asked again");
1255        assert!(
1256            matches!(
1257                unwitnessed
1258                    .handle_put(PointerPutRequest::new(Bytes::from(forged.clone())))
1259                    .await,
1260                PointerPutResponse::Error(_)
1261            ),
1262            "the record really does fail its signature check"
1263        );
1264
1265        // The proven state itself is not refused by its own proof.
1266        assert!(matches!(
1267            service.handle_put(put(&established)).await,
1268            PointerPutResponse::Success { .. }
1269        ));
1270    }
1271
1272    #[tokio::test]
1273    async fn two_final_states_raced_to_two_nodes_leave_each_on_its_first() {
1274        // The one fork ADR-0018 allows: the owner signs two final states and
1275        // sends one to each node before either has heard of the other. Each
1276        // keeps what it took first and refuses the other, whichever sorts
1277        // first. Nothing on a node can settle it; a reader decides by how many
1278        // of the group hold each side.
1279        let (first_node, _a) = service().await;
1280        let (second_node, _b) = service().await;
1281        let one = final_state(4, 0x09);
1282        let other = final_state(4, 0x01);
1283
1284        assert!(matches!(
1285            first_node.handle_put(put(&one)).await,
1286            PointerPutResponse::Success { .. }
1287        ));
1288        assert!(matches!(
1289            second_node.handle_put(put(&other)).await,
1290            PointerPutResponse::Success { .. }
1291        ));
1292        assert!(matches!(
1293            first_node.handle_put(put(&other)).await,
1294            PointerPutResponse::Stale { .. }
1295        ));
1296        assert!(matches!(
1297            second_node.handle_put(put(&one)).await,
1298            PointerPutResponse::Stale { .. }
1299        ));
1300        assert_eq!(
1301            first_node.store().state_id(&one.address()),
1302            Some(one.state_id())
1303        );
1304        assert_eq!(
1305            second_node.store().state_id(&other.address()),
1306            Some(other.state_id())
1307        );
1308    }
1309
1310    #[test]
1311    fn a_pointer_is_refused_where_a_chunk_already_sits() {
1312        // The two kinds share one 32-byte address space. A collision is
1313        // infeasible, not impossible, and silently picking one would destroy
1314        // the other's data.
1315        let address = [3u8; 32];
1316        match cross_kind_refusal(address, Ok(true)) {
1317            Some(PointerPutResponse::Error(ProtocolError::StorageFailed(message))) => {
1318                assert!(
1319                    message.contains("already occupied by a chunk"),
1320                    "got: {message}"
1321                );
1322            }
1323            other => panic!("a collision must be refused, got {other:?}"),
1324        }
1325    }
1326
1327    #[test]
1328    fn a_free_address_is_not_refused() {
1329        assert!(cross_kind_refusal([3u8; 32], Ok(false)).is_none());
1330    }
1331
1332    #[test]
1333    fn an_unreadable_chunk_store_refuses_rather_than_assumes() {
1334        // "I could not check" must not be treated as "nothing is there".
1335        let refusal = cross_kind_refusal([3u8; 32], Err(Error::Storage("disk gone".into())));
1336        match refusal {
1337            Some(PointerPutResponse::Error(ProtocolError::StorageFailed(message))) => {
1338                assert!(message.contains("cannot check"), "got: {message}");
1339            }
1340            other => panic!("expected a refusal, got {other:?}"),
1341        }
1342    }
1343}