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, Duration)>,
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 background acquisition of every object, bounded only by the
177    /// protocol geometry. Each round spends at most `slice` on one object; an
178    /// unfinished object resumes from its stored records in a later round. The
179    /// caller supplies an owned scratch directory. Only run(true) schedules it;
180    /// pruned archives perform no automatic content acquisition.
181    pub fn with_retention(mut self, scratch: PathBuf, slice: Duration) -> Result<Self, Error> {
182        if slice.is_zero() {
183            return Err(Error::Invalid(
184                "object retention slice must be nonzero".into(),
185            ));
186        }
187        self.retention = Some((scratch, slice));
188        Ok(self)
189    }
190
191    /// Run foreground. Network acquisition is opt-in; status works offline.
192    pub fn run(self, synchronize: bool) -> Result<(), Error> {
193        std::thread::scope(|scope| {
194            if synchronize {
195                scope.spawn(|| {
196                    while !self.stop.load(Ordering::Acquire) {
197                        self.worker_round();
198                        for _ in 0..20 {
199                            if self.stop.load(Ordering::Acquire) {
200                                break;
201                            }
202                            std::thread::sleep(Duration::from_millis(100));
203                        }
204                    }
205                });
206            }
207            let outcome = self.accept_loop();
208            self.stop.store(true, Ordering::Release);
209            outcome
210        })
211    }
212
213    fn worker_round(&self) {
214        let headers = self.engine.synchronize_headers_until(&self.stop);
215        // Discovery keeps connections and the book fresh before inventory
216        // sync uses them; it is independent of this round's header result.
217        self.discover_peers();
218        // Peer inventory is fast data: it runs before the full-block scan and
219        // independently of this round's header result, with its own status.
220        self.sync_next_inventory();
221        let result = headers
222            .and_then(|_| self.engine.scan_next_until(&self.stop))
223            .and_then(|status| {
224                if !self.stop.load(Ordering::Acquire) {
225                    self.engine.resolve_cached_dependency()?;
226                }
227                Ok(status)
228            });
229        record(&self.sync_error, &result);
230        self.acquire_next_dependency();
231        // Registered projections can use already scanned data
232        // even if this round's acquisition failed. They never
233        // create registrations or acquire missing history.
234        if !self.stop.load(Ordering::Acquire) {
235            let result = self.engine.maintain_next_names(&self.stop);
236            record(&self.names_error, &result);
237        }
238        // Full-block audit always gets its opportunity before
239        // one object attempt. A sync failure does not suppress
240        // independent recovery from the last selected view;
241        // its error remains separately visible in status.
242        if !self.stop.load(Ordering::Acquire) {
243            if let Some((scratch, slice)) = &self.retention {
244                let owned = self.record_sources();
245                let sources: Vec<&dyn RecordSource> = owned
246                    .iter()
247                    .map(|source| -> &dyn RecordSource { source.as_ref() })
248                    .collect();
249                let result = self
250                    .engine
251                    .retain_next_object(&sources, *slice, scratch, &self.stop);
252                record(&self.retention_error, &result);
253            }
254        }
255        // Independent local maintenance also runs after failed
256        // acquisition/projection/retention. It never opens a source.
257        if !self.stop.load(Ordering::Acquire) {
258            let result = self.engine.maintain_cache(self.cache_bytes, &self.stop);
259            if let Ok(mut status) = self.cache_status.lock() {
260                match result {
261                    Ok(receipt) => {
262                        status.receipt = Some(receipt);
263                        status.error = None;
264                    }
265                    Err(cause) => {
266                        status.error = Some(RecordedError::now(cause));
267                    }
268                }
269            }
270        }
271    }
272
273    fn acquire_next_dependency(&self) {
274        let Some(sources) = &self.commit_sources else {
275            return;
276        };
277        if self.stop.load(Ordering::Acquire) {
278            return;
279        }
280        let result = self.engine.resolve_next_dependency(sources, &self.stop);
281        if self.stop.load(Ordering::Acquire) {
282            return;
283        }
284        record(&self.dependency_error, &result);
285    }
286
287    fn status(&self) -> Result<ServiceStatus, Error> {
288        let (last_sync_error, last_sync_error_at) =
289            RecordedError::split(read(&self.sync_error, "sync")?);
290        let (last_retention_error, last_retention_error_at) =
291            RecordedError::split(read(&self.retention_error, "retention")?);
292        let (last_names_error, last_names_error_at) =
293            RecordedError::split(read(&self.names_error, "Names")?);
294        let (last_dependency_error, last_dependency_error_at) =
295            RecordedError::split(read(&self.dependency_error, "dependency")?);
296        let (last_inventory_error, last_inventory_error_at) =
297            RecordedError::split(read(&self.inventory_error, "inventory")?);
298        let (last_discovery_error, last_discovery_error_at) =
299            RecordedError::split(read(&self.discovery_error, "discovery")?);
300        let cache = self
301            .cache_status
302            .lock()
303            .map_err(|_| Error::Invalid("cache status poisoned".into()))?
304            .clone();
305        let (last_cache_error, last_cache_error_at) = RecordedError::split(cache.error);
306        let overlay = self.overlay_status()?;
307        let mut commit_sources = Vec::new();
308        for sources in self.commit_sources.iter() {
309            commit_sources.extend(sources.status()?);
310        }
311        let mut status = ServiceStatus::default();
312        status.archive = self.engine.status()?;
313        status.last_sync_error = last_sync_error;
314        status.last_sync_error_at = last_sync_error_at;
315        status.last_retention_error = last_retention_error;
316        status.last_retention_error_at = last_retention_error_at;
317        status.last_names_error = last_names_error;
318        status.last_names_error_at = last_names_error_at;
319        status.last_dependency_error = last_dependency_error;
320        status.last_dependency_error_at = last_dependency_error_at;
321        status.last_inventory_error = last_inventory_error;
322        status.last_inventory_error_at = last_inventory_error_at;
323        status.last_discovery_error = last_discovery_error;
324        status.last_discovery_error_at = last_discovery_error_at;
325        status.commit_sources = commit_sources;
326        status.cache_limit_bytes = self.cache_bytes;
327        status.last_cache_error = last_cache_error;
328        status.last_cache_error_at = last_cache_error_at;
329        status.last_cache_maintenance = cache.receipt;
330        status.overlay = overlay;
331        status.chain_peers = self.engine.chain_peers()?;
332        status.chain_target = self.engine.chain_target();
333        status.retention_configured = self.retention.is_some();
334        status.record_sources_configured = u64::try_from(self.record_source_count())
335            .map_err(|error| Error::Invalid(format!("record source count: {error}")))?;
336        status.capabilities = Self::CAPABILITIES.map(String::from).to_vec();
337        Ok(status)
338    }
339
340    fn accept_loop(&self) -> Result<(), Error> {
341        while !self.stop.load(Ordering::Acquire) {
342            match self.listener.accept() {
343                Ok((mut stream, peer)) => {
344                    if !peer.ip().is_loopback() {
345                        continue;
346                    }
347                    stream.set_read_timeout(Some(Duration::from_secs(2)))?;
348                    stream.set_write_timeout(Some(Duration::from_secs(2)))?;
349                    // A malformed or disconnected client never stops the service.
350                    let _ = self.request(&mut stream);
351                }
352                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
353                    std::thread::sleep(Duration::from_millis(50))
354                }
355                Err(e) => return Err(e.into()),
356            }
357        }
358        Ok(())
359    }
360
361    fn request(&self, stream: &mut TcpStream) -> Result<(), Error> {
362        let mut raw = Vec::new();
363        let began = std::time::Instant::now();
364        loop {
365            if raw.len() == 8192 || began.elapsed() > Duration::from_secs(3) {
366                return respond(stream, 400, json!({"error":"request header limit"}));
367            }
368            let mut byte = [0];
369            if stream.read(&mut byte)? == 0 {
370                return Ok(());
371            }
372            raw.push(byte[0]);
373            if began.elapsed() > Duration::from_secs(3) {
374                return respond(stream, 400, json!({"error":"request header deadline"}));
375            }
376            if raw.ends_with(b"\r\n\r\n") {
377                break;
378            }
379        }
380        let Ok(request) = std::str::from_utf8(&raw) else {
381            return respond(stream, 400, json!({"error":"invalid header encoding"}));
382        };
383        let mut lines = request.split("\r\n");
384        let first = lines.next().unwrap_or("");
385        let mut authorized = false;
386        let mut authorization_seen = false;
387        for line in lines.filter(|line| !line.is_empty()) {
388            let Some((name, value)) = line.split_once(':') else {
389                return respond(stream, 400, json!({"error":"malformed header"}));
390            };
391            if name.eq_ignore_ascii_case("authorization") {
392                if authorization_seen {
393                    return respond(stream, 400, json!({"error":"duplicate authorization"}));
394                }
395                authorization_seen = true;
396                authorized = value
397                    .trim()
398                    .strip_prefix("Bearer ")
399                    .is_some_and(|value| equal_token(value, &self.token));
400            }
401            if name.eq_ignore_ascii_case("transfer-encoding")
402                || (name.eq_ignore_ascii_case("content-length") && value.trim() != "0")
403            {
404                return respond(
405                    stream,
406                    400,
407                    json!({"error":"this control endpoint accepts no request body"}),
408                );
409            }
410        }
411        if !authorized {
412            return respond(stream, 401, json!({"error":"authentication required"}));
413        }
414        match first {
415            line if (line.starts_with("GET /v1/names/") || line.starts_with("POST /v1/names/"))
416                && line.ends_with(" HTTP/1.1") =>
417            {
418                let (method, path) = line[..line.len() - " HTTP/1.1".len()]
419                    .split_once(' ')
420                    .expect("matched HTTP method");
421                let request = match names_request(method, path) {
422                    Ok(Some(request)) => request,
423                    Ok(None) => {
424                        return respond(stream, 404, json!({"error":"unknown endpoint"}));
425                    }
426                    Err(_) => {
427                        return respond(stream, 400, json!({"error":"invalid Names request"}));
428                    }
429                };
430                // Reads never register or advance a registry. Mutations are
431                // explicit one-shot commands under the Engine archive mutex.
432                let result = match request {
433                    NamesRequest::Status(genesis) => match self.engine.names_status(genesis) {
434                        Ok(Some(status)) => serde_json::to_value(status).map_err(Error::from),
435                        Ok(None) => {
436                            return respond(
437                                stream,
438                                404,
439                                json!({"error":"Names registry is not registered locally"}),
440                            );
441                        }
442                        Err(error) => Err(error),
443                    },
444                    NamesRequest::Resolve(genesis, name) => self
445                        .engine
446                        .names_resolve(genesis, &name)
447                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
448                    NamesRequest::Register(genesis, point) => self
449                        .engine
450                        .register_names(genesis, point)
451                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
452                    NamesRequest::Step(genesis) => self
453                        .engine
454                        .names_step(genesis)
455                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
456                    NamesRequest::View(genesis, limit, cursor) => self
457                        .engine
458                        .names_view(genesis, cursor.as_ref(), limit)
459                        .and_then(|value| serde_json::to_value(value).map_err(Error::from)),
460                };
461                match result {
462                    Ok(value) => respond(stream, 200, value),
463                    Err(error) => control_error(stream, error),
464                }
465            }
466            line if line.starts_with("GET /v1/wire?") && line.ends_with(" HTTP/1.1") => {
467                let query = &line["GET /v1/wire?".len()..line.len() - " HTTP/1.1".len()];
468                let (limit, cursor) = match wire_query(query) {
469                    Ok(value) => value,
470                    Err(_) => {
471                        return respond(stream, 400, json!({"error":"invalid Wire page query"}));
472                    }
473                };
474                match self.engine.wire_page(cursor.as_ref(), limit) {
475                    Ok(page) => respond(stream, 200, serde_json::to_value(page)?),
476                    Err(error) => control_error(stream, error),
477                }
478            }
479            "POST /v1/cache/prune HTTP/1.1" => match self.engine.prune_cache() {
480                Ok(records_removed) => respond(
481                    stream,
482                    200,
483                    serde_json::to_value(crate::model::PruneReceipt { records_removed })?,
484                ),
485                Err(error) => control_error(stream, error),
486            },
487            line if line.starts_with("POST /v1/objects/") && line.ends_with(" HTTP/1.1") => {
488                let path = &line["POST /v1/objects/".len()..line.len() - " HTTP/1.1".len()];
489                let (id, pin) = match path.rsplit_once('/') {
490                    Some((id, "pin")) => (id, true),
491                    Some((id, "unpin")) => (id, false),
492                    _ => return respond(stream, 404, json!({"error":"unknown endpoint"})),
493                };
494                if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
495                    return respond(stream, 400, json!({"error":"invalid root transaction ID"}));
496                }
497                let root = id
498                    .parse()
499                    .map_err(|e| Error::Invalid(format!("TXID: {e}")))?;
500                // Engine serializes validation and mutation with pruning/reorg.
501                // The acknowledgement describes this operation's commit point;
502                // a lost response must not be treated as proof of no mutation.
503                match self.engine.set_pin(root, pin) {
504                    Ok(()) => respond(
505                        stream,
506                        200,
507                        serde_json::to_value(crate::model::PinReceipt { root, pinned: pin })?,
508                    ),
509                    Err(error) => control_error(stream, error),
510                }
511            }
512            line if line.starts_with("GET /v1/objects/") && line.ends_with(" HTTP/1.1") => {
513                let id = &line["GET /v1/objects/".len()..line.len() - " HTTP/1.1".len()];
514                if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
515                    return respond(stream, 400, json!({"error":"invalid root transaction ID"}));
516                }
517                let root = id
518                    .parse()
519                    .map_err(|e| Error::Invalid(format!("TXID: {e}")))?;
520                match self.engine.object_status(root)? {
521                    Some(status) => respond(stream, 200, serde_json::to_value(status)?),
522                    None => respond(
523                        stream,
524                        404,
525                        json!({"error":"no completed object recorded locally"}),
526                    ),
527                }
528            }
529            line if line.starts_with("GET /v1/records/") && line.ends_with(" HTTP/1.1") => {
530                let id = &line["GET /v1/records/".len()..line.len() - " HTTP/1.1".len()];
531                if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
532                    return respond(stream, 400, json!({"error":"invalid transaction ID"}));
533                }
534                let txid = id
535                    .parse()
536                    .map_err(|e| Error::Invalid(format!("TXID: {e}")))?;
537                match self.engine.record(txid)? {
538                    Some(record) => respond(stream, 200, serde_json::to_value(record)?),
539                    None => respond(
540                        stream,
541                        404,
542                        json!({"error":"record is not locally available in the selected view"}),
543                    ),
544                }
545            }
546            "GET /v1/status HTTP/1.1" => {
547                respond(stream, 200, serde_json::to_value(self.status()?)?)
548            }
549            // Ascending by height; only the newest (highest) 1024 rows are returned.
550            "GET /v1/overlay/omissions HTTP/1.1" => match self.engine.peer_omissions_latest(1024) {
551                Ok(omissions) => respond(stream, 200, serde_json::to_value(omissions)?),
552                Err(error) => control_error(stream, error),
553            },
554            "GET /v1/overlay/book HTTP/1.1" => match self.overlay_book() {
555                Ok(Some(book)) => respond(stream, 200, serde_json::to_value(book)?),
556                Ok(None) => respond(stream, 404, json!({"error":"overlay disabled"})),
557                Err(error) => control_error(stream, error),
558            },
559            "POST /v1/shutdown HTTP/1.1" => {
560                respond(stream, 200, json!({"stopping":true}))?;
561                self.stop.store(true, Ordering::Release);
562                Ok(())
563            }
564            _ => respond(stream, 404, json!({"error":"unknown endpoint"})),
565        }
566    }
567}
568
569enum NamesRequest {
570    Status(bitcoin::Txid),
571    Resolve(bitcoin::Txid, urma_names::name::Name),
572    Register(bitcoin::Txid, crate::model::ChainPoint),
573    Step(bitcoin::Txid),
574    View(bitcoin::Txid, u32, Option<crate::names::NamesCursor>),
575}
576
577fn names_request(method: &str, path: &str) -> Result<Option<NamesRequest>, Error> {
578    let invalid = || Error::Invalid("invalid Names request".into());
579    let path = path.strip_prefix("/v1/names/").ok_or_else(invalid)?;
580    let (id, operation) = path.split_once('/').unwrap_or((path, ""));
581    if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
582        return Err(invalid());
583    }
584    let genesis = id.parse().map_err(|_| invalid())?;
585    let request = match (method, operation) {
586        ("GET", "") => NamesRequest::Status(genesis),
587        ("GET", operation) if operation.starts_with("view?") => {
588            let (limit, cursor) = names_view_query(&operation["view?".len()..])?;
589            if cursor.as_ref().is_some_and(|c| c.genesis != genesis) {
590                return Err(invalid());
591            }
592            NamesRequest::View(genesis, limit, cursor)
593        }
594        ("GET", operation) if operation.starts_with("resolve/") => {
595            // Canonical Names V0 uses only ASCII letters, digits and hyphens;
596            // do not normalize, percent-decode or accept alternate spellings.
597            let name = urma_names::name::Name::parse(&operation["resolve/".len()..])
598                .map_err(|_| invalid())?;
599            NamesRequest::Resolve(genesis, name)
600        }
601        ("POST", "step") => NamesRequest::Step(genesis),
602        ("POST", operation) if operation.starts_with("register?") => {
603            let mut height = None;
604            let mut hash = None;
605            for field in operation["register?".len()..].split('&') {
606                match field.split_once('=') {
607                    Some(("height", value)) if height.is_none() => {
608                        if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
609                            return Err(invalid());
610                        }
611                        let value: u64 = value.parse().map_err(|_| invalid())?;
612                        if value > i64::MAX as u64 {
613                            return Err(invalid());
614                        }
615                        height = Some(value);
616                    }
617                    Some(("hash", value)) if hash.is_none() => {
618                        if value.len() != 64 || !value.bytes().all(|b| b.is_ascii_hexdigit()) {
619                            return Err(invalid());
620                        }
621                        hash = Some(value.parse().map_err(|_| invalid())?);
622                    }
623                    _ => return Err(invalid()),
624                }
625            }
626            NamesRequest::Register(
627                genesis,
628                crate::model::ChainPoint {
629                    height: height.ok_or_else(invalid)?,
630                    hash: hash.ok_or_else(invalid)?,
631                },
632            )
633        }
634        _ => return Ok(None),
635    };
636    Ok(Some(request))
637}
638
639fn names_view_query(query: &str) -> Result<(u32, Option<crate::names::NamesCursor>), Error> {
640    let invalid = || Error::Invalid("invalid Names view query".into());
641    let mut limit = None;
642    let mut cursor = None;
643    for field in query.split('&') {
644        match field.split_once('=') {
645            Some(("limit", value)) if limit.is_none() => {
646                if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
647                    return Err(invalid());
648                }
649                let value: u32 = value.parse().map_err(|_| invalid())?;
650                if !(1..=crate::names::MAX_NAMES_PAGE).contains(&value) {
651                    return Err(invalid());
652                }
653                limit = Some(value);
654            }
655            Some(("cursor", value)) if cursor.is_none() => {
656                if value.len() > 1024 {
657                    return Err(invalid());
658                }
659                let bytes = hex::decode(value).map_err(|_| invalid())?;
660                let decoded: crate::names::NamesCursor = serde_json::from_slice(&bytes)?;
661                if decoded.snapshot.instance.len() != 32
662                    || !decoded
663                        .snapshot
664                        .instance
665                        .bytes()
666                        .all(|b| b.is_ascii_hexdigit())
667                {
668                    return Err(invalid());
669                }
670                cursor = Some(decoded);
671            }
672            _ => return Err(invalid()),
673        }
674    }
675    Ok((limit.ok_or_else(invalid)?, cursor))
676}
677
678fn wire_query(query: &str) -> Result<(u32, Option<crate::projection::WireCursor>), Error> {
679    let invalid = || Error::Invalid("invalid Wire page query".into());
680    let mut limit = None;
681    let mut cursor = None;
682    for field in query.split('&') {
683        match field.split_once('=') {
684            Some(("limit", value)) if limit.is_none() => {
685                if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
686                    return Err(invalid());
687                }
688                let value: u32 = value.parse().map_err(|_| invalid())?;
689                if !(1..=crate::projection::MAX_WIRE_PAGE).contains(&value) {
690                    return Err(invalid());
691                }
692                limit = Some(value);
693            }
694            Some(("cursor", value)) if cursor.is_none() => {
695                if value.len() > 1024 {
696                    return Err(invalid());
697                }
698                let bytes = hex::decode(value).map_err(|_| invalid())?;
699                let decoded: crate::projection::WireCursor = serde_json::from_slice(&bytes)?;
700                if decoded.snapshot.instance.len() != 32
701                    || !decoded
702                        .snapshot
703                        .instance
704                        .bytes()
705                        .all(|b| b.is_ascii_hexdigit())
706                    || decoded.height > i64::MAX as u64
707                {
708                    return Err(invalid());
709                }
710                cursor = Some(decoded);
711            }
712            _ => return Err(invalid()),
713        }
714    }
715    Ok((limit.ok_or_else(invalid)?, cursor))
716}
717
718fn control_error(stream: &mut TcpStream, error: Error) -> Result<(), Error> {
719    match error {
720        Error::Invalid(message) => respond(stream, 422, json!({"error":message})),
721        error @ (Error::Busy(_)
722        | Error::PeerBusy
723        | Error::Transport(_)
724        | Error::DialDenied(_)
725        | Error::Stale) => respond(stream, 409, json!({"error":error.to_string()})),
726        // Do not expose database internals or local filesystem paths over HTTP.
727        _ => respond(
728            stream,
729            500,
730            json!({"error":"local archive operation failed"}),
731        ),
732    }
733}
734
735fn equal_token(left: &str, right: &str) -> bool {
736    if left.len() != right.len() {
737        return false;
738    }
739    left.bytes()
740        .zip(right.bytes())
741        .fold(0u8, |different, (a, b)| different | (a ^ b))
742        == 0
743}
744
745fn respond(stream: &mut TcpStream, code: u16, body: serde_json::Value) -> Result<(), Error> {
746    let body = serde_json::to_vec(&body)?;
747    if body.len() > 32 * 1024 * 1024 {
748        return respond(
749            stream,
750            413,
751            json!({"error":"record exceeds local API response limit"}),
752        );
753    }
754    let reason = match code {
755        200 => "OK",
756        400 => "Bad Request",
757        401 => "Unauthorized",
758        409 => "Conflict",
759        413 => "Content Too Large",
760        422 => "Unprocessable Content",
761        500 => "Internal Server Error",
762        _ => "Not Found",
763    };
764    write!(
765        stream,
766        "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",
767        body.len()
768    )?;
769    stream.write_all(&body)?;
770    Ok(())
771}
772
773/// New service token, never a wallet/signing/decryption key. Existing files
774/// are not overwritten. Platform-specific private ACL support is required.
775pub fn create_token(path: &Path) -> Result<(), Error> {
776    #[cfg(not(unix))]
777    return Err(Error::Invalid(
778        "private token ACL creation is not implemented for this platform".into(),
779    ));
780    #[cfg(unix)]
781    {
782        use std::os::unix::fs::OpenOptionsExt;
783        let mut bytes = [0u8; 32];
784        rand::rngs::OsRng.fill_bytes(&mut bytes);
785        let mut file = OpenOptions::new()
786            .write(true)
787            .create_new(true)
788            .mode(0o600)
789            .open(path)?;
790        file.write_all(hex::encode(bytes).as_bytes())?;
791        file.sync_all()?;
792        Ok(())
793    }
794}