lib

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

commit c638fb1665b200309a2621b0bd1891f2fe1e50d9
parent 3af7814ea4f76f2cca3d33d4c2bd8a854f3fb78f
Author: triesap <tyson@radroots.org>
Date:   Sat, 17 Oct 2026 02:00:55 +0000

domain: add bounded canonical amount values

- Implement nonnegative decimals, positive amounts and exact checked arithmetic.
- Enforce canonical string admission and serde encoding without floating conversion.
- Register unpublished native provenance and preserve the existing public release closure.
- Verify native and WASM profiles, value tests, coverage and owning contracts.

Diffstat:
MCargo.lock | 8++++++++
MCargo.toml | 2++
Mcontracts/architecture/deviations.toml | 26++++++++++++++++++++++++++
Mcontracts/coverage.toml | 1+
Mcontracts/crates/catalog.v2.toml | 20+++++++++++++++++++-
Mcontracts/crates/generated/package_groups.v1.toml | 10+++++-----
Mcontracts/crates/generated/platform_inventory.v1.toml | 4++--
Mcontracts/crates/generated/release_inventory.v2.toml | 4++--
Mcontracts/releases/publish_policy.toml | 1+
Acrates/domain/Cargo.toml | 26++++++++++++++++++++++++++
Acrates/domain/LICENSE-APACHE | 201+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/domain/LICENSE-MIT | 21+++++++++++++++++++++
Acrates/domain/README.md | 19+++++++++++++++++++
Acrates/domain/src/amount.rs | 290+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/domain/src/lib.rs | 8++++++++
Acrates/domain/tests/amount.rs | 289++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 920 insertions(+), 10 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3083,6 +3083,14 @@ dependencies = [ ] [[package]] +name = "radroots_domain" +version = "0.1.0-alpha" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] name = "radroots_event" version = "0.1.0-alpha" dependencies = [ diff --git a/Cargo.toml b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "crates/core", + "crates/domain", "crates/event", "crates/event_codec", "crates/blossom", @@ -111,6 +112,7 @@ dto_bindgen_core = { version = "0.1.0" } radroots = { path = "crates/radroots", version = "=0.1.0-alpha" } radroots_core_bindings = { path = "crates/core_bindings", version = "=0.1.0-alpha" } radroots_core = { package = "radroots_core", path = "crates/core", version = "=0.1.0-alpha", default-features = false } +radroots_domain = { path = "crates/domain", version = "=0.1.0-alpha", default-features = false } radroots_event = { package = "radroots_event", path = "crates/event", version = "=0.1.0-alpha", default-features = false } radroots_event_codec = { package = "radroots_event_codec", path = "crates/event_codec", version = "=0.1.0-alpha", default-features = false } radroots_event_bindings = { path = "crates/event_bindings", version = "=0.1.0-alpha" } 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-044" +date = "2026-10-17" +status = "closed" +approval = "The user authorizes the complete shared SDK successor, required breaking changes, verified source commits and master integration." +affected_steps = ["040", "050", "130"] +spec_anchors = ["contracts/crates/release_v1/radroots_crates_release_v1.toml#package.radroots_core"] +source_evidence = [ + "The approved shared SDK decision assigns exact values to crates/domain. The current core decimal admits negative amounts, scale 28 and floating conversion, which cannot supply the bounded nonnegative successor boundary.", + "The new value prerequisite needs only the already executed native Rust 1.99 compiler and approved ownership/value contracts. Actual pending Linux and unavailable Darwin Nix qualification remain separate obligations; no platform or runtime result follows from source preparation.", +] +replacement_action = "Independently implement bounded nonnegative decimal and positive-amount values in the approved domain owner, using the existing active unpublished native catalog introduction-tree mechanism. Preserve the nineteen-package current public release closure and all original core source/tests until actual caller replacement. Do not introduce legacy aliases, float conversion, rounding, guessed currencies or product qualification claims." +verification = [ + "Validate this prospective deviation before implementation; stage the complete new package before owning catalog generation and bind its exact introduction tree.", + "Run exact stable formatting, focused native/default and no-default/serde checking/tests, warning-denied lint/docs and actual WASM compilation. Prove bounds, canonical string encoding, normalization, positive amounts, ordering/hash, bounded admission and exact checked arithmetic.", + "Run current catalog, architecture and contract checks and inspect generated projections and complete lock records. Preserve all prior immutable evidence and report unfinished facade, execution, registry, platform and caller migration explicitly.", +] +unresolved_risk = "This bounded value implementation does not qualify the public facade, currency/economics, retained operation execution, native/browser ports, generated bindings, supported consumers, final platform matrix or package publication. Existing core APIs remain pending direct caller replacement." +normative_architecture_change = false +adr_required = false +closure_evidence = [ + "The independently authored domain value package enforces coefficient 999999999999, scale six, canonical string admission/serialization, positive-amount construction, numeric ordering/hash and exact checked addition/subtraction without floating conversion or rounding. No existing source or test is removed and no facade or operation is qualified.", + "Fourteen default cases pass; the same twelve non-serde cases pass without default features and all fourteen pass with serde alone. Exact stable format, native/profile checks, strict lint/docs and actual wasm32-unknown-unknown compilation pass. The preserved coverage nightly measures all 111 executable lines, all functions/regions and all 32 recorded branches covered; the unchanged ninety-percent gate passes.", + "Owning catalog generation/check, architecture and full contract validation pass after applying the existing explicit package-version convention. The native introduction tree is staged and digest-bound, all 600 prior complete lock records remain unchanged, and the current nineteen-package public release closure remains unchanged. Linux/Darwin Nix and successor execution/binding/consumer acceptance are not inferred.", +] + +[[deviation]] id = "RCRV1-DEV-043" date = "2026-10-16" status = "closed" diff --git a/contracts/coverage.toml b/contracts/coverage.toml @@ -56,6 +56,7 @@ crates = [ "radroots_blossom", "radroots_core", "radroots_core_bindings", + "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", diff --git a/contracts/crates/catalog.v2.toml b/contracts/crates/catalog.v2.toml @@ -7,7 +7,7 @@ rust_version = "1.99.0" edition = "2024" resolver = "3" public_package_count = 19 -package_count = 51 +package_count = 52 digest_algorithm = "sha256-raw-bytes-v1" source_tree_digest_algorithm = "sha256-git-ls-tree-r-v1" native_introduction_tree_digest_algorithm = "sha256-git-tree-records-z-v1" @@ -61,6 +61,24 @@ compatibility = ["rust_api", "features", "package"] replaces = [] [[package]] +name = "radroots_domain" +path = "crates/domain" +state = "active" +tier = "domain" +visibility = "private_boundary" +publish = false +version = "0.1.0-alpha" +license = "MIT OR Apache-2.0" +platforms = ["any"] +groups = ["coverage_required", "preview"] +owners = ["domain"] +permitted_dependency_tiers = ["foundation"] +provenance_kind = "native" +introduction_tree_sha256 = "30a184507a178e87c4077506757fd6fa314594e17baf40679805a859f45fae1f" +compatibility = ["package_private"] +replaces = [] + +[[package]] name = "radroots_identity" path = "crates/identity" state = "active" diff --git a/contracts/crates/generated/package_groups.v1.toml b/contracts/crates/generated/package_groups.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.package-groups.v1" -catalog_sha256 = "f6f0d6af573b28e5b5bf7c6862d26ba6a5583d5674149fb4e96f8a6630b51735" +catalog_sha256 = "dd9492323450398c9c7eb2e9880cdd595a950bde24d03060c3c957f7530cad61" [[group]] id = "boundaries" @@ -9,8 +9,8 @@ reserved_packages = [] [[group]] id = "coverage_required" -packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] -active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] reserved_packages = [] [[group]] @@ -21,8 +21,8 @@ reserved_packages = [] [[group]] id = "preview" -packages = ["radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] -active_packages = ["radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] +packages = ["radroots_domain", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] +active_packages = ["radroots_domain", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_transport_reticulum"] reserved_packages = [] [[group]] diff --git a/contracts/crates/generated/platform_inventory.v1.toml b/contracts/crates/generated/platform_inventory.v1.toml @@ -1,9 +1,9 @@ schema = "radroots.workspace.platform-inventory.v1" -catalog_sha256 = "f6f0d6af573b28e5b5bf7c6862d26ba6a5583d5674149fb4e96f8a6630b51735" +catalog_sha256 = "dd9492323450398c9c7eb2e9880cdd595a950bde24d03060c3c957f7530cad61" [[platform]] id = "any" -packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_event", "radroots_event_codec", "radroots_identity", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_replica_schema", "radroots_sdk", "radroots_signing", "radroots_simplex_agent_proto", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_test_fixtures", "radroots_trade", "radroots_transport"] +packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_identity", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_replica_schema", "radroots_sdk", "radroots_signing", "radroots_simplex_agent_proto", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_test_fixtures", "radroots_trade", "radroots_transport"] [[platform]] id = "native" diff --git a/contracts/crates/generated/release_inventory.v2.toml b/contracts/crates/generated/release_inventory.v2.toml @@ -1,7 +1,7 @@ schema = "radroots.workspace.release-inventory.v2" -catalog_sha256 = "f6f0d6af573b28e5b5bf7c6862d26ba6a5583d5674149fb4e96f8a6630b51735" +catalog_sha256 = "dd9492323450398c9c7eb2e9880cdd595a950bde24d03060c3c957f7530cad61" architecture = "radroots.crates.release.v2" version = "0.1.0-alpha" public_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_event", "radroots_event_codec", "radroots_geonames", "radroots_identity", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade", "radroots_transport", "radroots_transport_nostr"] -private_packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_reticulum", "xtask"] +private_packages = ["radroots_core_bindings", "radroots_domain", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_reticulum", "xtask"] reserved_packages = [] diff --git a/contracts/releases/publish_policy.toml b/contracts/releases/publish_policy.toml @@ -52,6 +52,7 @@ external_packages = [] [workspace_classification] private = [ + "radroots_domain", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", diff --git a/crates/domain/Cargo.toml b/crates/domain/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "radroots_domain" +publish = false +version = "0.1.0-alpha" +edition.workspace = true +authors.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +description = "Exact values and deterministic shared Radroots domain invariants" +readme = "README.md" + +[features] +default = ["std", "serde"] +std = [] +serde = ["dep:serde"] + +[dependencies] +serde = { workspace = true, optional = true } + +[dev-dependencies] +serde_json = { workspace = true } + +[lints] +workspace = true diff --git a/crates/domain/LICENSE-APACHE b/crates/domain/LICENSE-APACHE @@ -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 2025 Tyson Lupul + +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/LICENSE-MIT b/crates/domain/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2025 Tyson Lupul + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -0,0 +1,19 @@ +# Radroots domain + +Independently implemented exact values for the shared SDK successor. This +package is under construction and is not published or part of the current +public release closure. It does not yet implement listings, agreements or +command execution. + +`Decimal` has a nonnegative coefficient up to 999999999999 and scale 0–6. +Construction normalizes fractional trailing zeros. String admission requires +that canonical representation; JSON uses strings exclusively. `PositiveDecimal` +additionally rejects zero. Checked addition and subtraction are exact and +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. + +Licensed under MIT OR Apache-2.0; see LICENSE-MIT and LICENSE-APACHE. diff --git a/crates/domain/src/amount.rs b/crates/domain/src/amount.rs @@ -0,0 +1,290 @@ +use core::{cmp::Ordering, fmt, str::FromStr}; + +/// A validated, canonical, nonnegative decimal with no floating representation. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Decimal { + coefficient: u64, + scale: u8, +} + +/// A validated decimal strictly greater than zero. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct PositiveDecimal(Decimal); + +/// A bounded value admission or exact-arithmetic failure; never contains input. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum AmountError { + /// The input is not an unsigned ASCII decimal string. + InvalidFormat, + /// The spelling is not the canonical representation of its value. + NonCanonical, + /// The coefficient exceeds the supported twelve-digit bound. + CoefficientOutOfRange, + /// The scale exceeds six fractional digits. + ScaleOutOfRange, + /// A strictly positive amount was required. + MustBePositive, + /// Subtraction would produce a negative value. + NegativeResult, +} + +impl fmt::Display for AmountError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidFormat => "invalid decimal format", + Self::NonCanonical => "noncanonical decimal representation", + Self::CoefficientOutOfRange => "decimal coefficient exceeds supported bound", + Self::ScaleOutOfRange => "decimal scale exceeds supported bound", + Self::MustBePositive => "decimal must be positive", + Self::NegativeResult => "decimal subtraction would be negative", + }) + } +} + +impl core::error::Error for AmountError {} + +impl Decimal { + /// Largest supported canonical coefficient. + pub const MAX_COEFFICIENT: u64 = 999_999_999_999; + /// Largest supported scale. + pub const MAX_SCALE: u8 = 6; + /// Maximum syntax length, checked before examining untrusted string contents. + pub const MAX_ENCODED_LEN: usize = 19; + /// Canonical zero. + pub const ZERO: Self = Self { + coefficient: 0, + scale: 0, + }; + /// Canonical one. + pub const ONE: Self = Self { + coefficient: 1, + scale: 0, + }; + /// Largest supported value. + pub const MAX: Self = Self { + coefficient: Self::MAX_COEFFICIENT, + scale: 0, + }; + + /// Validates bounded input parts, then removes fractional trailing zeros. + /// + /// Both input bounds apply before normalization. Zero always has scale zero. + pub const fn from_parts(coefficient: u64, scale: u8) -> Result<Self, AmountError> { + if scale > Self::MAX_SCALE { + return Err(AmountError::ScaleOutOfRange); + } + if coefficient > Self::MAX_COEFFICIENT { + return Err(AmountError::CoefficientOutOfRange); + } + Ok(Self::normalized(coefficient, scale)) + } + + const fn normalized(mut coefficient: u64, mut scale: u8) -> Self { + if coefficient == 0 { + return Self::ZERO; + } + while scale > 0 && coefficient.is_multiple_of(10) { + coefficient /= 10; + scale -= 1; + } + Self { coefficient, scale } + } + + /// The canonical coefficient, without an implicit unit or currency. + pub const fn coefficient(self) -> u64 { + self.coefficient + } + /// The canonical number of fractional decimal digits. + pub const fn scale(self) -> u8 { + self.scale + } + /// Whether this amount is exactly zero. + pub const fn is_zero(self) -> bool { + self.coefficient == 0 + } + + // Validated coefficients times at most 10^6 fit in u64, including the + // addition of two such aligned values. These helpers never round. + fn aligned(self, scale: u8) -> u64 { + self.coefficient * 10_u64.pow(u32::from(scale - self.scale)) + } + + fn from_result(coefficient: u64, scale: u8) -> Result<Self, AmountError> { + let value = Self::normalized(coefficient, scale); + Self::from_parts(value.coefficient, value.scale) + } + + /// Adds exactly, rejecting a result outside the canonical coefficient bound. + pub fn checked_add(self, rhs: Self) -> Result<Self, AmountError> { + let scale = self.scale.max(rhs.scale); + let coefficient = self + .aligned(scale) + .checked_add(rhs.aligned(scale)) + .ok_or(AmountError::CoefficientOutOfRange)?; + Self::from_result(coefficient, scale) + } + + /// Subtracts exactly; negative or unrepresentable results are errors. + pub fn checked_sub(self, rhs: Self) -> Result<Self, AmountError> { + let scale = self.scale.max(rhs.scale); + let coefficient = self + .aligned(scale) + .checked_sub(rhs.aligned(scale)) + .ok_or(AmountError::NegativeResult)?; + Self::from_result(coefficient, scale) + } +} + +impl Ord for Decimal { + fn cmp(&self, rhs: &Self) -> Ordering { + let scale = self.scale.max(rhs.scale); + self.aligned(scale).cmp(&rhs.aligned(scale)) + } +} + +impl PartialOrd for Decimal { + fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> { + Some(self.cmp(rhs)) + } +} + +impl FromStr for Decimal { + type Err = AmountError; + + fn from_str(input: &str) -> Result<Self, Self::Err> { + if input.is_empty() || input.len() > Self::MAX_ENCODED_LEN { + return Err(AmountError::InvalidFormat); + } + let (whole, fraction) = match input.split_once('.') { + Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction), + Some(_) => return Err(AmountError::InvalidFormat), + None => (input, ""), + }; + if whole.is_empty() + || !whole + .bytes() + .chain(fraction.bytes()) + .all(|b| b.is_ascii_digit()) + { + return Err(AmountError::InvalidFormat); + } + if (whole.len() > 1 && whole.starts_with('0')) || fraction.ends_with('0') { + return Err(AmountError::NonCanonical); + } + if fraction.len() > usize::from(Self::MAX_SCALE) { + return Err(AmountError::ScaleOutOfRange); + } + let mut coefficient = 0_u64; + for digit in whole.bytes().chain(fraction.bytes()) { + coefficient = coefficient + .checked_mul(10) + .and_then(|v| v.checked_add(u64::from(digit - b'0'))) + .filter(|v| *v <= Self::MAX_COEFFICIENT) + .ok_or(AmountError::CoefficientOutOfRange)?; + } + // The length bound above proves conversion fits in u8. + Self::from_parts(coefficient, fraction.len() as u8) + } +} + +impl fmt::Display for Decimal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.scale == 0 { + return write!(f, "{}", self.coefficient); + } + let divisor = 10_u64.pow(u32::from(self.scale)); + write!( + f, + "{}.{:0width$}", + self.coefficient / divisor, + self.coefficient % divisor, + width = usize::from(self.scale) + ) + } +} + +impl PositiveDecimal { + /// Requires an already validated nonzero value. + pub const fn new(value: Decimal) -> Result<Self, AmountError> { + if value.is_zero() { + Err(AmountError::MustBePositive) + } else { + Ok(Self(value)) + } + } + /// Returns the validated nonnegative representation without losing precision. + pub const fn amount(self) -> Decimal { + self.0 + } +} + +impl TryFrom<Decimal> for PositiveDecimal { + type Error = AmountError; + fn try_from(value: Decimal) -> Result<Self, Self::Error> { + Self::new(value) + } +} + +impl From<PositiveDecimal> for Decimal { + fn from(value: PositiveDecimal) -> Self { + value.amount() + } +} + +impl FromStr for PositiveDecimal { + type Err = AmountError; + fn from_str(input: &str) -> Result<Self, Self::Err> { + Self::new(input.parse()?) + } +} + +impl fmt::Display for PositiveDecimal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +#[cfg(feature = "serde")] +mod serde_impl { + use super::{Decimal, PositiveDecimal}; + use core::fmt; + use serde::{ + Deserialize, Deserializer, Serialize, Serializer, + de::{self, Visitor}, + }; + + impl Serialize for Decimal { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.collect_str(self) + } + } + + impl<'de> Deserialize<'de> for Decimal { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + struct DecimalVisitor; + impl Visitor<'_> for DecimalVisitor { + type Value = Decimal; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a canonical Radroots decimal string") + } + fn visit_str<E: de::Error>(self, value: &str) -> Result<Decimal, E> { + value.parse().map_err(E::custom) + } + } + deserializer.deserialize_str(DecimalVisitor) + } + } + + impl Serialize for PositiveDecimal { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + self.amount().serialize(serializer) + } + } + + impl<'de> Deserialize<'de> for PositiveDecimal { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + Self::new(Decimal::deserialize(deserializer)?).map_err(de::Error::custom) + } + } +} diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -0,0 +1,8 @@ +#![doc = include_str!("../README.md")] +#![cfg_attr(not(feature = "std"), no_std)] +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod amount; + +pub use amount::{AmountError, Decimal, PositiveDecimal}; diff --git a/crates/domain/tests/amount.rs b/crates/domain/tests/amount.rs @@ -0,0 +1,289 @@ +use radroots_domain::{AmountError, Decimal, PositiveDecimal}; +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, +}; + +fn decimal(input: &str) -> Decimal { + input.parse().unwrap() +} + +#[test] +fn canonical_hand_vectors_round_trip_without_float_conversion() { + for (text, coefficient, scale) in [ + ("0", 0, 0), + ("1", 1, 0), + ("0.000001", 1, 6), + ("999999999999", 999_999_999_999, 0), + ("999999.999999", 999_999_999_999, 6), + ("12.345", 12_345, 3), + ("0.01", 1, 2), + ] { + let value = decimal(text); + assert_eq!(value.coefficient(), coefficient, "{text}"); + assert_eq!(value.scale(), scale, "{text}"); + assert_eq!(value.to_string(), text); + assert_eq!(Decimal::from_parts(coefficient, scale).unwrap(), value); + } + assert_eq!(Decimal::MAX, decimal("999999999999")); + assert_eq!(Decimal::ONE, decimal("1")); +} + +#[test] +fn construction_normalizes_fractional_zeros_and_zero() { + for scale in 0..=Decimal::MAX_SCALE { + assert_eq!(Decimal::from_parts(0, scale).unwrap(), Decimal::ZERO); + } + assert_eq!(Decimal::from_parts(123_000, 4).unwrap(), decimal("12.3")); + assert_eq!(Decimal::from_parts(100_000, 5).unwrap(), Decimal::ONE); + assert_eq!(Decimal::from_parts(120, 0).unwrap().coefficient(), 120); +} + +#[test] +fn constructor_checks_both_input_bounds_before_normalization() { + assert_eq!( + Decimal::from_parts(1_000_000_000_000, 1), + Err(AmountError::CoefficientOutOfRange) + ); + assert_eq!( + Decimal::from_parts(u64::MAX, 0), + Err(AmountError::CoefficientOutOfRange) + ); + assert_eq!(Decimal::from_parts(0, 7), Err(AmountError::ScaleOutOfRange)); + assert_eq!( + Decimal::from_parts(1, u8::MAX), + Err(AmountError::ScaleOutOfRange) + ); +} + +#[test] +fn strings_require_canonical_unsigned_ascii_spelling() { + for input in [ + "", "-0", "-1", "+1", ".1", "1.", "1..2", "1e2", "1E2", " 1", "1 ", "1\n", "1\t", "1,000", + "1_000", "1", "١", "NaN", "Infinity", + ] { + assert!(input.parse::<Decimal>().is_err(), "{input:?}"); + } + for input in ["00", "01", "00.1", "0.0", "1.0", "1.2300", "0.000000"] { + assert_eq!( + input.parse::<Decimal>(), + Err(AmountError::NonCanonical), + "{input}" + ); + } +} + +#[test] +fn combined_coefficient_and_scale_are_semantic_admission_bounds() { + // These fit the syntax's integer/fraction widths but exceed the combined bound. + for input in ["999999999999.1", "9999999.999999", "1000000000000"] { + assert_eq!( + input.parse::<Decimal>(), + Err(AmountError::CoefficientOutOfRange), + "{input}" + ); + } + assert_eq!( + "0.0000001".parse::<Decimal>(), + Err(AmountError::ScaleOutOfRange) + ); +} + +#[test] +fn overlong_inputs_fail_with_constant_redacted_diagnostics() { + let input = "sensitive_fixture_".repeat(4096); + let error = input.parse::<Decimal>().unwrap_err(); + assert_eq!(error, AmountError::InvalidFormat); + assert_eq!(error.to_string(), "invalid decimal format"); + assert!(!format!("{error:?}").contains("sensitive_fixture")); + assert_eq!( + "9".repeat(Decimal::MAX_ENCODED_LEN + 1).parse::<Decimal>(), + Err(AmountError::InvalidFormat) + ); +} + +#[test] +fn positivity_cannot_be_bypassed_by_construction_or_parsing() { + assert_eq!( + PositiveDecimal::new(Decimal::ZERO), + Err(AmountError::MustBePositive) + ); + assert_eq!( + PositiveDecimal::try_from(Decimal::ZERO), + Err(AmountError::MustBePositive) + ); + assert_eq!( + "0".parse::<PositiveDecimal>(), + Err(AmountError::MustBePositive) + ); + assert!("-1".parse::<PositiveDecimal>().is_err()); + for text in ["0.000001", "1", "999999999999"] { + let positive: PositiveDecimal = text.parse().unwrap(); + assert_eq!(positive.amount(), decimal(text)); + assert_eq!(Decimal::from(positive), decimal(text)); + assert_eq!(positive.to_string(), text); + } +} + +#[test] +fn ordering_is_numeric_across_scales_and_hashing_uses_canonical_parts() { + let ascending = [ + "0", + "0.000001", + "0.1", + "0.99", + "1", + "1.01", + "2", + "10", + "999999999999", + ]; + for pair in ascending.windows(2) { + assert!(decimal(pair[0]) < decimal(pair[1])); + assert!(decimal(pair[1]) > decimal(pair[0])); + } + let canonical = decimal("1.23"); + let normalized = Decimal::from_parts(123_000, 5).unwrap(); + assert_eq!(canonical, normalized); + assert_eq!( + canonical.partial_cmp(&normalized), + Some(core::cmp::Ordering::Equal) + ); + let hash = |v: Decimal| { + let mut h = DefaultHasher::new(); + v.hash(&mut h); + h.finish() + }; + assert_eq!(hash(canonical), hash(normalized)); + assert!("0.1".parse::<PositiveDecimal>().unwrap() < "1".parse().unwrap()); +} + +#[test] +fn addition_and_subtraction_preserve_exact_results_across_scales() { + for (left, right, sum) in [ + ("0.1", "0.2", "0.3"), + ("1", "0.000001", "1.000001"), + ("999999999998", "1", "999999999999"), + ("0.999999", "0.000001", "1"), + ("50000000000", "50000000000", "100000000000"), + ("0", "1.23", "1.23"), + ] { + let (left, right, sum) = (decimal(left), decimal(right), decimal(sum)); + assert_eq!(left.checked_add(right).unwrap(), sum); + assert_eq!(right.checked_add(left).unwrap(), sum); + assert_eq!(sum.checked_sub(left).unwrap(), right); + assert_eq!(sum.checked_sub(right).unwrap(), left); + } + assert_eq!(Decimal::MAX.checked_sub(Decimal::MAX), Ok(Decimal::ZERO)); +} + +#[test] +fn arithmetic_rejects_negative_or_unrepresentable_results_without_rounding() { + assert_eq!( + Decimal::ZERO.checked_sub(Decimal::ONE), + Err(AmountError::NegativeResult) + ); + assert_eq!( + Decimal::MAX.checked_add(Decimal::ONE), + Err(AmountError::CoefficientOutOfRange) + ); + assert_eq!( + Decimal::MAX.checked_add(decimal("0.000001")), + Err(AmountError::CoefficientOutOfRange) + ); + assert_eq!( + Decimal::MAX.checked_sub(decimal("0.000001")), + Err(AmountError::CoefficientOutOfRange) + ); + assert_eq!( + decimal("999999999998").checked_sub(Decimal::MAX), + Err(AmountError::NegativeResult) + ); +} + +#[test] +fn bounded_small_grid_matches_independent_integer_micro_units() { + // Independent integer oracle in millionths; no production parsing/arithmetic helpers. + for left in 0..=20_u64 { + for right in 0..=20_u64 { + for scale in 0..=6_u8 { + let a = Decimal::from_parts(left, scale).unwrap(); + let b = Decimal::from_parts(right, 6 - scale).unwrap(); + let expected = + left * 10_u64.pow(u32::from(6 - scale)) + right * 10_u64.pow(u32::from(scale)); + let sum = a.checked_add(b).unwrap(); + assert_eq!( + sum.coefficient() * 10_u64.pow(u32::from(6 - sum.scale())), + expected + ); + assert_eq!(sum.checked_sub(a).unwrap(), b); + } + } + } +} + +#[test] +fn all_error_messages_are_static_bounded_and_distinct() { + let errors = [ + AmountError::InvalidFormat, + AmountError::NonCanonical, + AmountError::CoefficientOutOfRange, + AmountError::ScaleOutOfRange, + AmountError::MustBePositive, + AmountError::NegativeResult, + ]; + let messages = errors.map(|e| e.to_string()); + for (i, message) in messages.iter().enumerate() { + assert!(!message.is_empty() && message.len() <= 64); + assert!(!messages[..i].contains(message)); + } +} + +#[cfg(feature = "serde")] +mod json { + use super::*; + + #[test] + fn decimal_and_positive_values_round_trip_only_as_canonical_strings() { + for text in ["0", "0.000001", "999999999999", "999999.999999"] { + let value = decimal(text); + let encoded = serde_json::to_string(&value).unwrap(); + assert_eq!(encoded, format!("\"{text}\"")); + assert_eq!(serde_json::from_str::<Decimal>(&encoded).unwrap(), value); + if !value.is_zero() { + let positive = PositiveDecimal::new(value).unwrap(); + assert_eq!(serde_json::to_string(&positive).unwrap(), encoded); + assert_eq!( + serde_json::from_str::<PositiveDecimal>(&encoded).unwrap(), + positive + ); + } + } + } + + #[test] + fn numbers_objects_and_noncanonical_values_cannot_bypass_admission() { + for input in [ + "1", + "1.5", + "null", + "true", + "[]", + "{}", + "{\"coefficient\":1,\"scale\":0}", + "\"-0\"", + "\"01\"", + "\"1.0\"", + "\"1e2\"", + "\"999999999999.1\"", + "\"0.0000001\"", + ] { + assert!(serde_json::from_str::<Decimal>(input).is_err(), "{input}"); + assert!( + serde_json::from_str::<PositiveDecimal>(input).is_err(), + "{input}" + ); + } + assert!(serde_json::from_str::<PositiveDecimal>("\"0\"").is_err()); + } +}