lib

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

commit 329978dbfbd7e1044a12d882c5f5ecf543f16638
parent 4b4aa8a7feaab08492c3f596df9182070ee8d814
Author: triesap <tyson@radroots.org>
Date:   Thu, 22 Oct 2026 14:47:31 +0000

domain: add pinned exact currency and money values

- Add validated currency, minor amount and money APIs with exact checked arithmetic.
- Require canonical string amounts, explicit exponents and closed object admission.
- Retain pinned registry provenance, licenses and notices with immutable source guards.
- Verify feature portability, public API, package contents and unchanged coverage gates.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acontracts/architecture/decisions/currency_registry.v1.json | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/Cargo.toml | 2+-
Mcrates/domain/README.md | 18+++++++++++++++---
Acrates/domain/data/currency_registry_v1.csv | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/domain/data/currency_registry_v1.license | 201+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/domain/data/currency_registry_v1.notice | 23+++++++++++++++++++++++
Acrates/domain/src/currency.rs | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/lib.rs | 7+++++++
Acrates/domain/src/money.rs | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/tests/context.rs | 192+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Mcrates/domain/tests/listing.rs | 3+++
Acrates/domain/tests/money.rs | 291++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/architecture/decision_package.rs | 5++++-
Atools/xtask/src/architecture/decision_package/currency_registry.rs | 309+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
15 files changed, 1697 insertions(+), 88 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -141,6 +141,14 @@ pub fn radroots_domain::ContextError::fmt(&self, &mut core::fmt::Formatter<'_>) #[non_exhaustive] pub enum radroots_domain::Coverage pub radroots_domain::Coverage::Partial pub radroots_domain::Coverage::ScopeSatisfied +#[non_exhaustive] pub enum radroots_domain::CurrencyError +pub radroots_domain::CurrencyError::InvalidFormat +pub radroots_domain::CurrencyError::UnsupportedCode +impl core::convert::From<radroots_domain::CurrencyError> for radroots_domain::MoneyError +pub fn radroots_domain::MoneyError::from(radroots_domain::CurrencyError) -> Self +impl core::error::Error for radroots_domain::CurrencyError +impl core::fmt::Display for radroots_domain::CurrencyError +pub fn radroots_domain::CurrencyError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_domain::IdentifierError pub radroots_domain::IdentifierError::InvalidEncoding pub radroots_domain::IdentifierError::InvalidLength @@ -152,6 +160,21 @@ pub radroots_domain::MessageError::LimitExceeded impl core::error::Error for radroots_domain::MessageError impl core::fmt::Display for radroots_domain::MessageError pub fn radroots_domain::MessageError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::MoneyError +pub radroots_domain::MoneyError::Currency(radroots_domain::CurrencyError) +pub radroots_domain::MoneyError::CurrencyMismatch +pub radroots_domain::MoneyError::ExponentMismatch +pub radroots_domain::MoneyError::InvalidExponent +pub radroots_domain::MoneyError::InvalidMinorFormat +pub radroots_domain::MoneyError::MinorOutOfRange +pub radroots_domain::MoneyError::NegativeResult +pub radroots_domain::MoneyError::NonCanonicalMinor +impl core::convert::From<radroots_domain::CurrencyError> for radroots_domain::MoneyError +pub fn radroots_domain::MoneyError::from(radroots_domain::CurrencyError) -> Self +impl core::error::Error for radroots_domain::MoneyError +pub fn radroots_domain::MoneyError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)> +impl core::fmt::Display for radroots_domain::MoneyError +pub fn radroots_domain::MoneyError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::ActorRef impl radroots_domain::ActorRef pub const fn radroots_domain::ActorRef::grant_id(self) -> core::option::Option<radroots_domain::GrantId> @@ -265,6 +288,21 @@ impl serde_core::ser::Serialize for radroots_domain::CorrelationId pub fn radroots_domain::CorrelationId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::CorrelationId pub fn radroots_domain::CorrelationId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::Currency +impl radroots_domain::Currency +pub const fn radroots_domain::Currency::code(self) -> &'static str +pub const fn radroots_domain::Currency::exponent(self) -> u8 +pub fn radroots_domain::Currency::from_code(&str) -> core::result::Result<Self, radroots_domain::CurrencyError> +pub fn radroots_domain::Currency::supported() -> impl core::iter::traits::iterator::Iterator<Item = Self> + core::clone::Clone +impl core::fmt::Debug for radroots_domain::Currency +pub fn radroots_domain::Currency::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::Currency +pub type radroots_domain::Currency::Err = radroots_domain::CurrencyError +pub fn radroots_domain::Currency::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::Currency +pub fn radroots_domain::Currency::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Currency +pub fn radroots_domain::Currency::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::Decimal impl radroots_domain::Decimal pub const radroots_domain::Decimal::MAX: Self @@ -396,6 +434,42 @@ impl serde_core::ser::Serialize for radroots_domain::MessageId pub fn radroots_domain::MessageId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::MessageId pub fn radroots_domain::MessageId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::MinorAmount(_) +impl radroots_domain::MinorAmount +pub const radroots_domain::MinorAmount::MAX: Self +pub const radroots_domain::MinorAmount::MAX_VALUE: u64 +pub const radroots_domain::MinorAmount::ZERO: Self +pub const fn radroots_domain::MinorAmount::get(self) -> u64 +pub const fn radroots_domain::MinorAmount::new(u64) -> core::result::Result<Self, radroots_domain::MoneyError> +impl core::convert::TryFrom<u64> for radroots_domain::MinorAmount +pub type radroots_domain::MinorAmount::Error = radroots_domain::MoneyError +pub fn radroots_domain::MinorAmount::try_from(u64) -> core::result::Result<Self, Self::Error> +impl core::fmt::Debug for radroots_domain::MinorAmount +pub fn radroots_domain::MinorAmount::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for radroots_domain::MinorAmount +pub fn radroots_domain::MinorAmount::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::MinorAmount +pub type radroots_domain::MinorAmount::Err = radroots_domain::MoneyError +pub fn radroots_domain::MinorAmount::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::MinorAmount +pub fn radroots_domain::MinorAmount::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::MinorAmount +pub fn radroots_domain::MinorAmount::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::Money +impl radroots_domain::Money +pub fn radroots_domain::Money::checked_add(self, Self) -> core::result::Result<Self, radroots_domain::MoneyError> +pub fn radroots_domain::Money::checked_sub(self, Self) -> core::result::Result<Self, radroots_domain::MoneyError> +pub const fn radroots_domain::Money::currency(self) -> radroots_domain::Currency +pub const fn radroots_domain::Money::exponent(self) -> u8 +pub fn radroots_domain::Money::from_parts(&str, &str, u8) -> core::result::Result<Self, radroots_domain::MoneyError> +pub const fn radroots_domain::Money::minor(self) -> radroots_domain::MinorAmount +pub const fn radroots_domain::Money::new(radroots_domain::Currency, radroots_domain::MinorAmount) -> Self +impl core::fmt::Debug for radroots_domain::Money +pub fn radroots_domain::Money::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_domain::Money +pub fn radroots_domain::Money::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Money +pub fn radroots_domain::Money::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::OperationId(_) impl radroots_domain::OperationId pub const fn radroots_domain::OperationId::as_bytes(&self) -> &[u8; 32] @@ -567,4 +641,7 @@ pub fn radroots_domain::WorkspaceId::serialize<S: serde_core::ser::Serializer>(& impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::WorkspaceId pub fn radroots_domain::WorkspaceId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub const radroots_domain::CHAT_MAX_BYTES: usize +pub const radroots_domain::CURRENCY_REGISTRY_ID: &str +pub const radroots_domain::CURRENCY_REGISTRY_SHA256: &str pub const radroots_domain::FIRST_ISSUANCE_MAX_SECONDS: u64 +pub const radroots_domain::SUPPORTED_CURRENCY_COUNT: usize diff --git a/contracts/architecture/decisions/currency_registry.v1.json b/contracts/architecture/decisions/currency_registry.v1.json @@ -0,0 +1,50 @@ +{ + "schema_version": 1, + "contract_id": "radroots.currency_registry.v1", + "state": "pinned_data_source", + "registry_id": "radroots.currency_registry.v1", + "implementation": "independent_rust_api_over_minimal_pinned_data", + "upstream": { + "repository": "https://github.com/rust-iso/rust_iso4217", + "revision": "ce6b74546b3645ce11866acc93117128d2f7b1e0", + "path": "src/lib.rs", + "sha256": "7401727ea4da05fcbf0d1d679705c0245989e83dbc697e831066f992875e183d", + "license": "Apache-2.0", + "license_sha256": "665618a8c4b9ef6ceafb35482a3e010834fae9e9cbb22041b74310bcc52ac500", + "copyright": "Copyright 2023-2026 rust_iso4217 contributors" + }, + "data": { + "path": "crates/domain/data/currency_registry_v1.csv", + "sha256": "60d8282b2d7ddc27929b097d4de9e76a900a64f1de4a5aa7a4cb3308b55b82d0", + "entries": 165, + "minimum_exponent": 0, + "maximum_exponent": 4, + "current_currency_and_funds_only": true, + "historic_entries_excluded": true, + "no_minor_unit_entries_excluded": true, + "guessed_default_exponents_allowed": false + }, + "notices": { + "license_path": "crates/domain/data/currency_registry_v1.license", + "license_sha256": "665618a8c4b9ef6ceafb35482a3e010834fae9e9cbb22041b74310bcc52ac500", + "notice_path": "crates/domain/data/currency_registry_v1.notice", + "notice_sha256": "c43ef0d0f9d6f64656ca6a619c3c43cd9cc2b378217ab19a083ca92255a91d7d", + "source_distribution_required": true, + "derived_artifact_inclusion_required_before_adoption": true, + "crate_owned_rust_license_unchanged": true + }, + "independent_crosscheck": { + "authority": "SIX ISO 4217 Maintenance Agency", + "url": "https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml", + "publication_date": "2026-09-17", + "source_sha256": "33139b438657d1cee116ba737807ea71d19d6de4b90f799a09c56f0cc6a1b0ff", + "all_selected_pairs_equal": true, + "official_xml_redistributed": false + }, + "limits": { + "runtime_io_allowed": false, + "automatic_updates_allowed": false, + "exchange_or_payment_semantics_allowed": false, + "qualified_economics_or_agreement_authoring_claimed": false + } +} diff --git a/crates/domain/Cargo.toml b/crates/domain/Cargo.toml @@ -10,7 +10,7 @@ repository.workspace = true homepage.workspace = true description = "Exact values and deterministic shared Radroots domain invariants" readme = "README.md" -include = ["src/**", "tests/**", "Cargo.toml", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +include = ["src/**", "tests/**", "data/**", "Cargo.toml", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] [features] default = ["std", "serde"] diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -12,8 +12,16 @@ reject results outside the supported representation. No floating conversion or implicit rounding is available. 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. +It performs no I/O, clock, randomness, storage or network work. + +`Currency` admits the 165 fixed supported currency/fund codes and their exact +minor-unit exponents. Unknown codes and unavailable minor units never receive +a guessed exponent. `MinorAmount` admits canonical integer strings up to +999999999999999. `Money` checks the explicit wire exponent against that registry +and performs checked signed 128-bit addition/subtraction within one currency. +JSON minor amounts remain strings; private monetary diagnostics are redacted. +Pricing, rounding, complete agreement terms and command effects remain separate +implementation requirements. Explicit zero money does not imply a price mode. Order, thread, workspace, executor and operation IDs have distinct Rust types. Each stores 32 bytes and uses exactly 64 lowercase hexadecimal characters in @@ -59,4 +67,8 @@ empty text and Unicode contents are preserved exactly. Private text uses zeroizing owned storage and redacted diagnostics, with no automatic payload serialization. Constructing a value proves no signature, history or installation. -Licensed under MIT OR Apache-2.0; see LICENSE-MIT and LICENSE-APACHE. +Crate-owned Rust is licensed under MIT OR Apache-2.0; see LICENSE-MIT and +LICENSE-APACHE. The minimal derived currency data retains its upstream +Apache-2.0 license, copyright and attribution in +`data/currency_registry_v1.license` and `data/currency_registry_v1.notice`. +No upstream Rust/generator, country/name data or official XML is included. diff --git a/crates/domain/data/currency_registry_v1.csv b/crates/domain/data/currency_registry_v1.csv @@ -0,0 +1,171 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2023-2026 rust_iso4217 contributors +# Derived from rust-iso/rust_iso4217 ce6b74546b3645ce11866acc93117128d2f7b1e0. +# Modified by Radroots: retain current currency/fund code and exponent pairs +# in range 0-4; sort by code; omit all names, countries, other data and code. +# See currency_registry_v1.license and currency_registry_v1.notice. +AED,2 +AFN,2 +ALL,2 +AMD,2 +AOA,2 +ARS,2 +AUD,2 +AWG,2 +AZN,2 +BAM,2 +BBD,2 +BDT,2 +BHD,3 +BIF,0 +BMD,2 +BND,2 +BOB,2 +BOV,2 +BRL,2 +BSD,2 +BTN,2 +BWP,2 +BYN,2 +BZD,2 +CAD,2 +CDF,2 +CHE,2 +CHF,2 +CHW,2 +CLF,4 +CLP,0 +CNY,2 +COP,2 +COU,2 +CRC,2 +CUP,2 +CVE,2 +CZK,2 +DJF,0 +DKK,2 +DOP,2 +DZD,2 +EGP,2 +ERN,2 +ETB,2 +EUR,2 +FJD,2 +FKP,2 +GBP,2 +GEL,2 +GHS,2 +GIP,2 +GMD,2 +GNF,0 +GTQ,2 +GYD,2 +HKD,2 +HNL,2 +HTG,2 +HUF,2 +IDR,2 +ILS,2 +INR,2 +IQD,3 +IRR,2 +ISK,0 +JMD,2 +JOD,3 +JPY,0 +KES,2 +KGS,2 +KHR,2 +KMF,0 +KPW,2 +KRW,0 +KWD,3 +KYD,2 +KZT,2 +LAK,2 +LBP,2 +LKR,2 +LRD,2 +LSL,2 +LYD,3 +MAD,2 +MDL,2 +MGA,2 +MKD,2 +MMK,2 +MNT,2 +MOP,2 +MRU,2 +MUR,2 +MVR,2 +MWK,2 +MXN,2 +MXV,2 +MYR,2 +MZN,2 +NAD,2 +NGN,2 +NIO,2 +NOK,2 +NPR,2 +NZD,2 +OMR,3 +PAB,2 +PEN,2 +PGK,2 +PHP,2 +PKR,2 +PLN,2 +PYG,0 +QAR,2 +RON,2 +RSD,2 +RUB,2 +RWF,0 +SAR,2 +SBD,2 +SCR,2 +SDG,2 +SEK,2 +SGD,2 +SHP,2 +SLE,2 +SOS,2 +SRD,2 +SSP,2 +STN,2 +SVC,2 +SYP,2 +SZL,2 +THB,2 +TJS,2 +TMT,2 +TND,3 +TOP,2 +TRY,2 +TTD,2 +TWD,2 +TZS,2 +UAH,2 +UGX,0 +USD,2 +USN,2 +UYI,0 +UYU,2 +UYW,4 +UZS,2 +VED,2 +VES,2 +VND,0 +VUV,0 +WST,2 +XAD,2 +XAF,0 +XCD,2 +XCG,2 +XOF,0 +XPF,0 +YER,2 +ZAR,2 +ZMW,2 +ZWG,2 diff --git a/crates/domain/data/currency_registry_v1.license b/crates/domain/data/currency_registry_v1.license @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023-2026 rust_iso4217 contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/domain/data/currency_registry_v1.notice b/crates/domain/data/currency_registry_v1.notice @@ -0,0 +1,23 @@ +Currency registry v1 data attribution + +Copyright 2023-2026 rust_iso4217 contributors +Apache License 2.0; see currency_registry_v1.license. + +Source: https://github.com/rust-iso/rust_iso4217 +Revision: ce6b74546b3645ce11866acc93117128d2f7b1e0 +Original material: src/lib.rs (SHA256 7401727ea4da05fcbf0d1d679705c0245989e83dbc697e831066f992875e183d). + +Radroots changes: extract only current currency/fund alphabetic code and +minor-unit exponent facts in range 0-4; sort them; omit historic entries, +no-minor-unit entries, names, countries, numeric identifiers and all upstream +Rust/generator implementation. The Rust API is independently implemented. +This derived data retains the upstream Apache-2.0 license and attribution. + +The publisher identifies SIX ISO 4217 lists as its currency source and Datahub +as its country-relationship source. No country relationships are included here. +All 165 selected pairs match the separately acquired official SIX List One +snapshot published 2026-09-17. The XML and ISO standard text are not distributed. +No cash/display rounding, exchange rate, payment rule or currency conversion +is implied. The registry is fixed; replacement requires explicit versioned +contract and provenance review. Derived artifacts must include this material +and its license/notice before adopting it. diff --git a/crates/domain/src/currency.rs b/crates/domain/src/currency.rs @@ -0,0 +1,163 @@ +use core::{fmt, str::FromStr}; + +/// Immutable supported code/exponent data contract. No runtime update is implied. +pub const CURRENCY_REGISTRY_ID: &str = "radroots.currency_registry.v1"; +/// SHA256 of the complete attributed source data used by this registry. +pub const CURRENCY_REGISTRY_SHA256: &str = + "60d8282b2d7ddc27929b097d4de9e76a900a64f1de4a5aa7a4cb3308b55b82d0"; + +const DATA: &str = include_str!("../data/currency_registry_v1.csv"); + +/// Number of supported currencies/funds in the fixed registry. +pub const SUPPORTED_CURRENCY_COUNT: usize = { + let bytes = DATA.as_bytes(); + let mut position = 0; + let mut count = 0; + let mut previous = [0_u8; 3]; + while position < bytes.len() { + if bytes[position] == b'#' { + while position < bytes.len() && bytes[position] != b'\n' { + position += 1; + } + assert!(position < bytes.len(), "unterminated registry attribution"); + position += 1; + continue; + } + assert!(position + 6 <= bytes.len(), "truncated currency row"); + let code = [bytes[position], bytes[position + 1], bytes[position + 2]]; + assert!( + code[0].is_ascii_uppercase() + && code[1].is_ascii_uppercase() + && code[2].is_ascii_uppercase(), + "noncanonical registry code" + ); + assert!( + bytes[position + 3] == b',' + && bytes[position + 4] >= b'0' + && bytes[position + 4] <= b'4' + && bytes[position + 5] == b'\n', + "invalid registry exponent or row" + ); + assert!( + count == 0 + || code[0] > previous[0] + || (code[0] == previous[0] && code[1] > previous[1]) + || (code[0] == previous[0] && code[1] == previous[1] && code[2] > previous[2]), + "unsorted or duplicate registry code" + ); + previous = code; + count += 1; + position += 6; + } + assert!(count == 165, "registry v1 membership changed"); + count +}; + +/// A validated supported currency/fund and its exact minor-unit exponent. +/// +/// This represents the fixed registry, without exchange, cash/display rounding, +/// payment or present-day legal-tender claims. +#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct Currency { + code: &'static str, + exponent: u8, +} + +/// Input-free currency admission failure; no fallback exponent is inferred. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum CurrencyError { + /// The code is not exactly three uppercase ASCII letters. + InvalidFormat, + /// The code has no supported numeric exponent in this fixed registry. + UnsupportedCode, +} + +impl Currency { + /// Admits exactly a supported uppercase ASCII code without allocation. + pub fn from_code(code: &str) -> Result<Self, CurrencyError> { + if code.len() != 3 || !code.bytes().all(|byte| byte.is_ascii_uppercase()) { + return Err(CurrencyError::InvalidFormat); + } + Self::supported() + .find(|currency| currency.code == code) + .ok_or(CurrencyError::UnsupportedCode) + } + + /// Iterates the fixed supported registry in canonical code order. + pub fn supported() -> impl Iterator<Item = Self> + Clone { + DATA.lines() + .filter(|line| !line.starts_with('#')) + .map(|line| { + // The compile-time data check proves every non-comment row is + // six ASCII bytes, including its newline, with an exponent 0-4. + Self { + code: &line[..3], + exponent: line.as_bytes()[4] - b'0', + } + }) + } + + /// Returns the canonical supported three-letter code. + pub const fn code(self) -> &'static str { + self.code + } + + /// Returns the fixed exponent; this is not a presentation-rounding rule. + pub const fn exponent(self) -> u8 { + self.exponent + } +} + +impl FromStr for Currency { + type Err = CurrencyError; + fn from_str(value: &str) -> Result<Self, Self::Err> { + Self::from_code(value) + } +} + +impl fmt::Debug for Currency { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Currency(<validated>)") + } +} + +impl fmt::Display for CurrencyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidFormat => "invalid currency code format", + Self::UnsupportedCode => "unsupported currency code", + }) + } +} + +impl core::error::Error for CurrencyError {} + +#[cfg(feature = "serde")] +mod serde_impl { + use super::Currency; + use core::fmt; + use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; + + impl Serialize for Currency { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.serialize_str(self.code()) + } + } + + impl<'de> Deserialize<'de> for Currency { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + struct Visitor; + impl de::Visitor<'_> for Visitor { + type Value = Currency; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a supported uppercase currency code") + } + fn visit_str<E: de::Error>(self, value: &str) -> Result<Currency, E> { + Currency::from_code(value).map_err(E::custom) + } + } + deserializer.deserialize_str(Visitor) + } + } +} diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -7,11 +7,13 @@ extern crate alloc; mod amount; mod context; +mod currency; mod identifier; mod issuance; /// Validated public-offer values; these establish no stock or command authority. pub mod listing; mod message; +mod money; /// The identity-owned validated participant key; no second key type is defined. pub use radroots_identity::PublicKey; @@ -21,6 +23,10 @@ pub use context::{ ActorRef, ActorRole, Approval, AuthorityRef, CheckpointRef, CommandContextData, ContextError, CorrelationId, Coverage, ExpectedOrder, Generation, Sequence, UnixSeconds, }; +pub use currency::{ + CURRENCY_REGISTRY_ID, CURRENCY_REGISTRY_SHA256, Currency, CurrencyError, + SUPPORTED_CURRENCY_COUNT, +}; pub use identifier::{ ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, ExecutorId, GrantId, IdentifierError, ListingOptionId, MessageId, OperationId, OrderId, RecordId, RouteDigest, @@ -28,3 +34,4 @@ pub use identifier::{ }; pub use issuance::{FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow}; pub use message::{CHAT_MAX_BYTES, ChatMessage, ChatRelation, MessageError}; +pub use money::{MinorAmount, Money, MoneyError}; diff --git a/crates/domain/src/money.rs b/crates/domain/src/money.rs @@ -0,0 +1,273 @@ +use crate::{Currency, CurrencyError}; +use core::{fmt, str::FromStr}; + +/// Exact bounded nonnegative minor amount; JSON uses a canonical integer string. +#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct MinorAmount(u64); + +/// Validated money with one supported currency and its fixed registry exponent. +#[derive(Clone, Copy, Eq, PartialEq, Hash)] +pub struct Money { + currency: Currency, + minor: MinorAmount, +} + +/// Input-free monetary admission or checked-arithmetic failure. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum MoneyError { + /// The input is not an unsigned ASCII integer string. + InvalidMinorFormat, + /// A leading zero makes the spelling noncanonical. + NonCanonicalMinor, + /// The supported fifteen-digit minor amount bound is exceeded. + MinorOutOfRange, + /// The supplied exponent exceeds the supported range 0-4. + InvalidExponent, + /// The supplied exponent disagrees with the supported currency registry. + ExponentMismatch, + /// Arithmetic operands have different currencies. + CurrencyMismatch, + /// Subtraction would produce a negative monetary value. + NegativeResult, + /// The currency could not be admitted. + Currency(CurrencyError), +} + +impl MinorAmount { + /// Largest supported exact minor amount. + pub const MAX_VALUE: u64 = 999_999_999_999_999; + /// Explicit valid zero; it does not imply a price mode or currency. + pub const ZERO: Self = Self(0); + /// Largest supported validated amount. + pub const MAX: Self = Self(Self::MAX_VALUE); + + /// Checks the exact minor-unit bound without a floating conversion. + pub const fn new(value: u64) -> Result<Self, MoneyError> { + if value > Self::MAX_VALUE { + Err(MoneyError::MinorOutOfRange) + } else { + Ok(Self(value)) + } + } + + /// Returns the exact bounded integer representation. + pub const fn get(self) -> u64 { + self.0 + } +} + +impl TryFrom<u64> for MinorAmount { + type Error = MoneyError; + fn try_from(value: u64) -> Result<Self, Self::Error> { + Self::new(value) + } +} + +impl FromStr for MinorAmount { + type Err = MoneyError; + fn from_str(value: &str) -> Result<Self, Self::Err> { + if value.is_empty() { + return Err(MoneyError::InvalidMinorFormat); + } + if value.len() > 15 { + return Err(MoneyError::MinorOutOfRange); + } + if !value.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(MoneyError::InvalidMinorFormat); + } + if value.len() > 1 && value.starts_with('0') { + return Err(MoneyError::NonCanonicalMinor); + } + let mut result = 0_u64; + for byte in value.bytes() { + result = result + .checked_mul(10) + .and_then(|n| n.checked_add(u64::from(byte - b'0'))) + .ok_or(MoneyError::MinorOutOfRange)?; + } + Self::new(result) + } +} + +impl fmt::Display for MinorAmount { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl fmt::Debug for MinorAmount { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("MinorAmount(<redacted>)") + } +} + +impl Money { + /// Combines already validated values. Zero is explicit money, not a quote. + pub const fn new(currency: Currency, minor: MinorAmount) -> Self { + Self { currency, minor } + } + + /// Admits wire/FFI parts and checks their explicit registry exponent. + pub fn from_parts(currency: &str, minor: &str, exponent: u8) -> Result<Self, MoneyError> { + let currency = Currency::from_code(currency)?; + let minor = minor.parse()?; + Self::from_wire(currency, minor, exponent) + } + + fn from_wire(currency: Currency, minor: MinorAmount, exponent: u8) -> Result<Self, MoneyError> { + if exponent > 4 { + return Err(MoneyError::InvalidExponent); + } + if exponent != currency.exponent() { + return Err(MoneyError::ExponentMismatch); + } + Ok(Self::new(currency, minor)) + } + + /// Returns the validated supported currency. + pub const fn currency(self) -> Currency { + self.currency + } + + /// Returns the exact validated minor amount. + pub const fn minor(self) -> MinorAmount { + self.minor + } + + /// Returns the currency's fixed minor exponent. + pub const fn exponent(self) -> u8 { + self.currency.exponent() + } + + /// Adds in checked signed 128-bit arithmetic, retaining currency and bounds. + pub fn checked_add(self, other: Self) -> Result<Self, MoneyError> { + if self.currency != other.currency { + return Err(MoneyError::CurrencyMismatch); + } + let result = i128::from(self.minor.get()) + .checked_add(i128::from(other.minor.get())) + .ok_or(MoneyError::MinorOutOfRange)?; + self.with_result(result) + } + + /// Subtracts exactly; different currencies and negative values are errors. + pub fn checked_sub(self, other: Self) -> Result<Self, MoneyError> { + if self.currency != other.currency { + return Err(MoneyError::CurrencyMismatch); + } + let result = i128::from(self.minor.get()) + .checked_sub(i128::from(other.minor.get())) + .filter(|result| *result >= 0) + .ok_or(MoneyError::NegativeResult)?; + self.with_result(result) + } + + fn with_result(self, value: i128) -> Result<Self, MoneyError> { + let value = u64::try_from(value).map_err(|_| MoneyError::MinorOutOfRange)?; + Ok(Self::new(self.currency, MinorAmount::new(value)?)) + } +} + +impl From<CurrencyError> for MoneyError { + fn from(value: CurrencyError) -> Self { + Self::Currency(value) + } +} + +impl fmt::Debug for Money { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Money(<redacted>)") + } +} + +impl fmt::Display for MoneyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidMinorFormat => "invalid minor amount format", + Self::NonCanonicalMinor => "noncanonical minor amount", + Self::MinorOutOfRange => "minor amount exceeds supported bound", + Self::InvalidExponent => "invalid currency exponent", + Self::ExponentMismatch => "currency exponent mismatch", + Self::CurrencyMismatch => "currency mismatch", + Self::NegativeResult => "monetary subtraction would be negative", + Self::Currency(error) => return error.fmt(f), + }) + } +} + +impl core::error::Error for MoneyError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Currency(error) => Some(error), + _ => None, + } + } +} + +#[cfg(feature = "serde")] +mod serde_impl { + use super::{MinorAmount, Money}; + use crate::Currency; + use core::fmt; + use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser::SerializeStruct}; + + impl Serialize for MinorAmount { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.collect_str(self) + } + } + + impl<'de> Deserialize<'de> for MinorAmount { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + struct Visitor; + impl de::Visitor<'_> for Visitor { + type Value = MinorAmount; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a bounded canonical minor amount string") + } + fn visit_str<E: de::Error>(self, value: &str) -> Result<MinorAmount, E> { + value.parse().map_err(E::custom) + } + } + deserializer.deserialize_str(Visitor) + } + } + + impl Serialize for Money { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("Money", 3)?; + state.serialize_field("currency", &self.currency())?; + state.serialize_field("minor", &self.minor())?; + state.serialize_field("exponent", &self.exponent())?; + state.end() + } + } + + impl<'de> Deserialize<'de> for Money { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Wire { + currency: Currency, + minor: MinorAmount, + exponent: u8, + } + struct Visitor; + impl<'de> de::Visitor<'de> for Visitor { + type Value = Money; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a money object with currency, minor and exponent") + } + + fn visit_map<A: de::MapAccess<'de>>(self, map: A) -> Result<Money, A::Error> { + let wire = Wire::deserialize(de::value::MapAccessDeserializer::new(map))?; + Money::from_wire(wire.currency, wire.minor, wire.exponent) + .map_err(de::Error::custom) + } + } + deserializer.deserialize_map(Visitor) + } + } +} diff --git a/crates/domain/tests/context.rs b/crates/domain/tests/context.rs @@ -1,5 +1,6 @@ use radroots_domain::*; use radroots_identity::PublicKey; +#[cfg(feature = "serde")] use serde_json::{Value, json}; use std::str::FromStr; @@ -45,19 +46,23 @@ fn exact_integers_never_round_or_accept_numeric_json_coercions() { let sequence = Sequence::new(value).unwrap(); assert_eq!(sequence.get(), value); assert_eq!(sequence.to_string().parse::<Sequence>(), Ok(sequence)); - assert_eq!( - serde_json::to_value(sequence).unwrap(), - json!(value.to_string()) - ); - assert_eq!( - serde_json::from_value::<Sequence>(json!(value.to_string())).unwrap(), - sequence - ); - assert!(serde_json::from_value::<Sequence>(json!(value)).is_err()); + #[cfg(feature = "serde")] + { + assert_eq!( + serde_json::to_value(sequence).unwrap(), + json!(value.to_string()) + ); + assert_eq!( + serde_json::from_value::<Sequence>(json!(value.to_string())).unwrap(), + sequence + ); + assert!(serde_json::from_value::<Sequence>(json!(value)).is_err()); + } if value > 0 { let generation = Generation::new(value).unwrap(); assert_eq!(generation.get(), value); assert_eq!(generation.to_string().parse::<Generation>(), Ok(generation)); + #[cfg(feature = "serde")] assert_eq!( serde_json::from_value::<Generation>(json!(value.to_string())).unwrap(), generation @@ -80,6 +85,7 @@ fn exact_integers_never_round_or_accept_numeric_json_coercions() { ] { assert!(text.parse::<Sequence>().is_err(), "{text:?}"); assert!(text.parse::<Generation>().is_err()); + #[cfg(feature = "serde")] assert!(serde_json::from_value::<Sequence>(json!(text)).is_err()); } assert!(Generation::new(0).is_err()); @@ -90,33 +96,41 @@ fn exact_integers_never_round_or_accept_numeric_json_coercions() { let timestamp = UnixSeconds::new(value).unwrap(); assert_eq!(timestamp.get(), value); assert_eq!(timestamp.to_string().parse::<UnixSeconds>(), Ok(timestamp)); - assert_eq!( - serde_json::from_value::<UnixSeconds>(json!(value.to_string())).unwrap(), - timestamp - ); - assert_eq!( - serde_json::to_value(timestamp).unwrap(), - json!(value.to_string()) - ); + #[cfg(feature = "serde")] + { + assert_eq!( + serde_json::from_value::<UnixSeconds>(json!(value.to_string())).unwrap(), + timestamp + ); + assert_eq!( + serde_json::to_value(timestamp).unwrap(), + json!(value.to_string()) + ); + } } assert!(UnixSeconds::new(253_402_300_800).is_err()); assert!("253402300800".parse::<UnixSeconds>().is_err()); + #[cfg(feature = "serde")] assert!(serde_json::from_value::<UnixSeconds>(json!(1)).is_err()); } #[test] fn captured_descriptors_preserve_every_field_and_explicit_null() { let data = context(); - let wire = serde_json::to_value(&data).unwrap(); - assert_eq!(wire["operation_id"], json!("01".repeat(32))); - assert_eq!(wire["authority"]["generation"], json!("9007199254740993")); - for name in ["approval", "expected", "correlation_id"] { - assert!(wire[name].is_null()); - } - assert_eq!( - serde_json::from_value::<CommandContextData>(wire.clone()).unwrap(), - data - ); + #[cfg(feature = "serde")] + let wire = { + let wire = serde_json::to_value(&data).unwrap(); + assert_eq!(wire["operation_id"], json!("01".repeat(32))); + assert_eq!(wire["authority"]["generation"], json!("9007199254740993")); + for name in ["approval", "expected", "correlation_id"] { + assert!(wire[name].is_null()); + } + assert_eq!( + serde_json::from_value::<CommandContextData>(wire.clone()).unwrap(), + data + ); + wire + }; assert_eq!(data.operation_id(), OperationId::from_bytes([1; 32])); assert_eq!(data.actor(), actor()); assert_eq!(data.workspace_id(), WorkspaceId::from_bytes([2; 32])); @@ -137,31 +151,34 @@ fn captured_descriptors_preserve_every_field_and_explicit_null() { assert_eq!(data.actor().role(), ActorRole::Buyer); assert_eq!(data.actor().organization(), None); assert_eq!(data.actor().grant_id(), Some(GrantId::from_bytes([4; 32]))); - for field in ["approval", "expected", "correlation_id"] { - let mut missing = wire.clone(); - missing.as_object_mut().unwrap().remove(field); - assert!( - serde_json::from_value::<CommandContextData>(missing).is_err(), - "required {field}" - ); - } - for field in ["organization", "grant_id"] { - let mut missing = wire.clone(); - missing["actor"].as_object_mut().unwrap().remove(field); - assert!( - serde_json::from_value::<CommandContextData>(missing).is_err(), - "required actor {field}" - ); + #[cfg(feature = "serde")] + { + for field in ["approval", "expected", "correlation_id"] { + let mut missing = wire.clone(); + missing.as_object_mut().unwrap().remove(field); + assert!( + serde_json::from_value::<CommandContextData>(missing).is_err(), + "required {field}" + ); + } + for field in ["organization", "grant_id"] { + let mut missing = wire.clone(); + missing["actor"].as_object_mut().unwrap().remove(field); + assert!( + serde_json::from_value::<CommandContextData>(missing).is_err(), + "required actor {field}" + ); + } + let raw = serde_json::to_string(&data).unwrap(); + let duplicate = format!("{{\"operation_id\":\"{}\",{}", "ff".repeat(32), &raw[1..]); + assert!(serde_json::from_str::<CommandContextData>(&duplicate).is_err()); + let mut unknown = wire.clone(); + unknown["authenticated"] = json!(true); + assert!(serde_json::from_value::<CommandContextData>(unknown).is_err()); + let mut unknown = wire; + unknown["actor"]["role"] = json!("operator"); + assert!(serde_json::from_value::<CommandContextData>(unknown).is_err()); } - let raw = serde_json::to_string(&data).unwrap(); - let duplicate = format!("{{\"operation_id\":\"{}\",{}", "ff".repeat(32), &raw[1..]); - assert!(serde_json::from_str::<CommandContextData>(&duplicate).is_err()); - let mut unknown = wire.clone(); - unknown["authenticated"] = json!(true); - assert!(serde_json::from_value::<CommandContextData>(unknown).is_err()); - let mut unknown = wire; - unknown["actor"]["role"] = json!("operator"); - assert!(serde_json::from_value::<CommandContextData>(unknown).is_err()); assert!(!format!("{data:?}").contains(KEY)); } @@ -200,29 +217,32 @@ fn complete_preconditions_and_approval_data_remain_untrusted_bounded_values() { expected.checkpoint().missing(), &[SourceId::from_bytes([9; 32])] ); - let mut wire = serde_json::to_value(context()).unwrap(); - wire["approval"] = serde_json::to_value(&approval).unwrap(); - wire["expected"] = serde_json::to_value(&expected).unwrap(); - wire["correlation_id"] = json!("synthetic diagnostic"); - let data: CommandContextData = serde_json::from_value(wire.clone()).unwrap(); - assert_eq!(data.approval(), Some(&approval)); - assert_eq!(data.expected(), Some(&expected)); - assert_eq!( - data.correlation_id().unwrap().as_str(), - "synthetic diagnostic" - ); - assert_eq!(serde_json::to_value(&data).unwrap(), wire); - for field in ["agreement", "buyer_head"] { - let mut missing = wire.clone(); - missing["expected"].as_object_mut().unwrap().remove(field); - assert!(serde_json::from_value::<CommandContextData>(missing).is_err()); - } - for nested in ["authority", "approval", "expected"] { - let mut changed = wire.clone(); - changed[nested]["extra"] = Value::Bool(true); - assert!(serde_json::from_value::<CommandContextData>(changed).is_err()); + #[cfg(feature = "serde")] + { + let mut wire = serde_json::to_value(context()).unwrap(); + wire["approval"] = serde_json::to_value(&approval).unwrap(); + wire["expected"] = serde_json::to_value(&expected).unwrap(); + wire["correlation_id"] = json!("synthetic diagnostic"); + let data: CommandContextData = serde_json::from_value(wire.clone()).unwrap(); + assert_eq!(data.approval(), Some(&approval)); + assert_eq!(data.expected(), Some(&expected)); + assert_eq!( + data.correlation_id().unwrap().as_str(), + "synthetic diagnostic" + ); + assert_eq!(serde_json::to_value(&data).unwrap(), wire); + for field in ["agreement", "buyer_head"] { + let mut missing = wire.clone(); + missing["expected"].as_object_mut().unwrap().remove(field); + assert!(serde_json::from_value::<CommandContextData>(missing).is_err()); + } + for nested in ["authority", "approval", "expected"] { + let mut changed = wire.clone(); + changed[nested]["extra"] = Value::Bool(true); + assert!(serde_json::from_value::<CommandContextData>(changed).is_err()); + } + assert!(!format!("{data:?}").contains("synthetic diagnostic")); } - assert!(!format!("{data:?}").contains("synthetic diagnostic")); assert!(!format!("{approval:?}").contains("orders.accept")); } @@ -231,13 +251,16 @@ fn bounds_and_coverage_claims_fail_without_echoing_sensitive_text() { assert!(CorrelationId::new("é".repeat(64)).is_ok()); assert!(CorrelationId::new("é".repeat(65)).is_err()); assert!(CorrelationId::new("diagnostic\nsecret").is_err()); - assert_eq!( - serde_json::from_str::<CorrelationId>("\"hello\"") - .unwrap() - .as_str(), - "hello" - ); - assert!(serde_json::from_value::<CorrelationId>(json!("x".repeat(129))).is_err()); + #[cfg(feature = "serde")] + { + assert_eq!( + serde_json::from_str::<CorrelationId>("\"hello\"") + .unwrap() + .as_str(), + "hello" + ); + assert!(serde_json::from_value::<CorrelationId>(json!("x".repeat(129))).is_err()); + } assert!( !format!("{:?}", CorrelationId::new("private diagnostic").unwrap()) .contains("private diagnostic") @@ -292,7 +315,10 @@ fn bounds_and_coverage_claims_fail_without_echoing_sensitive_text() { ContextError::InconsistentCoverage ); assert!(CheckpointRef::new(digest, sequence, Coverage::ScopeSatisfied, vec![]).is_ok()); - let mut invalid = serde_json::to_value(context()).unwrap(); - invalid["not_after"] = json!("0"); - assert!(serde_json::from_value::<CommandContextData>(invalid).is_err()); + #[cfg(feature = "serde")] + { + let mut invalid = serde_json::to_value(context()).unwrap(); + invalid["not_after"] = json!("0"); + assert!(serde_json::from_value::<CommandContextData>(invalid).is_err()); + } } diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -7,10 +7,12 @@ fn public_text_has_shared_unicode_bounds_and_revision_data_rejects_inverted_time let summary = "é".repeat(280); let body = " ".repeat(16_384); let value = ListingText::new(&title, &summary, &body).unwrap(); + #[cfg(feature = "serde")] assert_eq!( serde_json::to_value(&value).unwrap(), serde_json::json!({"title":title,"summary":summary,"description_markdown":body}) ); + assert!(!format!("{value:?}").contains('🥕')); for (title, summary, body) in [ ("🥕".repeat(161), "summary".into(), String::new()), ("title".into(), "é".repeat(281), String::new()), @@ -135,6 +137,7 @@ fn spare_caller_capacity_preserves_exact_terms_and_default_selection() { expanded.default_option().id(), ListingOptionId::from_bytes([2; 32]) ); + #[cfg(feature = "serde")] assert_eq!( serde_json::to_vec(&expanded).unwrap(), serde_json::to_vec(&expected).unwrap() diff --git a/crates/domain/tests/money.rs b/crates/domain/tests/money.rs @@ -0,0 +1,291 @@ +use radroots_domain::{ + CURRENCY_REGISTRY_ID, CURRENCY_REGISTRY_SHA256, Currency, CurrencyError, MinorAmount, Money, + MoneyError, SUPPORTED_CURRENCY_COUNT, +}; +use std::{collections::BTreeSet, error::Error}; + +fn money(code: &str, value: &str, exponent: u8) -> Money { + Money::from_parts(code, value, exponent).unwrap() +} + +#[test] +fn complete_pinned_registry_preserves_each_code_and_exponent_without_defaults() { + let expected = include_str!("../data/currency_registry_v1.csv") + .lines() + .filter(|line| !line.starts_with('#')) + .map(|line| { + let (code, exponent) = line.split_once(',').unwrap(); + (code, exponent.parse::<u8>().unwrap()) + }) + .collect::<Vec<_>>(); + assert_eq!(expected.len(), 165); + assert_eq!(SUPPORTED_CURRENCY_COUNT, expected.len()); + assert_eq!(CURRENCY_REGISTRY_ID, "radroots.currency_registry.v1"); + assert_eq!(CURRENCY_REGISTRY_SHA256.len(), 64); + let actual = Currency::supported() + .map(|currency| (currency.code(), currency.exponent())) + .collect::<Vec<_>>(); + assert_eq!(actual, expected); + assert_eq!( + actual + .iter() + .map(|row| row.0) + .collect::<BTreeSet<_>>() + .len(), + 165 + ); + for (code, exponent) in actual { + let currency: Currency = code.parse().unwrap(); + assert_eq!(currency.code(), code); + assert_eq!(currency.exponent(), exponent); + let value = money(code, "1", exponent); + assert_eq!(value.currency(), currency); + for other in 0..=4 { + if other != exponent { + assert_eq!( + Money::from_parts(code, "1", other), + Err(MoneyError::ExponentMismatch) + ); + } + } + } +} + +#[test] +fn independent_iso_minor_units_are_distinct_from_display_rounding() { + for (code, exponent) in [ + ("CAD", 2), + ("JPY", 0), + ("KWD", 3), + ("CLF", 4), + ("UYW", 4), + ("AFN", 2), + ("ALL", 2), + ("COP", 2), + ("HUF", 2), + ("XAD", 2), + ] { + assert_eq!(Currency::from_code(code).unwrap().exponent(), exponent); + } +} + +#[test] +fn currency_admission_is_ascii_canonical_bounded_and_supported_only() { + for input in [ + "", + "US", + "USDD", + "usd", + "Usd", + " USD", + "USD ", + "12A", + "éA", + "USD", + "A\0B", + ] { + assert_eq!( + Currency::from_code(input), + Err(CurrencyError::InvalidFormat) + ); + } + assert_eq!( + Currency::from_code(&"A".repeat(100_000)), + Err(CurrencyError::InvalidFormat) + ); + for input in [ + "ZZZ", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XDR", "XPD", "XPT", "XSU", "XTS", "XUA", + "XXX", "BGN", "ANG", + ] { + assert_eq!( + Currency::from_code(input), + Err(CurrencyError::UnsupportedCode) + ); + } +} + +#[test] +fn minor_amount_strings_and_numeric_construction_are_exact_at_both_bounds() { + for (text, expected) in [ + ("0", 0), + ("1", 1), + ("900719925474099", 900_719_925_474_099), + ("999999999999999", 999_999_999_999_999), + ] { + let amount: MinorAmount = text.parse().unwrap(); + assert_eq!(amount.get(), expected); + assert_eq!(amount.to_string(), text); + assert_eq!(MinorAmount::try_from(expected).unwrap(), amount); + } + assert_eq!(MinorAmount::ZERO.get(), 0); + assert_eq!(MinorAmount::MAX.get(), MinorAmount::MAX_VALUE); + assert_eq!( + MinorAmount::new(1_000_000_000_000_000), + Err(MoneyError::MinorOutOfRange) + ); + assert_eq!(MinorAmount::new(u64::MAX), Err(MoneyError::MinorOutOfRange)); + for input in [ + "", "-0", "-1", "+1", "1.0", "1e2", " 1", "1 ", "1\n", "1,000", "1_000", "1", "١", "NaN", + ] { + assert_eq!( + input.parse::<MinorAmount>(), + Err(MoneyError::InvalidMinorFormat) + ); + } + for input in ["00", "01", "000000000000000"] { + assert_eq!( + input.parse::<MinorAmount>(), + Err(MoneyError::NonCanonicalMinor) + ); + } + for input in ["1000000000000000", "9999999999999999", &"9".repeat(100_000)] { + assert_eq!( + input.parse::<MinorAmount>(), + Err(MoneyError::MinorOutOfRange) + ); + } +} + +#[test] +fn money_checks_explicit_exponents_and_never_changes_currency_or_price_mode() { + for (code, exponent) in [("JPY", 0), ("CAD", 2), ("KWD", 3), ("CLF", 4)] { + let value = money(code, "325", exponent); + assert_eq!(value.currency().code(), code); + assert_eq!(value.exponent(), exponent); + assert_eq!(value.minor().get(), 325); + assert_eq!(Money::new(value.currency(), value.minor()), value); + assert_eq!( + Money::from_parts(code, "325", 5), + Err(MoneyError::InvalidExponent) + ); + assert_eq!( + Money::from_parts(code, "325", u8::MAX), + Err(MoneyError::InvalidExponent) + ); + } + assert_eq!(money("CAD", "0", 2).minor(), MinorAmount::ZERO); + assert_eq!( + Money::from_parts("XXX", "0", 0), + Err(MoneyError::Currency(CurrencyError::UnsupportedCode)) + ); + assert_eq!( + Money::from_parts("cad", "0", 2), + Err(MoneyError::Currency(CurrencyError::InvalidFormat)) + ); + assert_eq!( + Money::from_parts("CAD", "0.1", 2), + Err(MoneyError::InvalidMinorFormat) + ); +} + +#[test] +fn checked_money_arithmetic_preserves_bounds_and_refuses_cross_currency_operations() { + let zero = money("CAD", "0", 2); + let one = money("CAD", "1", 2); + let maximum = money("CAD", "999999999999999", 2); + assert_eq!(maximum.checked_add(zero).unwrap(), maximum); + assert_eq!(maximum.checked_sub(zero).unwrap(), maximum); + assert_eq!(maximum.checked_sub(maximum).unwrap(), zero); + assert_eq!( + money("CAD", "998", 2).checked_add(one).unwrap(), + money("CAD", "999", 2) + ); + assert_eq!(maximum.checked_add(one), Err(MoneyError::MinorOutOfRange)); + assert_eq!( + maximum.checked_add(maximum), + Err(MoneyError::MinorOutOfRange) + ); + assert_eq!(zero.checked_sub(one), Err(MoneyError::NegativeResult)); + for other in [ + money("USD", "1", 2), + money("JPY", "1", 0), + money("CLF", "1", 4), + ] { + assert_eq!(one.checked_add(other), Err(MoneyError::CurrencyMismatch)); + assert_eq!(one.checked_sub(other), Err(MoneyError::CurrencyMismatch)); + } +} + +#[test] +fn diagnostics_are_fixed_and_money_values_are_redacted() { + let value = money("CAD", "928174615", 2); + for debug in [ + format!("{value:?}"), + format!("{:?}", value.minor()), + format!("{:?}", value.currency()), + ] { + assert!(!debug.contains("928174615")); + assert!(!debug.contains("CAD")); + } + for error in [ + MoneyError::InvalidMinorFormat, + MoneyError::NonCanonicalMinor, + MoneyError::MinorOutOfRange, + MoneyError::InvalidExponent, + MoneyError::ExponentMismatch, + MoneyError::CurrencyMismatch, + MoneyError::NegativeResult, + CurrencyError::InvalidFormat.into(), + CurrencyError::UnsupportedCode.into(), + ] { + assert!(!error.to_string().is_empty()); + assert!(!error.to_string().contains("928174615")); + assert!(!error.to_string().contains("CAD")); + } + assert!( + MoneyError::Currency(CurrencyError::UnsupportedCode) + .source() + .is_some() + ); + assert!(MoneyError::ExponentMismatch.source().is_none()); +} + +#[cfg(feature = "serde")] +#[test] +fn money_serde_is_closed_duplicate_safe_and_validates_every_explicit_field() { + let value = money("CAD", "999999999999999", 2); + let encoded = serde_json::to_string(&value).unwrap(); + assert_eq!( + encoded, + r#"{"currency":"CAD","minor":"999999999999999","exponent":2}"# + ); + assert_eq!(serde_json::from_str::<Money>(&encoded).unwrap(), value); + assert_eq!( + serde_json::to_string(&value.currency()).unwrap(), + r#""CAD""# + ); + assert_eq!( + serde_json::to_string(&value.minor()).unwrap(), + r#""999999999999999""# + ); + for input in [ + r#"{"currency":"CAD","minor":325,"exponent":2}"#, + r#"{"currency":"CAD","minor":"0325","exponent":2}"#, + r#"{"currency":"CAD","minor":"1000000000000000","exponent":2}"#, + r#"{"currency":"CAD","minor":"325","exponent":0}"#, + r#"{"currency":"CAD","minor":"325","exponent":5}"#, + r#"{"currency":"CAD","minor":"325","exponent":256}"#, + r#"{"currency":"CAD","minor":"325","exponent":-1}"#, + r#"{"currency":"CAD","minor":"325","exponent":"2"}"#, + r#"{"currency":"CAD","minor":"325","exponent":2.0}"#, + r#"{"currency":"XXX","minor":"0","exponent":0}"#, + r#"{"currency":"CAD","minor":"0","exponent":2,"extra":null}"#, + r#"{"currency":"CAD","currency":"USD","minor":"0","exponent":2}"#, + r#"{"currency":"CAD","minor":"0","minor":"1","exponent":2}"#, + r#"{"currency":"CAD","minor":"0","exponent":2,"exponent":2}"#, + r#"{"currency":"CAD","minor":"0"}"#, + r#"{"currency":"CAD","exponent":2}"#, + r#"{"minor":"0","exponent":2}"#, + r#"[]"#, + r#"["CAD","325",2]"#, + r#"null"#, + ] { + assert!(serde_json::from_str::<Money>(input).is_err(), "{input}"); + } + for input in ["325", "325.0", "null", r#""1.5""#, r#""-1""#] { + assert!(serde_json::from_str::<MinorAmount>(input).is_err()); + } + for input in ["325", "null", r#""cad""#, r#""ZZZ""#] { + assert!(serde_json::from_str::<Currency>(input).is_err()); + } +} diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -10,6 +10,8 @@ use serde::Deserialize; const CONTRACT: &str = "contracts/architecture/decisions/shared_sdk_refactor.v1.json"; const MAX_BYTES: usize = 65_536; +mod currency_registry; + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Policy { @@ -210,7 +212,8 @@ pub(super) fn validate(workspace_root: &Path) -> Result<(), String> { MAX_BYTES as u64, ) .map_err(|_| "shared SDK contract: bounded regular source admission failed".to_owned())?; - validate_bytes(&raw) + validate_bytes(&raw)?; + currency_registry::validate(workspace_root) } fn require(condition: bool, rule: &'static str) -> Result<(), String> { diff --git a/tools/xtask/src/architecture/decision_package/currency_registry.rs b/tools/xtask/src/architecture/decision_package/currency_registry.rs @@ -0,0 +1,309 @@ +use std::{collections::BTreeSet, path::Path}; + +use serde::Deserialize; +use sha2::{Digest, Sha256}; + +const CONTRACT: &str = "contracts/architecture/decisions/currency_registry.v1.json"; +const DATA: &str = "crates/domain/data/currency_registry_v1.csv"; +const LICENSE: &str = "crates/domain/data/currency_registry_v1.license"; +const NOTICE: &str = "crates/domain/data/currency_registry_v1.notice"; +const DATA_SHA256: &str = "60d8282b2d7ddc27929b097d4de9e76a900a64f1de4a5aa7a4cb3308b55b82d0"; +const LICENSE_SHA256: &str = "665618a8c4b9ef6ceafb35482a3e010834fae9e9cbb22041b74310bcc52ac500"; +const NOTICE_SHA256: &str = "c43ef0d0f9d6f64656ca6a619c3c43cd9cc2b378217ab19a083ca92255a91d7d"; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Policy { + schema_version: u16, + contract_id: String, + state: String, + registry_id: String, + implementation: String, + upstream: Upstream, + data: Data, + notices: Notices, + independent_crosscheck: Crosscheck, + limits: Limits, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Upstream { + repository: String, + revision: String, + path: String, + sha256: String, + license: String, + license_sha256: String, + copyright: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Data { + path: String, + sha256: String, + entries: usize, + minimum_exponent: u8, + maximum_exponent: u8, + current_currency_and_funds_only: bool, + historic_entries_excluded: bool, + no_minor_unit_entries_excluded: bool, + guessed_default_exponents_allowed: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Notices { + license_path: String, + license_sha256: String, + notice_path: String, + notice_sha256: String, + source_distribution_required: bool, + derived_artifact_inclusion_required_before_adoption: bool, + crate_owned_rust_license_unchanged: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Crosscheck { + authority: String, + url: String, + publication_date: String, + source_sha256: String, + all_selected_pairs_equal: bool, + official_xml_redistributed: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Limits { + runtime_io_allowed: bool, + automatic_updates_allowed: bool, + exchange_or_payment_semantics_allowed: bool, + qualified_economics_or_agreement_authoring_claimed: bool, +} + +pub(super) fn validate(root: &Path) -> Result<(), String> { + let read = |path: &str, max: u64| { + crate::safe_artifact_io::read_regular(root, Path::new(path), max) + .map_err(|_| "currency registry: bounded regular source admission failed".to_owned()) + }; + validate_materials( + &read(CONTRACT, 16_384)?, + &read(DATA, 4_096)?, + &read(LICENSE, 16_384)?, + &read(NOTICE, 4_096)?, + ) +} + +fn require(condition: bool, message: &'static str) -> Result<(), String> { + if condition { + Ok(()) + } else { + Err(format!("currency registry: {message}")) + } +} + +fn digest(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +fn validate_materials( + raw: &[u8], + data: &[u8], + license: &[u8], + notice: &[u8], +) -> Result<(), String> { + require(raw.len() <= 16_384, "policy exceeds bound")?; + let policy: Policy = serde_json::from_slice(raw) + .map_err(|_| "currency registry: invalid closed policy".to_owned())?; + require( + policy.schema_version == 1 + && policy.contract_id == "radroots.currency_registry.v1" + && policy.registry_id == policy.contract_id + && policy.state == "pinned_data_source" + && policy.implementation == "independent_rust_api_over_minimal_pinned_data", + "identity or implementation scope changed", + )?; + validate_upstream(&policy.upstream, &policy.independent_crosscheck)?; + let p = &policy.data; + require( + p.path == DATA + && p.sha256 == DATA_SHA256 + && p.entries == 165 + && p.minimum_exponent == 0 + && p.maximum_exponent == 4 + && p.current_currency_and_funds_only + && p.historic_entries_excluded + && p.no_minor_unit_entries_excluded + && !p.guessed_default_exponents_allowed, + "fixed supported data contract changed", + )?; + validate_notices(&policy.notices, license, notice)?; + require( + !policy.limits.runtime_io_allowed + && !policy.limits.automatic_updates_allowed + && !policy.limits.exchange_or_payment_semantics_allowed + && !policy + .limits + .qualified_economics_or_agreement_authoring_claimed, + "metadata cannot imply effects or qualification", + )?; + require( + data.len() <= 4_096 && digest(data) == DATA_SHA256, + "pinned data digest mismatch", + )?; + let text = + std::str::from_utf8(data).map_err(|_| "currency registry: invalid data UTF8".to_owned())?; + let mut codes = BTreeSet::new(); + let mut previous = None; + require(text.ends_with('\n'), "unterminated data")?; + for line in text.lines().filter(|line| !line.starts_with('#')) { + let bytes = line.as_bytes(); + require( + bytes.len() == 5 + && bytes[..3].iter().all(u8::is_ascii_uppercase) + && bytes[3] == b',' + && (b'0'..=b'4').contains(&bytes[4]), + "invalid data row", + )?; + let code = &line[..3]; + require( + previous.is_none_or(|p| p < code) && codes.insert(code), + "duplicate or unsorted code", + )?; + previous = Some(code); + } + require(codes.len() == 165, "incomplete fixed registry") +} + +fn validate_upstream(upstream: &Upstream, crosscheck: &Crosscheck) -> Result<(), String> { + require( + upstream.repository == "https://github.com/rust-iso/rust_iso4217" + && upstream.revision == "ce6b74546b3645ce11866acc93117128d2f7b1e0" + && upstream.path == "src/lib.rs" + && upstream.sha256 + == "7401727ea4da05fcbf0d1d679705c0245989e83dbc697e831066f992875e183d" + && upstream.license == "Apache-2.0" + && upstream.license_sha256 == LICENSE_SHA256 + && upstream.copyright == "Copyright 2023-2026 rust_iso4217 contributors", + "source or license provenance changed", + )?; + require( + crosscheck.authority == "SIX ISO 4217 Maintenance Agency" + && crosscheck.url + == "https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml" + && crosscheck.publication_date == "2026-09-17" + && crosscheck.source_sha256 + == "33139b438657d1cee116ba737807ea71d19d6de4b90f799a09c56f0cc6a1b0ff" + && crosscheck.all_selected_pairs_equal + && !crosscheck.official_xml_redistributed, + "independent factual crosscheck scope changed", + ) +} + +fn validate_notices(policy: &Notices, license: &[u8], notice: &[u8]) -> Result<(), String> { + require( + policy.license_path == LICENSE + && policy.license_sha256 == LICENSE_SHA256 + && policy.notice_path == NOTICE + && policy.notice_sha256 == NOTICE_SHA256 + && policy.source_distribution_required + && policy.derived_artifact_inclusion_required_before_adoption + && policy.crate_owned_rust_license_unchanged, + "notice distribution requirement changed", + )?; + require( + license.len() <= 16_384 + && digest(license) == LICENSE_SHA256 + && notice.len() <= 4_096 + && digest(notice) == NOTICE_SHA256, + "license or notice digest mismatch", + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const POLICY: &[u8] = + include_bytes!("../../../../../contracts/architecture/decisions/currency_registry.v1.json"); + const CSV: &[u8] = include_bytes!("../../../../../crates/domain/data/currency_registry_v1.csv"); + const LICENSE_BYTES: &[u8] = + include_bytes!("../../../../../crates/domain/data/currency_registry_v1.license"); + const NOTICE_BYTES: &[u8] = + include_bytes!("../../../../../crates/domain/data/currency_registry_v1.notice"); + + #[test] + fn fixed_source_data_license_and_notice_bindings_are_valid() { + validate_materials(POLICY, CSV, LICENSE_BYTES, NOTICE_BYTES).unwrap(); + } + + #[test] + fn forged_self_consistent_hashes_or_stripped_attribution_cannot_replace_registry_v1() { + let changed = String::from_utf8(CSV.to_vec()) + .unwrap() + .replace("CAD,2", "CAD,4"); + let mut policy: serde_json::Value = serde_json::from_slice(POLICY).unwrap(); + policy["data"]["sha256"] = json!(digest(changed.as_bytes())); + let raw = serde_json::to_vec(&policy).unwrap(); + assert!(validate_materials(&raw, changed.as_bytes(), LICENSE_BYTES, NOTICE_BYTES).is_err()); + assert!( + validate_materials(POLICY, changed.as_bytes(), LICENSE_BYTES, NOTICE_BYTES).is_err() + ); + assert!(validate_materials(POLICY, CSV, b"Apache-2.0", NOTICE_BYTES).is_err()); + assert!(validate_materials(POLICY, CSV, LICENSE_BYTES, b"notice").is_err()); + } + + #[test] + fn closed_policy_rejects_unpinned_defaults_wrong_sources_and_effect_claims() { + for (pointer, replacement) in [ + ("/upstream/license", json!("MIT")), + ("/upstream/revision", json!("master")), + ("/data/path", json!("../private.csv")), + ("/data/entries", json!(164)), + ("/data/guessed_default_exponents_allowed", json!(true)), + ( + "/independent_crosscheck/official_xml_redistributed", + json!(true), + ), + ( + "/notices/derived_artifact_inclusion_required_before_adoption", + json!(false), + ), + ("/limits/automatic_updates_allowed", json!(true)), + ( + "/limits/qualified_economics_or_agreement_authoring_claimed", + json!(true), + ), + ] { + let mut value: serde_json::Value = serde_json::from_slice(POLICY).unwrap(); + *value.pointer_mut(pointer).unwrap() = replacement; + assert!( + validate_materials( + &serde_json::to_vec(&value).unwrap(), + CSV, + LICENSE_BYTES, + NOTICE_BYTES + ) + .is_err(), + "{pointer}" + ); + } + let mut value: serde_json::Value = serde_json::from_slice(POLICY).unwrap(); + value["unknown"] = json!(true); + assert!( + validate_materials( + &serde_json::to_vec(&value).unwrap(), + CSV, + LICENSE_BYTES, + NOTICE_BYTES + ) + .is_err() + ); + assert!(validate_materials(b"{}", CSV, LICENSE_BYTES, NOTICE_BYTES).is_err()); + assert!(validate_materials(&vec![b' '; 16_385], CSV, LICENSE_BYTES, NOTICE_BYTES).is_err()); + } +}