lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit 176a4f967a06872745ffeceec271fec837beb778
parent c638fb1665b200309a2621b0bd1891f2fe1e50d9
Author: triesap <tyson@radroots.org>
Date:   Sat, 17 Oct 2026 02:33:42 +0000

domain: add distinct fixed-width operation identities

- Implement order, thread, workspace, executor and operation identifier types.
- Validate canonical lowercase hex and preserve exact bytes through serde.
- Prove namespace separation, every ASCII position and unchanged value behavior.
- Verify native and WASM profiles, strict lint, measured coverage and contracts.

Diffstat:
Mcontracts/architecture/deviations.toml | 26++++++++++++++++++++++++++
Mcrates/domain/README.md | 20++++++++++++++++++++
Acrates/domain/src/identifier.rs | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/lib.rs | 2++
Acrates/domain/tests/identifier.rs | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 351 insertions(+), 0 deletions(-)

diff --git a/contracts/architecture/deviations.toml b/contracts/architecture/deviations.toml @@ -2,6 +2,32 @@ schema_version = 1 architecture_id = "radroots.crates.release.v1" [[deviation]] +id = "RCRV1-DEV-045" +date = "2026-10-17" +status = "closed" +approval = "The user authorizes the complete shared SDK refactor, verified checkpoints, source publication and master integration." +affected_steps = ["040", "050", "060", "130"] +spec_anchors = ["contracts/crates/release_v1/radroots_crates_release_v1.toml#release_policy"] +source_evidence = [ + "The approved shared SDK contract requires durable operation, order, thread, workspace and executor identities as distinct typed namespaces, with 32-byte or canonical lowercase hex64 representations. Command names, local row keys and host handles do not supply those identities.", + "The native domain amount prerequisite is already implemented and verified. Its validated value owner can implement identifier representation without I/O or unavailable Nix execution. Representation admission does not prove randomness, authority, signing, persistence or operation admission.", +] +replacement_action = "Independently implement five distinct opaque identifier types with fixed-width bytes, strict canonical string admission and serde, private fields and typed input-free errors. Keep generation in the later qualified entropy/execution owner, omit Default and cross-namespace aliases/conversions, and preserve existing source/tests until actual caller replacement. Keep the package unpublished and preserve its original introduction-tree identity." +verification = [ + "Validate this prospective record before source changes. Bind exact original domain source, unchanged package/catalog/lock inputs and retained amount tests.", + "Prove independent byte/hex vectors, all five namespaces, malformed/oversized/Unicode input, exact equality/hash, lossless string-only serde and compile-time namespace/width separation under native/default, no-default and serde-only profiles; compile actual WASM.", + "Run strict lint/docs, actual pinned-nightly coverage with the unchanged gate, catalog/native provenance, architecture, contracts and preflight. Preserve prior evidence scope and leave CSPRNG, actual execution, generated bindings, caller integration and platform/final acceptance open.", +] +unresolved_risk = "Only validated identifier representations are implemented here. Qualified random generation, authenticated contexts, retained receipt/admission, native/browser effects, generated calls, namespace/caller cutover and final platform acceptance remain separate obligations. Parsing an ID grants no authority." +normative_architecture_change = false +adr_required = false +closure_evidence = [ + "All five namespaces store exact private 32-byte values and admit only canonical lowercase hex64 strings. Independent byte vectors, every ASCII character at all 64 positions, malformed widths/Unicode, numeric-input refusal, equality/hash and all five serde paths pass. Separate compile-failure examples prove namespace and byte-width distinctions without an unused binding.", + "The complete domain package passes 22 default and serde-only cases, the same 18 non-serde cases without default features, and two compile-failure doctests in every tested profile. Stable native/WASM checking, warnings-denied Clippy/Rustdoc, catalog, architecture and contracts pass. The initial Clippy finding is retained and corrected with fixed-size array chunks; no lint exception was added.", + "Actual preserved coverage-nightly execution measures all 148 executable lines, every function/region and all 34 recorded branches covered under unchanged thresholds. Cargo, dependency locks, catalog/publication policy, original introduction provenance and all earlier amount test bodies remain unchanged. Generation, execution, bindings, consumers and final platform acceptance remain required.", +] + +[[deviation]] id = "RCRV1-DEV-044" date = "2026-10-17" status = "closed" diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -16,4 +16,24 @@ The package supports `no_std`; `serde` and `std` are independent features. It performs no I/O, clock, randomness, storage or network work. Currency and economic rules remain separate implementation requirements. +Order, thread, workspace, executor and operation IDs have distinct Rust types. +Each stores 32 bytes and uses exactly 64 lowercase hexadecimal characters in +strings and JSON. Byte/string construction validates representation; generation +belongs to the execution owner's qualified CSPRNG boundary. + +Namespaces remain separate across native calls: + +```compile_fail +use radroots_domain::{OperationId, WorkspaceId}; +let operation = OperationId::from_bytes([0; 32]); +let _: WorkspaceId = operation; +``` + +Byte inputs have a fixed width: + +```compile_fail +use radroots_domain::OperationId; +let _ = OperationId::from_bytes([0; 31]); +``` + Licensed under MIT OR Apache-2.0; see LICENSE-MIT and LICENSE-APACHE. diff --git a/crates/domain/src/identifier.rs b/crates/domain/src/identifier.rs @@ -0,0 +1,124 @@ +use core::{fmt, str::FromStr}; + +/// An identifier representation failure with no retained input or context. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum IdentifierError { + /// The string does not contain exactly 64 bytes. + InvalidLength, + /// A character is outside lowercase ASCII hexadecimal. + InvalidEncoding, +} + +impl fmt::Display for IdentifierError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidLength => "identifier must contain 64 hexadecimal characters", + Self::InvalidEncoding => "identifier must use lowercase ASCII hexadecimal", + }) + } +} + +impl core::error::Error for IdentifierError {} + +fn nibble(byte: u8) -> Result<u8, IdentifierError> { + match byte { + b'0'..=b'9' => Ok(byte - b'0'), + b'a'..=b'f' => Ok(byte - b'a' + 10), + _ => Err(IdentifierError::InvalidEncoding), + } +} + +fn parse(input: &str) -> Result<[u8; 32], IdentifierError> { + if input.len() != 64 { + return Err(IdentifierError::InvalidLength); + } + let mut bytes = [0; 32]; + // Validated width gives exactly 32 complete pairs, with no remainder. + let (pairs, _) = input.as_bytes().as_chunks::<2>(); + for (target, &[high, low]) in bytes.iter_mut().zip(pairs) { + *target = nibble(high)? << 4 | nibble(low)?; + } + Ok(bytes) +} + +macro_rules! identifier { + ($name:ident, $description:literal) => { + #[doc = $description] + #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub struct $name([u8; 32]); + + impl $name { + /// Constructs the fixed-width representation; generation belongs to + /// the execution owner's qualified entropy boundary. + pub const fn from_bytes(bytes: [u8; 32]) -> Self { + Self(bytes) + } + + /// Borrows the exact identifier bytes without conversion. + pub const fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } + + /// Returns the exact identifier bytes without conversion. + pub const fn into_bytes(self) -> [u8; 32] { + self.0 + } + } + + impl FromStr for $name { + type Err = IdentifierError; + + fn from_str(input: &str) -> Result<Self, Self::Err> { + parse(input).map(Self) + } + } + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for byte in self.0 { + write!(f, "{byte:02x}")?; + } + Ok(()) + } + } + + #[cfg(feature = "serde")] + impl serde::Serialize for $name { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.collect_str(self) + } + } + + #[cfg(feature = "serde")] + impl<'de> serde::Deserialize<'de> for $name { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + struct IdentifierVisitor; + impl serde::de::Visitor<'_> for IdentifierVisitor { + type Value = $name; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a canonical lowercase hexadecimal identifier") + } + + fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<$name, E> { + value.parse().map_err(E::custom) + } + } + deserializer.deserialize_str(IdentifierVisitor) + } + } + }; +} + +identifier!(OrderId, "An exact 256-bit bilateral order identifier."); +identifier!(ThreadId, "An exact 256-bit private thread identifier."); +identifier!( + WorkspaceId, + "An exact 256-bit participant workspace identifier." +); +identifier!(ExecutorId, "An exact 256-bit selected executor identifier."); +identifier!( + OperationId, + "An exact 256-bit retained operation identifier." +); diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -4,5 +4,7 @@ #![warn(missing_docs)] mod amount; +mod identifier; pub use amount::{AmountError, Decimal, PositiveDecimal}; +pub use identifier::{ExecutorId, IdentifierError, OperationId, OrderId, ThreadId, WorkspaceId}; diff --git a/crates/domain/tests/identifier.rs b/crates/domain/tests/identifier.rs @@ -0,0 +1,179 @@ +use radroots_domain::{ExecutorId, IdentifierError, OperationId, OrderId, ThreadId, WorkspaceId}; +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, +}; + +const SEQUENTIAL: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"; + +#[test] +fn all_namespaces_match_independent_byte_and_hex_vectors() { + let bytes = core::array::from_fn(|i| i as u8); + macro_rules! check { + ($t:ty) => {{ + let id = <$t>::from_bytes(bytes); + assert_eq!(id.as_bytes(), &bytes); + assert_eq!(id.into_bytes(), bytes); + assert_eq!(id.to_string(), SEQUENTIAL); + assert_eq!(SEQUENTIAL.parse::<$t>().unwrap(), id); + let largest = <$t>::from_bytes([255; 32]); + assert_eq!(largest.to_string(), "f".repeat(64)); + assert_eq!(largest.to_string().parse::<$t>().unwrap(), largest); + }}; + } + check!(OrderId); + check!(ThreadId); + check!(WorkspaceId); + check!(ExecutorId); + check!(OperationId); +} + +#[test] +fn all_namespaces_reject_wrong_lengths_before_decoding() { + for input in [ + String::new(), + "0".repeat(63), + "0".repeat(65), + "0x".to_owned() + SEQUENTIAL, + "0".repeat(65_536), + ] { + macro_rules! check { + ($t:ty) => { + assert_eq!(input.parse::<$t>(), Err(IdentifierError::InvalidLength)); + }; + } + check!(OrderId); + check!(ThreadId); + check!(WorkspaceId); + check!(ExecutorId); + check!(OperationId); + } +} + +#[test] +fn encoding_is_ascii_lowercase_without_trimming_or_case_folding() { + for input in [ + "A".repeat(64), + "g".repeat(64), + "é".repeat(32), + " ".repeat(64), + "0".repeat(63) + "\n", + "0".repeat(63) + "\0", + "a".repeat(63) + "F", + ] { + macro_rules! check { + ($t:ty) => { + assert_eq!(input.parse::<$t>(), Err(IdentifierError::InvalidEncoding)); + }; + } + check!(OrderId); + check!(ThreadId); + check!(WorkspaceId); + check!(ExecutorId); + check!(OperationId); + } +} + +#[test] +fn every_ascii_character_is_checked_in_each_nibble_position() { + for byte in 0..=127_u8 { + for offset in 0..64 { + let mut input = [b'0'; 64]; + input[offset] = byte; + let result = core::str::from_utf8(&input).unwrap().parse::<OperationId>(); + if byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte) { + assert_eq!(result.unwrap().to_string().as_bytes(), input); + } else { + assert_eq!(result, Err(IdentifierError::InvalidEncoding)); + } + } + } +} + +#[test] +fn equality_order_and_hash_are_exact_bytes_within_each_namespace() { + fn hash<T: Hash>(value: &T) -> u64 { + let mut hasher = DefaultHasher::new(); + value.hash(&mut hasher); + hasher.finish() + } + macro_rules! check { + ($t:ty) => {{ + let id = SEQUENTIAL.parse::<$t>().unwrap(); + let copy = <$t>::from_bytes(id.into_bytes()); + assert_eq!(id, copy); + assert_eq!(hash(&id), hash(&copy)); + let mut bytes = id.into_bytes(); + bytes[31] += 1; + let later = <$t>::from_bytes(bytes); + assert_ne!(id, later); + assert!(id < later); + assert_eq!(id.partial_cmp(&later), Some(core::cmp::Ordering::Less)); + }}; + } + check!(OrderId); + check!(ThreadId); + check!(WorkspaceId); + check!(ExecutorId); + check!(OperationId); +} + +#[test] +fn errors_are_typed_bounded_and_do_not_retain_input() { + let errors = [ + IdentifierError::InvalidLength, + IdentifierError::InvalidEncoding, + ]; + for error in errors { + let object: &dyn core::error::Error = &error; + assert!(object.source().is_none()); + assert!(error.to_string().len() <= 64); + assert!(!format!("{error:?}").contains("sensitive_fixture")); + } + assert_ne!(errors[0].to_string(), errors[1].to_string()); +} + +#[cfg(feature = "serde")] +mod json { + use super::*; + + #[test] + fn each_namespace_round_trips_as_one_lossless_canonical_string() { + let encoded = format!("\"{SEQUENTIAL}\""); + macro_rules! check { + ($t:ty) => {{ + let id = SEQUENTIAL.parse::<$t>().unwrap(); + assert_eq!(serde_json::to_string(&id).unwrap(), encoded); + assert_eq!(serde_json::from_str::<$t>(&encoded).unwrap(), id); + }}; + } + check!(OrderId); + check!(ThreadId); + check!(WorkspaceId); + check!(ExecutorId); + check!(OperationId); + } + + #[test] + fn json_cannot_bypass_string_width_or_encoding_validation() { + for encoded in [ + "0".to_owned(), + "null".to_owned(), + "{}".to_owned(), + "[0]".to_owned(), + "\"0\"".to_owned(), + format!("\"{}\"", "F".repeat(64)), + ] { + macro_rules! check { + ($t:ty) => { + assert!(serde_json::from_str::<$t>(&encoded).is_err(), "{encoded}"); + }; + } + check!(OrderId); + check!(ThreadId); + check!(WorkspaceId); + check!(ExecutorId); + check!(OperationId); + } + } +}