Skip to main content

urma_node/
service.rs

1//! Small authenticated loopback control surface. The archive engine remains
2//! usable directly; HTTP is not a prerequisite for embedded applications.
3use crate::{
4    Error,
5    engine::Engine,
6    model::{CacheReceipt, ServiceStatus},
7    peer::SyncPeers,
8    peer_discovery::Discovery,
9    peer_sync::Scheduler,
10    recorded::{RecordedError, read, record},
11    retrieval::RecordSource,
12    source::{CommitSource, CommitSources},
13};
14
15mod overlay;
16use rand::RngCore;
17use serde_json::json;
18use std::{
19    fs::OpenOptions,
20    io::{Read, Write},
21    net::{SocketAddr, TcpListener, TcpStream},
22    path::{Path, PathBuf},
23    sync::{
24        Arc, Mutex,
25        atomic::{AtomicBool, Ordering},
26    },
27    time::Duration,
28};
29
30#[derive(Default, Clone)]
31struct CacheStatus {
32    receipt: Option<CacheReceipt>,
33    error: Option<RecordedError>,
34}
35
36type ErrorSlot = Arc<Mutex<Option<RecordedError>>>;
37
38/// Cooperative stop request shared with the owner of a running service.
39/// Requesting shutdown does not wait for completion or interrupt entered I/O
40/// or SQL. The owner must wait for `Service::run` to return before reopening
41/// its archive. Embedded services do not install process signal handlers.
42#[derive(Clone)]
43pub struct ShutdownHandle {
44    stop: Arc<AtomicBool>,
45}
46
47impl ShutdownHandle {
48    pub fn request(&self) {
49        self.stop.store(true, Ordering::Release);
50    }
51}
52
53pub struct Service {
54    listener: TcpListener,
55    token: String,
56    engine: Arc<Engine>,
57    stop: Arc<AtomicBool>,
58    sync_error: ErrorSlot,
59    names_error: ErrorSlot,
60    retention_error: ErrorSlot,
61    cache_status: Arc<Mutex<CacheStatus>>,
62    cache_bytes: u64,
63    retention: Option<(PathBuf, urma_runtime::multipart::RecoveryLimits)>,
64    sources: Vec<Arc<dyn RecordSource + Send + Sync>>,
65    record_peers: Option<SyncPeers>,
66    commit_sources: Option<CommitSources>,
67    dependency_error: ErrorSlot,
68    peer_sync: Option<Scheduler>,
69    inventory_error: ErrorSlot,
70    discovery: Option<Discovery>,
71    discovery_error: ErrorSlot,
72}
73
74impl Service {
75    const CAPABILITIES: [&str; 9] = [
76        "status",
77        "header-sync",
78        "full-block-scan",
79        "record-read",
80        "object-status",
81        "object-pin",
82        "cache-prune",
83        "wire-index",
84        "names-index",
85    ];
86
87    pub fn bind(address: SocketAddr, token: String, engine: Arc<Engine>) -> Result<Self, Error> {
88        if !address.ip().is_loopback()
89            || token.len() != 64
90            || !token.bytes().all(|c| c.is_ascii_hexdigit())
91        {
92            return Err(Error::Invalid(
93                "service requires loopback and a 32-byte hexadecimal bearer token".into(),
94            ));
95        }
96        let listener = TcpListener::bind(address)?;
97        listener.set_nonblocking(true)?;
98        Ok(Self {
99            listener,
100            token,
101            engine,
102            stop: Arc::new(AtomicBool::new(false)),
103            sync_error: Arc::new(Mutex::new(None)),
104            names_error: Arc::new(Mutex::new(None)),
105            retention_error: Arc::new(Mutex::new(None)),
106            cache_status: Arc::new(Mutex::new(CacheStatus::default())),
107            cache_bytes: crate::cache::DEFAULT_CACHE_BYTES,
108            retention: None,
109            sources: Vec::new(),
110            record_peers: None,
111            commit_sources: None,
112            dependency_error: Arc::new(Mutex::new(None)),
113            peer_sync: None,
114            inventory_error: Arc::new(Mutex::new(None)),
115            discovery: None,
116            discovery_error: Arc::new(Mutex::new(None)),
117        })
118    }
119
120    pub fn address(&self) -> Result<SocketAddr, Error> {
121        Ok(self.listener.local_addr()?)
122    }
123
124    pub fn shutdown_handle(&self) -> ShutdownHandle {
125        ShutdownHandle {
126            stop: Arc::clone(&self.stop),
127        }
128    }
129
130    /// Explicit optional candidates for background object recovery. Merely
131    /// configuring handles does not dial, fetch, change headers or scan coverage.
132    pub fn with_record_sources(
133        mut self,
134        sources: Vec<Arc<dyn RecordSource + Send + Sync>>,
135    ) -> Result<Self, Error> {
136        if sources.len() > 1024 {
137            return Err(Error::Invalid("too many configured record sources".into()));
138        }
139        self.sources = sources;
140        Ok(self)
141    }
142
143    pub fn with_commit_sources(mut self, sources: CommitSources) -> Result<Self, Error> {
144        if sources.is_empty() {
145            return Err(Error::Invalid("commit source set is empty".into()));
146        }
147        let expected = self.engine.status()?.chain_genesis;
148        let mut chains = sources.source_chains();
149        chains.push(sources.chain());
150        for chain in chains {
151            let genesis = chain
152                .genesis()
153                .map_err(|error| Error::Invalid(error.to_string()))?
154                .0;
155            if genesis != expected {
156                return Err(Error::Invalid(
157                    "commit source belongs to another chain".into(),
158                ));
159            }
160        }
161        self.commit_sources = Some(sources);
162        Ok(self)
163    }
164
165    /// Operational soft target, not persisted archive identity or a disk quota.
166    /// Only run(true) schedules enforcement; run(false) remains worker-free.
167    /// Zero requests eventual drainage of unprotected cache over bounded steps.
168    pub fn with_cache_limit(mut self, bytes: u64) -> Result<Self, Error> {
169        if bytes > i64::MAX as u64 {
170            return Err(Error::Invalid("cache limit exceeds storage range".into()));
171        }
172        self.cache_bytes = bytes;
173        Ok(self)
174    }
175
176    /// Configure bounded background object acquisition. The caller supplies an
177    /// owned scratch directory and explicit limits. Only run(true) schedules it;
178    /// pruned archives perform no automatic content acquisition.
179    pub fn with_retention(
180        mut self,
181        scratch: PathBuf,
182        limits: urma_runtime::multipart::RecoveryLimits,
183    ) -> Result<Self, Error> {
184        if limits.max_payload_bytes == 0 || limits.max_nodes == 0 || limits.timeout.is_zero() {
185            return Err(Error::Invalid(
186                "object retention limits must be nonzero".into(),
187            ));
188        }
189        self.retention = Some((scratch, limits));
190        Ok(self)
191    }
192
193    /// Run foreground. Network acquisition is opt-in; status works offline.
194    pub fn run(self, synchronize: bool) -> Result<(), Error> {
195        std::thread::scope(|scope| {
196            if synchronize {
197                scope.spawn(|| {
198                    while !self.stop.load(Ordering::Acquire) {
199                        self.worker_round();
200                        for _ in 0..20 {
201                            if self.stop.load(Ordering::Acquire) {
202                                break;
203                            }
204                            std::thread::sleep(Duration::from_millis(100));
205                        }
206                    }
207                });
208            }
209            let outcome = self.accept_loop();
210            self.stop.store(true, Ordering::Release);
211            outcome
212        })
213    }
214
215    fn worker_round(&self) {
216        let headers = self.engine.synchronize_headers_until(&self.stop);
217        // Discovery keeps connections and the book fresh before inventory
218        // sync uses them; it is independent of this round's header result.
219        self.discover_peers();
220        // Peer inventory is fast data: it runs before the full-block scan and
221        // independently of this round's header result, with its own status.
222        self.sync_next_inventory();
223        let result = headers
224            .and_then(|_| self.engine.scan_next_until(&self.stop))
225            .and_then(|status| {
226                if !self.stop.load(Ordering::Acquire) {
227                    self.engine.resolve_cached_dependency()?;
228                }
229                Ok(status)
230            });
231        record(&self.sync_error, &result);
232        self.acquire_next_dependency();
233        // Registered projections can use already scanned data
234        // even if this round's acquisition failed. They never
235        // create registrations or acquire missing history.
236        if !self.stop.load(Ordering::Acquire) {
237            let result = self.engine.maintain_next_names(&self.stop);
238            record(&self.names_error, &result);
239        }
240        // Full-block audit always gets its opportunity before
241        // one object attempt. A sync failure does not suppress
242        // independent recovery from the last selected view;
243        // its error remains separately visible in status.
244        if !self.stop.load(Ordering::Acquire) {
245            if let Some((scratch, limits)) = &self.retention {
246                let owned = self.record_sources();
247                let sources: Vec<&dyn RecordSource> = owned
248                    .iter()
249                    .map(|source| -> &dyn RecordSource { source.as_ref() })
250                    .collect();
251                let result = self
252                    .engine
253                    .retain_next_object(&sources, *limits, scratch, &self.stop);
254                record(&self.retention_error, &result);
255            }
256        }
257        // Independent local maintenance also runs after failed
258        // acquisition/projection/retention. It never opens a source.
259        if !self.stop.load(Ordering::Acquire) {
260            let result = self.engine.maintain_cache(self.cache_bytes, &self.stop);
261            if let Ok(mut status) = self.cache_status.lock() {
262                match result {
263                    Ok(receipt) => {
264                        status.receipt = Some(receipt);
265                        status.error = None;
266                    }
267                    Err(cause) => {
268                        status.error = Some(RecordedError::now(cause));
269                    }
270                }
271            }
272        }
273    }
274
275    fn acquire_next_dependency(&self) {
276        let Some(sources) = &self.commit_sources else {
277            return;
278        };
279        if self.stop.load(Ordering::Acquire) {
280            return;
281        }
282        let result = self.engine.resolve_next_dependency(sources, &self.stop);
283        if self.stop.load(Ordering::Acquire) {
284            return;
285        }
286        record(&self.dependency_error, &result);
287    }
288
289    fn status(&self) -> Result<ServiceStatus, Error> {
290        let (last_sync_error, last_sync_error_at) =
291            RecordedError::split(read(&self.sync_error, "sync")?);
292        let (last_retention_error, last_retention_error_at) =
293            RecordedError::split(read(&self.retention_error, "retention")?);
294        let (last_names_error, last_names_error_at) =
295            RecordedError::split(read(&self.names_error, "Names")?);
296        let (last_dependency_error, last_dependency_error_at) =
297            RecordedError::split(read(&self.dependency_error, "dependency")?);
298        let (last_inventory_error, last_inventory_error_at) =
299            RecordedError::split(read(&self.inventory_error, "inventory")?);
300        let (last_discovery_error, last_discovery_error_at) =
301            RecordedError::split(read(&self.discovery_error, "discovery")?);
302        let cache = self
303            .cache_status
304            .lock()
305            .map_err(|_| Error::Invalid("cache status poisoned".into()))?
306            .clone();
307        let (last_cache_error, last_cache_error_at) = RecordedError::split(cache.error);
308        let overlay = self.overlay_status()?;
309        let mut commit_sources = Vec::new();
310        for sources in self.commit_sources.iter() {
311            commit_sources.extend(sources.status()?);
312        }
313        Ok(ServiceStatus {
314            archive: self.engine.status()?,
315            last_sync_error,
316            last_sync_error_at,
317            last_retention_error,
318            last_retention_error_at,
319            last_names_error,
320            last_names_error_at,
321            last_dependency_error,
322            last_dependency_error_at,
323            last_inventory_error,
324            last_inventory_error_at,
325            last_discovery_error,
326            last_discovery_error_at,
327            commit_sources,
328            cache_limit_bytes: self.cache_bytes,
329            last_cache_error,
330            last_cache_error_at,
331            last_cache_maintenance: cache.receipt,
332            overlay,
333            chain_peers: self.engine.chain_peers()?,
334            retention_configured: self.retention.is_some(),
335            record_sources_configured: u64::try_from(self.record_source_count())
336                .map_err(|error| Error::Invalid(format!("record source count: {error}")))?,
337            capabilities: Self::CAPABILITIES.map(String::from).to_vec(),
338        })
339    }
340
341    fn accept_loop(&self) -> Result<(), Error> {
342        while !self.stop.load(Ordering::Acquire) {
343            match self.listener.accept() {
344                Ok((mut stream, peer)) => {
345                    if !peer.ip().is_loopback() {
346                        continue;
347                    }
348                    stream.set_read_timeout(Some(Duration::from_secs(2)))?;
349                    stream.set_write_timeout(Some(Duration::from_secs(2)))?;
350                    // A malformed or disconnected client never stops the service.
351                    let _ = self.request(&mut stream);
352                }
353                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
354                    std::thread::sleep(Duration::from_millis(50))
355                }
356                Err(e) => return Err(e.into()),
357            }
358        }
359        Ok(())
360    }
361
362    fn request(&self, stream: &mut TcpStream) -> Result<(), Error> {
363        let mut raw = Vec::new();
364        let began = std::time::Instant::now();
365        loop {
366            if raw.len() == 8192 || began.elapsed() > Duration::from_secs(3) {
367                return respond(stream, 400, json!({"error":"request header limit"}));
368            }
369            let mut byte = [0];
370            if stream.read(&mut byte)? == 0 {
371                return Ok(());
372            }
373            raw.push(byte[0]);
374            if began.elapsed() > Duration::from_secs(3) {
375                return respond(stream, 400, json!({"error":"request header deadline"}));
376            }
377            if raw.ends_with(b"\r\n\r\n") {
378                break;
379            }
380        }
381        let Ok(request) = std::str::from_utf8(&raw) else {
382            return respond(stream, 400, json!({"error":"invalid header encoding"}));
383        };
384        let mut lines = request.split("\r\n");
385        let first = lines.next().unwrap_or("");
386        let mut authorized = false;
387        let mut authorization_seen = false;
388        for line in lines.filter(|line| !line.is_empty()) {
389            let Some((name, value)) = line.split_once(':') else {
390                return respond(stream, 400, json!({"error":"malformed header"}));
391            };
392            if name.eq_ignore_ascii_case("authorization") {
393                if authorization_seen {
394                    return respond(stream, 400, json!({"error":"duplicate authorization"}));
395                }
396                authorization_seen = true;
397                authorized = value
398                    .trim()
399                    .strip_prefix("Bearer ")
400                    .is_some_and(|value| equal_token(value, &self.token));
401            }
402            if name.eq_ignore_ascii_case("transfer-encoding")
403                || (name.eq_ignore_ascii_case("content-length") && value.trim() != "0")
404            {
405                return respond(
406                    stream,
407                    400,
408                    json!({"error":"this control endpoint accepts no request body"}),
409                );
410            }
411        }
412        if !authorized {
413            return respond(stream, 401, json!({"error":"authentication required"}));
414        }
415        match first {
416            line if (line.starts_with("GET /v1/names/") || line.starts_with("POST /v1/names/"))
417                && line.ends_with(" HTTP/1.1") =>
418            {
419                let (method, path) = line[..line.len() - " HTTP/1.1".len()]
420                    .split_once(' ')
421                    .expect("matched HTTP method");
422                let request = match names_request(method, path) {
423                    Ok(Some(request)) => request,
424                    Ok(None) => {
425                        return respond(stream, 404, json!({"error":"unknown endpoint"}));
426                    }
427                    Err(_) => {
428                        return respond(stream, 400, json!({"error":"invalid Names request"}));
429                    }
430                };
431                // Reads never register or advance a registry. Mutations are
432                // explicit one-shot commands under the Engine archive mutex.
433                let result = match request {
434                    NamesRequest::Status(genesis) => match self.engine.names_status(genesis) {
435                        Ok(Some(status)) => serde_json::to_value(status).map_err(Error::from),
436                        Ok(None) => {
437                            return respond(
438                                stream,
439                                404,
440                                json!({"error":"Names registry is not registered locally"}),
441                            );
442                        }
443                        Err(error) => Err(error),
444                    },
445                    NamesRequest::Resolve(genesis, name) => self
446                        .engine
447                        .names_resolve(genesis, &name)
448                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
449                    NamesRequest::Register(genesis, point) => self
450                        .engine
451                        .register_names(genesis, point)
452                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
453                    NamesRequest::Step(genesis) => self
454                        .engine
455                        .names_step(genesis)
456                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
457                    NamesRequest::View(genesis, limit, cursor) => self
458                        .engine
459                        .names_view(genesis, cursor.as_ref(), limit)
460                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
461                };
462                match result {
463                    Ok(value) => respond(stream, 200, value),
464                    Err(error) => control_error(stream, error),
465                }
466            }
467            line if line.starts_with("GET /v1/wire?") && line.ends_with(" HTTP/1.1") => {
468                let query = &line["GET /v1/wire?".len()..line.len() - " HTTP/1.1".len()];
469                let (limit, cursor) = match wire_query(query) {
470                    Ok(value) => value,
471                    Err(_) => {
472                        return respond(stream, 400, json!({"error":"invalid Wire page query"}));
473                    }
474                };
475                match self.engine.wire_page(cursor.as_ref(), limit) {
476                    Ok(page) => respond(stream, 200, serde_json::to_value(page)?),
477                    Err(error) => control_error(stream, error),
478                }
479            }
480            "POST /v1/cache/prune HTTP/1.1" => match self.engine.prune_cache() {
481                Ok(records_removed) => respond(
482                    stream,
483                    200,
484                    serde_json::to_value(crate::model::PruneReceipt { records_removed })?,
485                ),
486                Err(error) => control_error(stream, error),
487            },
488            line if line.starts_with("POST /v1/objects/") && line.ends_with(" HTTP/1.1") => {
489                let path = &line["POST /v1/objects/".len()..line.len() - " HTTP/1.1".len()];
490                let (id, pin) = match path.rsplit_once('/') {
491                    Some((id, "pin")) => (id, true),
492                    Some((id, "unpin")) => (id, false),
493                    _ => return respond(stream, 404, json!({"error":"unknown endpoint"})),
494                };
495                if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
496                    return respond(stream, 400, json!({"error":"invalid root transaction ID"}));
497                }
498                let root = id
499                    .parse()
500                    .map_err(|e| Error::Invalid(format!("TXID: {e}")))?;
501                // Engine serializes validation and mutation with pruning/reorg.
502                // The acknowledgement describes this operation's commit point;
503                // a lost response must not be treated as proof of no mutation.
504                match self.engine.set_pin(root, pin) {
505                    Ok(()) => respond(
506                        stream,
507                        200,
508                        serde_json::to_value(crate::model::PinReceipt { root, pinned: pin })?,
509                    ),
510                    Err(error) => control_error(stream, error),
511                }
512            }
513            line if line.starts_with("GET /v1/objects/") && line.ends_with(" HTTP/1.1") => {
514                let id = &line["GET /v1/objects/".len()..line.len() - " HTTP/1.1".len()];
515                if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
516                    return respond(stream, 400, json!({"error":"invalid root transaction ID"}));
517                }
518                let root = id
519                    .parse()
520                    .map_err(|e| Error::Invalid(format!("TXID: {e}")))?;
521                match self.engine.object_status(root)? {
522                    Some(status) => respond(stream, 200, serde_json::to_value(status)?),
523                    None => respond(
524                        stream,
525                        404,
526                        json!({"error":"no completed object recorded locally"}),
527                    ),
528                }
529            }
530            line if line.starts_with("GET /v1/records/") && line.ends_with(" HTTP/1.1") => {
531                let id = &line["GET /v1/records/".len()..line.len() - " HTTP/1.1".len()];
532                if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
533                    return respond(stream, 400, json!({"error":"invalid transaction ID"}));
534                }
535                let txid = id
536                    .parse()
537                    .map_err(|e| Error::Invalid(format!("TXID: {e}")))?;
538                match self.engine.record(txid)? {
539                    Some(record) => respond(stream, 200, serde_json::to_value(record)?),
540                    None => respond(
541                        stream,
542                        404,
543                        json!({"error":"record is not locally available in the selected view"}),
544                    ),
545                }
546            }
547            "GET /v1/status HTTP/1.1" => {
548                respond(stream, 200, serde_json::to_value(self.status()?)?)
549            }
550            // Ascending by height; only the newest (highest) 1024 rows are returned.
551            "GET /v1/overlay/omissions HTTP/1.1" => match self.engine.peer_omissions_latest(1024) {
552                Ok(omissions) => respond(stream, 200, serde_json::to_value(omissions)?),
553                Err(error) => control_error(stream, error),
554            },
555            "GET /v1/overlay/book HTTP/1.1" => match self.overlay_book() {
556                Ok(Some(book)) => respond(stream, 200, serde_json::to_value(book)?),
557                Ok(None) => respond(stream, 404, json!({"error":"overlay disabled"})),
558                Err(error) => control_error(stream, error),
559            },
560            "POST /v1/shutdown HTTP/1.1" => {
561                respond(stream, 200, json!({"stopping":true}))?;
562                self.stop.store(true, Ordering::Release);
563                Ok(())
564            }
565            _ => respond(stream, 404, json!({"error":"unknown endpoint"})),
566        }
567    }
568}
569
570enum NamesRequest {
571    Status(bitcoin::Txid),
572    Resolve(bitcoin::Txid, urma_names::name::Name),
573    Register(bitcoin::Txid, crate::model::ChainPoint),
574    Step(bitcoin::Txid),
575    View(bitcoin::Txid, u32, Option<crate::names::NamesCursor>),
576}
577
578fn names_request(method: &str, path: &str) -> Result<Option<NamesRequest>, Error> {
579    let invalid = || Error::Invalid("invalid Names request".into());
580    let path = path.strip_prefix("/v1/names/").ok_or_else(invalid)?;
581    let (id, operation) = path.split_once('/').unwrap_or((path, ""));
582    if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
583        return Err(invalid());
584    }
585    let genesis = id.parse().map_err(|_| invalid())?;
586    let request = match (method, operation) {
587        ("GET", "") => NamesRequest::Status(genesis),
588        ("GET", operation) if operation.starts_with("view?") => {
589            let (limit, cursor) = names_view_query(&operation["view?".len()..])?;
590            if cursor.as_ref().is_some_and(|c| c.genesis != genesis) {
591                return Err(invalid());
592            }
593            NamesRequest::View(genesis, limit, cursor)
594        }
595        ("GET", operation) if operation.starts_with("resolve/") => {
596            // Canonical Names V0 uses only ASCII letters, digits and hyphens;
597            // do not normalize, percent-decode or accept alternate spellings.
598            let name = urma_names::name::Name::parse(&operation["resolve/".len()..])
599                .map_err(|_| invalid())?;
600            NamesRequest::Resolve(genesis, name)
601        }
602        ("POST", "step") => NamesRequest::Step(genesis),
603        ("POST", operation) if operation.starts_with("register?") => {
604            let mut height = None;
605            let mut hash = None;
606            for field in operation["register?".len()..].split('&') {
607                match field.split_once('=') {
608                    Some(("height", value)) if height.is_none() => {
609                        if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
610                            return Err(invalid());
611                        }
612                        let value: u64 = value.parse().map_err(|_| invalid())?;
613                        if value > i64::MAX as u64 {
614                            return Err(invalid());
615                        }
616                        height = Some(value);
617                    }
618                    Some(("hash", value)) if hash.is_none() => {
619                        if value.len() != 64 || !value.bytes().all(|b| b.is_ascii_hexdigit()) {
620                            return Err(invalid());
621                        }
622                        hash = Some(value.parse().map_err(|_| invalid())?);
623                    }
624                    _ => return Err(invalid()),
625                }
626            }
627            NamesRequest::Register(
628                genesis,
629                crate::model::ChainPoint {
630                    height: height.ok_or_else(invalid)?,
631                    hash: hash.ok_or_else(invalid)?,
632                },
633            )
634        }
635        _ => return Ok(None),
636    };
637    Ok(Some(request))
638}
639
640fn names_view_query(query: &str) -> Result<(u32, Option<crate::names::NamesCursor>), Error> {
641    let invalid = || Error::Invalid("invalid Names view query".into());
642    let mut limit = None;
643    let mut cursor = None;
644    for field in query.split('&') {
645        match field.split_once('=') {
646            Some(("limit", value)) if limit.is_none() => {
647                if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
648                    return Err(invalid());
649                }
650                let value: u32 = value.parse().map_err(|_| invalid())?;
651                if !(1..=crate::names::MAX_NAMES_PAGE).contains(&value) {
652                    return Err(invalid());
653                }
654                limit = Some(value);
655            }
656            Some(("cursor", value)) if cursor.is_none() => {
657                if value.len() > 1024 {
658                    return Err(invalid());
659                }
660                let bytes = hex::decode(value).map_err(|_| invalid())?;
661                let decoded: crate::names::NamesCursor = serde_json::from_slice(&bytes)?;
662                if decoded.snapshot.instance.len() != 32
663                    || !decoded
664                        .snapshot
665                        .instance
666                        .bytes()
667                        .all(|b| b.is_ascii_hexdigit())
668                {
669                    return Err(invalid());
670                }
671                cursor = Some(decoded);
672            }
673            _ => return Err(invalid()),
674        }
675    }
676    Ok((limit.ok_or_else(invalid)?, cursor))
677}
678
679fn wire_query(query: &str) -> Result<(u32, Option<crate::projection::WireCursor>), Error> {
680    let invalid = || Error::Invalid("invalid Wire page query".into());
681    let mut limit = None;
682    let mut cursor = None;
683    for field in query.split('&') {
684        match field.split_once('=') {
685            Some(("limit", value)) if limit.is_none() => {
686                if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
687                    return Err(invalid());
688                }
689                let value: u32 = value.parse().map_err(|_| invalid())?;
690                if !(1..=crate::projection::MAX_WIRE_PAGE).contains(&value) {
691                    return Err(invalid());
692                }
693                limit = Some(value);
694            }
695            Some(("cursor", value)) if cursor.is_none() => {
696                if value.len() > 1024 {
697                    return Err(invalid());
698                }
699                let bytes = hex::decode(value).map_err(|_| invalid())?;
700                let decoded: crate::projection::WireCursor = serde_json::from_slice(&bytes)?;
701                if decoded.snapshot.instance.len() != 32
702                    || !decoded
703                        .snapshot
704                        .instance
705                        .bytes()
706                        .all(|b| b.is_ascii_hexdigit())
707                    || decoded.height > i64::MAX as u64
708                {
709                    return Err(invalid());
710                }
711                cursor = Some(decoded);
712            }
713            _ => return Err(invalid()),
714        }
715    }
716    Ok((limit.ok_or_else(invalid)?, cursor))
717}
718
719fn control_error(stream: &mut TcpStream, error: Error) -> Result<(), Error> {
720    match error {
721        Error::Invalid(message) => respond(stream, 422, json!({"error":message})),
722        error @ (Error::Busy(_)
723        | Error::PeerBusy
724        | Error::Transport(_)
725        | Error::DialDenied(_)
726        | Error::Stale) => respond(stream, 409, json!({"error":error.to_string()})),
727        // Do not expose database internals or local filesystem paths over HTTP.
728        _ => respond(
729            stream,
730            500,
731            json!({"error":"local archive operation failed"}),
732        ),
733    }
734}
735
736fn equal_token(left: &str, right: &str) -> bool {
737    if left.len() != right.len() {
738        return false;
739    }
740    left.bytes()
741        .zip(right.bytes())
742        .fold(0u8, |different, (a, b)| different | (a ^ b))
743        == 0
744}
745
746fn respond(stream: &mut TcpStream, code: u16, body: serde_json::Value) -> Result<(), Error> {
747    let body = serde_json::to_vec(&body)?;
748    if body.len() > 32 * 1024 * 1024 {
749        return respond(
750            stream,
751            413,
752            json!({"error":"record exceeds local API response limit"}),
753        );
754    }
755    let reason = match code {
756        200 => "OK",
757        400 => "Bad Request",
758        401 => "Unauthorized",
759        409 => "Conflict",
760        413 => "Content Too Large",
761        422 => "Unprocessable Content",
762        500 => "Internal Server Error",
763        _ => "Not Found",
764    };
765    write!(
766        stream,
767        "HTTP/1.1 {code} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
768        body.len()
769    )?;
770    stream.write_all(&body)?;
771    Ok(())
772}
773
774/// New service token, never a wallet/signing/decryption key. Existing files
775/// are not overwritten. Platform-specific private ACL support is required.
776pub fn create_token(path: &Path) -> Result<(), Error> {
777    #[cfg(not(unix))]
778    return Err(Error::Invalid(
779        "private token ACL creation is not implemented for this platform".into(),
780    ));
781    #[cfg(unix)]
782    {
783        use std::os::unix::fs::OpenOptionsExt;
784        let mut bytes = [0u8; 32];
785        rand::rngs::OsRng.fill_bytes(&mut bytes);
786        let mut file = OpenOptions::new()
787            .write(true)
788            .create_new(true)
789            .mode(0o600)
790            .open(path)?;
791        file.write_all(hex::encode(bytes).as_bytes())?;
792        file.sync_all()?;
793        Ok(())
794    }
795}