1use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use serde::{Deserialize as _, Serialize};
7use serde_json::{json, Value as Json};
8use stratum_node_config::Change;
9use stratum_node_core::{ClaimBody, DidNostr, NostrSecretKey, OperationId, SignedEvent};
10
11use crate::changes::parse_changes;
12use crate::client::{self, Client, Response};
13use crate::error::CliError;
14use crate::exit;
15use crate::key::{generate_key_file, load_key_file};
16use crate::output::{sanitize, Output};
17use crate::private_file::{self, ModePolicy};
18use crate::url::LoopbackUrl;
19use crate::wire::{
20 ApplyRequest, ApplyResponse, BackupManifest, BackupRequest, BackupResponse, CheckpointResponse,
21 ConfigResponse, PreviewRequest, PreviewResponse, Readyz, BACKUP_FILES, BACKUP_FILES_SEALED,
22 BACKUP_FORMAT, BACKUP_FORMAT_VERSION, BACKUP_FORMAT_VERSION_PODS, BACKUP_FORMAT_VERSION_SEALED,
23 BACKUP_POD_ARCHIVE,
24};
25
26pub(crate) const READYZ: &str = "/readyz";
28const SCHEMA: &str = "/api/v1/config/schema";
30const CONFIG: &str = "/api/v1/config";
32pub(crate) const PREVIEW: &str = "/api/v1/config/preview";
34const APPLY: &str = "/api/v1/config/apply";
36const CHECKPOINT: &str = "/api/v1/audit/checkpoint";
38const BACKUP: &str = "/api/v1/backup";
40
41const BACKUP_TIMEOUT: Duration = Duration::from_secs(15 * 60);
47pub(crate) const CHALLENGE: &str = "/api/v1/bootstrap/challenge";
49pub(crate) const CLAIM: &str = "/api/v1/bootstrap/claim";
51
52const API_VERSION: u64 = 1;
54
55const MANIFEST_KIND: u16 = 30078;
57
58const CLAIM_BODY_FILE_LIMIT: usize = 64 * 1024;
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63#[non_exhaustive]
64pub enum Confirmation {
65 #[default]
67 Prompt,
68 Assumed,
70}
71
72#[derive(Debug, Clone, Default)]
74pub struct ApplyOptions {
75 pub sets: Vec<String>,
77 pub base_revision: Option<u64>,
80 pub operation_id: Option<String>,
82 pub confirmation: Confirmation,
84}
85
86#[derive(Debug, Clone, Default)]
88pub struct SetupOptions {
89 pub token_file: PathBuf,
91 pub sets: Vec<String>,
93 pub resume_file: Option<PathBuf>,
96 pub confirmation: Confirmation,
98 pub expect_node: Option<DidNostr>,
103 pub show_text: bool,
106}
107
108#[derive(Debug, Clone)]
132pub struct Session {
133 url: LoopbackUrl,
134 key_file: Option<PathBuf>,
135 output: Output,
136}
137
138impl Session {
139 pub fn new(url: LoopbackUrl, key_file: Option<PathBuf>, output: Output) -> Self {
142 Self {
143 url,
144 key_file,
145 output,
146 }
147 }
148
149 pub fn key_generate(&self, out: &Path) -> Result<u8, CliError> {
156 let key = generate_key_file(out).map_err(|source| CliError::KeyFile {
157 path: out.to_owned(),
158 source,
159 })?;
160 self.print_identity(&key.public(), out)
161 }
162
163 pub fn key_show(&self) -> Result<u8, CliError> {
169 let path = self.key_path()?;
170 let key = self.key()?;
171 self.print_identity(&key.public(), path)
172 }
173
174 pub fn status(&self) -> Result<u8, CliError> {
181 let client = self.client()?;
182 let response = client.get(READYZ, None)?;
183 let status = response.status;
184 let (readyz, raw): (Readyz, Json) = response.parse()?;
185 let code = match (status, readyz.status.as_str()) {
186 (200, "ready") => exit::OK,
187 (200, "unconfigured") => exit::UNCONFIGURED,
188 (503, "degraded") => exit::DEGRADED,
189 _ => {
190 return Err(CliError::Protocol(format!(
191 "readyz answered HTTP {status} with status {:?}",
192 sanitize(&readyz.status)
193 )))
194 }
195 };
196 self.output.json(&raw)?;
197 self.output.line(&format!("status: {}", readyz.status))?;
198 self.output.line(&format!("node: {}", readyz.node_did))?;
199 self.output
200 .line(&format!("version: {}", sanitize(&readyz.version)))?;
201 self.output
202 .line(&format!("api version: {}", readyz.api_version))?;
203 self.output.line(&format!(
204 "revision: head {}, active {}",
205 readyz.head_revision, readyz.active_revision
206 ))?;
207 self.output.line(&format!(
208 "public config hash: {}",
209 readyz
210 .public_config_hash
211 .as_deref()
212 .map_or_else(|| "none".to_owned(), sanitize)
213 ))?;
214 Ok(code)
215 }
216
217 pub fn config_schema(&self) -> Result<u8, CliError> {
223 let client = self.client()?;
224 let (schema, raw): (Json, Json) = client.get(SCHEMA, None)?.into_json()?;
225 self.output.json(&raw)?;
226 if let Some(version) = schema.get("schema_version") {
227 self.output.line(&format!("schema version {version}"))?;
228 }
229 let fields = schema
230 .get("fields")
231 .and_then(Json::as_array)
232 .ok_or_else(|| CliError::Protocol("schema has no fields list".to_owned()))?;
233 for field in fields {
234 let text = |name: &str| field.get(name).map_or_else(String::new, compact);
235 let kind = field
236 .get("type")
237 .and_then(|t| t.get("kind"))
238 .map_or_else(String::new, compact);
239 self.output.line(&sanitize(&format!(
240 "\n{} ({kind}, {}, default {})\n {}",
241 text("path").trim_matches('"'),
242 text("apply_class").trim_matches('"'),
243 text("default"),
244 text("description").trim_matches('"'),
245 )))?;
246 }
247 Ok(exit::OK)
248 }
249
250 pub fn config_show(&self) -> Result<u8, CliError> {
257 let key = self.key()?;
258 let client = self.client()?;
259 let (config, raw): (ConfigResponse, Json) = client.get(CONFIG, Some(&key))?.into_json()?;
260 self.output.json(&raw)?;
261 self.output.line(&format!(
262 "revision: head {}, active {}",
263 config.head_revision, config.active_revision
264 ))?;
265 self.output.line(&format!(
266 "public config hash: {}",
267 config.public_config_hash
268 ))?;
269 self.output.line("")?;
270 self.output.line(sanitize(&config.text).trim_end())?;
271 Ok(exit::OK)
272 }
273
274 pub fn config_preview(
284 &self,
285 sets: &[String],
286 base_revision: Option<u64>,
287 ) -> Result<u8, CliError> {
288 let changes = changes_from(sets)?;
289 let key = match self.key_file {
290 Some(_) => Some(self.key()?),
291 None => None,
292 };
293 let client = self.client()?;
294 let base = match base_revision {
295 Some(base) => base,
296 None => readyz(&client)?.head_revision,
297 };
298 let (preview, raw) = request_preview(&client, base, &changes, key.as_ref())?;
299 self.output.json(&raw)?;
300 self.show_preview(&preview)?;
301 if preview.errors.is_empty() {
302 Ok(exit::OK)
303 } else {
304 Err(invalid_preview(&preview))
305 }
306 }
307
308 pub fn config_apply(&self, options: &ApplyOptions) -> Result<u8, CliError> {
322 let changes = changes_from(&options.sets)?;
323 let operation_id = operation_id(options.operation_id.as_deref())?;
324 let key = self.key()?;
325 let client = self.client()?;
326 let ready = readyz(&client)?;
327 let base = options.base_revision.unwrap_or(ready.head_revision);
328 let (preview, preview_raw) = request_preview(&client, base, &changes, Some(&key))?;
329 self.show_preview(&preview)?;
330 let mut report = json!({
331 "operation_id": operation_id.as_str(),
332 "base_revision": base,
333 "preview": preview_raw,
334 "applied": false,
335 });
336 if !preview.errors.is_empty() {
337 self.output.json(&report)?;
338 return Err(invalid_preview(&preview));
339 }
340 if preview.changes.is_empty() {
341 self.output.json(&report)?;
342 self.output
343 .line("nothing to apply: the change leaves the configuration as it is")?;
344 return Ok(exit::OK);
345 }
346 if !self.confirmed("apply these changes?", options.confirmation)? {
347 self.output.json(&report)?;
348 return Err(CliError::NotConfirmed);
349 }
350 self.output.note(&format!(
351 "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
352 ))?;
353 let body = to_body(&ApplyRequest {
354 node: ready.node_did,
355 operation_id: &operation_id,
356 base_revision: base,
357 changes: &changes,
358 })?;
359 let (applied, applied_raw): (ApplyResponse, Json) =
360 client.post(APPLY, &body, Some(&key))?.into_json()?;
361 report["applied"] = Json::Bool(true);
362 report["result"] = applied_raw;
363 self.output.json(&report)?;
364 self.output
365 .line(&format!("applied: revision {}", applied.revision))?;
366 self.output.line(&format!(
367 "public config hash: {}",
368 applied.public_config_hash
369 ))?;
370 self.output.line(&format!(
371 "strictest apply class: {}",
372 applied
373 .strictest_apply_class
374 .as_deref()
375 .map_or_else(|| "none".to_owned(), sanitize)
376 ))?;
377 if applied.restart_required {
378 self.output
379 .line("restart required: the change takes effect after the controller restarts")?;
380 }
381 Ok(exit::OK)
382 }
383
384 pub fn audit_checkpoint(&self) -> Result<u8, CliError> {
393 let key = self.key()?;
394 let client = self.client()?;
395 let (checkpoint, raw): (CheckpointResponse, Json) =
396 client.get(CHECKPOINT, Some(&key))?.into_json()?;
397 let expected = format!("{}:{}", checkpoint.sequence, checkpoint.tail_hash);
398 if checkpoint.checkpoint != expected {
399 return Err(CliError::Protocol(
400 "checkpoint text does not match its sequence and tail hash".to_owned(),
401 ));
402 }
403 self.output.json(&raw)?;
404 self.output.line(&expected)?;
405 self.output
406 .line(&format!("node: {}", checkpoint.node_did))?;
407 Ok(exit::OK)
408 }
409
410 pub fn backup(
430 &self,
431 operation_id_arg: Option<&str>,
432 expect_node: Option<&DidNostr>,
433 ) -> Result<u8, CliError> {
434 let operation_id = operation_id(operation_id_arg)?;
435 let key = self.key()?;
436 let client = self.client()?;
437 let ready = readyz(&client)?;
438 check_expected_node(ready.node_did, expect_node)?;
439 self.output.note(&format!(
440 "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
441 ))?;
442 let body = to_body(&BackupRequest {
443 node: ready.node_did,
444 operation_id: &operation_id,
445 })?;
446 let (backup, raw): (BackupResponse, Json) = client
447 .post_with_timeout(BACKUP, &body, &key, BACKUP_TIMEOUT)?
448 .into_json()?;
449 let manifest = SignedEvent::deserialize(&backup.manifest).map_err(|_| {
450 CliError::Refused("the backup manifest is not a validly signed nostr event".to_owned())
451 })?;
452 if manifest.author() != ready.node_did {
453 return Err(CliError::Refused(format!(
454 "the backup manifest is signed by {}, not by the node {}",
455 manifest.author(),
456 ready.node_did
457 )));
458 }
459 if manifest.kind() != MANIFEST_KIND {
460 return Err(CliError::Refused(format!(
461 "the backup manifest is kind {}, not the NIP-78 kind {MANIFEST_KIND}",
462 manifest.kind()
463 )));
464 }
465 if !is_checkpoint(&backup.checkpoint) {
466 return Err(CliError::Protocol(
467 "backup checkpoint is not of the form <seq>:<64 hex>".to_owned(),
468 ));
469 }
470 let content =
471 check_manifest_content(manifest.content(), ready.node_did, &backup.checkpoint)?;
472 let report = json!({
473 "operation_id": operation_id.as_str(),
474 "node_did": ready.node_did,
475 "config_revision": content.config_revision,
476 "created_at": content.created_at,
477 "pod_archive": content.pod_archive,
478 "keystore_recipients": content.keystore_recipients,
479 "backup": raw,
480 });
481 self.output.json(&report)?;
482 self.output
483 .line(&format!("directory: {}", sanitize(&backup.directory)))?;
484 self.output
485 .line(&format!("checkpoint: {}", backup.checkpoint))?;
486 self.output
487 .line(&format!("config revision: {}", content.config_revision))?;
488 if let Some(pods) = content.pod_archive {
489 self.output.line(&format!(
490 "pod archive: {} entries, {} bytes",
491 pods.entries, pods.bytes
492 ))?;
493 }
494 if !content.keystore_recipients.is_empty() {
495 self.output.line(&format!(
496 "keystore sealed to {} signer recipient(s)",
497 content.keystore_recipients.len()
498 ))?;
499 }
500 self.output.line(&format!(
501 "manifest: event {} signed by the node {}",
502 manifest.id(),
503 manifest.author()
504 ))?;
505 Ok(exit::OK)
506 }
507
508 pub fn sign_challenge(
536 &self,
537 claim_body_file: &Path,
538 expect_node: &DidNostr,
539 ) -> Result<u8, CliError> {
540 let key = self.key()?;
541 let url = if self.url.is_origin() {
542 self.url.join(CLAIM)
543 } else if self.url.path() == CLAIM {
544 self.url.to_url_string()
545 } else {
546 return Err(CliError::Usage(format!(
547 "sign-challenge signs only for the claim route: --url must be an origin or end in {CLAIM}"
548 )));
549 };
550 let bytes = private_file::read(claim_body_file, CLAIM_BODY_FILE_LIMIT, ModePolicy::Any)
551 .map_err(|source| CliError::File {
552 path: claim_body_file.to_owned(),
553 source,
554 })?;
555 let body = ClaimBody::parse(&bytes).map_err(|err| CliError::FileContents {
556 path: claim_body_file.to_owned(),
557 message: format!("not a claim body: {err}"),
558 })?;
559 if bytes.last().is_some_and(u8::is_ascii_whitespace) {
560 self.output.note(
561 "warning: the claim body file ends in whitespace; the node compares the exact bytes it issued",
562 )?;
563 }
564 if body.claimant() != key.public() {
565 return Err(CliError::Refused(format!(
566 "the claim body names claimant {}, but this key is {}",
567 body.claimant(),
568 key.public()
569 )));
570 }
571 body.check(client::now()?, expect_node, &key.public())
572 .map_err(|err| CliError::Refused(err.to_string()))?;
573 let authorization = client::sign(&key, "POST", &url, Some(body.as_bytes()))?;
574 if self.output.is_json() {
575 self.output.json(&json!({
576 "url": url,
577 "method": "POST",
578 "authorization": authorization,
579 "claim": claim_json(&body),
580 }))?;
581 } else {
582 self.show_claim(&body)?;
583 self.output.note(&format!("signed for POST {url}"))?;
584 self.output.value_line(&authorization)?;
585 }
586 Ok(exit::OK)
587 }
588
589 pub(crate) fn client(&self) -> Result<Client, CliError> {
591 if !self.url.is_origin() {
592 return Err(CliError::Usage(
593 "--url must be an origin such as http://127.0.0.1:7460 for this command".to_owned(),
594 ));
595 }
596 Ok(Client::new(self.url.clone()))
597 }
598
599 pub(crate) fn key_path(&self) -> Result<&Path, CliError> {
601 self.key_file.as_deref().ok_or(CliError::MissingKeyFile)
602 }
603
604 pub(crate) fn key(&self) -> Result<NostrSecretKey, CliError> {
606 let path = self.key_path()?;
607 load_key_file(path).map_err(|source| CliError::KeyFile {
608 path: path.to_owned(),
609 source,
610 })
611 }
612
613 pub(crate) fn output(&self) -> &Output {
615 &self.output
616 }
617
618 pub(crate) fn confirmed(
620 &self,
621 question: &str,
622 confirmation: Confirmation,
623 ) -> Result<bool, CliError> {
624 match confirmation {
625 Confirmation::Assumed => Ok(true),
626 Confirmation::Prompt => {
627 if let Some(answer) = self.output.confirm(question)? {
628 return Ok(answer);
629 }
630 self.output
631 .note("standard input is not a terminal: pass --yes to confirm")?;
632 Ok(false)
633 }
634 }
635 }
636
637 pub(crate) fn show_preview(&self, preview: &PreviewResponse) -> Result<(), CliError> {
639 self.output.line(&format!(
640 "preview against revision {}:",
641 preview.base_revision
642 ))?;
643 if preview.diff.is_empty() {
644 self.output.line("(no textual change)")?;
645 } else {
646 self.output.line(sanitize(&preview.diff).trim_end())?;
647 }
648 if !preview.changes.is_empty() {
649 self.output.line("changes:")?;
650 for change in &preview.changes {
651 let old = change
652 .old
653 .as_ref()
654 .map_or_else(|| "unset".to_owned(), compact);
655 self.output.line(&sanitize(&format!(
656 " {}: {old} -> {} ({})",
657 change.path,
658 compact(&change.new),
659 change.apply_class
660 )))?;
661 }
662 }
663 self.output.line(&format!(
664 "strictest apply class: {}",
665 preview
666 .strictest_apply_class
667 .as_deref()
668 .map_or_else(|| "none".to_owned(), sanitize)
669 ))?;
670 for error in &preview.errors {
671 self.output
672 .line(&format!("invalid: {}", validation_line(error)))?;
673 }
674 Ok(())
675 }
676
677 pub(crate) fn show_claim(&self, body: &ClaimBody) -> Result<(), CliError> {
679 let fields = [
680 ("node", body.node().to_string()),
681 ("claimant", body.claimant().to_string()),
682 ("nonce", body.nonce().to_string()),
683 ("expires at", body.expires_at().to_string()),
684 ("base revision", body.base_revision().to_string()),
685 ("config sha256", body.config_sha256().to_string()),
686 ];
687 self.output.note("claim body:")?;
688 for (name, value) in fields {
689 self.output.note(&format!(" {name}: {value}"))?;
690 }
691 Ok(())
692 }
693
694 fn print_identity(&self, did: &DidNostr, path: &Path) -> Result<u8, CliError> {
696 self.output.json(&json!({
697 "did": did,
698 "npub": did.to_npub(),
699 "key_file": path.display().to_string(),
700 }))?;
701 self.output.line(&did.to_string())?;
702 self.output.line(&did.to_npub())?;
703 Ok(exit::OK)
704 }
705}
706
707pub(crate) fn readyz(client: &Client) -> Result<Readyz, CliError> {
709 let response: Response = client.get(READYZ, None)?;
710 let (ready, _raw): (Readyz, Json) = match response.status {
711 200 | 503 => response.parse()?,
712 _ => return Err(response.into_error()),
713 };
714 if ready.api_version != API_VERSION {
715 return Err(CliError::Protocol(format!(
716 "the node speaks API version {}; this client speaks {API_VERSION}",
717 ready.api_version
718 )));
719 }
720 Ok(ready)
721}
722
723pub(crate) fn check_expected_node(
726 actual: DidNostr,
727 expected: Option<&DidNostr>,
728) -> Result<(), CliError> {
729 match expected {
730 Some(expected) if *expected != actual => Err(CliError::Refused(format!(
731 "the node at this url reports {actual}, not the expected {expected}"
732 ))),
733 _ => Ok(()),
734 }
735}
736
737fn check_manifest_content(
740 content: &str,
741 node: DidNostr,
742 checkpoint: &str,
743) -> Result<BackupManifest, CliError> {
744 let not_manifest =
745 || CliError::Refused("the signed event is not a stratum backup manifest".to_owned());
746 let value: Json = serde_json::from_str(content).map_err(|_| not_manifest())?;
747 if value.get("format").and_then(Json::as_str) != Some(BACKUP_FORMAT) {
748 return Err(not_manifest());
749 }
750 let version = value.get("format_version").and_then(Json::as_u64);
751 let (pods_rule, files) = match version {
755 Some(BACKUP_FORMAT_VERSION) => (Some(false), BACKUP_FILES),
756 Some(BACKUP_FORMAT_VERSION_PODS) => (Some(true), BACKUP_FILES),
757 Some(BACKUP_FORMAT_VERSION_SEALED) => (None, BACKUP_FILES_SEALED),
758 _ => {
759 return Err(CliError::Refused(format!(
760 "the backup manifest has format version {}; this client reads versions \
761 {BACKUP_FORMAT_VERSION}, {BACKUP_FORMAT_VERSION_PODS} and \
762 {BACKUP_FORMAT_VERSION_SEALED}",
763 version.map_or_else(|| "none".to_owned(), |v| v.to_string())
764 )));
765 }
766 };
767 let manifest = BackupManifest::deserialize(&value).map_err(|_| not_manifest())?;
768 let pods = manifest.pod_archive.is_some();
769 if manifest.format != BACKUP_FORMAT
770 || Some(manifest.format_version) != version
771 || pods_rule.is_some_and(|required| required != pods)
772 {
773 return Err(not_manifest());
774 }
775 if manifest.node_did != node {
776 return Err(CliError::Refused(format!(
777 "the backup manifest is for node {}, not {node}",
778 manifest.node_did
779 )));
780 }
781 if manifest.audit_checkpoint != checkpoint {
782 return Err(CliError::Refused(format!(
783 "the signed manifest's audit checkpoint {} differs from the reported {checkpoint}",
784 sanitize(&manifest.audit_checkpoint)
785 )));
786 }
787 let mut expected = files.to_vec();
788 if pods {
789 expected.push(BACKUP_POD_ARCHIVE);
790 }
791 if !manifest
792 .files
793 .iter()
794 .map(|file| file.name.as_str())
795 .eq(expected.iter().copied())
796 {
797 return Err(CliError::Refused(format!(
798 "the backup manifest does not list exactly {}",
799 expected.join(", ")
800 )));
801 }
802 Ok(manifest)
803}
804
805pub(crate) fn request_preview(
807 client: &Client,
808 base_revision: u64,
809 changes: &[Change],
810 key: Option<&NostrSecretKey>,
811) -> Result<(PreviewResponse, Json), CliError> {
812 let body = to_body(&PreviewRequest {
813 base_revision,
814 changes,
815 })?;
816 let (preview, raw): (PreviewResponse, Json) = client.post(PREVIEW, &body, key)?.into_json()?;
817 if preview.base_revision != base_revision {
818 return Err(CliError::Protocol(format!(
819 "preview is against revision {}, not the requested {base_revision}",
820 preview.base_revision
821 )));
822 }
823 Ok((preview, raw))
824}
825
826pub(crate) fn changes_from(sets: &[String]) -> Result<Vec<Change>, CliError> {
828 let changes = parse_changes(sets).map_err(|err| CliError::Usage(err.to_string()))?;
829 if changes.is_empty() {
830 return Err(CliError::Usage(
831 "give at least one --set path=value".to_owned(),
832 ));
833 }
834 Ok(changes)
835}
836
837pub(crate) fn to_body<T: Serialize>(request: &T) -> Result<Vec<u8>, CliError> {
839 serde_json::to_vec(request)
840 .map_err(|err| CliError::Local(format!("encoding the request failed: {err}")))
841}
842
843pub(crate) fn operation_id(given: Option<&str>) -> Result<OperationId, CliError> {
845 if let Some(text) = given {
846 return text
847 .parse()
848 .map_err(|err| CliError::Usage(format!("--operation-id: {err}")));
849 }
850 let random = client::random_32()?;
851 let text = format!("op-{}", hex::encode(&random[..16]));
852 text.parse()
853 .map_err(|err| CliError::Local(format!("generated operation id: {err}")))
854}
855
856pub(crate) fn invalid_preview(preview: &PreviewResponse) -> CliError {
858 CliError::InvalidPreview {
859 details: preview.errors.iter().map(validation_line).collect(),
860 }
861}
862
863fn validation_line(error: &crate::wire::ValidationEntry) -> String {
865 match &error.path {
866 Some(path) => sanitize(&format!("{path}: {}", error.message)),
867 None => sanitize(&error.message),
868 }
869}
870
871fn compact(value: &Json) -> String {
873 value.to_string()
874}
875
876pub(crate) fn claim_json(body: &ClaimBody) -> Json {
878 json!({
879 "nonce": body.nonce(),
880 "node": body.node(),
881 "claimant": body.claimant(),
882 "expires_at": body.expires_at(),
883 "base_revision": body.base_revision(),
884 "config_sha256": body.config_sha256(),
885 })
886}
887
888fn is_checkpoint(text: &str) -> bool {
890 text.split_once(':').is_some_and(|(seq, hash)| {
891 !seq.is_empty()
892 && seq.bytes().all(|b| b.is_ascii_digit())
893 && hash.len() == 64
894 && hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
895 })
896}
897
898#[cfg(test)]
899mod tests {
900 use std::time::Duration;
901
902 use super::BACKUP_TIMEOUT;
903
904 #[test]
908 fn backup_outwaits_the_nodes_drain_bound() {
909 assert!(
910 BACKUP_TIMEOUT > Duration::from_secs(90 + 60),
911 "the drain bound plus time to snapshot and archive"
912 );
913 }
914}