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//!
20//! # Order of work
21//!
22//! ```text
23//! parse → compare with what is held → verify signature → check payment → commit
24//! ```
25//!
26//! The comparison precedes the signature check, so re-submitting a state the
27//! node already holds costs a parse and a map lookup rather than an ML-DSA
28//! verification. The payment check sits between validation and commit, and the
29//! commit re-checks, because a newer state can land while payment is verified.
30
31use std::sync::Arc;
32
33use ant_protocol::chunk::{
34    PointerGetRequest, PointerGetResponse, PointerPutRequest, PointerPutResponse, ProtocolError,
35    XorName,
36};
37use bytes::Bytes;
38use parking_lot::RwLock;
39use saorsa_core::P2PNode;
40use tokio::sync::mpsc;
41
42use crate::error::{Error, Result};
43use crate::logging::{debug, info, warn};
44use crate::payment::PaymentVerifier;
45use crate::pointer::store::{Inspected, PointerStore, PutOutcome};
46use crate::replication::admission;
47use crate::replication::pointer::PointerFreshWrite;
48use crate::storage::{ChunkStore, SELF_CLOSENESS_GATE_WIDTH};
49use ant_protocol::pointer::POINTER_WIRE_LEN;
50
51/// Handles pointer requests against a [`PointerStore`].
52#[derive(Clone)]
53pub struct PointerService {
54    /// Where pointers are kept.
55    store: PointerStore,
56    /// Consulted so an address held as a chunk is never overwritten by a
57    /// pointer.
58    chunks: Option<Arc<ChunkStore>>,
59    /// Confirms a state was paid for. `None` in tests that exercise the merge
60    /// rather than the payment.
61    payments: Option<Arc<PaymentVerifier>>,
62    /// Where a newly stored paid state goes to be offered to the rest of its
63    /// close group (ADR-0016 replication). Attached once the replication
64    /// engine exists, which is after this service is built; empty where
65    /// nothing replicates, as in unit tests and the devnet.
66    fresh_writes: Arc<RwLock<Option<mpsc::UnboundedSender<PointerFreshWrite>>>>,
67    /// The node's P2P handle, for the self-closeness gate.
68    ///
69    /// Attached after construction, because the node builds its protocol
70    /// handler before it has a running P2P node. `None` in unit tests that
71    /// never attach one, exactly as the chunk path does.
72    p2p_node: Arc<RwLock<Option<Arc<P2PNode>>>>,
73}
74
75impl std::fmt::Debug for PointerService {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("PointerService")
78            .field("records", &self.store.len())
79            .field("checks_chunk_collisions", &self.chunks.is_some())
80            .field("verifies_payment", &self.payments.is_some())
81            .finish_non_exhaustive()
82    }
83}
84
85impl PointerService {
86    /// Build a service over `store`.
87    #[must_use]
88    pub fn new(store: PointerStore) -> Self {
89        Self {
90            store,
91            chunks: None,
92            payments: None,
93            fresh_writes: Arc::new(RwLock::new(None)),
94            p2p_node: Arc::new(RwLock::new(None)),
95        }
96    }
97
98    /// Apply the self-closeness gate, so a pointer PUT is admitted only where
99    /// the node is actually responsible.
100    ///
101    /// Without it one valid proof can be replayed to every node on the network,
102    /// each of which would store the record and trigger replication for an
103    /// address it has no business holding.
104    pub fn attach_p2p_node(&self, p2p_node: Arc<P2PNode>) {
105        *self.p2p_node.write() = Some(p2p_node);
106    }
107
108    /// Consult `chunks` before storing, so a cross-kind address collision is
109    /// refused rather than resolved by whichever kind arrived last.
110    #[must_use]
111    pub fn with_chunk_store(mut self, chunks: Arc<ChunkStore>) -> Self {
112        self.chunks = Some(chunks);
113        self
114    }
115
116    /// Require payment, verified against each record's `state_id`.
117    #[must_use]
118    pub fn with_payments(mut self, payments: Arc<PaymentVerifier>) -> Self {
119        self.payments = Some(payments);
120        self
121    }
122
123    /// Hand every newly stored paid state to replication on `writes`.
124    pub fn attach_fresh_writes(&self, writes: mpsc::UnboundedSender<PointerFreshWrite>) {
125        *self.fresh_writes.write() = Some(writes);
126    }
127
128    /// The store this service fronts.
129    #[must_use]
130    pub const fn store(&self) -> &PointerStore {
131        &self.store
132    }
133
134    /// Handle a pointer PUT.
135    ///
136    /// Never returns `Err`: a rejection is a response the peer should see, so
137    /// every failure is mapped onto [`PointerPutResponse`].
138    pub async fn handle_put(&self, request: PointerPutRequest) -> PointerPutResponse {
139        // Cheap first: parse and compare against what is held. No signature is
140        // checked yet, so a forged record for an address this node does not
141        // serve is rejected by the gates below without buying an ML-DSA
142        // verification.
143        let parsed = match self.store.inspect(&request.record).await {
144            Ok(Inspected::Unchanged(state)) => {
145                return PointerPutResponse::Unchanged {
146                    address: state.address,
147                    state_id: state.state_id,
148                };
149            }
150            Ok(Inspected::Stale(state)) => {
151                // The state named is the one this node keeps, not the one that
152                // arrived: it is what the sender needs in order to catch up.
153                return PointerPutResponse::Stale {
154                    address: state.address,
155                    state_id: self.store.state_id(&state.address).unwrap_or_default(),
156                };
157            }
158            Ok(Inspected::Candidate(parsed)) => parsed,
159            Err(e) => {
160                debug!("Pointer PUT refused: {e}");
161                return PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
162            }
163        };
164
165        let address = parsed.state().address;
166        let state_id = parsed.state().state_id;
167
168        if let Some(refusal) = self.admit(parsed.state()).await {
169            return refusal;
170        }
171
172        // Only now is the record worth a signature check.
173        let record = match self.store.verify(parsed).await {
174            Ok(record) => record,
175            Err(e) => {
176                debug!("Pointer PUT refused: {e}");
177                return PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
178            }
179        };
180
181        // Payment is checked against the state, not the address: the address
182        // never changes, so paying against it would buy every future update.
183        if let Some(payments) = &self.payments {
184            if let Err(e) =
185                Self::verify_payment(payments, address, state_id, request.payment_proof.as_ref())
186                    .await
187            {
188                return PointerPutResponse::PaymentRequired {
189                    message: e.to_string(),
190                };
191            }
192        }
193
194        // Charge the bytes this write will take, and hold the charge until it
195        // lands. Checking capacity and then writing is the race the file store
196        // exists to close: concurrent writers all pass one cached measurement
197        // before any of them has written a byte, and cross the reserve
198        // together. A record is a fixed `POINTER_WIRE_LEN`, so that is the
199        // whole charge.
200        let reservation = match &self.chunks {
201            Some(chunks) => match chunks.reserve(POINTER_WIRE_LEN as u64) {
202                Ok(reservation) => Some(reservation),
203                Err(e) => {
204                    debug!("Rejecting pointer PUT for {}: {e}", hex::encode(address));
205                    return PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()));
206                }
207            },
208            None => None,
209        };
210        // The charge travels with the write. Settling it here instead would
211        // release it the moment this future is dropped, while the blocking
212        // transaction it started runs on and publishes the file.
213        let record_bytes = request.record.to_vec();
214        match self.store.commit(record, reservation).await {
215            Ok(PutOutcome::Changed) => {
216                // Offer it to the rest of the close group, proof included, so
217                // every member holds it whichever of them the client reached.
218                let writes = self.fresh_writes.read().clone();
219                if let (Some(writes), Some(proof)) = (writes, request.payment_proof) {
220                    if writes
221                        .send(PointerFreshWrite {
222                            record: record_bytes,
223                            payment_proof: proof,
224                        })
225                        .is_err()
226                    {
227                        debug!(
228                            "Replication is not running; pointer {} is not offered on",
229                            hex::encode(address)
230                        );
231                    }
232                }
233                PointerPutResponse::Success { address, state_id }
234            }
235            // The re-check under the commit lock found a newer state. The
236            // client paid for a state that lost a race; say so plainly.
237            Ok(PutOutcome::Unchanged) => PointerPutResponse::Unchanged { address, state_id },
238            Ok(PutOutcome::Stale) => PointerPutResponse::Stale {
239                address,
240                state_id: self.store.state_id(&address).unwrap_or(state_id),
241            },
242            Err(e) => {
243                warn!("Pointer commit failed for {}: {e}", hex::encode(address));
244                PointerPutResponse::Error(ProtocolError::StorageFailed(e.to_string()))
245            }
246        }
247    }
248
249    /// Everything that must hold before a record is worth verifying.
250    ///
251    /// `Some(response)` means refuse. Ordered cheapest first, and all of it
252    /// ahead of the signature check, so a forged record for an address this
253    /// node does not serve buys no cryptography.
254    async fn admit(
255        &self,
256        state: &ant_protocol::pointer::PointerState,
257    ) -> Option<PointerPutResponse> {
258        let address = state.address;
259
260        // Any state the merge rule prefers to what this node knows, whatever
261        // its counter: a node that missed updates, or joined the group after
262        // them, must take the next one or it never catches up. An arrival that
263        // loses to what is held was already answered as stale; this also
264        // covers a record the node lost, which that comparison cannot see, so
265        // a replay cannot roll it back.
266        if !self.store.admits(state) {
267            info!(
268                "Rejecting pointer PUT for {}: counter {} does not beat the state this node knows",
269                hex::encode(address),
270                state.counter
271            );
272            return Some(PointerPutResponse::Stale {
273                address,
274                state_id: self.store.state_id(&address).unwrap_or_default(),
275            });
276        }
277
278        if let Some(chunks) = &self.chunks {
279            // A chunk already here means the two kinds collided. Refuse rather
280            // than pick: whichever we chose, someone's data would vanish.
281            if let Some(refusal) = cross_kind_refusal(address, chunks.exists(&address)) {
282                return Some(refusal);
283            }
284            // Capacity before payment, as the chunk path does, and for the
285            // size a record actually is rather than for nothing. The binding
286            // charge is taken at the commit; this only avoids paying to find
287            // out the disk is full.
288            if let Err(e) = chunks.check_capacity_for(POINTER_WIRE_LEN as u64) {
289                let addr = hex::encode(address);
290                info!(
291                    target: "ant_node::storage::disk_precheck",
292                    addr = %addr,
293                    kind = "pointer",
294                    "Rejecting pointer PUT before payment verification: {e}"
295                );
296                return Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
297                    e.to_string(),
298                )));
299            }
300        }
301
302        // Self-closeness gate (ADR-0003), judged at the pointer's address
303        // because that is what the network routes on. Bind the handle out of
304        // the lock first: no guard may be held across an await.
305        let attached = self.p2p_node.read().as_ref().map(Arc::clone);
306        if let Some(p2p) = attached {
307            let self_id = *p2p.peer_id();
308            if !admission::is_responsible(&self_id, &address, &p2p, SELF_CLOSENESS_GATE_WIDTH).await
309            {
310                debug!(
311                    "Rejecting pointer PUT for {}: not within local closest peers",
312                    hex::encode(address)
313                );
314                return Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
315                    "node is not within its local closest peers for this address".to_string(),
316                )));
317            }
318        }
319        None
320    }
321
322    /// Handle a pointer GET.
323    pub async fn handle_get(&self, request: PointerGetRequest) -> PointerGetResponse {
324        match self.store.get(&request.address).await {
325            Ok(Some(record)) => PointerGetResponse::Success {
326                record: Bytes::from(record.to_bytes()),
327            },
328            Ok(None) => PointerGetResponse::NotFound {
329                address: request.address,
330            },
331            Err(e) => PointerGetResponse::Error(ProtocolError::StorageFailed(e.to_string())),
332        }
333    }
334
335    /// Confirm the submitted state was paid for.
336    ///
337    /// `routing_address` selects the close group whose quotes count;
338    /// `paid_content` is what the quote must name. They are different values
339    /// here, which is the whole point — the existing chunk path passes one
340    /// address for both jobs.
341    async fn verify_payment(
342        payments: &PaymentVerifier,
343        routing_address: XorName,
344        paid_content: XorName,
345        proof: Option<&Vec<u8>>,
346    ) -> Result<()> {
347        let Some(proof) = proof else {
348            return Err(Error::Payment(format!(
349                "a pointer update must be paid for; no proof supplied for state {}",
350                hex::encode(paid_content)
351            )));
352        };
353        payments
354            .verify_pointer_payment(&routing_address, &paid_content, proof)
355            .await
356    }
357}
358
359/// Decide whether a chunk already at `address` blocks this pointer.
360///
361/// Separated from the handler because the branch cannot be reached in a test
362/// any other way: a pointer address comes out of BLAKE3's derive-key mode and a
363/// chunk address out of a plain hash, so occupying both with real data would
364/// take a collision across the two. The decision is what matters, so the
365/// decision is what is tested.
366///
367/// `Some(response)` means refuse. Refusing is the only safe answer: whichever
368/// kind were chosen, the other's data would be destroyed, and the node cannot
369/// know which one the network expects.
370fn cross_kind_refusal(address: XorName, chunk_present: Result<bool>) -> Option<PointerPutResponse> {
371    match chunk_present {
372        Ok(true) => {
373            warn!(
374                "Refusing pointer at {}: a chunk already occupies that address",
375                hex::encode(address)
376            );
377            Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
378                format!(
379                    "address {} is already occupied by a chunk; refusing to store a \
380                     pointer over it",
381                    hex::encode(address)
382                ),
383            )))
384        }
385        Ok(false) => None,
386        Err(e) => Some(PointerPutResponse::Error(ProtocolError::StorageFailed(
387            format!("cannot check the chunk store for a collision: {e}"),
388        ))),
389    }
390}
391
392#[cfg(test)]
393#[allow(
394    clippy::unwrap_used,
395    clippy::expect_used,
396    clippy::panic,
397    reason = "test assertions"
398)]
399mod tests {
400    use super::*;
401    use crate::payment::{EvmVerifierConfig, PriceFloorConfig};
402    use ant_protocol::pointer::{Pointer, PointerTarget, PointerTargetKind};
403    use saorsa_pqc::api::sig::{ml_dsa_65, MlDsaPublicKey, MlDsaSecretKey};
404
405    fn keypair(seed: u8) -> (MlDsaPublicKey, MlDsaSecretKey) {
406        ml_dsa_65().generate_keypair_from_seed(&[seed; 32])
407    }
408
409    fn signed(seed: u8, counter: u64, target_byte: u8) -> Pointer {
410        let (pk, sk) = keypair(seed);
411        let target = PointerTarget::new(PointerTargetKind::Chunk, [target_byte; 32]);
412        Pointer::sign(&sk, &pk, counter, target).expect("sign")
413    }
414
415    async fn service() -> (PointerService, tempfile::TempDir) {
416        let dir = tempfile::tempdir().expect("tempdir");
417        let store = PointerStore::new(dir.path()).await.expect("store");
418        (PointerService::new(store), dir)
419    }
420
421    /// A service whose chunk store guards a disk that cannot take another byte.
422    async fn service_with_full_disk() -> (PointerService, tempfile::TempDir) {
423        let dir = tempfile::tempdir().expect("tempdir");
424        let store = PointerStore::new(dir.path()).await.expect("store");
425        let chunks = ChunkStore::new(crate::storage::ChunkStoreConfig {
426            root_dir: dir.path().to_path_buf(),
427            verify_on_read: false,
428            max_map_size: 0,
429            // Larger than any disk, so every capacity question answers "full".
430            disk_reserve: u64::MAX,
431            migration: crate::storage::MigrationConfig::default(),
432        })
433        .await
434        .expect("chunk store");
435        (
436            PointerService::new(store).with_chunk_store(Arc::new(chunks)),
437            dir,
438        )
439    }
440
441    #[tokio::test]
442    async fn a_full_disk_refuses_a_pointer_before_it_is_written() {
443        // A disk with no room refuses at the admission check, before payment,
444        // so a client is not charged to find out. This does not reach the
445        // reservation — the store-level tests cover that — it covers the early
446        // refusal and that nothing is stored when it fires.
447        let (service, _dir) = service_with_full_disk().await;
448        let record = signed(1, 0, 1);
449
450        match service.handle_put(put(&record)).await {
451            PointerPutResponse::Error(ProtocolError::StorageFailed(message)) => {
452                assert!(
453                    message.contains("disk space") || message.contains("reserve"),
454                    "a full disk should say so, got: {message}"
455                );
456            }
457            other => panic!("a full disk must refuse the write, got {other:?}"),
458        }
459
460        assert!(
461            matches!(
462                service
463                    .handle_get(PointerGetRequest::new(record.address()))
464                    .await,
465                PointerGetResponse::NotFound { .. }
466            ),
467            "nothing may be stored when the disk had no room for it"
468        );
469    }
470
471    #[tokio::test]
472    async fn concurrent_creations_are_each_charged_against_the_disk() {
473        // Every one of these would pass a bare capacity *check* against one
474        // cached measurement. What stops them collectively crossing the
475        // reserve is that each holds a charge until its write lands.
476        let (service, dir) = service().await;
477        let chunks = ChunkStore::new(crate::storage::ChunkStoreConfig {
478            root_dir: dir.path().to_path_buf(),
479            verify_on_read: false,
480            max_map_size: 0,
481            disk_reserve: 0,
482            migration: crate::storage::MigrationConfig::default(),
483        })
484        .await
485        .expect("chunk store");
486        let service = service.with_chunk_store(Arc::new(chunks));
487
488        let chunks = service.chunks.clone().expect("chunk store");
489        let (written_before, in_flight_before) = chunks.capacity_counters();
490
491        let mut writes = Vec::new();
492        for seed in 1..=8u8 {
493            let record = signed(seed, 0, 1);
494            let service = service.clone();
495            writes.push(tokio::spawn(async move {
496                (record.address(), service.handle_put(put(&record)).await)
497            }));
498        }
499
500        for write in writes {
501            let (address, response) = write.await.expect("join");
502            assert!(
503                matches!(response, PointerPutResponse::Success { .. }),
504                "a disk with room must take the write, got {response:?}"
505            );
506            assert!(matches!(
507                service.handle_get(PointerGetRequest::new(address)).await,
508                PointerGetResponse::Success { .. }
509            ));
510        }
511        assert_eq!(service.store().len(), 8);
512
513        // Each of the eight was charged, and none of the charges was left
514        // hanging. Without the counters this would pass just as well against a
515        // bare capacity check that charges nothing.
516        // Exactly eight allocation charges. An inequality against the raw
517        // record size would accept four: a record rounds up to the allocation
518        // unit, and four of those already exceed eight record sizes.
519        let one = ChunkStore::capacity_charge_for(POINTER_WIRE_LEN as u64);
520        assert_eq!(
521            chunks.capacity_counters(),
522            (written_before + 8 * one, in_flight_before),
523            "eight writes, eight charges, none left in flight"
524        );
525    }
526
527    fn put(record: &Pointer) -> PointerPutRequest {
528        PointerPutRequest::new(Bytes::from(record.to_bytes()))
529    }
530
531    #[tokio::test]
532    async fn a_put_then_a_get_round_trips_the_record() {
533        let (service, _dir) = service().await;
534        let record = signed(1, 0, 1);
535
536        match service.handle_put(put(&record)).await {
537            PointerPutResponse::Success { address, state_id } => {
538                assert_eq!(address, record.address());
539                assert_eq!(state_id, record.state_id());
540            }
541            other => panic!("expected Success, got {other:?}"),
542        }
543
544        match service
545            .handle_get(PointerGetRequest::new(record.address()))
546            .await
547        {
548            PointerGetResponse::Success { record: bytes } => {
549                assert_eq!(bytes.as_ref(), record.to_bytes());
550            }
551            other => panic!("expected Success, got {other:?}"),
552        }
553    }
554
555    #[tokio::test]
556    async fn an_update_replaces_and_a_stale_one_is_told_so() {
557        let (service, _dir) = service().await;
558        let first = signed(1, 0, 1);
559        let second = signed(1, 1, 1);
560        service.handle_put(put(&first)).await;
561
562        assert!(matches!(
563            service.handle_put(put(&second)).await,
564            PointerPutResponse::Success { .. }
565        ));
566
567        match service.handle_put(put(&first)).await {
568            PointerPutResponse::Stale { address, state_id } => {
569                assert_eq!(address, first.address());
570                assert_eq!(state_id, second.state_id(), "the newer state is reported");
571            }
572            other => panic!("expected Stale, got {other:?}"),
573        }
574    }
575
576    #[tokio::test]
577    async fn two_nodes_given_the_same_states_in_opposite_orders_agree() {
578        // The convergence property, driven through the request handler rather
579        // than the store. The gate in front of the merge rule is part of the
580        // production path, and a gate that admits records by arrival order
581        // would leave these two nodes holding different records for ever --
582        // which is the fork the merge rule exists to prevent.
583        let (first_node, _a) = service().await;
584        let (second_node, _b) = service().await;
585
586        // Two separately paid states at one counter. The merge rule says the
587        // smaller target wins, whichever arrives first.
588        let loser = signed(1, 0, 9);
589        let winner = signed(1, 0, 1);
590        assert!(winner.replaces(&loser));
591
592        for record in [&loser, &winner] {
593            first_node.handle_put(put(record)).await;
594        }
595        for record in [&winner, &loser] {
596            second_node.handle_put(put(record)).await;
597        }
598
599        for (name, node) in [("first", &first_node), ("second", &second_node)] {
600            match node
601                .handle_get(PointerGetRequest::new(winner.address()))
602                .await
603            {
604                PointerGetResponse::Success { record: bytes } => assert_eq!(
605                    Pointer::from_bytes(&bytes).expect("parse").state_id(),
606                    winner.state_id(),
607                    "the {name} node kept the wrong record"
608                ),
609                other => panic!("expected the winner, got {other:?}"),
610            }
611        }
612
613        // And the node that already had the winner refused to go back.
614        assert!(matches!(
615            second_node.handle_put(put(&loser)).await,
616            PointerPutResponse::Stale { .. }
617        ));
618    }
619
620    #[tokio::test]
621    async fn a_fork_between_two_nodes_is_healed_by_any_later_counter() {
622        // Two paid states at one counter, each reaching a different node: a
623        // fork no read can settle for them. The next update, at any later
624        // counter, lands on both and leaves them holding the same record.
625        let (first_node, _a) = service().await;
626        let (second_node, _b) = service().await;
627        let one_side = signed(1, 1, 9);
628        let other_side = signed(1, 1, 1);
629        assert!(matches!(
630            first_node.handle_put(put(&one_side)).await,
631            PointerPutResponse::Success { .. }
632        ));
633        assert!(matches!(
634            second_node.handle_put(put(&other_side)).await,
635            PointerPutResponse::Success { .. }
636        ));
637
638        let healed = signed(1, 5, 4);
639        for (name, node) in [("first", &first_node), ("second", &second_node)] {
640            match node.handle_put(put(&healed)).await {
641                PointerPutResponse::Success { address, state_id } => {
642                    assert_eq!(address, healed.address());
643                    assert_eq!(state_id, healed.state_id());
644                }
645                other => panic!("the {name} node refused the healing update: {other:?}"),
646            }
647            let held = node
648                .store()
649                .get(&healed.address())
650                .await
651                .expect("get")
652                .expect("present");
653            assert_eq!(held.state_id(), healed.state_id(), "the {name} node");
654        }
655    }
656
657    #[tokio::test]
658    async fn re_submitting_a_held_state_is_unchanged_not_success() {
659        // A client that retries must be able to tell "your update landed" from
660        // "you paid for something already stored".
661        let (service, _dir) = service().await;
662        let record = signed(1, 0, 4);
663        service.handle_put(put(&record)).await;
664
665        let variant = signed(1, 0, 4);
666        assert_ne!(variant.to_bytes(), record.to_bytes());
667        match service.handle_put(put(&variant)).await {
668            PointerPutResponse::Unchanged { address, state_id } => {
669                assert_eq!(address, record.address());
670                assert_eq!(state_id, record.state_id());
671            }
672            other => panic!("expected Unchanged, got {other:?}"),
673        }
674    }
675
676    #[tokio::test]
677    async fn an_absent_pointer_is_not_found() {
678        let (service, _dir) = service().await;
679        match service.handle_get(PointerGetRequest::new([7u8; 32])).await {
680            PointerGetResponse::NotFound { address } => assert_eq!(address, [7u8; 32]),
681            other => panic!("expected NotFound, got {other:?}"),
682        }
683    }
684
685    #[tokio::test]
686    async fn junk_is_refused_rather_than_stored() {
687        let (service, _dir) = service().await;
688        assert!(matches!(
689            service
690                .handle_put(PointerPutRequest::new(Bytes::from_static(b"not a pointer")))
691                .await,
692            PointerPutResponse::Error(_)
693        ));
694        assert!(service.store().is_empty());
695    }
696
697    #[tokio::test]
698    async fn a_forged_signature_is_refused() {
699        let (service, _dir) = service().await;
700        let record = signed(1, 0, 1);
701        let mut bytes = record.to_bytes();
702        if let Some(byte) = bytes.get_mut(ant_protocol::pointer::POINTER_BODY_LEN + 3) {
703            *byte ^= 0xff;
704        }
705        assert!(matches!(
706            service
707                .handle_put(PointerPutRequest::new(Bytes::from(bytes)))
708                .await,
709            PointerPutResponse::Error(_)
710        ));
711        assert!(service.store().is_empty());
712    }
713
714    #[tokio::test]
715    async fn payment_is_required_when_a_verifier_is_attached() {
716        use crate::payment::{PaymentVerifier, PaymentVerifierConfig};
717
718        let dir = tempfile::tempdir().expect("tempdir");
719        let store = PointerStore::new(dir.path()).await.expect("store");
720        let verifier = Arc::new(PaymentVerifier::new(PaymentVerifierConfig {
721            evm: EvmVerifierConfig::default(),
722            cache_capacity: 16,
723            close_group_size: ant_protocol::chunk::CLOSE_GROUP_SIZE,
724            local_rewards_address: evmlib::common::Address::new([1u8; 20]),
725            price_floor: PriceFloorConfig::default(),
726        }));
727        let service = PointerService::new(store).with_payments(verifier);
728
729        // No proof at all: refused as PaymentRequired, not stored.
730        match service.handle_put(put(&signed(1, 0, 1))).await {
731            PointerPutResponse::PaymentRequired { message } => {
732                assert!(message.contains("must be paid for"), "got: {message}");
733            }
734            other => panic!("expected PaymentRequired, got {other:?}"),
735        }
736        assert!(
737            service.store().is_empty(),
738            "an unpaid update must not be stored"
739        );
740    }
741
742    #[tokio::test]
743    async fn any_counter_that_beats_what_is_held_is_taken() {
744        let (service, _dir) = service().await;
745
746        // A node that joined after the pointer was created holds nothing, so
747        // the first record it sees need not be counter 0.
748        let first_seen = signed(1, 5, 1);
749        assert!(matches!(
750            service.handle_put(put(&first_seen)).await,
751            PointerPutResponse::Success { .. }
752        ));
753
754        // Anything older is stale, whatever else it says.
755        for older in [0u64, 4] {
756            assert!(
757                matches!(
758                    service.handle_put(put(&signed(1, older, 2))).await,
759                    PointerPutResponse::Stale { .. }
760                ),
761                "counter {older} must not replace counter 5"
762            );
763        }
764
765        // Anything newer lands, however far it skips.
766        for newer in [6u64, 99, u64::MAX] {
767            let record = signed(1, newer, 2);
768            match service.handle_put(put(&record)).await {
769                PointerPutResponse::Success { state_id, .. } => {
770                    assert_eq!(state_id, record.state_id());
771                }
772                other => panic!("counter {newer} was refused: {other:?}"),
773            }
774        }
775        let held = service
776            .store()
777            .get(&first_seen.address())
778            .await
779            .expect("get")
780            .expect("present");
781        assert_eq!(held.counter(), u64::MAX);
782    }
783
784    #[test]
785    fn a_pointer_is_refused_where_a_chunk_already_sits() {
786        // The two kinds share one 32-byte address space. A collision is
787        // infeasible, not impossible, and silently picking one would destroy
788        // the other's data.
789        let address = [3u8; 32];
790        match cross_kind_refusal(address, Ok(true)) {
791            Some(PointerPutResponse::Error(ProtocolError::StorageFailed(message))) => {
792                assert!(
793                    message.contains("already occupied by a chunk"),
794                    "got: {message}"
795                );
796            }
797            other => panic!("a collision must be refused, got {other:?}"),
798        }
799    }
800
801    #[test]
802    fn a_free_address_is_not_refused() {
803        assert!(cross_kind_refusal([3u8; 32], Ok(false)).is_none());
804    }
805
806    #[test]
807    fn an_unreadable_chunk_store_refuses_rather_than_assumes() {
808        // "I could not check" must not be treated as "nothing is there".
809        let refusal = cross_kind_refusal([3u8; 32], Err(Error::Storage("disk gone".into())));
810        match refusal {
811            Some(PointerPutResponse::Error(ProtocolError::StorageFailed(message))) => {
812                assert!(message.contains("cannot check"), "got: {message}");
813            }
814            other => panic!("expected a refusal, got {other:?}"),
815        }
816    }
817}