From 66e22cb41fb38185588831259c0fe82c52d13709 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:32:49 -0600 Subject: [PATCH] lxmf: require durable propagation acceptance and immutable messages --- .github/workflows/ci.yml | 2 +- .github/workflows/release.yml | 4 +- CHANGELOG.md | 9 + Cargo.lock | 43 +- Cargo.toml | 22 +- api/fixtures/Cargo.lock | 170 +- api/fixtures/src/lib.rs | 29 + api/migrations/1.4.md | 162 + api/migrations/relay-store-v2.md | 130 + api/snapshots/lxmf-core.txt | 783 ++++- api/snapshots/lxmf-tools.txt | 5 + api/snapshots/manifest-contract.json | 65 +- api/stability.json | 80 +- crates/lxmf-core/Cargo.toml | 8 +- crates/lxmf-core/examples/message.rs | 19 +- crates/lxmf-core/src/admission.rs | 618 ++++ crates/lxmf-core/src/admission_store.rs | 599 ++++ crates/lxmf-core/src/delivery_ratchet.rs | 33 +- crates/lxmf-core/src/lib.rs | 10 +- crates/lxmf-core/src/link_delivery.rs | 864 +++-- crates/lxmf-core/src/message.rs | 2875 ++++------------- crates/lxmf-core/src/message/draft.rs | 404 +++ crates/lxmf-core/src/message/field.rs | 341 ++ .../fixtures/python-reordered-public.bin | 1 + .../src/message/fixtures/python-reordered.bin | Bin 0 -> 165 bytes crates/lxmf-core/src/message/tests.rs | 733 +++++ crates/lxmf-core/src/persist.rs | 216 +- crates/lxmf-core/src/presentation.rs | 33 + crates/lxmf-core/src/propagation_client.rs | 833 ++++- .../lxmf-core/src/propagation_client_tests.rs | 483 ++- crates/lxmf-core/src/propagation_node.rs | 2034 +++++++----- crates/lxmf-core/src/propagation_send.rs | 292 ++ crates/lxmf-core/src/propagation_store_v2.rs | 456 +++ .../propagation_store_v2/android_container.rs | 207 ++ .../src/propagation_store_v2/migration.rs | 466 +++ .../src/propagation_store_v2/mobile.rs | 167 + .../src/propagation_store_v2/offline.rs | 165 + .../src/propagation_store_v2/recovery.rs | 330 ++ crates/lxmf-core/src/propagation_sync.rs | 371 ++- crates/lxmf-core/src/router.rs | 898 +++-- crates/lxmf-core/src/stamper.rs | 19 +- crates/lxmf-core/tests/durable_delivery.rs | 560 ++++ crates/lxmf-core/tests/relay_store_v2.rs | 243 ++ crates/lxmf-tools/Cargo.toml | 1 + crates/lxmf-tools/src/commands/lxmd.rs | 2589 +++++++++++---- crates/lxmf-tools/src/daemon.rs | 17 +- crates/lxmf-tools/src/lxmd_cli.rs | 17 + tools/check-api-baseline.py | 6 +- tools/check-api-compatibility.py | 64 +- 49 files changed, 13493 insertions(+), 4983 deletions(-) create mode 100644 api/migrations/1.4.md create mode 100644 api/migrations/relay-store-v2.md create mode 100644 crates/lxmf-core/src/admission.rs create mode 100644 crates/lxmf-core/src/admission_store.rs create mode 100644 crates/lxmf-core/src/message/draft.rs create mode 100644 crates/lxmf-core/src/message/field.rs create mode 100644 crates/lxmf-core/src/message/fixtures/python-reordered-public.bin create mode 100644 crates/lxmf-core/src/message/fixtures/python-reordered.bin create mode 100644 crates/lxmf-core/src/message/tests.rs create mode 100644 crates/lxmf-core/src/propagation_send.rs create mode 100644 crates/lxmf-core/src/propagation_store_v2.rs create mode 100644 crates/lxmf-core/src/propagation_store_v2/android_container.rs create mode 100644 crates/lxmf-core/src/propagation_store_v2/migration.rs create mode 100644 crates/lxmf-core/src/propagation_store_v2/mobile.rs create mode 100644 crates/lxmf-core/src/propagation_store_v2/offline.rs create mode 100644 crates/lxmf-core/src/propagation_store_v2/recovery.rs create mode 100644 crates/lxmf-core/tests/durable_delivery.rs create mode 100644 crates/lxmf-core/tests/relay_store_v2.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 02ddc4c..4d3951a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ permissions: contents: read env: - RSLXMF_RSRETICULUM_COMMIT: 799e946ac997f388395fec4e8c49ea55a03e5bc8 + RSLXMF_RSRETICULUM_COMMIT: 817a640ed1e11e3ff3e0ff048d8de13662bfdd78 jobs: api-compat: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a729bed..51cc4dc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,8 +24,8 @@ env: RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }} PACKAGE_ROOT: rsLXMF LXMF_BINS: lxmd-rs - RSLXMF_RSRETICULUM_VERSION: 1.3.0 - RSLXMF_RSRETICULUM_COMMIT: 799e946ac997f388395fec4e8c49ea55a03e5bc8 + RSLXMF_RSRETICULUM_VERSION: 1.4.0 + RSLXMF_RSRETICULUM_COMMIT: 817a640ed1e11e3ff3e0ff048d8de13662bfdd78 jobs: verify: diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e191bd..88c6c06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +## 1.4.0 - 2026-10-12 + +- Preserve each signed message exactly as received, including binary text and custom fields, and reject ambiguous field definitions. +- Remove downloaded messages from a propagation node only after the receiving application confirms durable acceptance. Failed items remain available for retry. +- Keep propagation messages encrypted in storage, quarantine untrusted legacy entries, and require storage recovery before a node becomes available. +- Keep stamps, encryption, and ticket state consistent across retries and restarts, and reject undecipherable messages instead of treating them as plaintext. +- Bound background delivery work, keep node downloads responsive during storage operations, and defer excess downloads without dropping valid messages during busy periods. +- Updated message construction and delivery APIs and require rsReticulum `~1.4.0`. This source-breaking release uses the `~1.4.0` compatibility line. + ## 1.3.0 - 2026-10-12 ### Added diff --git a/Cargo.lock b/Cargo.lock index 4f3bb49..8515ef2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -138,7 +138,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" dependencies = [ - "objc2", + "objc2 0.5.2", ] [[package]] @@ -643,11 +643,13 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "lxmf-core" -version = "1.3.0" +version = "1.4.0" dependencies = [ "base64", "bytes", "hex", + "jni", + "objc2 0.6.5", "proptest", "rand 0.8.5", "rmp", @@ -670,7 +672,7 @@ dependencies = [ [[package]] name = "lxmf-tools" -version = "1.3.0" +version = "1.4.0" dependencies = [ "base64", "bytes", @@ -688,6 +690,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "zeroize", ] [[package]] @@ -783,6 +786,15 @@ dependencies = [ "objc2-encode", ] +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + [[package]] name = "objc2-core-bluetooth" version = "0.2.2" @@ -790,7 +802,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111" dependencies = [ "bitflags 2.11.0", - "objc2", + "objc2 0.5.2", "objc2-foundation", ] @@ -809,7 +821,7 @@ dependencies = [ "bitflags 2.11.0", "block2", "libc", - "objc2", + "objc2 0.5.2", ] [[package]] @@ -1052,7 +1064,7 @@ dependencies = [ [[package]] name = "rns-crypto" -version = "1.3.0" +version = "1.4.0" dependencies = [ "aes", "cbc", @@ -1070,9 +1082,10 @@ dependencies = [ [[package]] name = "rns-identity" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", + "libc", "rand 0.8.5", "rmp-serde", "rmpv", @@ -1080,6 +1093,7 @@ dependencies = [ "rns-wire", "serde", "serde_bytes", + "sha2", "thiserror 2.0.18", "tracing", "windows-sys 0.61.2", @@ -1088,7 +1102,7 @@ dependencies = [ [[package]] name = "rns-interface" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -1097,7 +1111,7 @@ dependencies = [ "libc", "md-5", "mio", - "objc2", + "objc2 0.5.2", "objc2-core-bluetooth", "objc2-foundation", "rand 0.8.5", @@ -1117,7 +1131,7 @@ dependencies = [ [[package]] name = "rns-link" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", "rand 0.8.5", @@ -1132,7 +1146,7 @@ dependencies = [ [[package]] name = "rns-protocol" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bzip2", "hex", @@ -1141,6 +1155,7 @@ dependencies = [ "rns-crypto", "rns-link", "rns-wire", + "serde", "thiserror 2.0.18", "tokio", "tracing", @@ -1148,7 +1163,7 @@ dependencies = [ [[package]] name = "rns-runtime" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -1175,7 +1190,7 @@ dependencies = [ [[package]] name = "rns-transport" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -1194,7 +1209,7 @@ dependencies = [ [[package]] name = "rns-wire" -version = "1.3.0" +version = "1.4.0" dependencies = [ "rns-crypto", "sha2", diff --git a/Cargo.toml b/Cargo.toml index 1ebf351..d75c1da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,25 +6,25 @@ members = [ ] [workspace.package] -version = "1.3.0" +version = "1.4.0" edition = "2024" license = "AGPL-3.0-or-later" rust-version = "1.89" [workspace.dependencies] # Reticulum crates from a sibling rsReticulum checkout during development. -rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.3.0" } -rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.3.0" } -rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.3.0" } -rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.3.0" } -rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.3.0" } -rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.3.0" } -rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.3.0" } -rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.3.0" } +rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.4.0" } +rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.4.0" } +rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.4.0" } +rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.4.0" } +rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.4.0" } +rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.4.0" } +rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.4.0" } +rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.4.0" } # Workspace LXMF crates -lxmf-core = { path = "crates/lxmf-core", version = "1.3.0" } -lxmf-tools = { path = "crates/lxmf-tools", version = "1.3.0" } +lxmf-core = { path = "crates/lxmf-core", version = "~1.4.0" } +lxmf-tools = { path = "crates/lxmf-tools", version = "~1.4.0" } # Encoding base64 = "0.22" diff --git a/api/fixtures/Cargo.lock b/api/fixtures/Cargo.lock index 4bd43ca..98328e5 100644 --- a/api/fixtures/Cargo.lock +++ b/api/fixtures/Cargo.lock @@ -79,6 +79,12 @@ dependencies = [ "cipher", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cfg-if" version = "1.0.4" @@ -95,6 +101,16 @@ dependencies = [ "inout", ] +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -264,6 +280,48 @@ dependencies = [ "generic-array", ] +[[package]] +name = "jni" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec" +dependencies = [ + "cesu8", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "libbz2-rs-sys" version = "0.2.5" @@ -285,13 +343,21 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + [[package]] name = "lxmf-core" -version = "1.3.0" +version = "1.4.0" dependencies = [ "base64", "bytes", "hex", + "jni", + "objc2", "rand", "rmp", "rmp-serde", @@ -304,7 +370,7 @@ dependencies = [ "rns-wire", "serde", "sha2", - "thiserror", + "thiserror 2.0.20", "tokio", "tracing", "unicode-normalization", @@ -317,6 +383,12 @@ dependencies = [ "lxmf-core", ] +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "mio" version = "1.2.3" @@ -337,6 +409,21 @@ dependencies = [ "autocfg", ] +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + [[package]] name = "once_cell" version = "1.21.4" @@ -474,11 +561,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" dependencies = [ "rmp", + "serde", + "serde_bytes", ] [[package]] name = "rns-crypto" -version = "1.3.0" +version = "1.4.0" dependencies = [ "aes", "cbc", @@ -489,16 +578,17 @@ dependencies = [ "rand_core", "sha2", "subtle", - "thiserror", + "thiserror 2.0.20", "x25519-dalek", "zeroize", ] [[package]] name = "rns-identity" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", + "libc", "rand", "rmp-serde", "rmpv", @@ -506,7 +596,8 @@ dependencies = [ "rns-wire", "serde", "serde_bytes", - "thiserror", + "sha2", + "thiserror 2.0.20", "tracing", "windows-sys", "zeroize", @@ -514,7 +605,7 @@ dependencies = [ [[package]] name = "rns-link" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", "rand", @@ -522,14 +613,14 @@ dependencies = [ "rns-crypto", "rns-identity", "rns-wire", - "thiserror", + "thiserror 2.0.20", "tracing", "zeroize", ] [[package]] name = "rns-protocol" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bzip2", "hex", @@ -538,14 +629,15 @@ dependencies = [ "rns-crypto", "rns-link", "rns-wire", - "thiserror", + "serde", + "thiserror 2.0.20", "tokio", "tracing", ] [[package]] name = "rns-transport" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -557,18 +649,18 @@ dependencies = [ "rns-wire", "serde", "subtle", - "thiserror", + "thiserror 2.0.20", "tokio", "tracing", ] [[package]] name = "rns-wire" -version = "1.3.0" +version = "1.4.0" dependencies = [ "rns-crypto", "sha2", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -580,6 +672,15 @@ dependencies = [ "semver", ] +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -716,13 +817,33 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -837,12 +958,31 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + [[package]] name = "windows-link" version = "0.2.1" diff --git a/api/fixtures/src/lib.rs b/api/fixtures/src/lib.rs index e243766..c88a006 100644 --- a/api/fixtures/src/lib.rs +++ b/api/fixtures/src/lib.rs @@ -57,3 +57,32 @@ pub mod delivery_ownership { }); } } + +/// Reviewed immutable construction, full-width keys and source-bound verification. +pub mod immutable_messages { + use lxmf_core::message_api::{ + DeliveryMethod, FieldId, LxMessage, LxMessageDraft, MessageError, RecipientStamp, + VerifiedLxMessage, + }; + pub fn with_external_signer(signer: F) -> Result + where + F: FnOnce(&[u8]) -> Result<[u8; 64], E>, + E: std::fmt::Display, + { + let mut draft = + LxMessageDraft::new([1; 16], [2; 16], "title", "content", DeliveryMethod::Direct)?; + draft.set_field(FieldId::from(u64::MAX), vec![1, 2])?; + draft.set_msgpack_field(FieldId::from(i64::MIN), vec![0x91, 0x01])?; + let signed = draft.sign_with(signer)?; + let _id = signed.message_id(); + signed.finalize(Some(RecipientStamp::Ticket([0; 16]))) + } + pub fn inspect<'a>( + message: &'a LxMessage, + public_key: &[u8; 64], + ) -> Result, MessageError> { + let _same_owner = message.wire_owned(); + let _custom = message.fields().get(u64::MAX); + message.verify(public_key) + } +} diff --git a/api/migrations/1.4.md b/api/migrations/1.4.md new file mode 100644 index 0000000..d3a48c5 --- /dev/null +++ b/api/migrations/1.4.md @@ -0,0 +1,162 @@ +# 1.4 source migration (unreleased) + +Messages now retain the exact signed bytes received or finalized for sending. +Verification, storage, and delivery metadata cannot change those bytes. The +`message_api` and `message` module paths export the same types. + +## Construct, sign, then finalize + +```rust +use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft}; +use rns_crypto::ed25519::Ed25519PrivateKey; + +let mut draft = LxMessageDraft::new( + [0x11; 16], [0x22; 16], "Hello", "A message", DeliveryMethod::Direct, +)?; +draft.set_field(0x105_u64, vec![1, 2, 3])?; +// When using a router, prepare and durably commit its reply-ticket intent here. +let signed = draft.sign(&Ed25519PrivateKey::generate())?; +let stamp = signed.generate_recipient_stamp()?; +let message = signed.finalize(stamp)?; +let bytes = message.wire_bytes(); +# Ok::<(), lxmf_core::message_api::MessageError>(()) +``` + +Use `sign_with` for an external or hardware signer. Both signing methods consume +the draft. Signing refuses a router-prepared ticket whose persistence intent is +still pending. `SignedLxMessage` exposes the stable message ID for recipient +stamp work, but cannot be sent. `finalize(None)` explicitly chooses no recipient +stamp. A finalized message has no content setters, signing method, or assignable +hash/signature/stamp. To change content, construct a new draft and explicitly +copy the desired fields; reply tickets and authentication state are not copied +implicitly. Propagation encryption/stamps belong to their separate send owner. + +## Read the immutable message + +| Previous access | Replacement | +| --- | --- | +| `message.destination_hash`, `source_hash` | `destination_hash()`, `source_hash()` | +| `message.hash` or `message.message_id` | `message_id()`; always present | +| `message.signature` | `signature()`; always present | +| `message.title`, `content` | `title_text()`, `content_text()` return `Cow`; `*_bytes()` preserve exact bytes | +| `message.timestamp` | `timestamp()` | +| `message.fields`, `msgpack_field_ids` | `fields()` and coherent `FieldValueRef` | +| `message.stamp` | `recipient_stamp()` | +| `message.signature_validated` | successful source-bound `verify` capability | +| `message.wire_payload` | `wire_bytes()` for the complete image | + +Mutable delivery metadata remains available through `MessageMetadata` and +field access (`message.method`, `message.progress`, etc.). It cannot alter +content or create authentication authority. + +`wire_bytes()` borrows the complete image; `wire_owned()` cheaply shares its +ownership for asynchronous writes. `pack()` explicitly copies it into a Vec. +`pack_payload()` copies the original payload. `unpack_owned(Bytes, limits)` +takes ownership without copying; `unpack(&[u8])` makes a convenience copy. +Container and paper exports preserve these bytes. Repeated verification is pure. + +`verify(&full_reticulum_public_key)` checks that the complete 64-byte public key +binds the claimed `lxmf.delivery` source, then verifies the signature. It returns +a private-construction `VerifiedLxMessage` for sender-authorized operations such +as ticket learning. `verify_signature(&ed25519_key)` remains available for +detached diagnostics, but does not establish source identity. Parsing and an +unknown sender are not authenticated-sender status. + +## Fields and profiles + +`FieldId` preserves integers from `i64::MIN` through `u64::MAX`. Nonnegative IDs +serialize as MessagePack unsigned64; negative IDs as signed64. Equivalent +positive signed and unsigned integer encodings compare equal. Outer duplicate +IDs are rejected, including alternative encodings of the same number. IDs above +255 and negative IDs remain custom keys and never alias a standard field. + +`set_field` emits a binary value. `set_msgpack_field` accepts exactly one validated +encoded MessagePack value. `set_field_value` accepts their coherent `FieldValue` +representation. `FieldValueRef::encoded()` exposes exact encoded bytes; +`as_binary()` unwraps only binary. Binary bytes that happen to look like a map +or array do not become structured values. Recognized schema readers can use +`unique_map()` to reject duplicate integer/text keys before acting; unknown +nested values remain opaque. `MessagePayload` is a semantic DTO, not an archive +or signature source. + +The host default profile permits 4,096 outer fields and 134,217,727 complete +wire bytes. Use `new_with_limits` and `unpack_owned` with the same explicit +`MessageDecodeLimits` when selecting another local policy. Construction checks +count and exact size before signing and finalization, including stamp framing. +These are parser/construction ceilings, not transport promises: Resource segment +limits, metadata, encryption and propagation wrapping impose separate admission +checks. The embedded profile retains 64 fields and depth8; host-valid custom +messages are not automatically compatible with every device. + +Old corrupted files are never silently repaired or re-signed. A hash-shaped +filename that disagrees with its decoded message ID returns a distinct error; +the file is retained. Restore original bytes from a trusted backup when available. +Unknown sender keys cannot establish whether an old signature is valid. + +Use the reviewed compatible minor line (for example `~1.4.0`) or an exact source +revision when migrating dependents together. A default caret requirement permits +subsequent minor lines. Do not mix dependent code still using mutable messages +with this API. + + +## Router, propagation, and asynchronous ownership + +`prepare_outbound(&mut draft)` returns an `OutboundTicketIntent`; persist it +through the intended durable state store before signing. A pending intent blocks +the exact draft's signer. `submit_signed` takes a `SignedLxMessage` and handles +recipient-stamp work before finalization; `defer_stamp` and the deferred map also +own signed messages. The former mutable `get_stamp` work belongs to +`SignedLxMessage::generate_recipient_stamp`, while frozen-message stamp checks +are read-only and return a result for the current policy. + +`learn_ticket_from_inbound` takes a successful `VerifiedLxMessage`. When a worker +must retain authentication across an asynchronous handoff, use `to_owned()` and +later `OwnedVerifiedLxMessage::as_verified()`. The owned capability shares the +original bytes and does not expose mutable authenticated state. + +Replace `pack_propagated_encrypted*` with `PropagationEnvelope` in the +`propagation_send` module. It owns the frozen message, encrypted blob, exact TID +and PN stamp. Reuse that envelope for retries; regenerate only the work whose +policy changed. The old message `transient_id` and `propagation_stamp` fields no +longer exist. `PendingDelivery.message` is a retained delivery owner that can +release payload bytes when an idle Link only needs metadata/receipt state. + +Replace `take_received_messages` with `take_downloaded_messages`. Keep each +leased image and admission token until validation and durable local commit; +resolve the token with the explicit disposition and durable receipt. A fetched +message or Resource proof is not permission to purge remote data. + +Hosted propagation accepts a validated opaque encrypted/stamped blob through +`ValidatedOpaquePropagationBlob` and `plan_opaque_admission`, followed by the +plan's durable persistence and exact commit. Plain `accept_message`, +`accept_propagated_blob`, their old planning variants and sync plaintext +admission are removed: plaintext signatures are not relay storage authority. +Use a durable node store and follow the [relay store migration](relay-store-v2.md). +A nondurable `PropagationNode::new` cannot acknowledge relay storage. + +Hosted `/get` handlers must use the bounded deferred request API in +`rns_runtime::LinkManager`, after installing its exact endpoint dispatch handle. +Check the handler registration result. Retain `DeferredRequestResponder` inside +the actual blocking worker through store planning, durable purge and verified +file reads; cancellation of an async caller must not detach uncharged I/O. +Pass `response_byte_limit()` to both `handle_get_request_bounded` and +`into_response_with_served_count_bounded`, using the configured propagation +transfer ceiling when registering the handler. These methods reject malformed +requests before purge, deduplicate wants, preserve complete-message accounting +and build one bounded response. An absent client limit still obeys the local +ceiling. The runtime fences responses to the original Link generation and keeps +Resource credits until the transfer releases its data. `Sent` acknowledges +queue acceptance or Resource initiation, not remote delivery. + +`unpack_propagation_wrapper_owned(Bytes, limit)` returns shared `Bytes` payloads +and checks framing/counts before allocation. The Vec-returning compatibility +helper still copies explicitly. `FieldValueRef::from_encoded` validates exactly +one borrowed value, and `as_text` accepts UTF8 MessagePack text only; binary data +is not silently interpreted. Use `unique_map` before acting on recognized map +keys. Text/media projections borrow where possible; repaired UTF8 allocates only +the exact replacement length. + +The API ledger retains its original compatibility floor and lists exact removed +rendered lines. Metadata fields moved under `MessageMetadata` retain ordinary +field access through Deref; duplicate `message_api` snapshot paths describe the +same type migration. No unrelated API removal is waived. diff --git a/api/migrations/relay-store-v2.md b/api/migrations/relay-store-v2.md new file mode 100644 index 0000000..84a1e14 --- /dev/null +++ b/api/migrations/relay-store-v2.md @@ -0,0 +1,130 @@ +# Relay store migration + +Relay nodes now admit only validated opaque propagation data to a durable store. +A packet proof follows complete validation and acknowledged durable admission. +Resource completion still means transport completion; it does not certify the +receiver's application storage. Ordinary message archives are separate from +relay storage and must never be copied into it. + +## Startup and recovery + +A new store can initialize automatically. An existing legacy directory requires +explicit offline migration. An incomplete migration, invalid committed record, +unsupported filesystem, or unavailable storage prevents hosting. Daemons fail +startup when required relay storage is unavailable. Applications retain the +user's hosting preference but show hosting as unavailable until recovery succeeds. +There is no automatic in-memory fallback for a durable host. + +Stop every process that can write the store, including service supervisors and +scheduled restarts. Then run the candidate daemon against the correct config: + +```sh +lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped +``` + +Check `lxmd-rs --help` for the config-path option supported by your build. The +writer-stopped flag is an explicit assertion that supervisors have been stopped. +The tool also holds the store's OS lock and refuses when it finds another known +Ratspeak/LXMF daemon process, or cannot enumerate processes. Older binaries do not +honor the new lock; manually restarting one while migration runs is unsupported. +The process-name check cannot discover every renamed or custom relay program. + +On iOS and Android, use the application's inbox recovery action for its private +store. The app first stops and joins its hosting and sync workers. Recovery +checks native application ownership and takes the same exclusive store lock; +it does not run the desktop process-list command or accept arbitrary external +directories. iOS recovery is restricted to the main app's private data container, +excluding extensions and shared app groups. Android recovery additionally +requires an exclusive app UID, the default app process, and no declared secondary +processes. Shared storage, shared UIDs and unverified ownership remain unavailable +for automatic recovery. Keep the original files and resolve the ownership or +storage error before retrying; do not remove the guard or copy archives into the +live store. + +The migrator inventories relative paths, lengths and SHA-256 hashes before +moving anything. Symbolic links, special files, changed inventory and conflicting +unowned destinations stop migration without overwriting originals. It preserves +the legacy directory as `.legacy-quarantine`, writes a regular-file guard +at the old path, and creates `.v2`. The sibling `.migration` journal +records every transition. Interrupted runs resume through the same command; +do not remove journals or guards to force startup. Windows directory publication +uses recorded sibling moves rather than inferring durability from existence. + +The completion report gives the number and size of preserved files. Legacy +files are not offered, served, or counted as live relay messages. Their apparent +encryption shape, filename, previous app version, or old directory location does +not establish opaque-ingress provenance. Migration never automatically deletes +or expires the archive. + +## Explicitly trusted recovery + +Recovery requires independent, per-entry evidence of the original opaque +propagation ingress. A directory-wide assertion is insufficient. An operator +can supply a MessagePack named-map `TrustedRecoveryManifest` with these fields: + +| Field | Value | +| --- | --- | +| `version` | `2` | +| `provenance` | Nonempty explanation of the independently checked evidence | +| `entries` | Array of the exact authorized records | +| Entry `archive_relative_path` | Relative path from the committed inventory | +| Entry `content_hash` | SHA-256 of the complete stored bytes, as 32 integer bytes | +| Entry `transient_id` | SHA-256 of destination+ciphertext, excluding a trailing PN stamp | +| Entry `stamped` | Whether the file includes the 32-byte PN stamp | +| Entry `stored_at` | Finite, nonnegative receipt timestamp | + +Use the exported Rust structs and `rmp_serde::to_vec_named` to encode the record. +Review the manifest and independently record its SHA-256. Supply that approved +digest separately; merely hashing an unreviewed manifest does not establish trust. + +```sh +lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped \ + --recover-propagation-manifest /path/to/recovery.msgpack \ + --recovery-manifest-sha256 APPROVED_SHA256_HEX +``` + +The importer checks the complete archive against its committed inventory, every +selected path/hash/TID, ciphertext framing, positive plaintext rejection, actual +stamp strength, and current size/quota policy before publication. Unstamped +recovery requires both explicit provenance and a zero minimum stamp policy. +Entries without evidence remain quarantined. Repeating the exact approved import +is idempotent; it cannot replace a different first accepted image. A failed IO +can leave a valid subset committed, so retain the manifest and retry. + +## Library integration + +Use `PropagationNode::with_storage` for a durable host. Keep readiness bound to +the active identity generation and drain the old generation's workers before +opening or migrating its store. `begin_offline_migration` returns the retained +writer-exclusion guard used by both migration and trusted recovery. + +Mobile embeddings use `begin_ios_container_migration` or +`begin_android_container_migration` on the corresponding target. The Android +function takes the attached worker's JNI environment and real platform Context; +it obtains package, UID, component and data-directory metadata from the framework. +Neither API accepts a caller-provided container root or a flag to bypass ownership +checks. Hold the identity/session lifecycle guard through the actual blocking +operation and restart, including after the invoking UI task is canceled. An app +that launches additional native relay writers must stop and join those writers +too; the container boundary does not replace ownership of current-process work. + +For ingress, validate a complete packet batch before writing anything, then use +`plan_opaque_admission`. Run `Reserved(plan).persist()` on a blocking worker and +commit its returned capability to that same node. Await `Pending` outside the +bounded storage-worker slots. `CommittedDuplicate(check)` is only a plan: call +`check.verify()` on a blocking worker before treating it as durable. Keep the +original typed Link receipt alive through all these operations. A dropped worker +result yields no proof; retry reuses the first complete indexed image. + +The private format publishes an immutable object and provenance record, then a +per-TID active index. Unindexed remnants are never served. A durable deletion +intent revokes eligibility before cleanup; restart resumes cleanup. Purge and +maintenance operate on a particular admission path, so a stale plan cannot +delete a later admission of the same TID. Resolve `GetServePlan` and maintenance +plans off the actor; a failed purge intent cannot return an empty success array. + +The old-path guard prevents ordinary reopening of that exact legacy directory. +It cannot revoke objects already held in an old process or prevent an old daemon +from using another path or its in-memory fallback. If rolling back software, +keep **both relay hosting and propagation sync disabled**. Preserve the archive, +journal, guard and v2 store; never copy them back to the legacy layout. diff --git a/api/snapshots/lxmf-core.txt b/api/snapshots/lxmf-core.txt index 121b30c..28aa596 100644 --- a/api/snapshots/lxmf-core.txt +++ b/api/snapshots/lxmf-core.txt @@ -1,4 +1,125 @@ pub mod lxmf_core +pub mod lxmf_core::admission +pub enum lxmf_core::admission::AdmissionError +pub lxmf_core::admission::AdmissionError::CommitUncertain(alloc::string::String) +pub lxmf_core::admission::AdmissionError::DispositionLedgerFull +pub lxmf_core::admission::AdmissionError::NotCommitted(alloc::string::String) +pub lxmf_core::admission::AdmissionError::WrongScope +pub enum lxmf_core::admission::DownloadAdmissionOutcome +pub lxmf_core::admission::DownloadAdmissionOutcome::Accepted(lxmf_core::admission::DurableAdmissionReceipt) +pub lxmf_core::admission::DownloadAdmissionOutcome::Rejected(lxmf_core::admission::SuppressionReason) +pub enum lxmf_core::admission::DurableDisposition +pub lxmf_core::admission::DurableDisposition::Committed +pub lxmf_core::admission::DurableDisposition::Duplicate +pub lxmf_core::admission::DurableDisposition::PolicyDiscard +pub lxmf_core::admission::DurableDisposition::UserDeleted +pub enum lxmf_core::admission::SuppressionReason +pub lxmf_core::admission::SuppressionReason::Cancelled +pub lxmf_core::admission::SuppressionReason::DecryptionFailed +pub lxmf_core::admission::SuppressionReason::DispositionLedgerFull +pub lxmf_core::admission::SuppressionReason::InvalidSignature +pub lxmf_core::admission::SuppressionReason::InvalidStamp +pub lxmf_core::admission::SuppressionReason::Malformed +pub lxmf_core::admission::SuppressionReason::MissingKey +pub lxmf_core::admission::SuppressionReason::Quota +pub lxmf_core::admission::SuppressionReason::StorageBusy +pub lxmf_core::admission::SuppressionReason::StorageUnavailable +pub lxmf_core::admission::SuppressionReason::TooLarge +pub lxmf_core::admission::SuppressionReason::WorkerUnavailable +pub lxmf_core::admission::SuppressionReason::WrongDestination +impl lxmf_core::admission::SuppressionReason +pub fn lxmf_core::admission::SuppressionReason::is_transient(self) -> bool +pub struct lxmf_core::admission::AdmissionEpochs +pub lxmf_core::admission::AdmissionEpochs::budget: [u8; 32] +pub lxmf_core::admission::AdmissionEpochs::keys: [u8; 32] +pub lxmf_core::admission::AdmissionEpochs::policy: [u8; 32] +pub lxmf_core::admission::AdmissionEpochs::storage_health: [u8; 32] +pub struct lxmf_core::admission::AdmissionRecord +pub lxmf_core::admission::AdmissionRecord::committed_at: u64 +pub lxmf_core::admission::AdmissionRecord::disposition: lxmf_core::admission::DurableDisposition +pub lxmf_core::admission::AdmissionRecord::message_id: [u8; 32] +pub lxmf_core::admission::AdmissionRecord::received_wire_hash: [u8; 32] +pub lxmf_core::admission::AdmissionRecord::scope: lxmf_core::admission::AdmissionScope +pub lxmf_core::admission::AdmissionRecord::stored_message_wire_hash: core::option::Option<[u8; 32]> +pub struct lxmf_core::admission::AdmissionScope +pub lxmf_core::admission::AdmissionScope::identity: [u8; 16] +pub lxmf_core::admission::AdmissionScope::node: [u8; 16] +pub lxmf_core::admission::AdmissionScope::transient_id: [u8; 32] +pub struct lxmf_core::admission::DownloadAdmissionToken +impl lxmf_core::admission::DownloadAdmissionToken +pub fn lxmf_core::admission::DownloadAdmissionToken::is_current(&self) -> bool +pub fn lxmf_core::admission::DownloadAdmissionToken::resolve(self, lxmf_core::admission::DownloadAdmissionOutcome) -> core::result::Result<(), lxmf_core::admission::AdmissionError> +pub fn lxmf_core::admission::DownloadAdmissionToken::scope(&self) -> lxmf_core::admission::AdmissionScope +impl core::fmt::Debug for lxmf_core::admission::DownloadAdmissionToken +pub fn lxmf_core::admission::DownloadAdmissionToken::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::ops::drop::Drop for lxmf_core::admission::DownloadAdmissionToken +pub fn lxmf_core::admission::DownloadAdmissionToken::drop(&mut self) +pub struct lxmf_core::admission::DownloadedPropagationMessage +impl lxmf_core::admission::DownloadedPropagationMessage +pub fn lxmf_core::admission::DownloadedPropagationMessage::data(&self) -> &bytes::bytes::Bytes +pub fn lxmf_core::admission::DownloadedPropagationMessage::into_parts(self) -> (bytes::bytes::Bytes, lxmf_core::admission::DownloadAdmissionToken) +pub fn lxmf_core::admission::DownloadedPropagationMessage::scope(&self) -> lxmf_core::admission::AdmissionScope +pub struct lxmf_core::admission::DurableAdmissionReceipt +impl lxmf_core::admission::DurableAdmissionReceipt +pub fn lxmf_core::admission::DurableAdmissionReceipt::commit(impl lxmf_core::admission::DurableAdmissionBackend) -> core::result::Result +pub fn lxmf_core::admission::DurableAdmissionReceipt::record(&self) -> &lxmf_core::admission::AdmissionRecord +pub struct lxmf_core::admission::DurableHave +pub lxmf_core::admission::DurableHave::expires_at: core::option::Option +pub lxmf_core::admission::DurableHave::transient_id: [u8; 32] +impl lxmf_core::admission::DurableHave +pub fn lxmf_core::admission::DurableHave::active(self, u64) -> bool +pub fn lxmf_core::admission::DurableHave::from_record(&lxmf_core::admission::AdmissionRecord) -> Self +pub struct lxmf_core::admission::ProcessingLease +impl lxmf_core::admission::ProcessingLease +pub fn lxmf_core::admission::ProcessingLease::try_acquire(usize) -> core::result::Result +pub struct lxmf_core::admission::ProcessingMemoryLease +impl lxmf_core::admission::ProcessingMemoryLease +pub fn lxmf_core::admission::ProcessingMemoryLease::try_acquire(usize) -> core::result::Result +pub struct lxmf_core::admission::SuppressionLedger +impl lxmf_core::admission::SuppressionLedger +pub const lxmf_core::admission::SuppressionLedger::GLOBAL: usize +pub const lxmf_core::admission::SuppressionLedger::PER_IDENTITY: usize +pub const lxmf_core::admission::SuppressionLedger::PER_NODE: usize +pub fn lxmf_core::admission::SuppressionLedger::from_records(impl core::iter::traits::collect::IntoIterator) -> core::result::Result +pub fn lxmf_core::admission::SuppressionLedger::get(&self, &lxmf_core::admission::AdmissionScope) -> core::option::Option<&lxmf_core::admission::SuppressionRecord> +pub fn lxmf_core::admission::SuppressionLedger::prune(&mut self, u64, lxmf_core::admission::AdmissionEpochs) +pub fn lxmf_core::admission::SuppressionLedger::record_failure(&mut self, lxmf_core::admission::AdmissionScope, lxmf_core::admission::SuppressionReason, lxmf_core::admission::AdmissionEpochs, u64) -> core::result::Result<&lxmf_core::admission::SuppressionRecord, lxmf_core::admission::AdmissionError> +pub fn lxmf_core::admission::SuppressionLedger::records(&self) -> impl core::iter::traits::iterator::Iterator +pub fn lxmf_core::admission::SuppressionLedger::remove(&mut self, &lxmf_core::admission::AdmissionScope) +pub fn lxmf_core::admission::SuppressionLedger::saturated(&self, [u8; 16], [u8; 16]) -> bool +pub struct lxmf_core::admission::SuppressionRecord +pub lxmf_core::admission::SuppressionRecord::attempts: u16 +pub lxmf_core::admission::SuppressionRecord::epochs: lxmf_core::admission::AdmissionEpochs +pub lxmf_core::admission::SuppressionRecord::expires_at: u64 +pub lxmf_core::admission::SuppressionRecord::last_failure: u64 +pub lxmf_core::admission::SuppressionRecord::next_retry: u64 +pub lxmf_core::admission::SuppressionRecord::reason: lxmf_core::admission::SuppressionReason +pub lxmf_core::admission::SuppressionRecord::scope: lxmf_core::admission::AdmissionScope +impl lxmf_core::admission::SuppressionRecord +pub fn lxmf_core::admission::SuppressionRecord::active(&self, u64, lxmf_core::admission::AdmissionEpochs) -> bool +pub const lxmf_core::admission::MAX_DOWNLOAD_ITEMS: usize +pub const lxmf_core::admission::MAX_PROCESSING_BYTES: usize +pub const lxmf_core::admission::MAX_PROCESSORS: usize +pub const lxmf_core::admission::MAX_RETAINED_DOWNLOAD_BYTES: usize +pub const lxmf_core::admission::POLICY_RECEIPT_LIFETIME: u64 +pub trait lxmf_core::admission::DurableAdmissionBackend +pub fn lxmf_core::admission::DurableAdmissionBackend::commit(self) -> core::result::Result +impl lxmf_core::admission::DurableAdmissionBackend for lxmf_core::admission_store::FileAdmissionCommit +pub fn lxmf_core::admission_store::FileAdmissionCommit::commit(self) -> core::result::Result +pub mod lxmf_core::admission_store +pub struct lxmf_core::admission_store::FileAdmissionCommit +impl lxmf_core::admission::DurableAdmissionBackend for lxmf_core::admission_store::FileAdmissionCommit +pub fn lxmf_core::admission_store::FileAdmissionCommit::commit(self) -> core::result::Result +pub struct lxmf_core::admission_store::FileAdmissionStore +impl lxmf_core::admission_store::FileAdmissionStore +pub fn lxmf_core::admission_store::FileAdmissionStore::complete_hook(&self, [u8; 32]) -> core::result::Result<(), lxmf_core::admission::AdmissionError> +pub fn lxmf_core::admission_store::FileAdmissionStore::durable_haves(&self, [u8; 16], [u8; 16], u64) -> alloc::vec::Vec +pub fn lxmf_core::admission_store::FileAdmissionStore::haves(&self, [u8; 16], [u8; 16], u64) -> alloc::vec::Vec> +pub fn lxmf_core::admission_store::FileAdmissionStore::maintain(&self, u64) -> core::result::Result +pub fn lxmf_core::admission_store::FileAdmissionStore::mark_user_deleted(&self, [u8; 16], [u8; 32], u64) -> core::result::Result<(), lxmf_core::admission::AdmissionError> +pub fn lxmf_core::admission_store::FileAdmissionStore::open(&std::path::Path, &std::path::Path) -> core::result::Result +pub fn lxmf_core::admission_store::FileAdmissionStore::pending_hooks(&self) -> alloc::vec::Vec<([u8; 32], std::path::PathBuf)> +pub fn lxmf_core::admission_store::FileAdmissionStore::prepare(&self, lxmf_core::admission::AdmissionRecord, bytes::bytes::Bytes, bool) -> lxmf_core::admission_store::FileAdmissionCommit pub mod lxmf_core::constants #[repr(u8)] pub enum lxmf_core::constants::DeliveryMethod pub lxmf_core::constants::DeliveryMethod::Direct = 2 @@ -195,6 +316,7 @@ pub fn lxmf_core::delivery_ratchet::DeliveryRatchetState::load_or_initialize(&rn pub fn lxmf_core::delivery_ratchet::DeliveryRatchetState::ring(&self) -> &rns_identity::ratchet::RatchetRing pub fn lxmf_core::delivery_ratchet::DeliveryRatchetState::ring_path(&self) -> &std::path::Path pub fn lxmf_core::delivery_ratchet::DeliveryRatchetState::save(&self, &rns_identity::identity::Identity) +pub fn lxmf_core::delivery_ratchet::DeliveryRatchetState::save_durable(&self, &rns_identity::identity::Identity) -> core::io::error::Result<()> pub const lxmf_core::delivery_ratchet::DELIVERY_APP_NAME: &str pub mod lxmf_core::discovery_stamper pub struct lxmf_core::discovery_stamper::LxmfDiscoveryStamper @@ -406,6 +528,7 @@ pub lxmf_core::link_delivery::DirectLinkStartKind::NewDirect pub lxmf_core::link_delivery::DirectLinkStartKind::QueuedOnDirect pub lxmf_core::link_delivery::DirectLinkStartKind::ReusedActiveDirect pub enum lxmf_core::link_delivery::LinkDeliveryStartError +pub lxmf_core::link_delivery::LinkDeliveryStartError::InvalidTiming pub lxmf_core::link_delivery::LinkDeliveryStartError::TransportClosed pub lxmf_core::link_delivery::LinkDeliveryStartError::TransportFull impl core::error::Error for lxmf_core::link_delivery::LinkDeliveryStartError @@ -483,6 +606,7 @@ pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_backchannel_resourc pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_hmu(&mut self, &[u8; 16], &[u8]) pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_link_packet_proof(&mut self, &[u8; 16], &[u8]) -> bool pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_link_proof(&mut self, &[u8; 16], &[u8], &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 32], rns_transport::messages::InterfaceId) -> bool +pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_link_proof_with_owner(&mut self, &[u8; 16], &[u8], &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 32], rns_transport::messages::InterfaceId, core::option::Option) -> bool pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_request(&mut self, &[u8; 16], &[u8]) pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_resource_proof(&mut self, &[u8; 16], &[u8]) -> bool pub fn lxmf_core::link_delivery::LinkDeliveryManager::handle_resource_reject(&mut self, &[u8; 16], &[u8]) -> bool @@ -573,7 +697,7 @@ pub lxmf_core::link_delivery::PendingDelivery::dest_hash: [u8; 16] pub lxmf_core::link_delivery::PendingDelivery::establishment_timeout: core::time::Duration pub lxmf_core::link_delivery::PendingDelivery::failure_reason: core::option::Option pub lxmf_core::link_delivery::PendingDelivery::link: rns_link::link::Link -pub lxmf_core::link_delivery::PendingDelivery::message: lxmf_core::message::LxMessage +pub lxmf_core::link_delivery::PendingDelivery::message: lxmf_core::link_delivery::RetainedDeliveryMessage pub lxmf_core::link_delivery::PendingDelivery::msg_hash: core::option::Option<[u8; 32]> pub lxmf_core::link_delivery::PendingDelivery::packed_override: core::option::Option> pub lxmf_core::link_delivery::PendingDelivery::packet_proof_hash: core::option::Option<[u8; 32]> @@ -583,73 +707,129 @@ pub lxmf_core::link_delivery::PendingDelivery::started_at: std::time::Instant pub lxmf_core::link_delivery::PendingDelivery::state: lxmf_core::link_delivery::DeliveryState pub lxmf_core::link_delivery::PendingDelivery::timeout: core::time::Duration pub lxmf_core::link_delivery::PendingDelivery::transfer: core::option::Option +pub struct lxmf_core::link_delivery::RetainedDeliveryMessage +impl lxmf_core::link_delivery::RetainedDeliveryMessage +pub fn lxmf_core::link_delivery::RetainedDeliveryMessage::message_id(&self) -> [u8; 32] +pub fn lxmf_core::link_delivery::RetainedDeliveryMessage::retained_wire_bytes(&self) -> usize +impl core::convert::From for lxmf_core::link_delivery::RetainedDeliveryMessage +pub fn lxmf_core::link_delivery::RetainedDeliveryMessage::from(lxmf_core::message::LxMessage) -> Self +impl core::ops::deref::Deref for lxmf_core::link_delivery::RetainedDeliveryMessage +pub type lxmf_core::link_delivery::RetainedDeliveryMessage::Target = lxmf_core::message::MessageMetadata +pub fn lxmf_core::link_delivery::RetainedDeliveryMessage::deref(&self) -> &Self::Target +impl core::ops::deref::DerefMut for lxmf_core::link_delivery::RetainedDeliveryMessage +pub fn lxmf_core::link_delivery::RetainedDeliveryMessage::deref_mut(&mut self) -> &mut Self::Target pub fn lxmf_core::link_delivery::is_retryable_link_delivery_failure(&str) -> bool pub mod lxmf_core::message +pub enum lxmf_core::message::FieldMapKey<'a> +pub lxmf_core::message::FieldMapKey::Integer(lxmf_core::message::FieldId) +pub lxmf_core::message::FieldMapKey::Text(&'a str) +pub enum lxmf_core::message::FieldValue +pub lxmf_core::message::FieldValue::Binary(bytes::bytes::Bytes) +pub lxmf_core::message::FieldValue::MessagePack(lxmf_core::message::EncodedFieldValue) +impl serde_core::ser::Serialize for lxmf_core::message::FieldValue +pub fn lxmf_core::message::FieldValue::serialize(&self, S) -> core::result::Result<::Ok, ::Error> +impl<'de> serde_core::de::Deserialize<'de> for lxmf_core::message::FieldValue +pub fn lxmf_core::message::FieldValue::deserialize>(D) -> core::result::Result::Error> pub enum lxmf_core::message::MessageError +pub lxmf_core::message::MessageError::DuplicateField +pub lxmf_core::message::MessageError::HistoricalHashMismatch +pub lxmf_core::message::MessageError::InvalidByte +pub lxmf_core::message::MessageError::InvalidFieldId +pub lxmf_core::message::MessageError::InvalidSignature pub lxmf_core::message::MessageError::InvalidUri(alloc::string::String) pub lxmf_core::message::MessageError::NotSigned pub lxmf_core::message::MessageError::PackFailed(alloc::string::String) +pub lxmf_core::message::MessageError::SourceMismatch +pub lxmf_core::message::MessageError::TicketNotCommitted +pub lxmf_core::message::MessageError::TooLarge +pub lxmf_core::message::MessageError::TooLarge::limit: usize +pub lxmf_core::message::MessageError::TooLarge::size: usize +pub lxmf_core::message::MessageError::TooManyFields pub lxmf_core::message::MessageError::TooShort(usize) pub lxmf_core::message::MessageError::UnpackFailed(alloc::string::String) +pub enum lxmf_core::message::RecipientStamp +pub lxmf_core::message::RecipientStamp::ProofOfWork([u8; 32]) +pub lxmf_core::message::RecipientStamp::Ticket([u8; 16]) +impl lxmf_core::message::RecipientStamp +pub fn lxmf_core::message::RecipientStamp::as_bytes(&self) -> &[u8] +pub fn lxmf_core::message::RecipientStamp::from_bytes(&[u8]) -> core::option::Option pub struct lxmf_core::message::AudioField<'a> pub lxmf_core::message::AudioField::bytes: &'a [u8] pub lxmf_core::message::AudioField::mode: u8 +pub struct lxmf_core::message::EncodedFieldValue(_) +impl lxmf_core::message::EncodedFieldValue +pub fn lxmf_core::message::EncodedFieldValue::encoded(&self) -> &[u8] +pub fn lxmf_core::message::EncodedFieldValue::new(bytes::bytes::Bytes) -> core::result::Result +pub struct lxmf_core::message::FieldId(_) +impl lxmf_core::message::FieldId +pub const fn lxmf_core::message::FieldId::as_i128(self) -> i128 +pub fn lxmf_core::message::FieldId::as_standard(self) -> core::option::Option +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i16) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i32) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i64) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i8) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u16) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u32) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u64) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u8) -> Self +impl core::convert::TryFrom for lxmf_core::message::FieldId +pub type lxmf_core::message::FieldId::Error = lxmf_core::message::MessageError +pub fn lxmf_core::message::FieldId::try_from(i128) -> core::result::Result +impl serde_core::ser::Serialize for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::serialize(&self, S) -> core::result::Result<::Ok, ::Error> +impl<'de> serde_core::de::Deserialize<'de> for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::deserialize>(D) -> core::result::Result::Error> +pub struct lxmf_core::message::FieldValueRef<'a> +impl<'a> lxmf_core::message::FieldValueRef<'a> +pub fn lxmf_core::message::FieldValueRef<'a>::as_binary(self) -> core::option::Option<&'a [u8]> +pub fn lxmf_core::message::FieldValueRef<'a>::as_text(self) -> core::option::Option<&'a str> +pub fn lxmf_core::message::FieldValueRef<'a>::encoded(self) -> &'a [u8] +pub fn lxmf_core::message::FieldValueRef<'a>::from_encoded(&'a [u8]) -> core::result::Result +pub fn lxmf_core::message::FieldValueRef<'a>::to_owned(self) -> lxmf_core::message::FieldValue +impl<'a> lxmf_core::message::FieldValueRef<'a> +pub fn lxmf_core::message::FieldValueRef<'a>::unique_map(self) -> core::result::Result, lxmf_core::message::MessageError> +pub struct lxmf_core::message::Fields<'a> +impl<'a> lxmf_core::message::Fields<'a> +pub fn lxmf_core::message::Fields<'a>::contains(self, impl core::convert::Into) -> bool +pub fn lxmf_core::message::Fields<'a>::get(self, impl core::convert::Into) -> core::option::Option> +pub fn lxmf_core::message::Fields<'a>::is_empty(self) -> bool +pub fn lxmf_core::message::Fields<'a>::iter(self) -> impl core::iter::traits::exact_size::ExactSizeIterator)> +pub fn lxmf_core::message::Fields<'a>::len(self) -> usize pub struct lxmf_core::message::LxMessage -pub lxmf_core::message::LxMessage::auto_compress: bool -pub lxmf_core::message::LxMessage::callbacks: lxmf_core::message::MessageCallbacks -pub lxmf_core::message::LxMessage::content: alloc::string::String -pub lxmf_core::message::LxMessage::delivery_attempts: u32 -pub lxmf_core::message::LxMessage::destination_hash: [u8; 16] -pub lxmf_core::message::LxMessage::fields: alloc::collections::btree::map::BTreeMap> -pub lxmf_core::message::LxMessage::hash: core::option::Option<[u8; 32]> -pub lxmf_core::message::LxMessage::include_ticket: bool -pub lxmf_core::message::LxMessage::incoming: bool -pub lxmf_core::message::LxMessage::last_delivery_attempt: f64 -pub lxmf_core::message::LxMessage::message_id: core::option::Option<[u8; 32]> -pub lxmf_core::message::LxMessage::method: lxmf_core::constants::DeliveryMethod -pub lxmf_core::message::LxMessage::msgpack_field_ids: alloc::collections::btree::set::BTreeSet -pub lxmf_core::message::LxMessage::next_delivery_attempt: f64 -pub lxmf_core::message::LxMessage::outbound_ticket: core::option::Option<[u8; 16]> -pub lxmf_core::message::LxMessage::progress: f64 -pub lxmf_core::message::LxMessage::propagation_stamp: core::option::Option<[u8; 32]> -pub lxmf_core::message::LxMessage::ratchet_id: core::option::Option<[u8; 32]> -pub lxmf_core::message::LxMessage::representation: lxmf_core::constants::DeliveryRepresentation -pub lxmf_core::message::LxMessage::signature: core::option::Option<[u8; 64]> -pub lxmf_core::message::LxMessage::signature_validated: bool -pub lxmf_core::message::LxMessage::source_blackholed: bool -pub lxmf_core::message::LxMessage::source_hash: [u8; 16] -pub lxmf_core::message::LxMessage::stamp: core::option::Option> -pub lxmf_core::message::LxMessage::stamp_cost: core::option::Option -pub lxmf_core::message::LxMessage::stamp_value: core::option::Option -pub lxmf_core::message::LxMessage::state: lxmf_core::constants::MessageState -pub lxmf_core::message::LxMessage::timestamp: f64 -pub lxmf_core::message::LxMessage::title: alloc::string::String -pub lxmf_core::message::LxMessage::transient_id: core::option::Option -pub lxmf_core::message::LxMessage::transport_encrypted: bool -pub lxmf_core::message::LxMessage::transport_encryption: core::option::Option -pub lxmf_core::message::LxMessage::unverified_reason: core::option::Option -pub lxmf_core::message::LxMessage::wire_payload: core::option::Option> +pub lxmf_core::message::LxMessage::metadata: lxmf_core::message::MessageMetadata impl lxmf_core::message::LxMessage pub const lxmf_core::message::LxMessage::MIN_PROPAGATION_ENTRY_SIZE: usize pub fn lxmf_core::message::LxMessage::as_uri(&self, F) -> core::option::Option where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::audio_field(&self) -> core::result::Result>, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::cancel(&mut self) -pub fn lxmf_core::message::LxMessage::compute_hash(&mut self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::compute_hash(&self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::compute_propagation_transient_id(&[u8]) -> lxmf_core::types::PropagationTransientId +pub fn lxmf_core::message::LxMessage::content_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessage::content_text(&self) -> alloc::borrow::Cow<'_, str> +pub fn lxmf_core::message::LxMessage::decode_limits(&self) -> lxmf_core::message::MessageDecodeLimits pub fn lxmf_core::message::LxMessage::decode_paper_uri(&str) -> core::result::Result<([u8; 16], alloc::vec::Vec), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::destination_hash(&self) -> [u8; 16] pub fn lxmf_core::message::LxMessage::determine_compression_support(&mut self, core::option::Option<&[u8]>) +pub fn lxmf_core::message::LxMessage::fields(&self) -> lxmf_core::message::Fields<'_> pub fn lxmf_core::message::LxMessage::first_file_attachment(&self) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::from_paper_uri(&str, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::from_uri(&str, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::get_field(&self, u8) -> core::option::Option<&alloc::vec::Vec> -pub fn lxmf_core::message::LxMessage::get_stamp(&mut self) -> core::option::Option> +pub fn lxmf_core::message::LxMessage::get_field(&self, impl core::convert::Into) -> core::option::Option> pub fn lxmf_core::message::LxMessage::image_attachment(&self) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::mark_delivered(&mut self) pub fn lxmf_core::message::LxMessage::mark_failed(&mut self) pub fn lxmf_core::message::LxMessage::mark_rejected(&mut self) pub fn lxmf_core::message::LxMessage::mark_sending(&mut self) pub fn lxmf_core::message::LxMessage::mark_sent(&mut self) -pub fn lxmf_core::message::LxMessage::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> Self +pub fn lxmf_core::message::LxMessage::message_id(&self) -> [u8; 32] pub fn lxmf_core::message::LxMessage::notify_delivered(&self) pub fn lxmf_core::message::LxMessage::notify_failed(&self) pub fn lxmf_core::message::LxMessage::pack(&self) -> core::result::Result, lxmf_core::message::MessageError> @@ -657,40 +837,141 @@ pub fn lxmf_core::message::LxMessage::pack_container(&self) -> core::result::Res pub fn lxmf_core::message::LxMessage::pack_opportunistic_encrypted(&self, F) -> core::result::Result, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::pack_payload(&self) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::pack_propagated(&self) -> core::result::Result, lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted(&mut self, F) -> core::result::Result<(alloc::vec::Vec, lxmf_core::types::PropagationTransientId), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted_with_stamp(&mut self, F, u8) -> core::result::Result<(alloc::vec::Vec, lxmf_core::types::PropagationTransientId, u32), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::packed_len(&self) -> core::result::Result pub fn lxmf_core::message::LxMessage::read_from_file(&str) -> core::result::Result +pub fn lxmf_core::message::LxMessage::recipient_stamp(&self) -> core::option::Option<&lxmf_core::message::RecipientStamp> pub fn lxmf_core::message::LxMessage::register_delivery_callback(&mut self, F) where F: core::ops::function::Fn(&lxmf_core::message::LxMessage) + core::marker::Send + core::marker::Sync + 'static pub fn lxmf_core::message::LxMessage::register_failed_callback(&mut self, F) where F: core::ops::function::Fn(&lxmf_core::message::LxMessage) + core::marker::Send + core::marker::Sync + 'static -pub fn lxmf_core::message::LxMessage::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::set_field(&mut self, u8, alloc::vec::Vec) -pub fn lxmf_core::message::LxMessage::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::set_msgpack_field(&mut self, u8, alloc::vec::Vec) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::sign(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::sign_with(&mut self, F) -> core::result::Result<(), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display +pub fn lxmf_core::message::LxMessage::signature(&self) -> [u8; 64] +pub fn lxmf_core::message::LxMessage::source_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::LxMessage::timestamp(&self) -> f64 +pub fn lxmf_core::message::LxMessage::title_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessage::title_text(&self) -> alloc::borrow::Cow<'_, str> pub fn lxmf_core::message::LxMessage::to_paper_uri(&self, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::unpack(&[u8]) -> core::result::Result pub fn lxmf_core::message::LxMessage::unpack_container(&[u8]) -> core::result::Result +pub fn lxmf_core::message::LxMessage::unpack_owned(bytes::bytes::Bytes, lxmf_core::message::MessageDecodeLimits) -> core::result::Result pub fn lxmf_core::message::LxMessage::unpack_propagated(&[u8]) -> core::result::Result pub fn lxmf_core::message::LxMessage::unpack_propagation_wrapper(&[u8]) -> core::result::Result<(f64, alloc::vec::Vec>), lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::unpack_propagation_wrapper_bounded(&[u8], usize) -> core::result::Result<(f64, alloc::vec::Vec>), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&mut self, u8, core::option::Option<&[alloc::vec::Vec]>) -> bool -pub fn lxmf_core::message::LxMessage::verify(&mut self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool +pub fn lxmf_core::message::LxMessage::unpack_propagation_wrapper_owned(bytes::bytes::Bytes, usize) -> core::result::Result<(f64, alloc::vec::Vec), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&self, u8, core::option::Option<&[alloc::vec::Vec]>) -> bool +pub fn lxmf_core::message::LxMessage::validated_stamp_value(&self, u8, core::option::Option<&[alloc::vec::Vec]>) -> core::option::Option +pub fn lxmf_core::message::LxMessage::verify(&self, &[u8; 64]) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::verify_signature(&self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool +pub fn lxmf_core::message::LxMessage::wire_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessage::wire_owned(&self) -> bytes::bytes::Bytes pub fn lxmf_core::message::LxMessage::write_to_directory(&self, &str) -> core::result::Result +impl core::convert::From for lxmf_core::link_delivery::RetainedDeliveryMessage +pub fn lxmf_core::link_delivery::RetainedDeliveryMessage::from(lxmf_core::message::LxMessage) -> Self +impl core::ops::deref::Deref for lxmf_core::message::LxMessage +pub type lxmf_core::message::LxMessage::Target = lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::LxMessage::deref(&self) -> &Self::Target +impl core::ops::deref::DerefMut for lxmf_core::message::LxMessage +pub fn lxmf_core::message::LxMessage::deref_mut(&mut self) -> &mut Self::Target +pub struct lxmf_core::message::LxMessageDraft +pub lxmf_core::message::LxMessageDraft::include_ticket: bool +pub lxmf_core::message::LxMessageDraft::metadata: lxmf_core::message::MessageMetadata +pub lxmf_core::message::LxMessageDraft::outbound_ticket: core::option::Option<[u8; 16]> +pub lxmf_core::message::LxMessageDraft::stamp_cost: core::option::Option +impl lxmf_core::message::LxMessageDraft +pub fn lxmf_core::message::LxMessageDraft::checked_wire_len(&self) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::content_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessageDraft::destination_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::LxMessageDraft::fields(&self) -> &alloc::collections::btree::map::BTreeMap +pub fn lxmf_core::message::LxMessageDraft::get_field(&self, impl core::convert::Into) -> core::option::Option<&lxmf_core::message::FieldValue> +pub fn lxmf_core::message::LxMessageDraft::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::new_with_limits([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod, lxmf_core::message::MessageDecodeLimits) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::pack_payload(&self) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::remove_field(&mut self, impl core::convert::Into) -> core::option::Option +pub fn lxmf_core::message::LxMessageDraft::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_content(&mut self, &str) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_field(&mut self, impl core::convert::Into, impl core::convert::Into) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_field_value(&mut self, impl core::convert::Into, lxmf_core::message::FieldValue) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_msgpack_field(&mut self, impl core::convert::Into, impl core::convert::Into) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_timestamp(&mut self, f64) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_title(&mut self, &str) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::sign(self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::sign_with(self, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display +pub fn lxmf_core::message::LxMessageDraft::source_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::LxMessageDraft::timestamp(&self) -> f64 +pub fn lxmf_core::message::LxMessageDraft::title_bytes(&self) -> &[u8] +impl core::ops::deref::Deref for lxmf_core::message::LxMessageDraft +pub type lxmf_core::message::LxMessageDraft::Target = lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::LxMessageDraft::deref(&self) -> &Self::Target +impl core::ops::deref::DerefMut for lxmf_core::message::LxMessageDraft +pub fn lxmf_core::message::LxMessageDraft::deref_mut(&mut self) -> &mut Self::Target pub struct lxmf_core::message::MessageCallbacks pub lxmf_core::message::MessageCallbacks::on_delivered: core::option::Option pub lxmf_core::message::MessageCallbacks::on_failed: core::option::Option impl core::fmt::Debug for lxmf_core::message::MessageCallbacks pub fn lxmf_core::message::MessageCallbacks::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct lxmf_core::message::MessageDecodeLimits +pub lxmf_core::message::MessageDecodeLimits::max_top_level_fields: usize +pub lxmf_core::message::MessageDecodeLimits::max_wire_bytes: usize +impl core::default::Default for lxmf_core::message::MessageDecodeLimits +pub fn lxmf_core::message::MessageDecodeLimits::default() -> Self +pub struct lxmf_core::message::MessageMetadata +pub lxmf_core::message::MessageMetadata::auto_compress: bool +pub lxmf_core::message::MessageMetadata::callbacks: lxmf_core::message::MessageCallbacks +pub lxmf_core::message::MessageMetadata::delivery_attempts: u32 +pub lxmf_core::message::MessageMetadata::incoming: bool +pub lxmf_core::message::MessageMetadata::last_delivery_attempt: f64 +pub lxmf_core::message::MessageMetadata::method: lxmf_core::constants::DeliveryMethod +pub lxmf_core::message::MessageMetadata::next_delivery_attempt: f64 +pub lxmf_core::message::MessageMetadata::progress: f64 +pub lxmf_core::message::MessageMetadata::ratchet_id: core::option::Option<[u8; 32]> +pub lxmf_core::message::MessageMetadata::representation: lxmf_core::constants::DeliveryRepresentation +pub lxmf_core::message::MessageMetadata::source_blackholed: bool +pub lxmf_core::message::MessageMetadata::state: lxmf_core::constants::MessageState +pub lxmf_core::message::MessageMetadata::transport_encrypted: bool +pub lxmf_core::message::MessageMetadata::transport_encryption: core::option::Option +pub lxmf_core::message::MessageMetadata::unverified_reason: core::option::Option +impl core::default::Default for lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::MessageMetadata::default() -> Self pub struct lxmf_core::message::MessagePayload pub lxmf_core::message::MessagePayload::content: alloc::string::String -pub lxmf_core::message::MessagePayload::fields: alloc::collections::btree::map::BTreeMap> -pub lxmf_core::message::MessagePayload::msgpack_field_ids: alloc::collections::btree::set::BTreeSet +pub lxmf_core::message::MessagePayload::fields: alloc::collections::btree::map::BTreeMap pub lxmf_core::message::MessagePayload::stamp: core::option::Option> pub lxmf_core::message::MessagePayload::timestamp: f64 pub lxmf_core::message::MessagePayload::title: alloc::string::String +pub struct lxmf_core::message::OwnedVerifiedLxMessage +impl lxmf_core::message::OwnedVerifiedLxMessage +pub fn lxmf_core::message::OwnedVerifiedLxMessage::as_verified(&self) -> lxmf_core::message::VerifiedLxMessage<'_> +pub struct lxmf_core::message::SignedLxMessage +impl lxmf_core::message::SignedLxMessage +pub fn lxmf_core::message::SignedLxMessage::content_bytes(&self) -> &[u8] +pub fn lxmf_core::message::SignedLxMessage::content_text(&self) -> alloc::borrow::Cow<'_, str> +pub fn lxmf_core::message::SignedLxMessage::destination_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::SignedLxMessage::fields(&self) -> lxmf_core::message::Fields<'_> +pub fn lxmf_core::message::SignedLxMessage::finalize(self, core::option::Option) -> core::result::Result +pub fn lxmf_core::message::SignedLxMessage::generate_recipient_stamp(&self) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::message::SignedLxMessage::message_id(&self) -> [u8; 32] +pub fn lxmf_core::message::SignedLxMessage::outbound_ticket(&self) -> core::option::Option<[u8; 16]> +pub fn lxmf_core::message::SignedLxMessage::packed_len(&self) -> core::result::Result +pub fn lxmf_core::message::SignedLxMessage::payload_len(&self) -> usize +pub fn lxmf_core::message::SignedLxMessage::source_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::SignedLxMessage::stamp_cost(&self) -> core::option::Option +pub fn lxmf_core::message::SignedLxMessage::timestamp(&self) -> f64 +pub fn lxmf_core::message::SignedLxMessage::title_bytes(&self) -> &[u8] +pub fn lxmf_core::message::SignedLxMessage::title_text(&self) -> alloc::borrow::Cow<'_, str> +impl core::ops::deref::Deref for lxmf_core::message::SignedLxMessage +pub type lxmf_core::message::SignedLxMessage::Target = lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::SignedLxMessage::deref(&self) -> &Self::Target +impl core::ops::deref::DerefMut for lxmf_core::message::SignedLxMessage +pub fn lxmf_core::message::SignedLxMessage::deref_mut(&mut self) -> &mut Self::Target +pub struct lxmf_core::message::UniqueFieldMap<'a> +impl<'a> lxmf_core::message::UniqueFieldMap<'a> +pub fn lxmf_core::message::UniqueFieldMap<'a>::get(&self, lxmf_core::message::FieldMapKey<'_>) -> core::option::Option> +pub fn lxmf_core::message::UniqueFieldMap<'a>::is_empty(&self) -> bool +pub fn lxmf_core::message::UniqueFieldMap<'a>::len(&self) -> usize +pub struct lxmf_core::message::VerifiedLxMessage<'a> +impl<'a> lxmf_core::message::VerifiedLxMessage<'a> +pub fn lxmf_core::message::VerifiedLxMessage<'a>::message(&self) -> &'a lxmf_core::message::LxMessage +pub fn lxmf_core::message::VerifiedLxMessage<'a>::source_public_key(&self) -> &[u8; 64] +pub fn lxmf_core::message::VerifiedLxMessage<'a>::to_owned(&self) -> lxmf_core::message::OwnedVerifiedLxMessage pub type lxmf_core::message::MessageCallback = alloc::sync::Arc<(dyn core::ops::function::Fn(&lxmf_core::message::LxMessage) + core::marker::Send + core::marker::Sync)> pub mod lxmf_core::message_api #[repr(u8)] pub enum lxmf_core::message_api::DeliveryMethod @@ -705,10 +986,31 @@ pub lxmf_core::message_api::DeliveryRepresentation::Packet = 1 pub lxmf_core::message_api::DeliveryRepresentation::Paper = 5 pub lxmf_core::message_api::DeliveryRepresentation::Resource = 2 pub lxmf_core::message_api::DeliveryRepresentation::Unknown = 0 +pub enum lxmf_core::message_api::FieldMapKey<'a> +pub lxmf_core::message_api::FieldMapKey::Integer(lxmf_core::message::FieldId) +pub lxmf_core::message_api::FieldMapKey::Text(&'a str) +pub enum lxmf_core::message_api::FieldValue +pub lxmf_core::message_api::FieldValue::Binary(bytes::bytes::Bytes) +pub lxmf_core::message_api::FieldValue::MessagePack(lxmf_core::message::EncodedFieldValue) +impl serde_core::ser::Serialize for lxmf_core::message::FieldValue +pub fn lxmf_core::message::FieldValue::serialize(&self, S) -> core::result::Result<::Ok, ::Error> +impl<'de> serde_core::de::Deserialize<'de> for lxmf_core::message::FieldValue +pub fn lxmf_core::message::FieldValue::deserialize>(D) -> core::result::Result::Error> pub enum lxmf_core::message_api::MessageError +pub lxmf_core::message_api::MessageError::DuplicateField +pub lxmf_core::message_api::MessageError::HistoricalHashMismatch +pub lxmf_core::message_api::MessageError::InvalidByte +pub lxmf_core::message_api::MessageError::InvalidFieldId +pub lxmf_core::message_api::MessageError::InvalidSignature pub lxmf_core::message_api::MessageError::InvalidUri(alloc::string::String) pub lxmf_core::message_api::MessageError::NotSigned pub lxmf_core::message_api::MessageError::PackFailed(alloc::string::String) +pub lxmf_core::message_api::MessageError::SourceMismatch +pub lxmf_core::message_api::MessageError::TicketNotCommitted +pub lxmf_core::message_api::MessageError::TooLarge +pub lxmf_core::message_api::MessageError::TooLarge::limit: usize +pub lxmf_core::message_api::MessageError::TooLarge::size: usize +pub lxmf_core::message_api::MessageError::TooManyFields pub lxmf_core::message_api::MessageError::TooShort(usize) pub lxmf_core::message_api::MessageError::UnpackFailed(alloc::string::String) #[repr(u8)] pub enum lxmf_core::message_api::MessageState @@ -720,68 +1022,92 @@ pub lxmf_core::message_api::MessageState::Outbound = 1 pub lxmf_core::message_api::MessageState::Rejected = 253 pub lxmf_core::message_api::MessageState::Sending = 2 pub lxmf_core::message_api::MessageState::Sent = 4 +pub enum lxmf_core::message_api::RecipientStamp +pub lxmf_core::message_api::RecipientStamp::ProofOfWork([u8; 32]) +pub lxmf_core::message_api::RecipientStamp::Ticket([u8; 16]) +impl lxmf_core::message::RecipientStamp +pub fn lxmf_core::message::RecipientStamp::as_bytes(&self) -> &[u8] +pub fn lxmf_core::message::RecipientStamp::from_bytes(&[u8]) -> core::option::Option #[repr(u8)] pub enum lxmf_core::message_api::UnverifiedReason pub lxmf_core::message_api::UnverifiedReason::SignatureInvalid = 2 pub lxmf_core::message_api::UnverifiedReason::SourceUnknown = 1 pub struct lxmf_core::message_api::AudioField<'a> pub lxmf_core::message_api::AudioField::bytes: &'a [u8] pub lxmf_core::message_api::AudioField::mode: u8 +pub struct lxmf_core::message_api::EncodedFieldValue(_) +impl lxmf_core::message::EncodedFieldValue +pub fn lxmf_core::message::EncodedFieldValue::encoded(&self) -> &[u8] +pub fn lxmf_core::message::EncodedFieldValue::new(bytes::bytes::Bytes) -> core::result::Result +pub struct lxmf_core::message_api::FieldId(_) +impl lxmf_core::message::FieldId +pub const fn lxmf_core::message::FieldId::as_i128(self) -> i128 +pub fn lxmf_core::message::FieldId::as_standard(self) -> core::option::Option +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i16) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i32) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i64) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(i8) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u16) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u32) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u64) -> Self +impl core::convert::From for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::from(u8) -> Self +impl core::convert::TryFrom for lxmf_core::message::FieldId +pub type lxmf_core::message::FieldId::Error = lxmf_core::message::MessageError +pub fn lxmf_core::message::FieldId::try_from(i128) -> core::result::Result +impl serde_core::ser::Serialize for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::serialize(&self, S) -> core::result::Result<::Ok, ::Error> +impl<'de> serde_core::de::Deserialize<'de> for lxmf_core::message::FieldId +pub fn lxmf_core::message::FieldId::deserialize>(D) -> core::result::Result::Error> +pub struct lxmf_core::message_api::FieldValueRef<'a> +impl<'a> lxmf_core::message::FieldValueRef<'a> +pub fn lxmf_core::message::FieldValueRef<'a>::as_binary(self) -> core::option::Option<&'a [u8]> +pub fn lxmf_core::message::FieldValueRef<'a>::as_text(self) -> core::option::Option<&'a str> +pub fn lxmf_core::message::FieldValueRef<'a>::encoded(self) -> &'a [u8] +pub fn lxmf_core::message::FieldValueRef<'a>::from_encoded(&'a [u8]) -> core::result::Result +pub fn lxmf_core::message::FieldValueRef<'a>::to_owned(self) -> lxmf_core::message::FieldValue +impl<'a> lxmf_core::message::FieldValueRef<'a> +pub fn lxmf_core::message::FieldValueRef<'a>::unique_map(self) -> core::result::Result, lxmf_core::message::MessageError> +pub struct lxmf_core::message_api::Fields<'a> +impl<'a> lxmf_core::message::Fields<'a> +pub fn lxmf_core::message::Fields<'a>::contains(self, impl core::convert::Into) -> bool +pub fn lxmf_core::message::Fields<'a>::get(self, impl core::convert::Into) -> core::option::Option> +pub fn lxmf_core::message::Fields<'a>::is_empty(self) -> bool +pub fn lxmf_core::message::Fields<'a>::iter(self) -> impl core::iter::traits::exact_size::ExactSizeIterator)> +pub fn lxmf_core::message::Fields<'a>::len(self) -> usize pub struct lxmf_core::message_api::LxMessage -pub lxmf_core::message_api::LxMessage::auto_compress: bool -pub lxmf_core::message_api::LxMessage::callbacks: lxmf_core::message::MessageCallbacks -pub lxmf_core::message_api::LxMessage::content: alloc::string::String -pub lxmf_core::message_api::LxMessage::delivery_attempts: u32 -pub lxmf_core::message_api::LxMessage::destination_hash: [u8; 16] -pub lxmf_core::message_api::LxMessage::fields: alloc::collections::btree::map::BTreeMap> -pub lxmf_core::message_api::LxMessage::hash: core::option::Option<[u8; 32]> -pub lxmf_core::message_api::LxMessage::include_ticket: bool -pub lxmf_core::message_api::LxMessage::incoming: bool -pub lxmf_core::message_api::LxMessage::last_delivery_attempt: f64 -pub lxmf_core::message_api::LxMessage::message_id: core::option::Option<[u8; 32]> -pub lxmf_core::message_api::LxMessage::method: lxmf_core::constants::DeliveryMethod -pub lxmf_core::message_api::LxMessage::msgpack_field_ids: alloc::collections::btree::set::BTreeSet -pub lxmf_core::message_api::LxMessage::next_delivery_attempt: f64 -pub lxmf_core::message_api::LxMessage::outbound_ticket: core::option::Option<[u8; 16]> -pub lxmf_core::message_api::LxMessage::progress: f64 -pub lxmf_core::message_api::LxMessage::propagation_stamp: core::option::Option<[u8; 32]> -pub lxmf_core::message_api::LxMessage::ratchet_id: core::option::Option<[u8; 32]> -pub lxmf_core::message_api::LxMessage::representation: lxmf_core::constants::DeliveryRepresentation -pub lxmf_core::message_api::LxMessage::signature: core::option::Option<[u8; 64]> -pub lxmf_core::message_api::LxMessage::signature_validated: bool -pub lxmf_core::message_api::LxMessage::source_blackholed: bool -pub lxmf_core::message_api::LxMessage::source_hash: [u8; 16] -pub lxmf_core::message_api::LxMessage::stamp: core::option::Option> -pub lxmf_core::message_api::LxMessage::stamp_cost: core::option::Option -pub lxmf_core::message_api::LxMessage::stamp_value: core::option::Option -pub lxmf_core::message_api::LxMessage::state: lxmf_core::constants::MessageState -pub lxmf_core::message_api::LxMessage::timestamp: f64 -pub lxmf_core::message_api::LxMessage::title: alloc::string::String -pub lxmf_core::message_api::LxMessage::transient_id: core::option::Option -pub lxmf_core::message_api::LxMessage::transport_encrypted: bool -pub lxmf_core::message_api::LxMessage::transport_encryption: core::option::Option -pub lxmf_core::message_api::LxMessage::unverified_reason: core::option::Option -pub lxmf_core::message_api::LxMessage::wire_payload: core::option::Option> +pub lxmf_core::message_api::LxMessage::metadata: lxmf_core::message::MessageMetadata impl lxmf_core::message::LxMessage pub const lxmf_core::message::LxMessage::MIN_PROPAGATION_ENTRY_SIZE: usize pub fn lxmf_core::message::LxMessage::as_uri(&self, F) -> core::option::Option where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::audio_field(&self) -> core::result::Result>, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::cancel(&mut self) -pub fn lxmf_core::message::LxMessage::compute_hash(&mut self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::compute_hash(&self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::compute_propagation_transient_id(&[u8]) -> lxmf_core::types::PropagationTransientId +pub fn lxmf_core::message::LxMessage::content_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessage::content_text(&self) -> alloc::borrow::Cow<'_, str> +pub fn lxmf_core::message::LxMessage::decode_limits(&self) -> lxmf_core::message::MessageDecodeLimits pub fn lxmf_core::message::LxMessage::decode_paper_uri(&str) -> core::result::Result<([u8; 16], alloc::vec::Vec), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::destination_hash(&self) -> [u8; 16] pub fn lxmf_core::message::LxMessage::determine_compression_support(&mut self, core::option::Option<&[u8]>) +pub fn lxmf_core::message::LxMessage::fields(&self) -> lxmf_core::message::Fields<'_> pub fn lxmf_core::message::LxMessage::first_file_attachment(&self) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::from_paper_uri(&str, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::from_uri(&str, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::get_field(&self, u8) -> core::option::Option<&alloc::vec::Vec> -pub fn lxmf_core::message::LxMessage::get_stamp(&mut self) -> core::option::Option> +pub fn lxmf_core::message::LxMessage::get_field(&self, impl core::convert::Into) -> core::option::Option> pub fn lxmf_core::message::LxMessage::image_attachment(&self) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::mark_delivered(&mut self) pub fn lxmf_core::message::LxMessage::mark_failed(&mut self) pub fn lxmf_core::message::LxMessage::mark_rejected(&mut self) pub fn lxmf_core::message::LxMessage::mark_sending(&mut self) pub fn lxmf_core::message::LxMessage::mark_sent(&mut self) -pub fn lxmf_core::message::LxMessage::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> Self +pub fn lxmf_core::message::LxMessage::message_id(&self) -> [u8; 32] pub fn lxmf_core::message::LxMessage::notify_delivered(&self) pub fn lxmf_core::message::LxMessage::notify_failed(&self) pub fn lxmf_core::message::LxMessage::pack(&self) -> core::result::Result, lxmf_core::message::MessageError> @@ -789,28 +1115,130 @@ pub fn lxmf_core::message::LxMessage::pack_container(&self) -> core::result::Res pub fn lxmf_core::message::LxMessage::pack_opportunistic_encrypted(&self, F) -> core::result::Result, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::pack_payload(&self) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::pack_propagated(&self) -> core::result::Result, lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted(&mut self, F) -> core::result::Result<(alloc::vec::Vec, lxmf_core::types::PropagationTransientId), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted_with_stamp(&mut self, F, u8) -> core::result::Result<(alloc::vec::Vec, lxmf_core::types::PropagationTransientId, u32), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::packed_len(&self) -> core::result::Result pub fn lxmf_core::message::LxMessage::read_from_file(&str) -> core::result::Result +pub fn lxmf_core::message::LxMessage::recipient_stamp(&self) -> core::option::Option<&lxmf_core::message::RecipientStamp> pub fn lxmf_core::message::LxMessage::register_delivery_callback(&mut self, F) where F: core::ops::function::Fn(&lxmf_core::message::LxMessage) + core::marker::Send + core::marker::Sync + 'static pub fn lxmf_core::message::LxMessage::register_failed_callback(&mut self, F) where F: core::ops::function::Fn(&lxmf_core::message::LxMessage) + core::marker::Send + core::marker::Sync + 'static -pub fn lxmf_core::message::LxMessage::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::set_field(&mut self, u8, alloc::vec::Vec) -pub fn lxmf_core::message::LxMessage::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::set_msgpack_field(&mut self, u8, alloc::vec::Vec) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::sign(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<(), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::sign_with(&mut self, F) -> core::result::Result<(), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display +pub fn lxmf_core::message::LxMessage::signature(&self) -> [u8; 64] +pub fn lxmf_core::message::LxMessage::source_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::LxMessage::timestamp(&self) -> f64 +pub fn lxmf_core::message::LxMessage::title_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessage::title_text(&self) -> alloc::borrow::Cow<'_, str> pub fn lxmf_core::message::LxMessage::to_paper_uri(&self, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::unpack(&[u8]) -> core::result::Result pub fn lxmf_core::message::LxMessage::unpack_container(&[u8]) -> core::result::Result +pub fn lxmf_core::message::LxMessage::unpack_owned(bytes::bytes::Bytes, lxmf_core::message::MessageDecodeLimits) -> core::result::Result pub fn lxmf_core::message::LxMessage::unpack_propagated(&[u8]) -> core::result::Result pub fn lxmf_core::message::LxMessage::unpack_propagation_wrapper(&[u8]) -> core::result::Result<(f64, alloc::vec::Vec>), lxmf_core::message::MessageError> pub fn lxmf_core::message::LxMessage::unpack_propagation_wrapper_bounded(&[u8], usize) -> core::result::Result<(f64, alloc::vec::Vec>), lxmf_core::message::MessageError> -pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&mut self, u8, core::option::Option<&[alloc::vec::Vec]>) -> bool -pub fn lxmf_core::message::LxMessage::verify(&mut self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool +pub fn lxmf_core::message::LxMessage::unpack_propagation_wrapper_owned(bytes::bytes::Bytes, usize) -> core::result::Result<(f64, alloc::vec::Vec), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&self, u8, core::option::Option<&[alloc::vec::Vec]>) -> bool +pub fn lxmf_core::message::LxMessage::validated_stamp_value(&self, u8, core::option::Option<&[alloc::vec::Vec]>) -> core::option::Option +pub fn lxmf_core::message::LxMessage::verify(&self, &[u8; 64]) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessage::verify_signature(&self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool +pub fn lxmf_core::message::LxMessage::wire_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessage::wire_owned(&self) -> bytes::bytes::Bytes pub fn lxmf_core::message::LxMessage::write_to_directory(&self, &str) -> core::result::Result +impl core::convert::From for lxmf_core::link_delivery::RetainedDeliveryMessage +pub fn lxmf_core::link_delivery::RetainedDeliveryMessage::from(lxmf_core::message::LxMessage) -> Self +impl core::ops::deref::Deref for lxmf_core::message::LxMessage +pub type lxmf_core::message::LxMessage::Target = lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::LxMessage::deref(&self) -> &Self::Target +impl core::ops::deref::DerefMut for lxmf_core::message::LxMessage +pub fn lxmf_core::message::LxMessage::deref_mut(&mut self) -> &mut Self::Target +pub struct lxmf_core::message_api::LxMessageDraft +pub lxmf_core::message_api::LxMessageDraft::include_ticket: bool +pub lxmf_core::message_api::LxMessageDraft::metadata: lxmf_core::message::MessageMetadata +pub lxmf_core::message_api::LxMessageDraft::outbound_ticket: core::option::Option<[u8; 16]> +pub lxmf_core::message_api::LxMessageDraft::stamp_cost: core::option::Option +impl lxmf_core::message::LxMessageDraft +pub fn lxmf_core::message::LxMessageDraft::checked_wire_len(&self) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::content_bytes(&self) -> &[u8] +pub fn lxmf_core::message::LxMessageDraft::destination_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::LxMessageDraft::fields(&self) -> &alloc::collections::btree::map::BTreeMap +pub fn lxmf_core::message::LxMessageDraft::get_field(&self, impl core::convert::Into) -> core::option::Option<&lxmf_core::message::FieldValue> +pub fn lxmf_core::message::LxMessageDraft::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::new_with_limits([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod, lxmf_core::message::MessageDecodeLimits) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::pack_payload(&self) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::remove_field(&mut self, impl core::convert::Into) -> core::option::Option +pub fn lxmf_core::message::LxMessageDraft::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_content(&mut self, &str) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_field(&mut self, impl core::convert::Into, impl core::convert::Into) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_field_value(&mut self, impl core::convert::Into, lxmf_core::message::FieldValue) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_msgpack_field(&mut self, impl core::convert::Into, impl core::convert::Into) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_timestamp(&mut self, f64) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::set_title(&mut self, &str) -> core::result::Result<(), lxmf_core::message::MessageError> +pub fn lxmf_core::message::LxMessageDraft::sign(self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result +pub fn lxmf_core::message::LxMessageDraft::sign_with(self, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display +pub fn lxmf_core::message::LxMessageDraft::source_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::LxMessageDraft::timestamp(&self) -> f64 +pub fn lxmf_core::message::LxMessageDraft::title_bytes(&self) -> &[u8] +impl core::ops::deref::Deref for lxmf_core::message::LxMessageDraft +pub type lxmf_core::message::LxMessageDraft::Target = lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::LxMessageDraft::deref(&self) -> &Self::Target +impl core::ops::deref::DerefMut for lxmf_core::message::LxMessageDraft +pub fn lxmf_core::message::LxMessageDraft::deref_mut(&mut self) -> &mut Self::Target +pub struct lxmf_core::message_api::MessageDecodeLimits +pub lxmf_core::message_api::MessageDecodeLimits::max_top_level_fields: usize +pub lxmf_core::message_api::MessageDecodeLimits::max_wire_bytes: usize +impl core::default::Default for lxmf_core::message::MessageDecodeLimits +pub fn lxmf_core::message::MessageDecodeLimits::default() -> Self +pub struct lxmf_core::message_api::MessageMetadata +pub lxmf_core::message_api::MessageMetadata::auto_compress: bool +pub lxmf_core::message_api::MessageMetadata::callbacks: lxmf_core::message::MessageCallbacks +pub lxmf_core::message_api::MessageMetadata::delivery_attempts: u32 +pub lxmf_core::message_api::MessageMetadata::incoming: bool +pub lxmf_core::message_api::MessageMetadata::last_delivery_attempt: f64 +pub lxmf_core::message_api::MessageMetadata::method: lxmf_core::constants::DeliveryMethod +pub lxmf_core::message_api::MessageMetadata::next_delivery_attempt: f64 +pub lxmf_core::message_api::MessageMetadata::progress: f64 +pub lxmf_core::message_api::MessageMetadata::ratchet_id: core::option::Option<[u8; 32]> +pub lxmf_core::message_api::MessageMetadata::representation: lxmf_core::constants::DeliveryRepresentation +pub lxmf_core::message_api::MessageMetadata::source_blackholed: bool +pub lxmf_core::message_api::MessageMetadata::state: lxmf_core::constants::MessageState +pub lxmf_core::message_api::MessageMetadata::transport_encrypted: bool +pub lxmf_core::message_api::MessageMetadata::transport_encryption: core::option::Option +pub lxmf_core::message_api::MessageMetadata::unverified_reason: core::option::Option +impl core::default::Default for lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::MessageMetadata::default() -> Self +pub struct lxmf_core::message_api::OwnedVerifiedLxMessage +impl lxmf_core::message::OwnedVerifiedLxMessage +pub fn lxmf_core::message::OwnedVerifiedLxMessage::as_verified(&self) -> lxmf_core::message::VerifiedLxMessage<'_> +pub struct lxmf_core::message_api::SignedLxMessage +impl lxmf_core::message::SignedLxMessage +pub fn lxmf_core::message::SignedLxMessage::content_bytes(&self) -> &[u8] +pub fn lxmf_core::message::SignedLxMessage::content_text(&self) -> alloc::borrow::Cow<'_, str> +pub fn lxmf_core::message::SignedLxMessage::destination_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::SignedLxMessage::fields(&self) -> lxmf_core::message::Fields<'_> +pub fn lxmf_core::message::SignedLxMessage::finalize(self, core::option::Option) -> core::result::Result +pub fn lxmf_core::message::SignedLxMessage::generate_recipient_stamp(&self) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::message::SignedLxMessage::message_id(&self) -> [u8; 32] +pub fn lxmf_core::message::SignedLxMessage::outbound_ticket(&self) -> core::option::Option<[u8; 16]> +pub fn lxmf_core::message::SignedLxMessage::packed_len(&self) -> core::result::Result +pub fn lxmf_core::message::SignedLxMessage::payload_len(&self) -> usize +pub fn lxmf_core::message::SignedLxMessage::source_hash(&self) -> [u8; 16] +pub fn lxmf_core::message::SignedLxMessage::stamp_cost(&self) -> core::option::Option +pub fn lxmf_core::message::SignedLxMessage::timestamp(&self) -> f64 +pub fn lxmf_core::message::SignedLxMessage::title_bytes(&self) -> &[u8] +pub fn lxmf_core::message::SignedLxMessage::title_text(&self) -> alloc::borrow::Cow<'_, str> +impl core::ops::deref::Deref for lxmf_core::message::SignedLxMessage +pub type lxmf_core::message::SignedLxMessage::Target = lxmf_core::message::MessageMetadata +pub fn lxmf_core::message::SignedLxMessage::deref(&self) -> &Self::Target +impl core::ops::deref::DerefMut for lxmf_core::message::SignedLxMessage +pub fn lxmf_core::message::SignedLxMessage::deref_mut(&mut self) -> &mut Self::Target +pub struct lxmf_core::message_api::UniqueFieldMap<'a> +impl<'a> lxmf_core::message::UniqueFieldMap<'a> +pub fn lxmf_core::message::UniqueFieldMap<'a>::get(&self, lxmf_core::message::FieldMapKey<'_>) -> core::option::Option> +pub fn lxmf_core::message::UniqueFieldMap<'a>::is_empty(&self) -> bool +pub fn lxmf_core::message::UniqueFieldMap<'a>::len(&self) -> usize +pub struct lxmf_core::message_api::VerifiedLxMessage<'a> +impl<'a> lxmf_core::message::VerifiedLxMessage<'a> +pub fn lxmf_core::message::VerifiedLxMessage<'a>::message(&self) -> &'a lxmf_core::message::LxMessage +pub fn lxmf_core::message::VerifiedLxMessage<'a>::source_public_key(&self) -> &[u8; 64] +pub fn lxmf_core::message::VerifiedLxMessage<'a>::to_owned(&self) -> lxmf_core::message::OwnedVerifiedLxMessage pub type lxmf_core::message_api::DestinationHash = [u8; 16] pub type lxmf_core::message_api::IdentityHash = [u8; 16] pub type lxmf_core::message_api::MessageId = [u8; 32] @@ -915,13 +1343,17 @@ pub const lxmf_core::persist::STAMP_COSTS_FILE: &str pub const lxmf_core::persist::TICKETS_FILE: &str pub fn lxmf_core::persist::load_local_deliveries(&std::path::Path) -> core::io::error::Result> pub fn lxmf_core::persist::load_locally_processed(&std::path::Path) -> core::io::error::Result> +pub fn lxmf_core::persist::load_node_policies(&std::path::Path) -> core::io::error::Result> pub fn lxmf_core::persist::load_node_stats(&std::path::Path) -> core::io::error::Result pub fn lxmf_core::persist::load_stamp_costs(&std::path::Path) -> core::io::error::Result> +pub fn lxmf_core::persist::load_suppression(&std::path::Path) -> core::io::error::Result pub fn lxmf_core::persist::load_tickets(&std::path::Path) -> core::io::error::Result<(lxmf_core::ticket::TicketStoreSnapshot, core::option::Option>)> pub fn lxmf_core::persist::save_local_deliveries(&std::path::Path, &std::collections::hash::map::HashMap) -> core::io::error::Result<()> pub fn lxmf_core::persist::save_locally_processed(&std::path::Path, &std::collections::hash::map::HashMap) -> core::io::error::Result<()> +pub fn lxmf_core::persist::save_node_policies(&std::path::Path, &std::collections::hash::map::HashMap<[u8; 16], lxmf_core::propagation_send::AdvertisedNodePolicy>) -> core::io::error::Result<()> pub fn lxmf_core::persist::save_node_stats(&std::path::Path, &lxmf_core::persist::PersistedNodeStats) -> core::io::error::Result<()> pub fn lxmf_core::persist::save_stamp_costs(&std::path::Path, &std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry>) -> core::io::error::Result<()> +pub fn lxmf_core::persist::save_suppression(&std::path::Path, &lxmf_core::admission::SuppressionLedger) -> core::io::error::Result<()> pub fn lxmf_core::persist::save_tickets(&std::path::Path, &lxmf_core::ticket::TicketStoreSnapshot) -> core::io::error::Result<()> pub fn lxmf_core::persist::write_file_atomic(&std::path::Path, &[u8]) -> core::io::error::Result<()> pub mod lxmf_core::presentation @@ -1083,6 +1515,7 @@ pub const lxmf_core::propagation_admission::PN_INVALID_STAMP_THROTTLE: core::tim pub const lxmf_core::propagation_admission::PN_MIN_MAX_INBOUND_SYNCS: usize pub mod lxmf_core::propagation_client pub enum lxmf_core::propagation_client::PropagationClientState +pub lxmf_core::propagation_client::PropagationClientState::AwaitingAdmission pub lxmf_core::propagation_client::PropagationClientState::Complete pub lxmf_core::propagation_client::PropagationClientState::Failed pub lxmf_core::propagation_client::PropagationClientState::GetRequested @@ -1090,29 +1523,59 @@ pub lxmf_core::propagation_client::PropagationClientState::Idle pub lxmf_core::propagation_client::PropagationClientState::LinkEstablished pub lxmf_core::propagation_client::PropagationClientState::LinkEstablishing pub lxmf_core::propagation_client::PropagationClientState::ListRequested +pub lxmf_core::propagation_client::PropagationClientState::Partial pub lxmf_core::propagation_client::PropagationClientState::PurgeRequested pub lxmf_core::propagation_client::PropagationClientState::Receiving +pub struct lxmf_core::propagation_client::PropagationAdmissionCounts +pub lxmf_core::propagation_client::PropagationAdmissionCounts::committed: usize +pub lxmf_core::propagation_client::PropagationAdmissionCounts::downloaded: usize +pub lxmf_core::propagation_client::PropagationAdmissionCounts::duplicate: usize +pub lxmf_core::propagation_client::PropagationAdmissionCounts::policy_discarded: usize +pub lxmf_core::propagation_client::PropagationAdmissionCounts::rejected: usize +pub lxmf_core::propagation_client::PropagationAdmissionCounts::retryable: usize +pub lxmf_core::propagation_client::PropagationAdmissionCounts::user_deleted: usize +pub struct lxmf_core::propagation_client::PropagationAdmissionStatus +pub lxmf_core::propagation_client::PropagationAdmissionStatus::admission_paused: bool +pub lxmf_core::propagation_client::PropagationAdmissionStatus::deferred_count: usize +pub lxmf_core::propagation_client::PropagationAdmissionStatus::ledger_full: bool +pub lxmf_core::propagation_client::PropagationAdmissionStatus::next_retry: core::option::Option +pub lxmf_core::propagation_client::PropagationAdmissionStatus::node_capacity: usize +pub lxmf_core::propagation_client::PropagationAdmissionStatus::node_records: usize +pub lxmf_core::propagation_client::PropagationAdmissionStatus::suppressed_count: usize pub struct lxmf_core::propagation_client::PropagationClient impl lxmf_core::propagation_client::PropagationClient +pub fn lxmf_core::propagation_client::PropagationClient::acknowledge_suppression_persistence(&mut self, u64) -> bool pub fn lxmf_core::propagation_client::PropagationClient::acknowledge_transfer(&mut self) -> bool pub fn lxmf_core::propagation_client::PropagationClient::add_local_message(&mut self, lxmf_core::types::PropagationTransientId) pub fn lxmf_core::propagation_client::PropagationClient::add_local_message_id(&mut self, alloc::vec::Vec) +pub fn lxmf_core::propagation_client::PropagationClient::admission_status(&self) -> lxmf_core::propagation_client::PropagationAdmissionStatus pub fn lxmf_core::propagation_client::PropagationClient::available_messages(&self) -> &[alloc::vec::Vec] pub fn lxmf_core::propagation_client::PropagationClient::cancel_download(&mut self) pub fn lxmf_core::propagation_client::PropagationClient::drain_events(&mut self, &std::collections::hash::map::HashMap) pub fn lxmf_core::propagation_client::PropagationClient::new(tokio::sync::mpsc::bounded::Sender, core::option::Option<[u8; 64]>, core::option::Option) -> Self pub fn lxmf_core::propagation_client::PropagationClient::received_count(&self) -> usize +pub fn lxmf_core::propagation_client::PropagationClient::replace_durable_haves(&mut self, impl core::iter::traits::collect::IntoIterator) pub fn lxmf_core::propagation_client::PropagationClient::replace_local_message_ids(&mut self, I) where I: core::iter::traits::collect::IntoIterator> pub fn lxmf_core::propagation_client::PropagationClient::set_delivery_limit(&mut self, f64) pub fn lxmf_core::propagation_client::PropagationClient::set_propagation_node(&mut self, [u8; 16]) pub fn lxmf_core::propagation_client::PropagationClient::set_retain_synced_on_node(&mut self, bool) +pub fn lxmf_core::propagation_client::PropagationClient::set_suppression_ledger(&mut self, lxmf_core::admission::SuppressionLedger, lxmf_core::admission::AdmissionEpochs) pub fn lxmf_core::propagation_client::PropagationClient::start_download(&mut self) -> bool pub fn lxmf_core::propagation_client::PropagationClient::start_download_with_limit(&mut self, core::option::Option) -> bool pub const fn lxmf_core::propagation_client::PropagationClient::state(&self) -> lxmf_core::propagation_client::PropagationClientState -pub fn lxmf_core::propagation_client::PropagationClient::take_received_messages(&mut self) -> alloc::vec::Vec> +pub fn lxmf_core::propagation_client::PropagationClient::suppression_ledger(&self) -> &lxmf_core::admission::SuppressionLedger +pub fn lxmf_core::propagation_client::PropagationClient::suppression_persistence_failed(&mut self) +pub fn lxmf_core::propagation_client::PropagationClient::suppression_persistence_pending(&self) -> bool +pub fn lxmf_core::propagation_client::PropagationClient::suppression_revision(&self) -> u64 +pub fn lxmf_core::propagation_client::PropagationClient::take_downloaded_messages(&mut self) -> alloc::vec::Vec +pub fn lxmf_core::propagation_client::PropagationClient::take_suppression_updates(&mut self) -> alloc::vec::Vec pub fn lxmf_core::propagation_client::PropagationClient::tick(&mut self) pub const fn lxmf_core::propagation_client::PropagationClient::transfer_status(&self) -> lxmf_core::propagation_client::PropagationTransferStatus +pub fn lxmf_core::propagation_client::PropagationClient::update_admission_epochs(&mut self, lxmf_core::admission::AdmissionEpochs) +impl core::ops::drop::Drop for lxmf_core::propagation_client::PropagationClient +pub fn lxmf_core::propagation_client::PropagationClient::drop(&mut self) pub struct lxmf_core::propagation_client::PropagationTransferStatus +pub lxmf_core::propagation_client::PropagationTransferStatus::admission: lxmf_core::propagation_client::PropagationAdmissionCounts pub lxmf_core::propagation_client::PropagationTransferStatus::data_size: core::option::Option pub lxmf_core::propagation_client::PropagationTransferStatus::progress: f64 pub lxmf_core::propagation_client::PropagationTransferStatus::result: core::option::Option @@ -1126,6 +1589,16 @@ pub lxmf_core::propagation_node::GetRequestAction::ServeFiles(lxmf_core::propaga impl lxmf_core::propagation_node::GetRequestAction pub fn lxmf_core::propagation_node::GetRequestAction::into_response(self) -> alloc::vec::Vec pub fn lxmf_core::propagation_node::GetRequestAction::into_response_with_served_count(self) -> (alloc::vec::Vec, u64) +pub fn lxmf_core::propagation_node::GetRequestAction::into_response_with_served_count_bounded(self, usize) -> (alloc::vec::Vec, u64) +pub enum lxmf_core::propagation_node::PropagationAdmission +pub lxmf_core::propagation_node::PropagationAdmission::CommittedDuplicate(lxmf_core::propagation_node::PropagationDuplicateCheck) +pub lxmf_core::propagation_node::PropagationAdmission::Pending(lxmf_core::propagation_node::PropagationAdmissionWaiter) +pub lxmf_core::propagation_node::PropagationAdmission::Rejected +pub lxmf_core::propagation_node::PropagationAdmission::Reserved(alloc::boxed::Box) +pub enum lxmf_core::propagation_node::PropagationAdmissionOutcome +pub lxmf_core::propagation_node::PropagationAdmissionOutcome::Committed +pub lxmf_core::propagation_node::PropagationAdmissionOutcome::Failed +pub lxmf_core::propagation_node::PropagationAdmissionOutcome::Pending pub struct lxmf_core::propagation_node::GetServePlan impl lxmf_core::propagation_node::GetServePlan pub fn lxmf_core::propagation_node::GetServePlan::serve(&self) -> alloc::vec::Vec @@ -1140,12 +1613,16 @@ pub struct lxmf_core::propagation_node::PersistedPropagationStoreWrite pub struct lxmf_core::propagation_node::PlannedMessageRead pub lxmf_core::propagation_node::PlannedMessageRead::path: std::path::PathBuf pub lxmf_core::propagation_node::PlannedMessageRead::transient_id: lxmf_core::types::PropagationTransientId +pub struct lxmf_core::propagation_node::PropagationAdmissionWaiter +impl lxmf_core::propagation_node::PropagationAdmissionWaiter +pub async fn lxmf_core::propagation_node::PropagationAdmissionWaiter::wait(self) -> lxmf_core::propagation_node::PropagationAdmissionOutcome +pub struct lxmf_core::propagation_node::PropagationDuplicateCheck +impl lxmf_core::propagation_node::PropagationDuplicateCheck +pub fn lxmf_core::propagation_node::PropagationDuplicateCheck::verify(self) -> core::io::error::Result<()> pub struct lxmf_core::propagation_node::PropagationNode pub lxmf_core::propagation_node::PropagationNode::dest_hash: [u8; 16] impl lxmf_core::propagation_node::PropagationNode pub fn lxmf_core::propagation_node::PropagationNode::abort_store_write(&mut self, &lxmf_core::types::PropagationTransientId, usize) -pub fn lxmf_core::propagation_node::PropagationNode::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool -pub fn lxmf_core::propagation_node::PropagationNode::accept_propagated_blob(&mut self, &[u8], u8) -> bool pub fn lxmf_core::propagation_node::PropagationNode::accept_stamped_propagated_blob(&mut self, &[u8], &[u8; 32], u8) -> bool pub fn lxmf_core::propagation_node::PropagationNode::commit_store_write(&mut self, lxmf_core::propagation_node::PersistedPropagationStoreWrite) -> bool pub fn lxmf_core::propagation_node::PropagationNode::complete_sync(&mut self, &[u8; 16]) @@ -1158,9 +1635,11 @@ pub fn lxmf_core::propagation_node::PropagationNode::evaluate_offer_request(&sel pub fn lxmf_core::propagation_node::PropagationNode::get_session(&self, &[u8; 16]) -> core::option::Option<&lxmf_core::sync::SyncSession> pub fn lxmf_core::propagation_node::PropagationNode::get_session_mut(&mut self, &[u8; 16]) -> core::option::Option<&mut lxmf_core::sync::SyncSession> pub fn lxmf_core::propagation_node::PropagationNode::handle_get_request(&mut self, &[u8], &[u8; 16]) -> lxmf_core::propagation_node::GetRequestAction +pub fn lxmf_core::propagation_node::PropagationNode::handle_get_request_bounded(&mut self, &[u8], &[u8; 16], usize) -> lxmf_core::propagation_node::GetRequestAction pub fn lxmf_core::propagation_node::PropagationNode::handle_offer_request(&mut self, &[u8], lxmf_core::propagation_node::OfferRequestContext<'_>) -> alloc::vec::Vec pub fn lxmf_core::propagation_node::PropagationNode::ignore_destination(&mut self, [u8; 16]) pub fn lxmf_core::propagation_node::PropagationNode::is_destination_ignored(&self, &[u8; 16]) -> bool +pub fn lxmf_core::propagation_node::PropagationNode::is_durable(&self) -> bool pub fn lxmf_core::propagation_node::PropagationNode::load_peers(&self) -> alloc::vec::Vec pub fn lxmf_core::propagation_node::PropagationNode::mark_peer_handled(&mut self, &[u8; 16], &lxmf_core::types::PropagationTransientId) pub fn lxmf_core::propagation_node::PropagationNode::message_count(&self) -> usize @@ -1170,10 +1649,10 @@ pub fn lxmf_core::propagation_node::PropagationNode::new(lxmf_core::propagation_ pub fn lxmf_core::propagation_node::PropagationNode::offer_generation(&self) -> u64 pub fn lxmf_core::propagation_node::PropagationNode::offer_request(&mut self, [u8; 16], &[lxmf_core::types::PropagationTransientId]) -> alloc::vec::Vec pub fn lxmf_core::propagation_node::PropagationNode::persist_peer_handled(&self, &lxmf_core::peer::OutboundOfferPolicy, &[lxmf_core::types::PropagationTransientId]) -> core::io::error::Result<()> -pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_message(&mut self, &lxmf_core::message::LxMessage) -> core::option::Option -pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_propagated_blob(&mut self, &[u8], u8) -> core::option::Option pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_stamped_propagated_blob(&mut self, &[u8], &[u8; 32], u8) -> core::option::Option +pub fn lxmf_core::propagation_node::PropagationNode::plan_maintenance(&mut self) -> lxmf_core::propagation_node::PropagationRetirementPlan pub fn lxmf_core::propagation_node::PropagationNode::plan_message_reads(&self, &[lxmf_core::types::PropagationTransientId]) -> alloc::vec::Vec +pub fn lxmf_core::propagation_node::PropagationNode::plan_opaque_admission(&mut self, lxmf_core::propagation_node::ValidatedOpaquePropagationBlob) -> lxmf_core::propagation_node::PropagationAdmission pub fn lxmf_core::propagation_node::PropagationNode::prepare_sync_offer(&mut self, [u8; 16]) -> lxmf_core::sync::SyncOffer pub fn lxmf_core::propagation_node::PropagationNode::prepare_sync_offer_with_policy(&mut self, &lxmf_core::peer::OutboundOfferPolicy) -> lxmf_core::sync::SyncOffer pub fn lxmf_core::propagation_node::PropagationNode::prioritise_destination(&mut self, [u8; 16]) @@ -1200,11 +1679,20 @@ pub lxmf_core::propagation_node::PropagationNodeConfig::min_stamp_cost: u8 pub lxmf_core::propagation_node::PropagationNodeConfig::peering_cost: u8 impl core::default::Default for lxmf_core::propagation_node::PropagationNodeConfig pub fn lxmf_core::propagation_node::PropagationNodeConfig::default() -> Self +pub struct lxmf_core::propagation_node::PropagationRetirementPlan +impl lxmf_core::propagation_node::PropagationRetirementPlan +pub fn lxmf_core::propagation_node::PropagationRetirementPlan::is_empty(&self) -> bool +pub fn lxmf_core::propagation_node::PropagationRetirementPlan::persist(&self) -> core::io::error::Result<()> pub struct lxmf_core::propagation_node::PropagationStoreWritePlan impl lxmf_core::propagation_node::PropagationStoreWritePlan pub fn lxmf_core::propagation_node::PropagationStoreWritePlan::persist(self) -> core::io::error::Result pub fn lxmf_core::propagation_node::PropagationStoreWritePlan::size(&self) -> usize pub fn lxmf_core::propagation_node::PropagationStoreWritePlan::transient_id(&self) -> lxmf_core::types::PropagationTransientId +pub struct lxmf_core::propagation_node::ValidatedOpaquePropagationBlob +impl lxmf_core::propagation_node::ValidatedOpaquePropagationBlob +pub fn lxmf_core::propagation_node::ValidatedOpaquePropagationBlob::stamp_value(&self) -> u8 +pub fn lxmf_core::propagation_node::ValidatedOpaquePropagationBlob::transient_id(&self) -> lxmf_core::types::PropagationTransientId +pub fn lxmf_core::propagation_node::ValidatedOpaquePropagationBlob::validate(bytes::bytes::Bytes, u8) -> core::option::Option pub fn lxmf_core::propagation_node::read_planned_messages(&[lxmf_core::propagation_node::PlannedMessageRead]) -> alloc::vec::Vec<(lxmf_core::types::PropagationTransientId, alloc::vec::Vec)> pub mod lxmf_core::propagation_offer pub enum lxmf_core::propagation_offer::PnOfferEvaluation @@ -1219,6 +1707,69 @@ pub lxmf_core::propagation_offer::PnOfferEvaluationError::InvalidData pub lxmf_core::propagation_offer::PnOfferEvaluationError::InvalidKey impl lxmf_core::propagation_offer::PnOfferEvaluationError pub fn lxmf_core::propagation_offer::PnOfferEvaluationError::wire_response(self) -> lxmf_core::sync::OfferResponse +pub mod lxmf_core::propagation_send +pub enum lxmf_core::propagation_send::MissingPropagationInput +pub lxmf_core::propagation_send::MissingPropagationInput::NodeIdentity +pub lxmf_core::propagation_send::MissingPropagationInput::NodePath +pub lxmf_core::propagation_send::MissingPropagationInput::NodePolicy +pub lxmf_core::propagation_send::MissingPropagationInput::RecipientIdentity +pub struct lxmf_core::propagation_send::AdvertisedNodePolicy +pub lxmf_core::propagation_send::AdvertisedNodePolicy::recorded_at: f64 +pub lxmf_core::propagation_send::AdvertisedNodePolicy::stamp_cost: u8 +pub lxmf_core::propagation_send::AdvertisedNodePolicy::transfer_limit_kb: f64 +pub struct lxmf_core::propagation_send::PreparedNode +pub lxmf_core::propagation_send::PreparedNode::node: [u8; 16] +pub lxmf_core::propagation_send::PreparedNode::policy: lxmf_core::propagation_send::AdvertisedNodePolicy +pub struct lxmf_core::propagation_send::PropagationEnvelope +impl lxmf_core::propagation_send::PropagationEnvelope +pub fn lxmf_core::propagation_send::PropagationEnvelope::ciphertext(&self) -> &bytes::bytes::Bytes +pub fn lxmf_core::propagation_send::PropagationEnvelope::matches(&self, &lxmf_core::message::LxMessage, &[u8; 32]) -> bool +pub fn lxmf_core::propagation_send::PropagationEnvelope::message(&self) -> &lxmf_core::message::LxMessage +pub fn lxmf_core::propagation_send::PropagationEnvelope::new(lxmf_core::message::LxMessage, [u8; 32], u8, F) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::propagation_send::PropagationEnvelope::new_cancellable(lxmf_core::message::LxMessage, [u8; 32], u8, F, &core::sync::atomic::AtomicBool) -> core::result::Result where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::propagation_send::PropagationEnvelope::pack_for(&mut self, lxmf_core::propagation_send::PreparedNode, f64) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::propagation_send::PropagationEnvelope::pack_for_cancellable(&mut self, lxmf_core::propagation_send::PreparedNode, f64, &core::sync::atomic::AtomicBool) -> core::result::Result, lxmf_core::message::MessageError> +pub fn lxmf_core::propagation_send::PropagationEnvelope::stamp(&self) -> &[u8; 32] +pub fn lxmf_core::propagation_send::PropagationEnvelope::stamp_value(&self) -> u32 +pub fn lxmf_core::propagation_send::PropagationEnvelope::transient_id(&self) -> [u8; 32] +pub const lxmf_core::propagation_send::NODE_METADATA_MAX_AGE: f64 +pub fn lxmf_core::propagation_send::propagation_readiness([u8; 16], bool, bool, core::option::Option, bool, f64) -> core::result::Result +pub mod lxmf_core::propagation_store_v2 +pub enum lxmf_core::propagation_store_v2::OpaqueIngress +pub lxmf_core::propagation_store_v2::OpaqueIngress::TrustedRecovery +pub lxmf_core::propagation_store_v2::OpaqueIngress::ValidatedPropagation +pub struct lxmf_core::propagation_store_v2::MigrationReport +pub lxmf_core::propagation_store_v2::MigrationReport::quarantine: lxmf_core::propagation_store_v2::QuarantineSummary +pub lxmf_core::propagation_store_v2::MigrationReport::store: std::path::PathBuf +pub struct lxmf_core::propagation_store_v2::MigrationRequired +pub struct lxmf_core::propagation_store_v2::OfflineMigrationGuard +pub struct lxmf_core::propagation_store_v2::QuarantineSummary +pub lxmf_core::propagation_store_v2::QuarantineSummary::bytes: u64 +pub lxmf_core::propagation_store_v2::QuarantineSummary::files: usize +pub lxmf_core::propagation_store_v2::QuarantineSummary::reason: &'static str +pub struct lxmf_core::propagation_store_v2::RecoveryEntry +pub lxmf_core::propagation_store_v2::RecoveryEntry::archive_relative_path: std::path::PathBuf +pub lxmf_core::propagation_store_v2::RecoveryEntry::content_hash: [u8; 32] +pub lxmf_core::propagation_store_v2::RecoveryEntry::stamped: bool +pub lxmf_core::propagation_store_v2::RecoveryEntry::stored_at: f64 +pub lxmf_core::propagation_store_v2::RecoveryEntry::transient_id: [u8; 32] +pub struct lxmf_core::propagation_store_v2::RecoveryPolicy +pub lxmf_core::propagation_store_v2::RecoveryPolicy::maximum_message_bytes: usize +pub lxmf_core::propagation_store_v2::RecoveryPolicy::maximum_store_bytes: usize +pub lxmf_core::propagation_store_v2::RecoveryPolicy::minimum_stamp_cost: u8 +pub struct lxmf_core::propagation_store_v2::RecoveryReport +pub lxmf_core::propagation_store_v2::RecoveryReport::already_present: usize +pub lxmf_core::propagation_store_v2::RecoveryReport::imported: usize +pub struct lxmf_core::propagation_store_v2::TrustedRecoveryManifest +pub lxmf_core::propagation_store_v2::TrustedRecoveryManifest::entries: alloc::vec::Vec +pub lxmf_core::propagation_store_v2::TrustedRecoveryManifest::provenance: alloc::string::String +pub lxmf_core::propagation_store_v2::TrustedRecoveryManifest::version: u8 +pub fn lxmf_core::propagation_store_v2::begin_offline_migration(&std::path::Path, bool) -> core::io::error::Result +pub fn lxmf_core::propagation_store_v2::import_trusted_recovery_manifest(&lxmf_core::propagation_store_v2::OfflineMigrationGuard, &std::path::Path, [u8; 32], lxmf_core::propagation_store_v2::RecoveryPolicy) -> core::io::error::Result +pub fn lxmf_core::propagation_store_v2::is_migration_required(&core::io::error::Error) -> bool +pub fn lxmf_core::propagation_store_v2::migrate_store_offline(&lxmf_core::propagation_store_v2::OfflineMigrationGuard) -> core::io::error::Result +pub fn lxmf_core::propagation_store_v2::open_store(&std::path::Path) -> core::io::error::Result +pub fn lxmf_core::propagation_store_v2::quarantine_summary(&std::path::Path) -> core::io::error::Result pub mod lxmf_core::propagation_sync pub enum lxmf_core::propagation_sync::PeerSyncTerminalState pub lxmf_core::propagation_sync::PeerSyncTerminalState::Complete @@ -1245,7 +1796,6 @@ pub struct lxmf_core::propagation_sync::PropagationSyncTask pub lxmf_core::propagation_sync::PropagationSyncTask::propagation_node: alloc::sync::Arc> pub lxmf_core::propagation_sync::PropagationSyncTask::state: lxmf_core::propagation_sync::SyncTaskState impl lxmf_core::propagation_sync::PropagationSyncTask -pub fn lxmf_core::propagation_sync::PropagationSyncTask::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool pub fn lxmf_core::propagation_sync::PropagationSyncTask::cancel_peer_sync(&mut self, &[u8; 16]) -> bool pub fn lxmf_core::propagation_sync::PropagationSyncTask::drain_events(&mut self, &std::collections::hash::map::HashMap) pub fn lxmf_core::propagation_sync::PropagationSyncTask::message_count(&self) -> usize @@ -1306,6 +1856,7 @@ pub fn lxmf_core::router::SendError::fmt(&self, &mut core::fmt::Formatter<'_>) - pub enum lxmf_core::router::TicketPreparationError pub lxmf_core::router::TicketPreparationError::AlreadySigned pub lxmf_core::router::TicketPreparationError::Encode(alloc::string::String) +pub lxmf_core::router::TicketPreparationError::PendingPersistence pub struct lxmf_core::router::AutopeerCandidate pub lxmf_core::router::AutopeerCandidate::destination_hash: [u8; 16] pub lxmf_core::router::AutopeerCandidate::hops: core::option::Option @@ -1330,6 +1881,7 @@ pub lxmf_core::router::DirectRouteSnapshot::interface_name: core::option::Option pub lxmf_core::router::DirectRouteSnapshot::learned_at: core::option::Option impl lxmf_core::router::DirectRouteSnapshot pub fn lxmf_core::router::DirectRouteSnapshot::new([u8; 16], u8) -> Self +pub struct lxmf_core::router::InboundReservation pub struct lxmf_core::router::LxmRouter pub lxmf_core::router::LxmRouter::active_deferred_stamp: core::option::Option pub lxmf_core::router::LxmRouter::allowed: alloc::vec::Vec<[u8; 16]> @@ -1343,7 +1895,7 @@ pub lxmf_core::router::LxmRouter::ignored: alloc::vec::Vec<[u8; 16]> pub lxmf_core::router::LxmRouter::outbound_propagation_node: core::option::Option<[u8; 16]> pub lxmf_core::router::LxmRouter::outbound_stamp_costs: std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry> pub lxmf_core::router::LxmRouter::peers: std::collections::hash::map::HashMap<[u8; 16], lxmf_core::peer::LxmPeer> -pub lxmf_core::router::LxmRouter::pending_deferred_stamps: std::collections::hash::map::HashMap<[u8; 32], lxmf_core::message::LxMessage> +pub lxmf_core::router::LxmRouter::pending_deferred_stamps: std::collections::hash::map::HashMap<[u8; 32], lxmf_core::message::SignedLxMessage> pub lxmf_core::router::LxmRouter::pending_outbound: alloc::vec::Vec pub lxmf_core::router::LxmRouter::prioritized: std::collections::hash::map::HashMap<[u8; 16], u8> pub lxmf_core::router::LxmRouter::processing_count: u64 @@ -1358,6 +1910,7 @@ pub lxmf_core::router::LxmRouter::transport_tx: core::option::Option bool pub fn lxmf_core::router::LxmRouter::allow(&mut self, [u8; 16]) pub fn lxmf_core::router::LxmRouter::allow_control(&mut self, [u8; 16]) @@ -1368,12 +1921,13 @@ pub fn lxmf_core::router::LxmRouter::cancel_inbound(&self, &[u8; 32]) -> bool pub fn lxmf_core::router::LxmRouter::cancel_inbound_exact(&self, lxmf_core::inbound_resource::InboundResourceKey) -> bool pub fn lxmf_core::router::LxmRouter::cancel_outbound(&mut self, &[u8; 32]) -> bool pub fn lxmf_core::router::LxmRouter::clean_throttled_peers(&mut self) +pub fn lxmf_core::router::LxmRouter::commit_inbound(&mut self, lxmf_core::router::InboundReservation, &lxmf_core::message::LxMessage, &lxmf_core::admission::DurableAdmissionReceipt, core::option::Option<&lxmf_core::message::VerifiedLxMessage<'_>>) -> bool pub fn lxmf_core::router::LxmRouter::complete_outbound_message(&mut self, lxmf_core::message::LxMessage) pub fn lxmf_core::router::LxmRouter::control_status(&self) -> core::option::Option pub fn lxmf_core::router::LxmRouter::cull_propagation(&mut self) pub fn lxmf_core::router::LxmRouter::cull_stamp_costs(&mut self) pub fn lxmf_core::router::LxmRouter::defer_outbound_for_path_request(&mut self, &[u8; 32], f64) -> bool -pub fn lxmf_core::router::LxmRouter::defer_stamp(&mut self, lxmf_core::message::LxMessage) -> core::option::Option +pub fn lxmf_core::router::LxmRouter::defer_stamp(&mut self, lxmf_core::message::SignedLxMessage) pub fn lxmf_core::router::LxmRouter::deliver_inbound(&mut self, &lxmf_core::message::LxMessage, bool) -> bool pub fn lxmf_core::router::LxmRouter::disallow(&mut self, &[u8; 16]) pub fn lxmf_core::router::LxmRouter::disallow_control(&mut self, &[u8; 16]) @@ -1401,7 +1955,7 @@ pub fn lxmf_core::router::LxmRouter::ingest_lxm_uri(&mut self, &str, F) -> co pub fn lxmf_core::router::LxmRouter::is_allowed(&self, &[u8; 16]) -> bool pub fn lxmf_core::router::LxmRouter::is_control_allowed(&self, &[u8; 16]) -> bool pub fn lxmf_core::router::LxmRouter::is_peer_throttled(&self, &[u8; 16]) -> bool -pub fn lxmf_core::router::LxmRouter::learn_ticket_from_inbound(&mut self, &lxmf_core::message::LxMessage) -> bool +pub fn lxmf_core::router::LxmRouter::learn_ticket_from_inbound(&mut self, &lxmf_core::message::VerifiedLxMessage<'_>) -> bool pub fn lxmf_core::router::LxmRouter::load_state(&mut self, &std::path::Path) -> core::io::error::Result<()> pub fn lxmf_core::router::LxmRouter::mark_outbound_delivered(&mut self, &[u8; 32]) -> bool pub fn lxmf_core::router::LxmRouter::mark_outbound_failed(&mut self, &[u8; 32]) -> bool @@ -1409,7 +1963,7 @@ pub fn lxmf_core::router::LxmRouter::mark_outbound_rejected(&mut self, &[u8; 32] pub fn lxmf_core::router::LxmRouter::message_storage_limit(&self) -> core::option::Option pub fn lxmf_core::router::LxmRouter::message_storage_size(&self) -> usize pub fn lxmf_core::router::LxmRouter::new(lxmf_core::router::RouterConfig) -> Self -pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessage) -> core::result::Result<(), lxmf_core::router::TicketPreparationError> +pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessageDraft) -> core::result::Result pub fn lxmf_core::router::LxmRouter::prioritise(&mut self, [u8; 16], u8) pub fn lxmf_core::router::LxmRouter::process_deferred_stamps(&mut self) pub fn lxmf_core::router::LxmRouter::process_outbound(&mut self) -> alloc::vec::Vec @@ -1418,6 +1972,7 @@ pub fn lxmf_core::router::LxmRouter::register_delivery_callback(&mut self, F) pub fn lxmf_core::router::LxmRouter::remember_ticket(&mut self, [u8; 16], [u8; 16], f64) pub fn lxmf_core::router::LxmRouter::remove_peer(&mut self, &[u8; 16]) pub fn lxmf_core::router::LxmRouter::requires_authentication(&self) -> bool +pub fn lxmf_core::router::LxmRouter::reserve_inbound(&mut self, &lxmf_core::message::LxMessage) -> core::option::Option pub fn lxmf_core::router::LxmRouter::retain_node_lxms(&self) -> bool pub fn lxmf_core::router::LxmRouter::rotate_peers(&mut self) pub fn lxmf_core::router::LxmRouter::run_jobs_tick(&mut self) @@ -1437,6 +1992,7 @@ pub fn lxmf_core::router::LxmRouter::set_stamp_requirements(&mut self, u8, u8) pub fn lxmf_core::router::LxmRouter::set_transport(&mut self, tokio::sync::mpsc::bounded::Sender) pub fn lxmf_core::router::LxmRouter::state_snapshot(&self) -> lxmf_core::router::RouterStateSnapshot pub fn lxmf_core::router::LxmRouter::stats(&self) -> lxmf_core::router::RouterStats +pub fn lxmf_core::router::LxmRouter::submit_signed(&mut self, lxmf_core::message::SignedLxMessage) -> core::result::Result<(), lxmf_core::message::MessageError> pub fn lxmf_core::router::LxmRouter::sync_peer_policies_for_store(&self, u64) -> alloc::vec::Vec pub fn lxmf_core::router::LxmRouter::sync_peers(&mut self) -> alloc::vec::Vec<[u8; 16]> pub fn lxmf_core::router::LxmRouter::throttle_peer(&mut self, [u8; 16]) @@ -1466,6 +2022,10 @@ pub lxmf_core::router::NodeStats::storage_limit: core::option::Option pub lxmf_core::router::NodeStats::sync_limit: usize pub lxmf_core::router::NodeStats::total_peers: usize pub lxmf_core::router::NodeStats::uptime: f64 +pub struct lxmf_core::router::OutboundTicketIntent +impl lxmf_core::router::OutboundTicketIntent +pub fn lxmf_core::router::OutboundTicketIntent::persist(self, &std::path::Path, &mut lxmf_core::message::LxMessageDraft) -> core::io::error::Result<()> +pub fn lxmf_core::router::OutboundTicketIntent::requires_persistence(&self) -> bool pub struct lxmf_core::router::PeerStats pub lxmf_core::router::PeerStats::alive: bool pub lxmf_core::router::PeerStats::incoming: u64 @@ -1532,6 +2092,7 @@ impl lxmf_core::stamper::DeferredStampHandle pub fn lxmf_core::stamper::DeferredStampHandle::cancel(&self) pub fn lxmf_core::stamper::DeferredStampHandle::is_cancelled(&self) -> bool pub fn lxmf_core::stamper::generate_stamp(&[u8], u8, usize) -> core::option::Option<([u8; 32], u32)> +pub fn lxmf_core::stamper::generate_stamp_cancellable(&[u8], u8, usize, &core::sync::atomic::AtomicBool) -> core::option::Option<([u8; 32], u32)> pub fn lxmf_core::stamper::generate_stamp_limited(&[u8], u8, usize, u64) -> core::option::Option<[u8; 32]> pub fn lxmf_core::stamper::spawn_deferred_stamp([u8; 32], u8, usize) -> (lxmf_core::stamper::DeferredStampHandle, tokio::sync::oneshot::Receiver) pub fn lxmf_core::stamper::spawn_deferred_stamp_on(&tokio::runtime::handle::Handle, [u8; 32], u8, usize) -> (lxmf_core::stamper::DeferredStampHandle, tokio::sync::oneshot::Receiver) diff --git a/api/snapshots/lxmf-tools.txt b/api/snapshots/lxmf-tools.txt index 73fd80d..9e7b1ce 100644 --- a/api/snapshots/lxmf-tools.txt +++ b/api/snapshots/lxmf-tools.txt @@ -72,6 +72,7 @@ pub fn lxmf_tools::daemon::PythonLxmdConfig::from_config(&rns_runtime::config::C pub fn lxmf_tools::daemon::create_router(&lxmf_tools::daemon::DaemonConfig) -> lxmf_core::router::LxmRouter pub fn lxmf_tools::daemon::create_router_with_transport(&lxmf_tools::daemon::DaemonConfig, tokio::sync::mpsc::bounded::Sender) -> lxmf_core::router::LxmRouter pub fn lxmf_tools::daemon::execute_on_inbound(&str, &str) -> core::io::error::Result<()> +pub fn lxmf_tools::daemon::execute_on_inbound_with_event(&str, &str, &str) -> core::io::error::Result<()> pub fn lxmf_tools::daemon::persist_inbound_and_execute(&std::path::Path, &[u8], core::option::Option<&str>) -> core::io::error::Result<()> pub mod lxmf_tools::lxmd_cli pub enum lxmf_tools::lxmd_cli::SendMethod @@ -84,10 +85,14 @@ pub struct lxmf_tools::lxmd_cli::Args pub lxmf_tools::lxmd_cli::Args::config: core::option::Option pub lxmf_tools::lxmd_cli::Args::exampleconfig: bool pub lxmf_tools::lxmd_cli::Args::identity: core::option::Option +pub lxmf_tools::lxmd_cli::Args::migrate_propagation_store: bool pub lxmf_tools::lxmd_cli::Args::on_inbound: core::option::Option pub lxmf_tools::lxmd_cli::Args::peers: bool pub lxmf_tools::lxmd_cli::Args::propagation_node: bool pub lxmf_tools::lxmd_cli::Args::quiet: u8 +pub lxmf_tools::lxmd_cli::Args::recover_propagation_manifest: core::option::Option +pub lxmf_tools::lxmd_cli::Args::recovery_manifest_sha256: core::option::Option +pub lxmf_tools::lxmd_cli::Args::relay_writers_stopped: bool pub lxmf_tools::lxmd_cli::Args::remote: core::option::Option pub lxmf_tools::lxmd_cli::Args::rnsconfig: core::option::Option pub lxmf_tools::lxmd_cli::Args::send: core::option::Option> diff --git a/api/snapshots/manifest-contract.json b/api/snapshots/manifest-contract.json index 961f6dd..fa50308 100644 --- a/api/snapshots/manifest-contract.json +++ b/api/snapshots/manifest-contract.json @@ -4,7 +4,7 @@ "packages": [ { "name": "lxmf-core", - "version": "1.3.0", + "version": "1.4.0", "rustVersion": "1.89", "edition": "2024", "features": {}, @@ -95,7 +95,9 @@ "requirement": "^1", "optional": false, "defaultFeatures": true, - "features": [], + "features": [ + "with-serde" + ], "sourceKind": "registry" }, { @@ -103,7 +105,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -114,7 +116,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -125,7 +127,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -136,7 +138,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -147,7 +149,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -158,7 +160,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -233,12 +235,34 @@ "defaultFeatures": true, "features": [], "sourceKind": "registry" + }, + { + "name": "jni", + "rename": null, + "kind": null, + "target": "cfg(target_os = \"android\")", + "requirement": "^0.19", + "optional": false, + "defaultFeatures": true, + "features": [], + "sourceKind": "registry" + }, + { + "name": "objc2", + "rename": null, + "kind": null, + "target": "cfg(target_os = \"ios\")", + "requirement": "^0.6", + "optional": false, + "defaultFeatures": true, + "features": [], + "sourceKind": "registry" } ] }, { "name": "lxmf-tools", - "version": "1.3.0", + "version": "1.4.0", "rustVersion": "1.89", "edition": "2024", "features": {}, @@ -306,7 +330,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "^1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -328,7 +352,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -339,7 +363,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -350,7 +374,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [ @@ -363,7 +387,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -374,7 +398,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -425,6 +449,17 @@ "defaultFeatures": true, "features": [], "sourceKind": "registry" + }, + { + "name": "zeroize", + "rename": null, + "kind": null, + "target": null, + "requirement": "^1", + "optional": false, + "defaultFeatures": true, + "features": [], + "sourceKind": "registry" } ] } diff --git a/api/stability.json b/api/stability.json index b24d280..b2d115d 100644 --- a/api/stability.json +++ b/api/stability.json @@ -24,8 +24,8 @@ "tier": "candidate-stable", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxmf-core.txt", - "itemCount": 1647, - "sha256": "b7b1d52406e2c97a204a5fb567abc6a216733594a7abd63797ff55a70d8d3b73" + "itemCount": 2208, + "sha256": "e25c207398c8124dbd73cd800d2eb53d5f5615ae47485e654dc39c56d955f653" }, { "name": "lxmf-tools", @@ -33,8 +33,78 @@ "tier": "tool-internal", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxmf-tools.txt", - "itemCount": 185, - "sha256": "0427d0fab38f8061cbf7f11b701f29f438490478f133524b0a8e4e7cfe6f3924" + "itemCount": 190, + "sha256": "c8591cf56d1d315da43ecab8149057447ff02726fa371e01439a4106be45976f" } - ] + ], + "approvedBreakingChanges": { + "releaseLine": "1.4", + "migrationGuide": "api/migrations/1.4.md", + "removed": { + "lxmf-core": [ + "pub fn lxmf_core::message::LxMessage::compute_hash(&mut self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::get_field(&self, u8) -> core::option::Option<&alloc::vec::Vec>", + "pub fn lxmf_core::message::LxMessage::get_stamp(&mut self) -> core::option::Option>", + "pub fn lxmf_core::message::LxMessage::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> Self", + "pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted(&mut self, F) -> core::result::Result<(alloc::vec::Vec, lxmf_core::types::PropagationTransientId), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted_with_stamp(&mut self, F, u8) -> core::result::Result<(alloc::vec::Vec, lxmf_core::types::PropagationTransientId, u32), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result, lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::set_field(&mut self, u8, alloc::vec::Vec)", + "pub fn lxmf_core::message::LxMessage::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::set_msgpack_field(&mut self, u8, alloc::vec::Vec) -> core::result::Result<(), lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::sign(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<(), lxmf_core::message::MessageError>", + "pub fn lxmf_core::message::LxMessage::sign_with(&mut self, F) -> core::result::Result<(), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display", + "pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&mut self, u8, core::option::Option<&[alloc::vec::Vec]>) -> bool", + "pub fn lxmf_core::message::LxMessage::verify(&mut self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool", + "pub fn lxmf_core::propagation_client::PropagationClient::take_received_messages(&mut self) -> alloc::vec::Vec>", + "pub fn lxmf_core::propagation_node::PropagationNode::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool", + "pub fn lxmf_core::propagation_node::PropagationNode::accept_propagated_blob(&mut self, &[u8], u8) -> bool", + "pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_message(&mut self, &lxmf_core::message::LxMessage) -> core::option::Option", + "pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_propagated_blob(&mut self, &[u8], u8) -> core::option::Option", + "pub fn lxmf_core::propagation_sync::PropagationSyncTask::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool", + "pub fn lxmf_core::router::LxmRouter::defer_stamp(&mut self, lxmf_core::message::LxMessage) -> core::option::Option", + "pub fn lxmf_core::router::LxmRouter::learn_ticket_from_inbound(&mut self, &lxmf_core::message::LxMessage) -> bool", + "pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessage) -> core::result::Result<(), lxmf_core::router::TicketPreparationError>", + "pub lxmf_core::link_delivery::PendingDelivery::message: lxmf_core::message::LxMessage", + "pub lxmf_core::message::LxMessage::auto_compress: bool", + "pub lxmf_core::message::LxMessage::callbacks: lxmf_core::message::MessageCallbacks", + "pub lxmf_core::message::LxMessage::content: alloc::string::String", + "pub lxmf_core::message::LxMessage::delivery_attempts: u32", + "pub lxmf_core::message::LxMessage::destination_hash: [u8; 16]", + "pub lxmf_core::message::LxMessage::fields: alloc::collections::btree::map::BTreeMap>", + "pub lxmf_core::message::LxMessage::hash: core::option::Option<[u8; 32]>", + "pub lxmf_core::message::LxMessage::include_ticket: bool", + "pub lxmf_core::message::LxMessage::incoming: bool", + "pub lxmf_core::message::LxMessage::last_delivery_attempt: f64", + "pub lxmf_core::message::LxMessage::message_id: core::option::Option<[u8; 32]>", + "pub lxmf_core::message::LxMessage::method: lxmf_core::constants::DeliveryMethod", + "pub lxmf_core::message::LxMessage::msgpack_field_ids: alloc::collections::btree::set::BTreeSet", + "pub lxmf_core::message::LxMessage::next_delivery_attempt: f64", + "pub lxmf_core::message::LxMessage::outbound_ticket: core::option::Option<[u8; 16]>", + "pub lxmf_core::message::LxMessage::progress: f64", + "pub lxmf_core::message::LxMessage::propagation_stamp: core::option::Option<[u8; 32]>", + "pub lxmf_core::message::LxMessage::ratchet_id: core::option::Option<[u8; 32]>", + "pub lxmf_core::message::LxMessage::representation: lxmf_core::constants::DeliveryRepresentation", + "pub lxmf_core::message::LxMessage::signature: core::option::Option<[u8; 64]>", + "pub lxmf_core::message::LxMessage::signature_validated: bool", + "pub lxmf_core::message::LxMessage::source_blackholed: bool", + "pub lxmf_core::message::LxMessage::source_hash: [u8; 16]", + "pub lxmf_core::message::LxMessage::stamp: core::option::Option>", + "pub lxmf_core::message::LxMessage::stamp_cost: core::option::Option", + "pub lxmf_core::message::LxMessage::stamp_value: core::option::Option", + "pub lxmf_core::message::LxMessage::state: lxmf_core::constants::MessageState", + "pub lxmf_core::message::LxMessage::timestamp: f64", + "pub lxmf_core::message::LxMessage::title: alloc::string::String", + "pub lxmf_core::message::LxMessage::transient_id: core::option::Option", + "pub lxmf_core::message::LxMessage::transport_encrypted: bool", + "pub lxmf_core::message::LxMessage::transport_encryption: core::option::Option", + "pub lxmf_core::message::LxMessage::unverified_reason: core::option::Option", + "pub lxmf_core::message::LxMessage::wire_payload: core::option::Option>", + "pub lxmf_core::message::MessagePayload::fields: alloc::collections::btree::map::BTreeMap>", + "pub lxmf_core::message::MessagePayload::msgpack_field_ids: alloc::collections::btree::set::BTreeSet", + "pub lxmf_core::router::LxmRouter::pending_deferred_stamps: std::collections::hash::map::HashMap<[u8; 32], lxmf_core::message::LxMessage>" + ] + } + } } diff --git a/crates/lxmf-core/Cargo.toml b/crates/lxmf-core/Cargo.toml index a74b477..0cb4386 100644 --- a/crates/lxmf-core/Cargo.toml +++ b/crates/lxmf-core/Cargo.toml @@ -21,13 +21,19 @@ bytes = { workspace = true } tracing = { workspace = true } rmp = { workspace = true } rmp-serde = { workspace = true } -rmpv = { workspace = true } +rmpv = { workspace = true, features = ["with-serde"] } serde = { workspace = true } sha2 = { workspace = true } rand = { workspace = true } hex = { workspace = true } unicode-normalization = { workspace = true } +[target.'cfg(target_os = "ios")'.dependencies] +objc2 = "0.6" + +[target.'cfg(target_os = "android")'.dependencies] +jni = "0.19" + [dev-dependencies] tempfile = { workspace = true } proptest = { workspace = true } diff --git a/crates/lxmf-core/examples/message.rs b/crates/lxmf-core/examples/message.rs index 4cf7bcb..8b6cbce 100644 --- a/crates/lxmf-core/examples/message.rs +++ b/crates/lxmf-core/examples/message.rs @@ -1,21 +1,20 @@ -//! Construct, sign, pack, and inspect an LXMF message through the canonical API. - -use lxmf_core::message_api::{DeliveryMethod, LxMessage, MessageState}; +//! Construct, sign, freeze, and inspect a message through the canonical API. +use lxmf_core::message_api::{DeliveryMethod, LxMessage, LxMessageDraft, MessageState}; use rns_crypto::ed25519::Ed25519PrivateKey; fn main() -> Result<(), Box> { - let mut message = LxMessage::new( + let mut draft = LxMessageDraft::new( [0x11; 16], [0x22; 16], "Hello", "LXMF from Rust", DeliveryMethod::Direct, - ); - message.sign(&Ed25519PrivateKey::generate())?; - - let packed = message.pack()?; - let unpacked = LxMessage::unpack(&packed)?; - assert_eq!(unpacked.title, "Hello"); + )?; + draft.set_field(0x105_u64, vec![1, 2, 3])?; + let message = draft.sign(&Ed25519PrivateKey::generate())?.finalize(None)?; + let unpacked = LxMessage::unpack(message.wire_bytes())?; + assert_eq!(unpacked.title_text(), "Hello"); assert_eq!(unpacked.state, MessageState::Generating); + assert_eq!(unpacked.wire_bytes(), message.wire_bytes()); Ok(()) } diff --git a/crates/lxmf-core/src/admission.rs b/crates/lxmf-core/src/admission.rs new file mode 100644 index 0000000..4114621 --- /dev/null +++ b/crates/lxmf-core/src/admission.rs @@ -0,0 +1,618 @@ +//! Durable propagation-download admission and non-purging retry policy. +//! +//! A transport Resource proof is not an application receipt. The trusted local +//! adapter implements [`DurableAdmissionBackend`] and commits its body/effects +//! and receipt together before a download token can authorize remote deletion. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; + +use bytes::Bytes; +use serde::{Deserialize, Serialize}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc}; + +pub const MAX_DOWNLOAD_ITEMS: usize = 4096; +pub const MAX_RETAINED_DOWNLOAD_BYTES: usize = 134_217_727; +pub const MAX_PROCESSING_BYTES: usize = 256 * 1024 * 1024; +pub const MAX_PROCESSORS: usize = 4; +pub const POLICY_RECEIPT_LIFETIME: u64 = 90 * 86400; + +/// Exact remote and local ownership of a ciphertext transient ID. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct AdmissionScope { + pub identity: [u8; 16], + pub node: [u8; 16], + pub transient_id: [u8; 32], +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DurableDisposition { + Committed, + Duplicate, + PolicyDiscard, + UserDeleted, +} + +/// Persisted effect identity. A duplicate need not have the same complete wire +/// hash: the optional recipient stamp is excluded from the signed message ID. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AdmissionRecord { + pub scope: AdmissionScope, + pub message_id: [u8; 32], + pub received_wire_hash: [u8; 32], + pub stored_message_wire_hash: Option<[u8; 32]>, + pub disposition: DurableDisposition, + pub committed_at: u64, +} + +/// Verified local purge authority with its finite policy lifetime. Adapters +/// supply these only after checking the referenced durable effect. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DurableHave { + pub transient_id: [u8; 32], + pub expires_at: Option, +} +impl DurableHave { + pub fn from_record(record: &AdmissionRecord) -> Self { + Self { + transient_id: record.scope.transient_id, + expires_at: matches!( + record.disposition, + DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted + ) + .then(|| record.committed_at.saturating_add(POLICY_RECEIPT_LIFETIME)), + } + } + pub fn active(self, now: u64) -> bool { + self.expires_at.is_none_or(|expiry| now < expiry) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum AdmissionError { + #[error("admission was not committed: {0}")] + NotCommitted(String), + #[error("admission publication is uncertain; reconcile all durability barriers: {0}")] + CommitUncertain(String), + #[error("durable disposition ledger is full")] + DispositionLedgerFull, + #[error("admission scope does not match the downloaded ciphertext")] + WrongScope, +} + +/// Trusted persistence adapter boundary. Implementations must atomically commit +/// the receipt with the message/effect, or reference a previously durable effect. +/// In particular, returning a record after a failed/uncertain filesystem or SQL +/// commit violates this contract. SQLite implementations use the dedicated FULL +/// connection; file implementations use the intent/body/commit journal. +pub trait DurableAdmissionBackend { + fn commit(self) -> Result; +} + +#[derive(Debug)] +pub struct DurableAdmissionReceipt { + record: AdmissionRecord, +} + +impl DurableAdmissionReceipt { + pub fn commit(backend: impl DurableAdmissionBackend) -> Result { + Ok(Self { + record: backend.commit()?, + }) + } + + pub fn record(&self) -> &AdmissionRecord { + &self.record + } +} + +/// Persisted, deterministic epochs; never reset these to a process generation. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct AdmissionEpochs { + pub policy: [u8; 32], + pub keys: [u8; 32], + pub budget: [u8; 32], + pub storage_health: [u8; 32], +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SuppressionReason { + Malformed, + WrongDestination, + InvalidSignature, + InvalidStamp, + DecryptionFailed, + TooLarge, + MissingKey, + StorageUnavailable, + StorageBusy, + Quota, + WorkerUnavailable, + DispositionLedgerFull, + Cancelled, +} + +impl SuppressionReason { + pub fn is_transient(self) -> bool { + matches!( + self, + Self::MissingKey + | Self::StorageUnavailable + | Self::StorageBusy + | Self::Quota + | Self::WorkerUnavailable + | Self::DispositionLedgerFull + | Self::Cancelled + ) + } + + fn epoch_matches(self, before: AdmissionEpochs, now: AdmissionEpochs) -> bool { + match self { + Self::DecryptionFailed | Self::MissingKey => before.keys == now.keys, + Self::InvalidSignature => before.keys == now.keys && before.policy == now.policy, + Self::TooLarge => before.budget == now.budget, + Self::StorageUnavailable + | Self::StorageBusy + | Self::Quota + | Self::DispositionLedgerFull => before.storage_health == now.storage_health, + _ => before.policy == now.policy, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SuppressionRecord { + pub scope: AdmissionScope, + pub reason: SuppressionReason, + pub epochs: AdmissionEpochs, + pub attempts: u16, + pub last_failure: u64, + pub next_retry: u64, + pub expires_at: u64, +} + +impl SuppressionRecord { + pub fn active(&self, now: u64, epochs: AdmissionEpochs) -> bool { + now < self.expires_at + && now < self.next_retry + && self.reason.epoch_matches(self.epochs, epochs) + } +} + +/// Quotas bound metadata independently of message bytes. Full ledgers preserve +/// existing entries and pause new wants, rather than evicting into a retry loop. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct SuppressionLedger { + records: HashMap, +} + +impl SuppressionLedger { + pub const PER_NODE: usize = 4096; + pub const PER_IDENTITY: usize = 16384; + pub const GLOBAL: usize = 65536; + + /// Restore typed rows only after duplicate and quota validation. Never + /// silently overwrite persisted scope decisions during hydration. + pub fn from_records( + records: impl IntoIterator, + ) -> Result { + let mut ledger = Self::default(); + let mut identities = HashMap::<[u8; 16], usize>::new(); + let mut nodes = HashMap::<([u8; 16], [u8; 16]), usize>::new(); + for record in records { + if ledger.records.contains_key(&record.scope) { + return Err(AdmissionError::NotCommitted( + "duplicate suppression scope".into(), + )); + } + if record.attempts == 0 + || record.next_retry < record.last_failure + || record.expires_at <= record.last_failure + || record.expires_at > record.last_failure.saturating_add(30 * 86400) + { + return Err(AdmissionError::NotCommitted( + "invalid suppression interval".into(), + )); + } + let identity = identities.entry(record.scope.identity).or_default(); + let node = nodes + .entry((record.scope.identity, record.scope.node)) + .or_default(); + if ledger.records.len() >= Self::GLOBAL + || *identity >= Self::PER_IDENTITY + || *node >= Self::PER_NODE + { + return Err(AdmissionError::DispositionLedgerFull); + } + *identity += 1; + *node += 1; + ledger.records.insert(record.scope, record); + } + Ok(ledger) + } + + pub fn records(&self) -> impl Iterator { + self.records.values() + } + pub fn get(&self, scope: &AdmissionScope) -> Option<&SuppressionRecord> { + self.records.get(scope) + } + pub fn remove(&mut self, scope: &AdmissionScope) { + self.records.remove(scope); + } + pub fn prune(&mut self, now: u64, epochs: AdmissionEpochs) { + self.records.retain(|_, record| { + now < record.expires_at && record.reason.epoch_matches(record.epochs, epochs) + }); + } + pub fn saturated(&self, identity: [u8; 16], node: [u8; 16]) -> bool { + self.records.len() >= Self::GLOBAL + || self + .records + .keys() + .filter(|k| k.identity == identity) + .count() + >= Self::PER_IDENTITY + || self + .records + .keys() + .filter(|k| k.identity == identity && k.node == node) + .count() + >= Self::PER_NODE + } + pub fn record_failure( + &mut self, + scope: AdmissionScope, + reason: SuppressionReason, + epochs: AdmissionEpochs, + now: u64, + ) -> Result<&SuppressionRecord, AdmissionError> { + self.prune(now, epochs); + if !self.records.contains_key(&scope) && self.saturated(scope.identity, scope.node) { + return Err(AdmissionError::DispositionLedgerFull); + } + let attempts = self + .records + .get(&scope) + .filter(|r| r.reason == reason) + .map_or(1, |r| r.attempts.saturating_add(1)); + let (next_retry, expires_at) = if reason.is_transient() { + let base = (60u64 << attempts.saturating_sub(1).min(6)).min(3600); + // Stable +/-10% jitter avoids synchronized retries after restart. + let jitter = + u16::from_be_bytes([scope.transient_id[0], scope.transient_id[1]]) as u64 % 21; + ( + now.saturating_add(base * (90 + jitter) / 100), + now.saturating_add(86400), + ) + } else { + ( + now.saturating_add(30 * 86400), + now.saturating_add(30 * 86400), + ) + }; + self.records.insert( + scope, + SuppressionRecord { + scope, + reason, + epochs, + attempts, + last_failure: now, + next_retry, + expires_at, + }, + ); + Ok(&self.records[&scope]) + } +} + +#[derive(Debug)] +pub enum DownloadAdmissionOutcome { + Accepted(DurableAdmissionReceipt), + Rejected(SuppressionReason), +} + +pub(crate) struct AdmissionResolution { + pub generation: u64, + pub scope: AdmissionScope, + pub outcome: DownloadAdmissionOutcome, +} + +/// Single-use, generation-bound authority. Dropping it reports a retryable +/// failure; cancelling its client generation cannot cancel a blocking commit. +pub struct DownloadAdmissionToken { + scope: AdmissionScope, + generation: u64, + current_generation: Arc, + tx: Option>, +} + +impl std::fmt::Debug for DownloadAdmissionToken { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DownloadAdmissionToken") + .field("scope", &self.scope) + .field("generation", &self.generation) + .finish_non_exhaustive() + } +} + +impl DownloadAdmissionToken { + pub(crate) fn new( + scope: AdmissionScope, + generation: u64, + current_generation: Arc, + tx: mpsc::UnboundedSender, + ) -> Self { + Self { + scope, + generation, + current_generation, + tx: Some(tx), + } + } + pub fn scope(&self) -> AdmissionScope { + self.scope + } + /// Check immediately after durable commit before publishing current-generation effects. + /// Cancellation cannot stop an in-flight commit or release its memory lease. + pub fn is_current(&self) -> bool { + self.current_generation.load(Ordering::Acquire) == self.generation + } + pub fn resolve(mut self, outcome: DownloadAdmissionOutcome) -> Result<(), AdmissionError> { + if let DownloadAdmissionOutcome::Accepted(receipt) = &outcome + && receipt.record.scope != self.scope + { + return Err(AdmissionError::WrongScope); + } + if !self.is_current() { + self.tx.take(); + return Err(AdmissionError::NotCommitted( + "download generation was revoked".into(), + )); + } + let tx = self.tx.take().ok_or_else(|| { + AdmissionError::NotCommitted("download authority already consumed".into()) + })?; + tx.send(AdmissionResolution { + generation: self.generation, + scope: self.scope, + outcome, + }) + .map_err(|_| AdmissionError::NotCommitted("download consumer is closed".into()))?; + // The client rechecks the exact generation while consuming. This result + // reports enqueue only; adapters need their lifecycle gate around any + // current-generation UI effects, not an atomic-cancellation promise. + if !self.is_current() { + return Err(AdmissionError::NotCommitted( + "download generation was revoked".into(), + )); + } + Ok(()) + } +} + +impl Drop for DownloadAdmissionToken { + fn drop(&mut self) { + if let Some(tx) = self.tx.take() { + let _ = tx.send(AdmissionResolution { + generation: self.generation, + scope: self.scope, + outcome: DownloadAdmissionOutcome::Rejected(SuppressionReason::Cancelled), + }); + } + } +} + +#[derive(Debug)] +pub struct DownloadedPropagationMessage { + data: Bytes, + token: DownloadAdmissionToken, +} + +impl DownloadedPropagationMessage { + pub(crate) fn new(data: Bytes, token: DownloadAdmissionToken) -> Self { + Self { data, token } + } + pub fn data(&self) -> &Bytes { + &self.data + } + pub fn scope(&self) -> AdmissionScope { + self.token.scope + } + pub fn into_parts(self) -> (Bytes, DownloadAdmissionToken) { + (self.data, self.token) + } +} + +fn raw_budget() -> &'static Arc { + static BUDGET: OnceLock> = OnceLock::new(); + BUDGET.get_or_init(|| Arc::new(Semaphore::new(MAX_RETAINED_DOWNLOAD_BYTES))) +} + +struct RetainedResponse { + bytes: Bytes, + _credit: OwnedSemaphorePermit, +} +impl AsRef<[u8]> for RetainedResponse { + fn as_ref(&self) -> &[u8] { + &self.bytes + } +} + +/// Credit follows every Bytes clone/slice, including payloads in cancelled +/// blocking workers. Moving a response out of the client never releases it. +pub(crate) fn retain_response( + bytes: Bytes, + local_limit: usize, +) -> Result { + if bytes.len() > local_limit.min(MAX_RETAINED_DOWNLOAD_BYTES) { + return Err(SuppressionReason::TooLarge); + } + let credit = raw_budget() + .clone() + .try_acquire_many_owned(bytes.len() as u32) + .map_err(|_| SuppressionReason::WorkerUnavailable)?; + Ok(Bytes::from_owner(RetainedResponse { + bytes, + _credit: credit, + })) +} + +/// Full peak reservation is obtained before decrypting while raw ciphertext is +/// retained separately. Never wait for a partial reservation while holding the +/// parent response. This bounds Rust-owned buffers, not SQLite's native heap. +fn processing_budget() -> &'static Arc { + static BYTES: OnceLock> = OnceLock::new(); + BYTES.get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSING_BYTES))) +} + +/// Additional explicitly bounded adapter state, sharing the processing byte +/// budget without taking a second worker slot. Admission is always nonblocking. +pub struct ProcessingMemoryLease { + _bytes: OwnedSemaphorePermit, +} +impl ProcessingMemoryLease { + pub fn try_acquire(amount: usize) -> Result { + if amount > MAX_PROCESSING_BYTES { + return Err(SuppressionReason::TooLarge); + } + Ok(Self { + _bytes: processing_budget() + .clone() + .try_acquire_many_owned(amount as u32) + .map_err(|_| SuppressionReason::WorkerUnavailable)?, + }) + } +} + +pub struct ProcessingLease { + _bytes: OwnedSemaphorePermit, + _worker: OwnedSemaphorePermit, +} + +impl ProcessingLease { + pub fn try_acquire(cipher_len: usize) -> Result { + static WORKERS: OnceLock> = OnceLock::new(); + let amount = cipher_len + .checked_mul(4) + .and_then(|v| v.checked_add(128 * 1024 + 256)) + .filter(|v| *v <= MAX_PROCESSING_BYTES) + .ok_or(SuppressionReason::TooLarge)?; + let bytes = processing_budget() + .clone() + .try_acquire_many_owned(amount as u32) + .map_err(|_| SuppressionReason::WorkerUnavailable)?; + let worker = WORKERS + .get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSORS))) + .clone() + .try_acquire_owned() + .map_err(|_| SuppressionReason::WorkerUnavailable)?; + Ok(Self { + _bytes: bytes, + _worker: worker, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn scope(n: u8) -> AdmissionScope { + AdmissionScope { + identity: [1; 16], + node: [2; 16], + transient_id: [n; 32], + } + } + #[test] + fn resolution_rejects_revoked_generation_and_closed_consumer() { + let generation = Arc::new(AtomicU64::new(1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let token = DownloadAdmissionToken::new(scope(1), 1, generation.clone(), tx.clone()); + generation.store(2, Ordering::Release); + assert!( + token + .resolve(DownloadAdmissionOutcome::Rejected( + SuppressionReason::Cancelled + )) + .is_err() + ); + assert!(rx.try_recv().is_err()); + let token = DownloadAdmissionToken::new(scope(2), 2, generation, tx); + drop(rx); + assert!( + token + .resolve(DownloadAdmissionOutcome::Rejected( + SuppressionReason::Cancelled + )) + .is_err() + ); + } + #[test] + fn permanent_failures_revalidate_on_epoch_change_or_expiry() { + let mut ledger = SuppressionLedger::default(); + let epoch = AdmissionEpochs::default(); + let r = ledger + .record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100) + .unwrap(); + assert!(r.active(101, epoch)); + let mut changed = epoch; + changed.keys[0] = 1; + assert!(!r.active(101, changed)); + assert!(!r.active(100 + 30 * 86400, epoch)); + assert!(rmp_serde::to_vec(r).unwrap().len() <= 512); + } + #[test] + fn temporary_storage_failure_is_retryable_and_bounded() { + let mut ledger = SuppressionLedger::default(); + for _ in 0..20 { + ledger + .record_failure( + scope(1), + SuppressionReason::StorageBusy, + AdmissionEpochs::default(), + 100, + ) + .unwrap(); + } + let r = ledger.get(&scope(1)).unwrap(); + assert!((3340..=4060).contains(&r.next_retry)); + assert_eq!(r.expires_at, 86500); + } + #[test] + fn full_node_ledger_does_not_evict_existing_suppression() { + let mut ledger = SuppressionLedger::default(); + for n in 0..SuppressionLedger::PER_NODE { + let mut s = scope(0); + s.transient_id[..8].copy_from_slice(&(n as u64).to_be_bytes()); + ledger + .record_failure( + s, + SuppressionReason::Malformed, + AdmissionEpochs::default(), + 100, + ) + .unwrap(); + } + assert!( + ledger + .record_failure( + scope(255), + SuppressionReason::Malformed, + AdmissionEpochs::default(), + 100 + ) + .is_err() + ); + assert_eq!(ledger.records().count(), SuppressionLedger::PER_NODE); + } + #[test] + fn impossible_processing_size_rejects_without_partial_wait() { + assert!(matches!( + ProcessingLease::try_acquire(MAX_PROCESSING_BYTES), + Err(SuppressionReason::TooLarge) + )); + } +} diff --git a/crates/lxmf-core/src/admission_store.rs b/crates/lxmf-core/src/admission_store.rs new file mode 100644 index 0000000..16e5f8a --- /dev/null +++ b/crates/lxmf-core/src/admission_store.rs @@ -0,0 +1,599 @@ +//! File adapter for lxmd's durable download receipts and hook outbox. +//! The original ciphertext TID is journaled before publishing decrypted bytes. +use crate::admission::*; +use bytes::Bytes; +use rns_identity::persistence::{ + DurableCommitPhase, DurableWriteError, durable_create_dir_all, durable_reconcile, + durable_remove, durable_write, +}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct AdmissionIntent { + version: u8, + admission_id: [u8; 32], + record: AdmissionRecord, + body_path: Option, + hook_event: Option<[u8; 32]>, +} + +/// One atomic logical commit publishes both the receipt and pending hook event. +#[derive(Debug, Clone, Serialize, Deserialize)] +struct AdmissionCommit { + intent: AdmissionIntent, + hook_completed: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct UserDeletedMessage { + version: u8, + identity: [u8; 16], + message_id: [u8; 32], + deleted_at: u64, +} + +struct Inner { + journal: PathBuf, + bodies: PathBuf, + committed: HashMap, + deleted: HashMap<([u8; 16], [u8; 32]), UserDeletedMessage>, +} + +#[derive(Clone)] +pub struct FileAdmissionStore { + inner: Arc>, +} + +fn error(e: DurableWriteError) -> AdmissionError { + match e.phase { + DurableCommitPhase::NotCommitted => AdmissionError::NotCommitted(e.to_string()), + _ => AdmissionError::CommitUncertain(e.to_string()), + } +} +fn other(e: impl std::fmt::Display) -> AdmissionError { + AdmissionError::NotCommitted(e.to_string()) +} +fn encode(value: &T) -> Result, AdmissionError> { + rmp_serde::to_vec_named(value).map_err(other) +} +fn read_bounded(path: &Path, limit: usize) -> Result, AdmissionError> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(path) + .map_err(other)? + .take(limit as u64 + 1) + .read_to_end(&mut bytes) + .map_err(other)?; + if bytes.len() > limit { + return Err(other("admission artifact exceeds limit")); + } + Ok(bytes) +} +fn admission_id(scope: &AdmissionScope) -> Result<[u8; 32], AdmissionError> { + Ok(rns_crypto::sha::full_hash(&encode(scope)?)) +} + +impl FileAdmissionStore { + /// Parent is the daemon's already configured state directory. A strict + /// outside bootstrap receipt witnesses creation of journal/body directories. + pub fn open(state_dir: &Path, bodies: &Path) -> Result { + let journal = state_dir.join("download-admission-v1"); + let parent = state_dir + .ancestors() + .find(|parent| { + bodies.starts_with(parent) && *parent != bodies && parent.parent().is_some() + }) + .ok_or_else(|| other("admission state and bodies need a private common ancestor"))?; + let scope = encode(&(1u8, state_dir, bodies))?; + let bootstrap_path = parent.join(format!( + "download-admission-{}.bootstrap", + hex::encode(rns_crypto::sha::full_hash(&scope)) + )); + let bootstrap = durable_write(&bootstrap_path, &scope).map_err(error)?; + durable_create_dir_all(&journal, &bootstrap).map_err(error)?; + durable_create_dir_all(bodies, &bootstrap).map_err(error)?; + let mut inner = Inner { + journal, + bodies: bodies.to_owned(), + committed: HashMap::new(), + deleted: HashMap::new(), + }; + inner.recover()?; + Ok(Self { + inner: Arc::new(Mutex::new(inner)), + }) + } + + pub fn prepare( + &self, + mut record: AdmissionRecord, + wire: Bytes, + run_hook: bool, + ) -> FileAdmissionCommit { + // The caller cannot mislabel the incoming image even for a duplicate. + record.received_wire_hash = rns_crypto::sha::full_hash(&wire); + FileAdmissionCommit { + store: self.clone(), + record, + wire, + run_hook, + } + } + + /// Durable visible receipts remain while their referenced message exists; + /// invisible policy/TID accelerators expire after the local90-day policy. + pub fn haves(&self, identity: [u8; 16], node: [u8; 16], now: u64) -> Vec> { + let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner()); + inner + .committed + .values() + .filter(|c| { + c.intent.record.scope.identity == identity + && c.intent.record.scope.node == node + && live(&c.intent.record, now) + }) + .map(|c| c.intent.record.scope.transient_id.to_vec()) + .collect() + } + + pub fn durable_haves( + &self, + identity: [u8; 16], + node: [u8; 16], + now: u64, + ) -> Vec { + let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner()); + inner + .committed + .values() + .filter(|c| { + c.intent.record.scope.identity == identity + && c.intent.record.scope.node == node + && live(&c.intent.record, now) + }) + .map(|c| super::admission::DurableHave::from_record(&c.intent.record)) + .collect() + } + + /// Explicit user deletion is a permanent message-ID decision, separate + /// from expiring per-node TID accelerators. No filesystem absence is treated + /// as user authorization. Removing this tombstone requires explicit reset. + pub fn mark_user_deleted( + &self, + identity: [u8; 16], + message_id: [u8; 32], + now: u64, + ) -> Result<(), AdmissionError> { + let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner()); + let tombstone = UserDeletedMessage { + version: 1, + identity, + message_id, + deleted_at: now, + }; + let path = inner.journal.join(format!( + "{}-{}.deleted", + hex::encode(identity), + hex::encode(message_id) + )); + let witness = durable_write(&path, &encode(&tombstone)?).map_err(error)?; + inner.deleted.insert((identity, message_id), tombstone); + let targets = inner + .committed + .iter() + .filter(|(_, c)| { + c.intent.record.scope.identity == identity + && c.intent.record.message_id == message_id + }) + .map(|(scope, c)| (*scope, c.clone())) + .collect::>(); + for (scope, mut commit) in targets { + commit.intent.body_path = None; + commit.intent.hook_event = None; + commit.hook_completed = true; + commit.intent.record.disposition = DurableDisposition::UserDeleted; + commit.intent.record.stored_message_wire_hash = None; + commit.intent.record.committed_at = now; + durable_write( + &inner.intent_path(&commit.intent.admission_id), + &encode(&commit.intent)?, + ) + .map_err(error)?; + durable_write( + &inner.commit_path(&commit.intent.admission_id), + &encode(&commit)?, + ) + .map_err(error)?; + inner.committed.insert(scope, commit); + } + durable_remove( + &inner + .bodies + .join(format!("{}.lxm", hex::encode(message_id))), + &witness, + ) + .map_err(error)?; + Ok(()) + } + + /// Prune only expired invisible TID receipts. Visible archive authority and + /// permanent UserDeleted message decisions are retained independently. + pub fn maintain(&self, now: u64) -> Result { + let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner()); + let expired = inner + .committed + .iter() + .filter(|(_, c)| !live(&c.intent.record, now)) + .map(|(scope, c)| (*scope, c.intent.admission_id)) + .collect::>(); + if expired.is_empty() { + return Ok(0); + } + let witness = durable_write( + &inner.journal.join("receipt-pruning-v1"), + &encode(&(1u8, &expired))?, + ) + .map_err(error)?; + let mut removed = 0; + for (scope, id) in expired { + durable_remove(&inner.intent_path(&id), &witness).map_err(error)?; + durable_remove(&inner.commit_path(&id), &witness).map_err(error)?; + inner.committed.remove(&scope); + removed += 1; + } + Ok(removed) + } + + pub fn pending_hooks(&self) -> Vec<([u8; 32], PathBuf)> { + let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner()); + inner + .committed + .values() + .filter(|c| !c.hook_completed) + .filter_map(|c| Some((c.intent.hook_event?, c.intent.body_path.clone()?))) + .collect() + } + + pub fn complete_hook(&self, event: [u8; 32]) -> Result<(), AdmissionError> { + let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner()); + let Some(scope) = inner + .committed + .iter() + .find_map(|(s, c)| (c.intent.hook_event == Some(event)).then_some(*s)) + else { + return Ok(()); + }; + let mut updated = inner.committed[&scope].clone(); + updated.hook_completed = true; + durable_write( + &inner.commit_path(&updated.intent.admission_id), + &encode(&updated)?, + ) + .map_err(error)?; + inner.committed.insert(scope, updated); + Ok(()) + } +} + +fn live(record: &AdmissionRecord, now: u64) -> bool { + !matches!( + record.disposition, + DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted + ) || now.saturating_sub(record.committed_at) < POLICY_RECEIPT_LIFETIME +} + +pub struct FileAdmissionCommit { + store: FileAdmissionStore, + record: AdmissionRecord, + wire: Bytes, + run_hook: bool, +} +impl DurableAdmissionBackend for FileAdmissionCommit { + fn commit(self) -> Result { + let mut inner = self.store.inner.lock().unwrap_or_else(|p| p.into_inner()); + let parsed = crate::message::LxMessage::unpack_owned(self.wire.clone(), Default::default()) + .map_err(other)?; + if parsed.message_id() != self.record.message_id { + return Err(other("admission message identity mismatch")); + } + if let Some(existing) = inner.committed.get(&self.record.scope) { + if existing.intent.record.received_wire_hash != self.record.received_wire_hash { + return Err(other("ciphertext TID receipt wire mismatch")); + } + if !inner + .deleted + .contains_key(&(self.record.scope.identity, self.record.message_id)) + && live(&existing.intent.record, self.record.committed_at) + && matches!( + existing.intent.record.disposition, + DurableDisposition::Committed | DurableDisposition::Duplicate + ) + && self.record.disposition == DurableDisposition::Committed + { + inner.validate_body(&existing.intent)?; + let mut duplicate = existing.intent.record.clone(); + duplicate.disposition = DurableDisposition::Duplicate; + return Ok(duplicate); + } + } + let mut record = self.record; + if inner + .deleted + .contains_key(&(record.scope.identity, record.message_id)) + { + record.disposition = DurableDisposition::UserDeleted; + } + let invisible = matches!( + record.disposition, + DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted + ); + if invisible { + let existing = inner.committed.values().filter(|c| { + matches!( + c.intent.record.disposition, + DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted + ) && live(&c.intent.record, record.committed_at) + }); + let global = existing.clone().count(); + let identity = existing + .filter(|c| c.intent.record.scope.identity == record.scope.identity) + .count(); + if global >= 65536 || identity >= 16384 { + return Err(AdmissionError::DispositionLedgerFull); + } + } + let body_path = (!invisible).then(|| { + inner + .bodies + .join(format!("{}.lxm", hex::encode(record.message_id))) + }); + let mut body = None; + let mut newly_visible = false; + if let Some(path) = &body_path { + match std::fs::metadata(path) { + Ok(_) => { + let existing = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?; + // Keep the first immutable archive. Same message ID can have + // a different fifth-stamp image; record both hashes. + let parsed = crate::message::LxMessage::unpack(&existing).map_err(other)?; + if parsed.message_id() != record.message_id { + return Err(other("existing archive has a different message ID")); + } + record.stored_message_wire_hash = Some(rns_crypto::sha::full_hash(&existing)); + record.disposition = DurableDisposition::Duplicate; + body = Some(Bytes::from(existing)); + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + record.stored_message_wire_hash = Some(record.received_wire_hash); + newly_visible = true; + body = Some(self.wire.clone()); + } + Err(e) => return Err(other(e)), + } + } + let admission_id = admission_id(&record.scope)?; + let intent = AdmissionIntent { + version: 1, + admission_id, + record: record.clone(), + body_path, + hook_event: (self.run_hook && newly_visible).then_some(admission_id), + }; + durable_write(&inner.intent_path(&admission_id), &encode(&intent)?).map_err(error)?; + if let (Some(path), Some(body)) = (&intent.body_path, body) { + if newly_visible { + durable_write(path, &body).map_err(error)?; + } else { + durable_reconcile(path, &body).map_err(error)?; + } + } + let commit = AdmissionCommit { + intent, + hook_completed: false, + }; + durable_write(&inner.commit_path(&admission_id), &encode(&commit)?).map_err(error)?; + inner.committed.insert(record.scope, commit); + Ok(record) + } +} + +impl Inner { + fn intent_path(&self, id: &[u8; 32]) -> PathBuf { + self.journal.join(format!("{}.intent", hex::encode(id))) + } + fn commit_path(&self, id: &[u8; 32]) -> PathBuf { + self.journal.join(format!("{}.commit", hex::encode(id))) + } + fn validate_body(&self, intent: &AdmissionIntent) -> Result<(), AdmissionError> { + if intent.version != 1 || admission_id(&intent.record.scope)? != intent.admission_id { + return Err(other("unknown admission journal version or identity")); + } + if self + .deleted + .contains_key(&(intent.record.scope.identity, intent.record.message_id)) + && intent.record.disposition != DurableDisposition::UserDeleted + { + return Err(other("message was explicitly deleted")); + } + if let Some(path) = &intent.body_path { + if path.parent() != Some(self.bodies.as_path()) + || path.file_name().and_then(|n| n.to_str()) + != Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str()) + { + return Err(other("admission archive path escapes configured inbox")); + } + let body = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?; + if Some(rns_crypto::sha::full_hash(&body)) != intent.record.stored_message_wire_hash { + return Err(other("admission archive content mismatch")); + } + // A previous CommitUncertain becomes authoritative only after all + // native barriers succeed again, never merely after readback. + durable_reconcile(path, &body).map_err(error)?; + } else if !matches!( + intent.record.disposition, + DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted + ) { + return Err(other("visible admission is missing its archive")); + } + Ok(()) + } + fn recover(&mut self) -> Result<(), AdmissionError> { + // Stream directory passes: directory size must not itself allocate an + // unbounded vector. Malformed artifacts remain private and unavailable. + for file in std::fs::read_dir(&self.journal).map_err(other)? { + let path = file.map_err(other)?.path(); + if path.extension().and_then(|s| s.to_str()) != Some("deleted") { + continue; + } + let data = read_bounded(&path, 2048)?; + let tombstone: UserDeletedMessage = rmp_serde::from_slice(&data).map_err(other)?; + if tombstone.version != 1 + || path.file_name().and_then(|s| s.to_str()) + != Some( + format!( + "{}-{}.deleted", + hex::encode(tombstone.identity), + hex::encode(tombstone.message_id) + ) + .as_str(), + ) + { + return Err(other("invalid user deletion tombstone")); + } + let witness = durable_reconcile(&path, &data).map_err(error)?; + durable_remove( + &self + .bodies + .join(format!("{}.lxm", hex::encode(tombstone.message_id))), + &witness, + ) + .map_err(error)?; + self.deleted + .insert((tombstone.identity, tombstone.message_id), tombstone); + } + for file in std::fs::read_dir(&self.journal).map_err(other)? { + let path = file.map_err(other)?.path(); + if path.extension().and_then(|s| s.to_str()) != Some("commit") { + continue; + } + let result = (|| { + let data = read_bounded(&path, 16 * 1024)?; + let commit: AdmissionCommit = rmp_serde::from_slice(&data).map_err(other)?; + if path != self.commit_path(&commit.intent.admission_id) { + return Err(other("commit filename mismatch")); + } + self.validate_body(&commit.intent)?; + durable_reconcile(&path, &data).map_err(error)?; + Ok(commit) + })(); + match result { + Ok(commit) => { + self.committed.insert(commit.intent.record.scope, commit); + } + Err(error) => { + tracing::warn!(%error,path=%path.display(),"unavailable admission preserved without purge authority") + } + } + } + for file in std::fs::read_dir(&self.journal).map_err(other)? { + let path = file.map_err(other)?.path(); + if path.extension().and_then(|s| s.to_str()) != Some("intent") { + continue; + } + let result = (|| { + let data = read_bounded(&path, 16 * 1024)?; + let intent: AdmissionIntent = rmp_serde::from_slice(&data).map_err(other)?; + if path != self.intent_path(&intent.admission_id) { + return Err(other("intent filename mismatch")); + } + if self + .committed + .get(&intent.record.scope) + .is_some_and(|c| c.intent.record == intent.record) + { + return Ok(None); + } + self.validate_body(&intent)?; + durable_reconcile(&path, &data).map_err(error)?; + let commit = AdmissionCommit { + intent, + hook_completed: false, + }; + durable_write( + &self.commit_path(&commit.intent.admission_id), + &encode(&commit)?, + ) + .map_err(error)?; + Ok(Some(commit)) + })(); + match result { + Ok(Some(commit)) => { + self.committed.insert(commit.intent.record.scope, commit); + } + Ok(None) => {} + Err(error) => { + tracing::warn!(%error,path=%path.display(),"uncommitted admission preserved without purge authority") + } + } + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn committed_receipt_survives_reopen_and_hook_is_in_same_commit() { + let temp = tempfile::tempdir().unwrap(); + let bodies = temp.path().join("messages"); + let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + let message = crate::message::test_message( + [1; 16], + [2; 16], + "", + "body", + crate::constants::DeliveryMethod::Propagated, + ); + let scope = AdmissionScope { + identity: [3; 16], + node: [4; 16], + transient_id: [5; 32], + }; + let record = AdmissionRecord { + scope, + message_id: message.message_id(), + received_wire_hash: [0; 32], + stored_message_wire_hash: None, + disposition: DurableDisposition::Committed, + committed_at: 100, + }; + let receipt = DurableAdmissionReceipt::commit(store.prepare( + record, + Bytes::copy_from_slice(message.wire_bytes()), + true, + )) + .unwrap(); + assert_eq!( + receipt.record().received_wire_hash, + rns_crypto::sha::full_hash(message.wire_bytes()) + ); + drop(store); + let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + assert_eq!( + recovered.haves(scope.identity, scope.node, 101), + vec![scope.transient_id.to_vec()] + ); + assert_eq!(recovered.pending_hooks().len(), 1); + recovered + .complete_hook(recovered.pending_hooks()[0].0) + .unwrap(); + assert!(recovered.pending_hooks().is_empty()); + } +} diff --git a/crates/lxmf-core/src/delivery_ratchet.rs b/crates/lxmf-core/src/delivery_ratchet.rs index 3827496..10b8aea 100644 --- a/crates/lxmf-core/src/delivery_ratchet.rs +++ b/crates/lxmf-core/src/delivery_ratchet.rs @@ -87,7 +87,7 @@ impl DeliveryRatchetState { let format = loaded.format(); let ring = loaded.into_ring(); if format == RatchetRingFormat::LegacyRust { - match ring.save_verified(&ring_path, identity) { + match ring.save_verified_durable(&ring_path, identity) { Ok(()) => tracing::info!( path = %ring_path.display(), "migrated legacy Rust ratchet ring to canonical format" @@ -145,7 +145,7 @@ impl DeliveryRatchetState { if ring.is_empty() && ring_file_trusted && control_file_trusted { let prepared = ring.prepare_rotation_at(wall_now as f64); - match prepared.ring().save_verified(&ring_path, identity) { + match prepared.ring().save_verified_durable(&ring_path, identity) { Ok(()) => { ring.commit_prepared_rotation(prepared); control = control.with_rotation_at(wall_now); @@ -161,7 +161,7 @@ impl DeliveryRatchetState { if control_file_trusted && (!control_existed || control_changed) - && let Err(error) = control.save_verified(&control_path, identity) + && let Err(error) = control.save_verified_durable(&control_path, identity) { tracing::warn!( path = %control_path.display(), @@ -241,7 +241,10 @@ impl DeliveryRatchetState { let mut ratchet_public = self.ring.current_public_key(); if rotation_due && self.ring_file_trusted { let prepared = self.ring.prepare_rotation_at(wall_now as f64); - match prepared.ring().save_verified(&self.ring_path, identity) { + match prepared + .ring() + .save_verified_durable(&self.ring_path, identity) + { Ok(()) => { ratchet_public = Some(prepared.public_key()); candidate_control = candidate_control.with_rotation_at(wall_now); @@ -256,7 +259,7 @@ impl DeliveryRatchetState { } candidate_control - .save_verified(&self.control_path, identity) + .save_verified_durable(&self.control_path, identity) .map_err(|source| DeliveryRatchetError::PersistControl { path: self.control_path.clone(), source, @@ -293,17 +296,33 @@ impl DeliveryRatchetState { /// never overwritten by this operation. pub fn save(&self, identity: &Identity) { if self.ring_file_trusted - && let Err(error) = self.ring.save_verified(&self.ring_path, identity) + && let Err(error) = self.ring.save_verified_durable(&self.ring_path, identity) { tracing::warn!(%error, "failed to save ratchet ring"); } if self.control_file_trusted - && let Err(error) = self.control.save_verified(&self.control_path, identity) + && let Err(error) = self + .control + .save_verified_durable(&self.control_path, identity) { tracing::warn!(%error, "failed to save ratchet control state"); } } + /// Checked strict checkpoint. Invalid files discovered during load remain + /// untouched and prevent a successful checkpoint claim. + pub fn save_durable(&self, identity: &Identity) -> std::io::Result<()> { + if !self.ring_file_trusted || !self.control_file_trusted { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "ratchet checkpoint contains untrusted state", + )); + } + self.ring.save_verified_durable(&self.ring_path, identity)?; + self.control + .save_verified_durable(&self.control_path, identity) + } + pub fn ring_path(&self) -> &Path { &self.ring_path } diff --git a/crates/lxmf-core/src/lib.rs b/crates/lxmf-core/src/lib.rs index a2dfef5..8e5d85d 100644 --- a/crates/lxmf-core/src/lib.rs +++ b/crates/lxmf-core/src/lib.rs @@ -43,6 +43,8 @@ pub(crate) fn now_f64() -> f64 { .as_secs_f64() } +pub mod admission; +pub mod admission_store; pub mod constants; pub mod delivery_ratchet; pub mod discovery_stamper; @@ -58,6 +60,8 @@ pub mod propagation_admission; pub mod propagation_client; pub mod propagation_node; pub mod propagation_offer; +pub mod propagation_send; +pub mod propagation_store_v2; pub mod propagation_sync; pub mod router; pub mod stamper; @@ -74,7 +78,11 @@ pub mod message_api { pub use crate::constants::{ DeliveryMethod, DeliveryRepresentation, MessageState, UnverifiedReason, }; - pub use crate::message::{AudioField, LxMessage, MessageError}; + pub use crate::message::{ + AudioField, EncodedFieldValue, FieldId, FieldMapKey, FieldValue, FieldValueRef, Fields, + LxMessage, LxMessageDraft, MessageDecodeLimits, MessageError, MessageMetadata, + OwnedVerifiedLxMessage, RecipientStamp, SignedLxMessage, UniqueFieldMap, VerifiedLxMessage, + }; pub use crate::types::{DestinationHash, IdentityHash, MessageId}; } diff --git a/crates/lxmf-core/src/link_delivery.rs b/crates/lxmf-core/src/link_delivery.rs index d480113..382b680 100644 --- a/crates/lxmf-core/src/link_delivery.rs +++ b/crates/lxmf-core/src/link_delivery.rs @@ -288,9 +288,72 @@ pub enum DeliveryState { Failed, } +/// Payload ownership for a reusable Link. Terminal settlement removes the +/// immutable image and callbacks; the idle Link retains no message body. +#[derive(Debug)] +pub struct RetainedDeliveryMessage { + image: Option, + metadata: crate::message::MessageMetadata, + id: [u8; 32], +} +impl From for RetainedDeliveryMessage { + fn from(mut message: LxMessage) -> Self { + let metadata = std::mem::take(&mut message.metadata); + Self { + id: message.message_id(), + image: Some(message), + metadata, + } + } +} +impl std::ops::Deref for RetainedDeliveryMessage { + type Target = crate::message::MessageMetadata; + fn deref(&self) -> &Self::Target { + &self.metadata + } +} +impl std::ops::DerefMut for RetainedDeliveryMessage { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.metadata + } +} +impl RetainedDeliveryMessage { + pub fn message_id(&self) -> [u8; 32] { + self.id + } + pub fn retained_wire_bytes(&self) -> usize { + self.image + .as_ref() + .map_or(0, |message| message.wire_bytes().len()) + } + fn pack(&self) -> Result, crate::message::MessageError> { + self.image + .as_ref() + .ok_or_else(|| { + crate::message::MessageError::PackFailed("delivery payload already settled".into()) + })? + .pack() + } + fn mark_rejected(&mut self) { + self.metadata.state = crate::constants::MessageState::Rejected; + } + fn release(&mut self) { + self.image = None; + self.metadata = crate::message::MessageMetadata::default(); + } + fn take(&mut self) -> LxMessage { + let mut message = self + .image + .take() + .expect("active delivery owns one immutable payload"); + message.metadata = std::mem::take(&mut self.metadata); + message + } +} + /// An in-progress link-based delivery. pub struct PendingDelivery { - pub message: LxMessage, + pub message: RetainedDeliveryMessage, pub dest_hash: [u8; 16], pub packed_override: Option>, pub auto_compress: bool, @@ -309,6 +372,9 @@ pub struct PendingDelivery { /// an initiator that never receives LRPROOF should fail on the Link /// establishment clock, not on the active-link inactivity clock. pub establishment_timeout: Duration, + link_request_result: Option< + oneshot::Receiver>, + >, /// Ordinary Link-packet proof window, installed when the packet is /// locally admitted. Resource transfers use their own progress watchdog. pub timeout: Duration, @@ -349,7 +415,7 @@ struct QueuedDelivery { impl QueuedDelivery { fn new(message: LxMessage, packed_override: Option>, auto_compress: bool) -> Self { - let msg_hash = message.hash; + let msg_hash = Some(message.message_id()); Self { message, packed_override, @@ -384,7 +450,7 @@ impl PendingDelivery { let Some(next) = self.queued.pop_front() else { return false; }; - self.message = next.message; + self.message = next.message.into(); self.packed_override = next.packed_override; self.auto_compress = next.auto_compress; self.transfer = None; @@ -421,7 +487,7 @@ impl BackchannelProofKey { struct PendingBackchannelStart { receiver: ReadyReceipt>, - message: LxMessage, + message: RetainedDeliveryMessage, dest_hash: [u8; 16], link_id: [u8; 16], requested_at: Instant, @@ -462,6 +528,7 @@ struct EarlyBackchannelResourceConclusion { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LinkDeliveryStartError { + InvalidTiming, TransportFull, TransportClosed, } @@ -469,6 +536,7 @@ pub enum LinkDeliveryStartError { impl fmt::Display for LinkDeliveryStartError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::InvalidTiming => f.write_str("invalid link establishment timing"), Self::TransportFull => f.write_str("transport full"), Self::TransportClosed => f.write_str("transport closed"), } @@ -1147,7 +1215,7 @@ impl LinkDeliveryManager { )); results.push(DeliveryResult::Failed { link_id: delivery.link_id, - msg_hash: delivery.message.hash, + msg_hash: Some(delivery.message.message_id()), dest_hash: delivery.dest_hash, message: delivery.message, reason: reason.to_string(), @@ -1324,7 +1392,7 @@ impl LinkDeliveryManager { } }; let auto_compress = message.auto_compress; - let msg_hash = message.hash; + let msg_hash = Some(message.message_id()); let attempts = message.delivery_attempts; let (result_tx, result_rx) = oneshot::channel(); let command = BackchannelSendCommand { @@ -1384,7 +1452,7 @@ impl LinkDeliveryManager { self.pending_backchannel_starts .push(PendingBackchannelStart { receiver: result_rx.into(), - message, + message: message.into(), dest_hash, link_id, requested_at: Instant::now(), @@ -1451,7 +1519,7 @@ impl LinkDeliveryManager { .get_mut(&link_id) .filter(|delivery| delivery.reusable) { - let msg_hash = message.hash; + let msg_hash = Some(message.message_id()); let attempts = message.delivery_attempts; let state = delivery.state; let link_state = delivery.link.state; @@ -1514,7 +1582,7 @@ impl LinkDeliveryManager { } } - let msg_hash = message.hash; + let msg_hash = Some(message.message_id()); let attempts = message.delivery_attempts; let link_id = self.start_delivery_inner( message, @@ -1565,9 +1633,17 @@ impl LinkDeliveryManager { auto_compress, reusable, } = options; - let msg_hash = message.hash; + let msg_hash = Some(message.message_id()); let (mut link, request_data) = Link::new_initiator(dest_hash, hops); - link.extend_establishment_timeout(timing.first_hop_timeout().as_secs_f64()); + if link + .try_extend_establishment_timeout(timing.first_hop_timeout().as_secs_f64()) + .is_err() + { + return Err(LinkDeliveryStartFailure { + error: LinkDeliveryStartError::InvalidTiming, + message: Box::new(message), + }); + } let link_id = link.link_id; let pending_count = self.pending_count(); @@ -1634,10 +1710,14 @@ impl LinkDeliveryManager { app_name: "lxmf.delivery.link".to_string(), delivery_tx: Some(self.event_tx.clone()), }); - outbound_permit.send(TransportMessage::Outbound(OutboundRequest { - raw: Bytes::from(raw), - destination_hash: dest_hash, - })); + let (request_tx, request_rx) = oneshot::channel(); + outbound_permit.send(TransportMessage::SendLinkRequest { + request: OutboundRequest { + raw: Bytes::from(raw), + destination_hash: dest_hash, + }, + result_tx: request_tx, + }); let establishment_timeout = timing.timeout_for_hops(hops); let establishment_timeout_secs = establishment_timeout.as_secs_f64(); @@ -1647,7 +1727,7 @@ impl LinkDeliveryManager { self.pending.insert( link_id, PendingDelivery { - message, + message: message.into(), dest_hash, packed_override, auto_compress, @@ -1658,6 +1738,7 @@ impl LinkDeliveryManager { remaining_segments: None, packet_proof_hash: None, establishment_timeout, + link_request_result: Some(request_rx), timeout: Duration::from_secs_f64(timeout_secs), msg_hash, failure_reason: None, @@ -1695,6 +1776,28 @@ impl LinkDeliveryManager { Ok(link_id) } + fn poll_link_requests(&mut self) { + for delivery in self.pending.values_mut() { + let Some(mut receiver) = delivery.link_request_result.take() else { + continue; + }; + match receiver.try_recv() { + Ok(Ok(())) => {} + Ok(Err(error)) => { + delivery.state = DeliveryState::Failed; + delivery.failure_reason = Some(error.to_string()); + } + Err(oneshot::error::TryRecvError::Closed) => { + delivery.state = DeliveryState::Failed; + delivery.failure_reason = Some("Link request transport unavailable".into()); + } + Err(oneshot::error::TryRecvError::Empty) => { + delivery.link_request_result = Some(receiver) + } + } + } + } + fn poll_packet_dispatches(&mut self) { self.pending_packet_dispatches.retain_mut(|pending| { let Some(delivery) = self.pending.get_mut(&pending.link_id) else { @@ -1946,6 +2049,7 @@ impl LinkDeliveryManager { /// Call before [`Self::tick`] each cycle. Routes `LRPROOF`, `ResourceHmu`, `ResourceReq`, /// and `ResourcePrf` contexts to their handlers. pub fn drain_events(&mut self, known_identities: &HashMap) { + self.poll_link_requests(); self.poll_endpoint_control(); let mut events = Vec::with_capacity(32); if let Some(event) = self.ready_event.take() { @@ -1964,7 +2068,10 @@ impl LinkDeliveryManager { self.handle_link_closed(&link_id, None); } DestinationEvent::InboundPacket { - raw, interface_id, .. + raw, + interface_id, + interface_owner, + .. } => { let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) { Ok(h) => h, @@ -2021,12 +2128,13 @@ impl LinkDeliveryManager { if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes) { - self.handle_link_proof( + self.handle_link_proof_with_owner( &link_id, data, &verify_key, &ed25519_bytes, interface_id, + interface_owner, ); } } else { @@ -2063,12 +2171,13 @@ impl LinkDeliveryManager { if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes) { - self.handle_link_proof( + self.handle_link_proof_with_owner( &link_id, data, &verify_key, &ed25519_bytes, interface_id, + interface_owner, ); } } else { @@ -2166,6 +2275,24 @@ impl LinkDeliveryManager { identity_verify_key: &Ed25519PublicKey, identity_ed25519_pub: &[u8; 32], interface_id: InterfaceId, + ) -> bool { + self.handle_link_proof_with_owner( + link_id, + proof_data, + identity_verify_key, + identity_ed25519_pub, + interface_id, + None, + ) + } + pub fn handle_link_proof_with_owner( + &mut self, + link_id: &[u8; 16], + proof_data: &[u8], + identity_verify_key: &Ed25519PublicKey, + identity_ed25519_pub: &[u8; 32], + interface_id: InterfaceId, + interface_owner: Option, ) -> bool { let Some(delivery) = self.pending.get_mut(link_id) else { return false; @@ -2203,6 +2330,7 @@ impl LinkDeliveryManager { destination_hash: *link_id, }; let binding = LinkEndpointBinding { + interface_owner, link_id: *link_id, interface_id, role: LinkEndpointRole::Initiator, @@ -2270,7 +2398,25 @@ impl LinkDeliveryManager { let Some(delivery) = self.pending.get_mut(link_id) else { return false; }; - if !delivery.reusable || !delivery.link.is_active() { + if !delivery.link.is_active() { + return false; + } + let Ok(plaintext) = delivery.link.decrypt(encrypted_data) else { + return false; + }; + delivery.link.record_inbound(); + delivery.link.record_rx(encrypted_data.len()); + if !delivery.reusable { + let mut input = plaintext.as_slice(); + let rejection = rmpv::decode::read_value(&mut input).ok(); + if input.is_empty() + && matches!(rejection, Some(rmpv::Value::Array(ref a)) if a.len() == 1 && a[0].as_u64() == Some(245)) + { + delivery.message.mark_rejected(); + delivery.state = DeliveryState::Rejected; + delivery.failure_reason = Some("propagation node rejected stamp".to_string()); + return true; + } return false; } @@ -2293,12 +2439,6 @@ impl LinkDeliveryManager { }; let mut proof_raw = proof_header.pack(); proof_raw.extend_from_slice(&proof_data); - delivery.link.record_inbound(); - delivery.link.record_rx(encrypted_data.len()); - let Ok(plaintext) = delivery.link.decrypt(encrypted_data) else { - return false; - }; - if let Err(reason) = stage_link_endpoint_with_success( &self.transport_tx, &mut self.pending_transport, @@ -2744,6 +2884,7 @@ impl LinkDeliveryManager { /// Drive pending deliveries forward; call periodically after [`Self::drain_events`]. pub fn tick(&mut self) -> Vec { + self.poll_link_requests(); let mut results = self.tick_backchannels(); self.poll_endpoint_control(); if let Err(reason) = flush_staged_transport(&self.transport_tx, &mut self.pending_transport) @@ -3349,7 +3490,7 @@ impl LinkDeliveryManager { self.pending_backchannel_deliveries.insert( key, PendingBackchannelDelivery { - message: start.message, + message: start.message.take(), dest_hash: start.dest_hash, link_id: start.link_id, representation, @@ -3506,7 +3647,7 @@ impl LinkDeliveryManager { )); results.push(DeliveryResult::Failed { link_id: delivery.link_id, - msg_hash: delivery.message.hash, + msg_hash: Some(delivery.message.message_id()), dest_hash: delivery.dest_hash, message: delivery.message, reason, @@ -3953,7 +4094,7 @@ impl LinkDeliveryManager { )); Some(DeliveryResult::Rejected { link_id: delivery.link_id, - msg_hash: delivery.message.hash, + msg_hash: Some(delivery.message.message_id()), dest_hash: delivery.dest_hash, message: delivery.message, reason, @@ -3978,7 +4119,7 @@ impl LinkDeliveryManager { )); Some(DeliveryResult::Failed { link_id: delivery.link_id, - msg_hash: delivery.message.hash, + msg_hash: Some(delivery.message.message_id()), dest_hash: delivery.dest_hash, message: delivery.message, reason, @@ -4021,7 +4162,7 @@ impl LinkDeliveryManager { ); Some(DeliveryResult::Complete { link_id: delivery.link_id, - msg_hash: delivery.message.hash, + msg_hash: Some(delivery.message.message_id()), }) } @@ -4243,11 +4384,9 @@ impl LinkDeliveryManager { return results; } - if let Some(pos) = self - .pending_backchannel_starts - .iter() - .position(|start| !start.cancelled && start.message.hash == Some(msg_hash)) - { + if let Some(pos) = self.pending_backchannel_starts.iter().position(|start| { + !start.cancelled && Some(start.message.message_id()) == Some(msg_hash) + }) { let start = self.pending_backchannel_starts.remove(pos); self.remove_backchannel_owner(start.dest_hash, start.link_id); results.push(self.retain_failed_backchannel_start(start, reason.to_string())); @@ -4258,7 +4397,9 @@ impl LinkDeliveryManager { let pending_key = self .pending_backchannel_deliveries .iter() - .find_map(|(key, delivery)| (delivery.message.hash == Some(msg_hash)).then_some(*key)); + .find_map(|(key, delivery)| { + (Some(delivery.message.message_id()) == Some(msg_hash)).then_some(*key) + }); if let Some(key) = pending_key && let Some(delivery) = self.pending_backchannel_deliveries.remove(&key) { @@ -4287,7 +4428,7 @@ impl LinkDeliveryManager { )); results.push(DeliveryResult::Failed { link_id: delivery.link_id, - msg_hash: delivery.message.hash, + msg_hash: Some(delivery.message.message_id()), dest_hash: delivery.dest_hash, message: delivery.message, reason: reason.to_string(), @@ -4374,22 +4515,16 @@ impl LinkDeliveryManager { if let Some(index) = self .pending_backchannel_starts .iter() - .position(|start| start.message.hash == Some(msg_hash)) + .position(|start| Some(start.message.message_id()) == Some(msg_hash)) { let start = &mut self.pending_backchannel_starts[index]; if start.cancelled { return false; } start.cancelled = true; - let mut placeholder = LxMessage::new( - start.dest_hash, - start.message.source_hash, - "", - "", - start.message.method, - ); - placeholder.hash = start.message.hash; - start.message = placeholder; + // The adapter owns any dispatched bytes and its leases. Retain + // only the exact receipt waiter needed to cancel late settlement. + start.message.release(); if start.cancellation_aware { start.receiver.close(); if let Ok(receipt) = start.receiver.try_recv() { @@ -4405,7 +4540,9 @@ impl LinkDeliveryManager { let pending_key = self .pending_backchannel_deliveries .iter() - .find_map(|(key, delivery)| (delivery.message.hash == Some(msg_hash)).then_some(*key)); + .find_map(|(key, delivery)| { + (Some(delivery.message.message_id()) == Some(msg_hash)).then_some(*key) + }); if let Some(key) = pending_key { let delivery = self.pending_backchannel_deliveries.remove(&key).unwrap(); self.cancel_backchannel_packet_key(key, delivery.packet_cancellation); @@ -4562,7 +4699,7 @@ impl LinkDeliveryManager { for start in &self.pending_backchannel_starts { if !start.cancelled && start.closed_reason.is_none() - && start.message.hash == Some(msg_hash) + && Some(start.message.message_id()) == Some(msg_hash) { return Some((start.requested_at, BACKCHANNEL_SEND_COMMAND_TIMEOUT)); } @@ -4570,19 +4707,22 @@ impl LinkDeliveryManager { self.pending_backchannel_deliveries .iter() .find_map(|(key, delivery)| { - (!delivery.link_closed && delivery.message.hash == Some(msg_hash)).then(|| { - let mut wait = delivery.wait.unwrap_or(BackchannelWaitWindow { - started_at: delivery.started_at, - timeout: BACKCHANNEL_DELIVERY_TIMEOUT, - awaiting_admission: false, - }); - if delivery.wait.is_some() && matches!(key, BackchannelProofKey::Resource(..)) { - wait.timeout = wait - .timeout - .saturating_add(BACKCHANNEL_RESOURCE_OBSERVATION_GRACE); - } - (wait.started_at, wait.timeout) - }) + (!delivery.link_closed && Some(delivery.message.message_id()) == Some(msg_hash)) + .then(|| { + let mut wait = delivery.wait.unwrap_or(BackchannelWaitWindow { + started_at: delivery.started_at, + timeout: BACKCHANNEL_DELIVERY_TIMEOUT, + awaiting_admission: false, + }); + if delivery.wait.is_some() + && matches!(key, BackchannelProofKey::Resource(..)) + { + wait.timeout = wait + .timeout + .saturating_add(BACKCHANNEL_RESOURCE_OBSERVATION_GRACE); + } + (wait.started_at, wait.timeout) + }) }) } @@ -4623,7 +4763,7 @@ impl LinkDeliveryManager { } for start in &self.pending_backchannel_starts { - if !start.cancelled && start.message.hash == Some(msg_hash) { + if !start.cancelled && Some(start.message.message_id()) == Some(msg_hash) { return Some(MessageDeliverySnapshot { link_id: start.link_id, dest_hash: start.dest_hash, @@ -4643,7 +4783,7 @@ impl LinkDeliveryManager { } for (key, delivery) in &self.pending_backchannel_deliveries { - if delivery.message.hash == Some(msg_hash) { + if Some(delivery.message.message_id()) == Some(msg_hash) { let link_id = match key { BackchannelProofKey::Packet(link_id, _) | BackchannelProofKey::Resource(link_id, _) => *link_id, @@ -4820,9 +4960,30 @@ fn queued_delivery_event( } } +trait DeliveryObservation { + fn observed_message_id(&self) -> [u8; 32]; + fn observed_attempts(&self) -> u32; +} +impl DeliveryObservation for LxMessage { + fn observed_message_id(&self) -> [u8; 32] { + self.message_id() + } + fn observed_attempts(&self) -> u32 { + self.delivery_attempts + } +} +impl DeliveryObservation for RetainedDeliveryMessage { + fn observed_message_id(&self) -> [u8; 32] { + self.id + } + fn observed_attempts(&self) -> u32 { + self.delivery_attempts + } +} + struct BackchannelDeliveryEventInput<'a> { kind: LxmfDeliveryEventKind, - message: &'a LxMessage, + message: &'a dyn DeliveryObservation, dest_hash: [u8; 16], link_id: [u8; 16], representation: DeliveryRepresentation, @@ -4838,8 +4999,8 @@ fn backchannel_delivery_event(input: BackchannelDeliveryEventInput<'_>) -> LxmfD method: LxmfDeliveryEventMethod::Direct, link_id: input.link_id, dest_hash: input.dest_hash, - msg_hash: input.message.hash, - attempts: input.message.delivery_attempts, + msg_hash: Some(input.message.observed_message_id()), + attempts: input.message.observed_attempts(), progress: input.progress, representation: input.representation, link_state: input.link_state, @@ -4877,18 +5038,11 @@ fn fail_backchannel_start_in_place( link_state: LinkState::Closed, delivery_state: DeliveryState::Failed, })); - let placeholder = LxMessage::new( - start.dest_hash, - start.message.source_hash, - "", - "", - start.message.method, - ); - let message = std::mem::replace(&mut start.message, placeholder); + let message = start.message.take(); start.cancelled = true; DeliveryResult::Failed { link_id: start.link_id, - msg_hash: message.hash, + msg_hash: Some(message.message_id()), dest_hash: start.dest_hash, message, reason, @@ -4979,6 +5133,8 @@ fn finish_reusable_delivery( return; } + delivery.message.release(); + delivery.packed_override = None; delivery.state = DeliveryState::Idle; } @@ -4992,6 +5148,8 @@ fn finish_unsuccessful_reusable_delivery(delivery: &mut PendingDelivery) { return; } + delivery.message.release(); + delivery.packed_override = None; delivery.state = DeliveryState::Idle; } @@ -5047,17 +5205,10 @@ fn push_failed_delivery_and_queue( } /// Move the potentially large attachment-bearing message into its terminal -/// result. Reusable Link sessions retain only a tiny placeholder until the -/// next queued message replaces it, avoiding a full deep clone on failure. +/// result. Reusable Link sessions retain only delivery observations until the +/// next queued message replaces them; no placeholder signed image is created. fn take_current_delivery_message(delivery: &mut PendingDelivery) -> LxMessage { - let placeholder = LxMessage::new( - delivery.dest_hash, - delivery.message.source_hash, - "", - "", - delivery.message.method, - ); - std::mem::replace(&mut delivery.message, placeholder) + delivery.message.take() } fn fail_queued_deliveries( @@ -6094,15 +6245,16 @@ mod tests { let (tx, _rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); let signing_key = Ed25519PrivateKey::generate(); - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Timed", "cancel remains local", crate::constants::DeliveryMethod::Direct, - ); - message.sign(&signing_key).unwrap(); - let message_hash = message.hash.unwrap(); + ) + .unwrap(); + let message = message.sign(&signing_key).unwrap().finalize(None).unwrap(); + let message_hash = message.message_id(); let timing = LinkEstablishmentTiming::from_first_hop_bitrate(3_515); let expected = timing.timeout_for_hops(3); @@ -6127,6 +6279,10 @@ mod tests { while let Ok(message) = rx.try_recv() { match message { TransportMessage::Outbound(request) => return request.raw.to_vec(), + TransportMessage::SendLinkRequest { request, result_tx } => { + let _ = result_tx.send(Ok(())); + return request.raw.to_vec(); + } TransportMessage::SendLinkEndpoint { request, result_tx, .. } => { @@ -6293,6 +6449,7 @@ mod tests { proof_raw.extend_from_slice(&proof_data); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: proof_raw.into(), interface_id: 0, metrics: Default::default(), @@ -6309,15 +6466,19 @@ mod tests { } fn timing_message(label: &str) -> LxMessage { - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], label, "bounded delivery", crate::constants::DeliveryMethod::Direct, - ); - message.sign(&Ed25519PrivateKey::generate()).unwrap(); + ) + .unwrap(); message + .sign(&Ed25519PrivateKey::generate()) + .unwrap() + .finalize(None) + .unwrap() } #[tokio::test] @@ -6353,12 +6514,13 @@ mod tests { driver_tx, ), ); + let interface_owner = actor.interfaces[&7].owner.id(); let dispatch = actor.link_endpoint_dispatch_handle(); let (tx, mut rx) = mpsc::channel(32); let mut mgr = LinkDeliveryManager::new(tx, None, None); mgr.set_link_endpoint_dispatch_handle(dispatch.clone()); let message = timing_message("cancel before exact bind"); - let hash = message.hash.unwrap(); + let hash = message.message_id(); let dest = [0x95; 16]; let link_id = mgr.start_delivery(message, dest, 1).unwrap(); let raw = next_outbound(&mut rx); @@ -6366,7 +6528,14 @@ mod tests { let key = Ed25519PrivateKey::generate(); let (_, proof) = Link::new_responder(&raw[offset..], &key, dest, 1).unwrap(); let public = key.public_key(); - assert!(mgr.handle_link_proof(&link_id, &proof, &public, &public.to_bytes(), 7)); + assert!(mgr.handle_link_proof_with_owner( + &link_id, + &proof, + &public, + &public.to_bytes(), + 7, + Some(interface_owner) + )); assert!(mgr.pending[&link_id].link.is_active()); assert!(mgr.cancel_delivery_by_message_hash(hash)); assert!(mgr.pending_endpoint_binds.is_empty()); @@ -6376,6 +6545,7 @@ mod tests { let receipt = dispatch .try_bind( LinkEndpointBinding { + interface_owner: Some(interface_owner), link_id, interface_id: 7, role: LinkEndpointRole::Initiator, @@ -6429,6 +6599,7 @@ mod tests { actor .path_table .insert(dest, PathEntry::new(None, 1, 7, InterfaceMode::Full)); + let interface_owner = actor.interfaces[&7].owner.id(); let dispatch = actor.link_endpoint_dispatch_handle(); let task = tokio::spawn(actor.run()); let mut mgr = LinkDeliveryManager::new(tx.clone(), None, None); @@ -6438,7 +6609,7 @@ mod tests { timing_message("second"), timing_message("third"), ]; - let hashes = messages.each_ref().map(|message| message.hash.unwrap()); + let hashes = messages.each_ref().map(|message| message.message_id()); let payloads = messages.each_mut().map(|message| message.pack().unwrap()); let [first, second, third] = messages; let link_id = mgr.start_delivery(first, dest, 1).unwrap(); @@ -6457,7 +6628,14 @@ mod tests { if mode != 1 { assert!(mgr.cancel_delivery_by_message_hash(hashes[cancelled_index])); } - assert!(mgr.handle_link_proof(&link_id, &proof, &public, &public.to_bytes(), 7)); + assert!(mgr.handle_link_proof_with_owner( + &link_id, + &proof, + &public, + &public.to_bytes(), + 7, + Some(interface_owner) + )); if mode == 1 { assert!(mgr.cancel_delivery_by_message_hash(hashes[0])); assert!(mgr.pending_endpoint_binds.contains_key(&link_id)); @@ -6540,6 +6718,7 @@ mod tests { actor .path_table .insert(dest, PathEntry::new(None, 1, 7, InterfaceMode::Full)); + let interface_owner = actor.interfaces[&7].owner.id(); let handle = actor.link_endpoint_dispatch_handle(); let actor_task = tokio::spawn(actor.run()); let identity = Ed25519PrivateKey::generate(); @@ -6552,7 +6731,7 @@ mod tests { ); mgr.set_link_endpoint_dispatch_handle(handle); let message = timing_message("exact driver admission"); - let message_hash = message.hash.unwrap(); + let message_hash = message.message_id(); let link_id = if packed { mgr.start_packed_delivery(message, dest, 1, b"packed propagation".to_vec(), false) .unwrap() @@ -6567,7 +6746,14 @@ mod tests { let key = Ed25519PrivateKey::generate(); let (mut responder, proof) = Link::new_responder(&raw[offset..], &key, dest, 1).unwrap(); let public = key.public_key(); - assert!(mgr.handle_link_proof(&link_id, &proof, &public, &public.to_bytes(), 7)); + assert!(mgr.handle_link_proof_with_owner( + &link_id, + &proof, + &public, + &public.to_bytes(), + 7, + Some(interface_owner) + )); tokio::time::timeout(Duration::from_secs(2), async { loop { mgr.poll_endpoint_control(); @@ -6706,7 +6892,7 @@ mod tests { )); mgr.pending.get_mut(&link_id).unwrap().link.rtt = Some(rtt); let fading = timing_message("fade"); - let fading_hash = fading.hash.unwrap(); + let fading_hash = fading.message_id(); assert_eq!(mgr.start_delivery(fading, dest, 1).unwrap(), link_id); assert!(mgr.tick().is_empty()); let TransportMessage::SendLinkEndpoint { result_tx, .. } = rx.try_recv().unwrap() @@ -6731,7 +6917,7 @@ mod tests { assert!(proof_window.0.elapsed() < Duration::from_secs(1)); let queued = timing_message("queued behind fade"); - let queued_hash = queued.hash.unwrap(); + let queued_hash = queued.message_id(); assert_eq!(mgr.start_delivery(queued, dest, 1).unwrap(), link_id); assert!(mgr.message_timeout_window(queued_hash).is_none()); // Even a still-active Link must not hide the missing packet proof. @@ -6785,7 +6971,7 @@ mod tests { let responder_key = Ed25519PrivateKey::generate(); let dest = [0x93; 16]; let first = timing_message("proof beats local acknowledgement"); - let first_hash = first.hash.unwrap(); + let first_hash = first.message_id(); let (link_id, responder) = establish_active_delivery(&mut mgr, &mut rx, first, &responder_key, dest); mgr.tick(); @@ -6807,7 +6993,7 @@ mod tests { )); assert!(mgr.message_timeout_window(first_hash).is_none()); let next = timing_message("next packet"); - let next_hash = next.hash.unwrap(); + let next_hash = next.message_id(); mgr.start_delivery(next, dest, 1).unwrap(); mgr.tick(); let next_window = mgr.message_timeout_window(next_hash).unwrap(); @@ -6833,7 +7019,7 @@ mod tests { let peer_key = Ed25519PrivateKey::generate(); let dest = [0x25; 16]; let first = timing_message("old packet proof owner"); - let first_hash = first.hash.unwrap(); + let first_hash = first.message_id(); let (link_id, peer) = establish_active_delivery(&mut mgr, &mut rx, first, &peer_key, dest); mgr.pending.get_mut(&link_id).unwrap().link.rtt = Some(Duration::from_secs(1)); @@ -6847,7 +7033,7 @@ mod tests { )) .unwrap(); let next = timing_message("new packet proof owner"); - let next_hash = next.hash.unwrap(); + let next_hash = next.message_id(); let next_packed = next.pack().unwrap(); assert_eq!(mgr.start_delivery(next, dest, 1).unwrap(), link_id); if cancel_first { @@ -6912,10 +7098,14 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let peer_key = Ed25519PrivateKey::generate(); let dest = [0x26; 16]; - let mut resource = timing_message("cancel active Resource"); - resource.content = "resource body".repeat(1_000); - resource.sign(&Ed25519PrivateKey::generate()).unwrap(); - let cancelled_hash = resource.hash.unwrap(); + let resource = crate::message::test_message( + [0xAA; 16], + [0xBB; 16], + "cancel active Resource", + &"resource body".repeat(1_000), + crate::constants::DeliveryMethod::Direct, + ); + let cancelled_hash = resource.message_id(); let (link_id, peer) = establish_active_delivery(&mut mgr, &mut rx, resource, &peer_key, dest); mgr.pending.get_mut(&link_id).unwrap().link.rtt = Some(Duration::from_secs(1)); @@ -6941,7 +7131,7 @@ mod tests { timing_message("queued after Resource one"), timing_message("queued after Resource two"), ]; - let hashes = followers.each_ref().map(|message| message.hash.unwrap()); + let hashes = followers.each_ref().map(|message| message.message_id()); let packed = followers.each_mut().map(|message| message.pack().unwrap()); for message in followers { assert_eq!(mgr.start_delivery(message, dest, 1).unwrap(), link_id); @@ -7012,7 +7202,7 @@ mod tests { let new_resource = [0x2A; 32]; mgr.register_backchannel(dest, link_id); let first = timing_message("old same-Link Resource"); - let first_hash = first.hash.unwrap(); + let first_hash = first.message_id(); mgr.start_backchannel_delivery(first, dest).unwrap(); command_rx .try_recv() @@ -7039,7 +7229,7 @@ mod tests { ); } let next = timing_message("new same-Link Resource"); - let next_hash = next.hash.unwrap(); + let next_hash = next.message_id(); mgr.start_backchannel_delivery(next, dest).unwrap(); let next_receipt = command_rx.try_recv().unwrap(); let command_window = mgr.message_timeout_window(next_hash).unwrap(); @@ -7153,7 +7343,7 @@ mod tests { let peer_key = Ed25519PrivateKey::generate(); let dest = [0x2B; 16]; let first = timing_message("historical idle delivery"); - let historical_hash = first.hash.unwrap(); + let historical_hash = first.message_id(); let retry_same_hash = first.clone(); let (link_id, peer) = establish_active_delivery(&mut mgr, &mut rx, first, &peer_key, dest); @@ -7177,6 +7367,8 @@ mod tests { }] if *hash == historical_hash)); } assert_eq!(mgr.pending[&link_id].state, DeliveryState::Idle); + assert_eq!(mgr.pending[&link_id].message.retained_wire_bytes(), 0); + assert!(mgr.pending[&link_id].packed_override.is_none()); assert_eq!(mgr.pending[&link_id].msg_hash, Some(historical_hash)); assert_eq!(mgr.pending_count(), 0); mgr.take_delivery_events(); @@ -7194,7 +7386,7 @@ mod tests { // The same logical hash is not globally blacklisted: a new queued // attempt is a live owner and remains independently cancellable. let next = timing_message("future distinct owner"); - let next_hash = next.hash.unwrap(); + let next_hash = next.message_id(); let next_packed = next.pack().unwrap(); assert_eq!(mgr.start_delivery(next, dest, 1).unwrap(), link_id); assert_eq!( @@ -7243,7 +7435,7 @@ mod tests { let resource_hash = [0x96; 32]; mgr.register_backchannel(dest, link_id); let message = timing_message("slow resource"); - let hash = message.hash.unwrap(); + let hash = message.message_id(); mgr.start_backchannel_delivery(message, dest).unwrap(); let command = cmd_rx.try_recv().unwrap(); let original = Instant::now() - Duration::from_secs(400); @@ -7320,7 +7512,7 @@ mod tests { mgr.register_backchannel(dest, link_id); mgr.set_backchannel_sender(command_tx.clone()); let legacy = timing_message("legacy cancellation policy"); - let legacy_hash = legacy.hash.unwrap(); + let legacy_hash = legacy.message_id(); mgr.start_backchannel_delivery(legacy, dest).unwrap(); let legacy_command = commands.try_recv().unwrap(); mgr.set_cancellation_aware_backchannel_sender(command_tx.clone()); @@ -7338,7 +7530,7 @@ mod tests { .unwrap(); assert!(mgr.tick().is_empty()); let aware = timing_message("cancellation-aware command not yet issued"); - let aware_hash = aware.hash.unwrap(); + let aware_hash = aware.message_id(); mgr.start_backchannel_delivery(aware, dest).unwrap(); let aware_command = commands.try_recv().unwrap(); mgr.set_backchannel_sender(command_tx.clone()); @@ -7349,7 +7541,7 @@ mod tests { ); assert!(mgr.message_delivery_snapshot(aware_hash).is_none()); let already_published = timing_message("published before cancellation close"); - let published_hash = already_published.hash.unwrap(); + let published_hash = already_published.message_id(); mgr.set_cancellation_aware_backchannel_sender(command_tx); mgr.start_backchannel_delivery(already_published, dest) .unwrap(); @@ -7370,7 +7562,7 @@ mod tests { assert!( mgr.pending_backchannel_starts .iter() - .all(|start| start.message.hash != Some(published_hash)) + .all(|start| Some(start.message.message_id()) != Some(published_hash)) ); assert!(mgr.tick().is_empty()); } @@ -7384,15 +7576,34 @@ mod tests { let dest = [0x53; 16]; let old_link = [0x54; 16]; mgr.register_backchannel(dest, old_link); - for _ in 0..256 { - mgr.start_backchannel_delivery(timing_message("bounded receipt reservation"), dest) - .unwrap(); + for index in 0..256 { + let message = if index == 0 { + crate::message::test_message( + [0xAA; 16], + [0xBB; 16], + "bounded receipt reservation", + &"large cancelled payload".repeat(100_000), + crate::constants::DeliveryMethod::Direct, + ) + } else { + timing_message("bounded receipt reservation") + }; + mgr.start_backchannel_delivery(message, dest).unwrap(); } - let cancelled_hash = mgr.pending_backchannel_starts[0].message.hash.unwrap(); - mgr.pending_backchannel_starts[0].message.content = - "large cancelled payload".repeat(100_000); + let cancelled_hash = mgr.pending_backchannel_starts[0].message.message_id(); + assert!( + mgr.pending_backchannel_starts[0] + .message + .retained_wire_bytes() + > 2_000_000 + ); assert!(mgr.cancel_delivery_by_message_hash(cancelled_hash)); - assert!(mgr.pending_backchannel_starts[0].message.content.is_empty()); + assert!( + mgr.pending_backchannel_starts[0] + .message + .retained_wire_bytes() + == 0 + ); for start in &mut mgr.pending_backchannel_starts { start.requested_at = Instant::now() - Duration::from_secs(11); } @@ -7402,7 +7613,7 @@ mod tests { assert!( mgr.pending_backchannel_starts .iter() - .all(|start| start.message.content.is_empty()) + .all(|start| start.message.retained_wire_bytes() == 0) ); let new_link = [0x55; 16]; mgr.register_backchannel(dest, new_link); @@ -7476,7 +7687,7 @@ mod tests { let old_link = [0x32; 16]; let replacement = [0x33; 16]; let message = timing_message("old owner must not evict replacement"); - let hash = message.hash.unwrap(); + let hash = message.message_id(); mgr.register_backchannel(dest, old_link); mgr.start_backchannel_delivery(message, dest).unwrap(); let command = commands.try_recv().unwrap(); @@ -7570,6 +7781,7 @@ mod tests { driver_tx, ), ); + let interface_owner = actor.interfaces[&7].owner.id(); let dispatch = actor.link_endpoint_dispatch_handle(); let actor_task = tokio::spawn(actor.run()); let link_id = [0x59; 16]; @@ -7578,6 +7790,7 @@ mod tests { let token = dispatch .try_bind( LinkEndpointBinding { + interface_owner: Some(interface_owner), link_id, interface_id: 7, role: LinkEndpointRole::Responder, @@ -7597,7 +7810,7 @@ mod tests { } mgr.register_backchannel(dest, link_id); let message = timing_message("cancel exact actor packet"); - let hash = message.hash.unwrap(); + let hash = message.message_id(); mgr.start_backchannel_delivery(message, dest).unwrap(); let command = command_rx.try_recv().unwrap(); let raw = link_data_packet( @@ -7709,7 +7922,7 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let key = Ed25519PrivateKey::generate(); let message = timing_message("legacy queued packet"); - let hash = message.hash.unwrap(); + let hash = message.message_id(); let (link_id, _) = establish_active_delivery(&mut mgr, &mut rx, message, &key, [0x63; 16]); mgr.pending.get_mut(&link_id).unwrap().link.rtt = Some(Duration::from_millis(1)); assert!(mgr.tick().is_empty()); @@ -7743,7 +7956,7 @@ mod tests { let resource_hash = [0x66; 32]; mgr.register_backchannel(dest, link_id); let message = timing_message("queued resource phase renewal"); - let hash = message.hash.unwrap(); + let hash = message.message_id(); mgr.start_backchannel_delivery(message, dest).unwrap(); cmd_rx .try_recv() @@ -7858,15 +8071,16 @@ mod tests { ); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "packet proof", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = Some(msg.message_id()); let report = mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); assert_eq!(report.link_id, link_id); @@ -7930,15 +8144,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "proof raced receipt", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = Some(msg.message_id()); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -7980,14 +8195,15 @@ mod tests { assert!(mgr.early_backchannel_proofs.is_empty()); assert_eq!(mgr.pending_count(), 0); - let mut next = LxMessage::new( + let next = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "next delivery is not blocked", crate::constants::DeliveryMethod::Direct, - ); - next.sign(&sign_key).unwrap(); + ) + .unwrap(); + let next = next.sign(&sign_key).unwrap().finalize(None).unwrap(); mgr.start_backchannel_delivery(next, dest_hash).unwrap(); assert!(cmd_rx.try_recv().is_ok()); } @@ -8005,15 +8221,17 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "proof then close then receipt", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let message_id = msg.message_id(); + let msg_hash = Some(message_id); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -8025,7 +8243,7 @@ mod tests { assert!(!mgr.delivery_link_available(&dest_hash)); assert_eq!(mgr.pending_count(), 1); assert_eq!(mgr.early_backchannel_proofs.len(), 1); - let settling = mgr.message_delivery_snapshot(msg_hash.unwrap()).unwrap(); + let settling = mgr.message_delivery_snapshot(message_id).unwrap(); assert_eq!(settling.link_state, LinkState::Closed); assert_eq!(mgr.stats().pending_backchannel_starts, 1); @@ -8074,15 +8292,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "cancel before resource receipt", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash.unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = msg.message_id(); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -8123,15 +8342,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "cancel before packet receipt", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash.unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = msg.message_id(); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -8167,15 +8387,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "cancel installed resource", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash.unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = msg.message_id(); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); cmd_rx @@ -8217,15 +8438,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "resource rejected", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = Some(msg.message_id()); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); cmd_rx @@ -8291,15 +8513,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "rejection before resource receipt", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = Some(msg.message_id()); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -8386,15 +8609,17 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "rejection then close then receipt", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let message_id = msg.message_id(); + let msg_hash = Some(message_id); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -8410,7 +8635,7 @@ mod tests { assert!(mgr.fail_backchannel_link(link_id, "link closed").is_empty()); assert_eq!(mgr.pending_count(), 1); assert!(!mgr.delivery_link_available(&dest_hash)); - let settling = mgr.message_delivery_snapshot(msg_hash.unwrap()).unwrap(); + let settling = mgr.message_delivery_snapshot(message_id).unwrap(); assert_eq!(settling.link_state, LinkState::Closed); assert_eq!(mgr.stats().pending_backchannel_starts, 1); @@ -8457,15 +8682,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "send failure", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = Some(msg.message_id()); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -8533,15 +8759,16 @@ mod tests { mgr.register_backchannel(dest_hash, link_id); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "closed while awaiting proof", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = Some(msg.message_id()); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); let command = cmd_rx.try_recv().expect("backchannel send command"); @@ -8632,15 +8859,16 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let dest_hash = [0xD3; 16]; let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Direct", "stale reusable delivery", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash.unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = msg.message_id(); let link_id = mgr.start_delivery(msg, dest_hash, 1).unwrap(); if let Some(delivery) = mgr.pending.get_mut(&link_id) { @@ -8682,15 +8910,16 @@ mod tests { let dest_hash = [0xD4; 16]; let link_id = [0xE4; 16]; let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Backchannel", "stale backchannel delivery", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash.unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = msg.message_id(); mgr.register_backchannel(dest_hash, link_id); mgr.start_backchannel_delivery(msg, dest_hash).unwrap(); @@ -8719,7 +8948,7 @@ mod tests { let (tx, mut rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Test Subject", @@ -8768,14 +8997,14 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let dest_hash = [0xCD; 16]; - let first = LxMessage::new( + let first = crate::message::test_message( [0xAA; 16], [0xBB; 16], "First", "first queued message", crate::constants::DeliveryMethod::Direct, ); - let second = LxMessage::new( + let second = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Second", @@ -8803,7 +9032,12 @@ mod tests { TransportMessage::RegisterDestination { .. } )); let request = rx.try_recv().unwrap(); - assert!(matches!(request, TransportMessage::Outbound(_))); + match request { + TransportMessage::SendLinkRequest { result_tx, .. } => { + let _ = result_tx.send(Ok(())); + } + other => panic!("expected Link request admission, got {other:?}"), + } assert!( rx.try_recv().is_err(), "second message must wait on the cached pending link" @@ -8829,7 +9063,7 @@ mod tests { let (tx, _rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); let dest_hash = [0xC1; 16]; - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Propagation", @@ -8858,14 +9092,15 @@ mod tests { let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCE; 16]; - let mut first = LxMessage::new( + let first = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "First", "first direct message", crate::constants::DeliveryMethod::Direct, - ); - first.sign(&sign_key).unwrap(); + ) + .unwrap(); + let first = first.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, first, &responder_key, dest_hash); @@ -8884,14 +9119,15 @@ mod tests { DeliveryState::Idle ); - let mut second = LxMessage::new( + let second = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Second", "second direct message", crate::constants::DeliveryMethod::Direct, - ); - second.sign(&sign_key).unwrap(); + ) + .unwrap(); + let second = second.sign(&sign_key).unwrap().finalize(None).unwrap(); let report = mgr .start_delivery_with_report(second, dest_hash, 1) .unwrap(); @@ -8933,14 +9169,15 @@ mod tests { let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCF; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Identify", "identify after delivery", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, mut responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); @@ -8979,14 +9216,15 @@ mod tests { let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xC7; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Initial", "initial direct message", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); @@ -9005,6 +9243,7 @@ mod tests { let packet_hash = rns_wire::hash::packet_hash(&raw, rns_wire::flags::HeaderType::Header1); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: raw.clone(), interface_id: 0, metrics: Default::default(), @@ -9099,14 +9338,15 @@ mod tests { let responder_key = Ed25519PrivateKey::generate(); let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xE7; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Initial", "establish reusable link", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); assert!(mgr.tick().is_empty()); @@ -9144,6 +9384,7 @@ mod tests { let encrypted_advertisement = responder_link.encrypt(&advertisement).unwrap(); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceAdv, @@ -9173,6 +9414,7 @@ mod tests { if let TransferAction::SendPart(_, part) = action { mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::Resource, @@ -9223,14 +9465,15 @@ mod tests { let responder_key = Ed25519PrivateKey::generate(); let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xE8; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Initial", "establish reusable link", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); assert!(mgr.tick().is_empty()); @@ -9252,6 +9495,7 @@ mod tests { let encrypted = responder_link.encrypt(&advertisement).unwrap(); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceAdv, @@ -9283,14 +9527,15 @@ mod tests { let responder_key = Ed25519PrivateKey::generate(); let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xE9; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Initial", "establish reusable link", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); assert!(mgr.tick().is_empty()); @@ -9312,6 +9557,7 @@ mod tests { let encrypted_advertisement = responder_link.encrypt(&advertisement).unwrap(); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceAdv, @@ -9332,6 +9578,7 @@ mod tests { let encrypted_cancel = responder_link.encrypt(&resource_hash).unwrap(); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceIcl, @@ -9355,14 +9602,15 @@ mod tests { let responder_key = Ed25519PrivateKey::generate(); let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xEA; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Initial", "establish reusable link", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); assert!(mgr.tick().is_empty()); @@ -9383,6 +9631,7 @@ mod tests { }; mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceAdv, @@ -9413,6 +9662,7 @@ mod tests { } mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet(link_id, rns_wire::context::PacketContext::Resource, &part), interface_id: 0, metrics: Default::default(), @@ -9440,14 +9690,15 @@ mod tests { let responder_key = Ed25519PrivateKey::generate(); let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xEB; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Initial", "establish reusable link", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); assert!(mgr.tick().is_empty()); @@ -9486,14 +9737,15 @@ mod tests { let sign_key = Ed25519PrivateKey::generate(); let dest_hash = [0xD7; 16]; - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAC; 16], [0xBC; 16], "Initial", "header2 direct reply", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let (link_id, responder_link) = establish_active_delivery(&mut mgr, &mut rx, msg, &responder_key, dest_hash); @@ -9516,6 +9768,7 @@ mod tests { let packet_hash = rns_wire::hash::packet_hash(&raw, rns_wire::flags::HeaderType::Header2); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: raw.clone(), interface_id: 0, metrics: Default::default(), @@ -9547,7 +9800,7 @@ mod tests { let (tx, mut rx) = mpsc::channel(1); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0; 16], [0; 16], "Full", @@ -9576,7 +9829,7 @@ mod tests { drop(rx); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0; 16], [0; 16], "Closed", @@ -9600,7 +9853,7 @@ mod tests { let (tx, mut rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0; 16], [0; 16], "Timeout", @@ -9620,8 +9873,14 @@ mod tests { ); while let Ok(message) = rx.try_recv() { - if let TransportMessage::SendLinkEndpoint { result_tx, .. } = message { - let _ = result_tx.send(LinkEndpointSendResult::Sent); + match message { + TransportMessage::SendLinkEndpoint { result_tx, .. } => { + let _ = result_tx.send(LinkEndpointSendResult::Sent); + } + TransportMessage::SendLinkRequest { result_tx, .. } => { + let _ = result_tx.send(Ok(())); + } + _ => {} } } @@ -9653,15 +9912,16 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Large Message", &"x".repeat(1000), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - let expected_hash = msg.hash; + ) + .unwrap(); + let msg = msg.sign(&key).unwrap().finalize(None).unwrap(); + let expected_hash = Some(msg.message_id()); let link_id = mgr.start_delivery(msg, [0xCC; 16], 1).unwrap(); let delivery = mgr.pending.get(&link_id).unwrap(); @@ -9674,14 +9934,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Split Direct", &"x".repeat(MAX_EFFICIENT_SIZE + 256), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); assert!(msg.pack().unwrap().len() > MAX_EFFICIENT_SIZE); let responder_key = Ed25519PrivateKey::generate(); @@ -9719,14 +9980,15 @@ mod tests { let (tx, mut rx) = mpsc::channel(2); let mut mgr = LinkDeliveryManager::new(tx.clone(), None, None); let signing_key = Ed25519PrivateKey::generate(); - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( [0xA0; 16], [0xB0; 16], "backpressure", "payload", crate::constants::DeliveryMethod::Direct, - ); - message.sign(&signing_key).unwrap(); + ) + .unwrap(); + let message = message.sign(&signing_key).unwrap().finalize(None).unwrap(); let destination_hash = [0xC0; 16]; let link_id = mgr.start_delivery(message, destination_hash, 1).unwrap(); let request_raw = next_outbound(&mut rx); @@ -9786,14 +10048,15 @@ mod tests { let (tx, mut rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); let signing_key = Ed25519PrivateKey::generate(); - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( [0xA8; 16], [0xB8; 16], "endpoint result", "must fail closed", crate::constants::DeliveryMethod::Direct, - ); - message.sign(&signing_key).unwrap(); + ) + .unwrap(); + let message = message.sign(&signing_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let (link_id, _) = establish_active_delivery(&mut mgr, &mut rx, message, &responder_key, [0xC8; 16]); @@ -9823,14 +10086,15 @@ mod tests { let (inbound_tx, mut inbound_rx) = mpsc::unbounded_channel(); mgr.set_inbound_packet_sender(inbound_tx); let signing_key = Ed25519PrivateKey::generate(); - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( [0xA1; 16], [0xB1; 16], "interface", "gate", crate::constants::DeliveryMethod::Direct, - ); - message.sign(&signing_key).unwrap(); + ) + .unwrap(); + let message = message.sign(&signing_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let (link_id, responder) = establish_active_delivery(&mut mgr, &mut rx, message, &responder_key, [0xC1; 16]); @@ -9844,6 +10108,7 @@ mod tests { let encrypted = responder.encrypt(b"wrong-interface").unwrap(); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet(link_id, rns_wire::context::PacketContext::None, &encrypted), interface_id: 99, metrics: Default::default(), @@ -9866,14 +10131,15 @@ mod tests { let (inbound_tx, mut inbound_rx) = mpsc::unbounded_channel(); mgr.set_inbound_packet_sender(inbound_tx); let signing_key = Ed25519PrivateKey::generate(); - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( [0xA2; 16], [0xB2; 16], "proof", "before plaintext", crate::constants::DeliveryMethod::Direct, - ); - message.sign(&signing_key).unwrap(); + ) + .unwrap(); + let message = message.sign(&signing_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let (link_id, responder) = establish_active_delivery(&mut mgr, &mut rx, message, &responder_key, [0xC2; 16]); @@ -9884,6 +10150,7 @@ mod tests { let encrypted = responder.encrypt(b"must-not-publish").unwrap(); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet(link_id, rns_wire::context::PacketContext::None, &encrypted), interface_id: 0, metrics: Default::default(), @@ -9902,7 +10169,7 @@ mod tests { fn invalid_direct_lrproof_does_not_block_later_valid_interface_binding() { let (tx, mut rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let message = LxMessage::new( + let message = crate::message::test_message( [0xA3; 16], [0xB3; 16], "proof", @@ -9957,7 +10224,7 @@ mod tests { let first = establish_active_delivery( &mut mgr, &mut rx, - LxMessage::new( + crate::message::test_message( [1; 16], [2; 16], "first", @@ -9971,7 +10238,7 @@ mod tests { let second = establish_active_delivery( &mut mgr, &mut rx, - LxMessage::new( + crate::message::test_message( [4; 16], [5; 16], "second", @@ -9986,6 +10253,7 @@ mod tests { mgr.endpoint_lifecycle_tx .send(LinkEndpointLifecycleEvent { binding: LinkEndpointBinding { + interface_owner: None, link_id: first, interface_id: 0, role: LinkEndpointRole::Initiator, @@ -10016,7 +10284,7 @@ mod tests { ] { let (tx, mut rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let mut message = LxMessage::new( + let mut message = crate::message::test_message( [0xA5; 16], [0xB5; 16], "byte progress", @@ -10024,7 +10292,6 @@ mod tests { crate::constants::DeliveryMethod::Direct, ); message.auto_compress = compress; - message.sign(&Ed25519PrivateKey::generate()).unwrap(); let (link_id, _) = establish_active_delivery( &mut mgr, &mut rx, @@ -10087,7 +10354,7 @@ mod tests { for stale in [false, true] { let (tx, mut rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let mut message = LxMessage::new( + let mut message = crate::message::test_message( [0xA4; 16], [0xB4; 16], "resource liveness", @@ -10095,7 +10362,6 @@ mod tests { crate::constants::DeliveryMethod::Direct, ); message.auto_compress = false; - message.sign(&Ed25519PrivateKey::generate()).unwrap(); let (link_id, responder) = establish_active_delivery( &mut mgr, &mut rx, @@ -10130,6 +10396,7 @@ mod tests { for (payload, interface_id) in [(vec![0; encrypted.len()], 0), (encrypted.clone(), 9)] { mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceReq, @@ -10148,6 +10415,7 @@ mod tests { } mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceReq, @@ -10177,14 +10445,15 @@ mod tests { let (tx, mut rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); let signing_key = Ed25519PrivateKey::generate(); - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( [0xA4; 16], [0xB4; 16], "progressive resource", &"x".repeat(4_000), crate::constants::DeliveryMethod::Direct, - ); - message.sign(&signing_key).unwrap(); + ) + .unwrap(); + let message = message.sign(&signing_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let destination_hash = [0xC4; 16]; let (link_id, _responder) = @@ -10215,15 +10484,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); let message = |text: &str| { - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], text, &"x".repeat(600), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - msg + ) + .unwrap(); + msg.sign(&sign_key).unwrap().finalize(None).unwrap() }; let dest = [0xCC; 16]; let responder_key = Ed25519PrivateKey::generate(); @@ -10254,14 +10523,15 @@ mod tests { let (tx, mut rx) = mpsc::channel(512); let mut mgr = LinkDeliveryManager::new(tx, None, None); let key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "first", &"x".repeat(600), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let dest = [0xCC; 16]; let (link, _) = @@ -10302,15 +10572,16 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Snapshot Direct", &"x".repeat(MAX_EFFICIENT_SIZE + 256), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash.unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = msg.message_id(); let responder_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCC; 16]; @@ -10337,15 +10608,16 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Cancel Direct", &"x".repeat(MAX_EFFICIENT_SIZE + 256), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); - let msg_hash = msg.hash.unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); + let msg_hash = msg.message_id(); let responder_key = Ed25519PrivateKey::generate(); let dest_hash = [0xC8; 16]; @@ -10397,14 +10669,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Split Direct", &"y".repeat(MAX_EFFICIENT_SIZE + 128), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCC; 16]; @@ -10473,14 +10746,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Resource Reject", &"z".repeat(1000), crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCC; 16]; @@ -10527,14 +10801,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Remote Close", "close before delivery proof", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCD; 16]; @@ -10548,6 +10823,7 @@ mod tests { .expect("remote active link emits authenticated teardown"); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::LinkClose, @@ -10576,14 +10852,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Bad Close", "ignore invalid close packet", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCE; 16]; @@ -10592,6 +10869,7 @@ mod tests { mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]), interface_id: 0, metrics: Default::default(), @@ -10612,14 +10890,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Small Direct", "fits in one link packet", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let packed = msg.pack().unwrap(); let responder_key = Ed25519PrivateKey::generate(); @@ -10684,6 +10963,7 @@ mod tests { proof_raw.extend_from_slice(&proof_data); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: proof_raw.into(), interface_id: 0, metrics: Default::default(), @@ -10708,14 +10988,15 @@ mod tests { let mut mgr = LinkDeliveryManager::new(tx, None, None); let sign_key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Small Direct", "fits in one link packet", crate::constants::DeliveryMethod::Direct, - ); - msg.sign(&sign_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&sign_key).unwrap().finalize(None).unwrap(); let responder_key = Ed25519PrivateKey::generate(); let dest_hash = [0xCC; 16]; @@ -10730,6 +11011,7 @@ mod tests { .expect("remote active link emits authenticated teardown after proof"); mgr.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::LinkClose, diff --git a/crates/lxmf-core/src/message.rs b/crates/lxmf-core/src/message.rs index 3c1b591..8260a93 100644 --- a/crates/lxmf-core/src/message.rs +++ b/crates/lxmf-core/src/message.rs @@ -1,60 +1,60 @@ -//! LXMF message construction, packing, unpacking, and state machine. +//! Immutable signed LXMF messages and checked outbound construction. //! -//! Python reference: LXMF/LXMessage.py. -//! -//! # Wire formats -//! -//! Direct / link / opportunistic: -//! `[dest_hash:16][src_hash:16][signature:64][msgpack([ts, title, content, fields, ?stamp])]`. -//! Title and content are msgpack `bin` (not `str`) to match Python/C++. -//! -//! Propagation (LXMessage.py:434-441): -//! ```text -//! encrypted_data = destination.encrypt(packed[16..]) -//! lxmf_data = packed[..16] + encrypted_data -//! transient_id = full_hash(lxmf_data) -//! lxmf_data += ?propagation_stamp -//! propagation_packed = msgpack([timestamp, [lxmf_data]]) -//! ``` -//! -//! Signed blob: `dest_hash + src_hash + payload + SHA256(dest_hash + src_hash + payload)` -//! (LXMessage.py:380-383). - -use std::collections::{BTreeMap, BTreeSet}; -use std::io::Write; -use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; - +//! Construct [`LxMessageDraft`], sign it, then finalize its recipient stamp. +//! Received and finalized messages retain one exact immutable wire image. +use crate::constants::*; +use crate::types::PropagationTransientId; +use bytes::Bytes; use rns_crypto::sha::{full_hash, sha256, truncated_hash}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::io::Write; +use std::ops::{Deref, DerefMut, Range}; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; +mod draft; +mod field; +pub use draft::{LxMessageDraft, SignedLxMessage}; +use field::FieldIndex; +pub use field::{ + EncodedFieldValue, FieldId, FieldMapKey, FieldValue, FieldValueRef, Fields, UniqueFieldMap, +}; -use crate::constants::*; -use crate::types::PropagationTransientId; +/// Lossy projection with a single exact-sized allocation. Standard UTF-8 +/// replacement semantics are preserved, but geometric String growth cannot +/// exceed the processing lease's three-output-bytes-per-input-byte allowance. +fn bounded_lossy_text(bytes: &[u8]) -> Cow<'_, str> { + if let Ok(text) = std::str::from_utf8(bytes) { + return Cow::Borrowed(text); + } + let required = bytes + .utf8_chunks() + .map(|chunk| chunk.valid().len() + if chunk.invalid().is_empty() { 0 } else { 3 }) + .sum(); + let mut text = String::with_capacity(required); + for chunk in bytes.utf8_chunks() { + text.push_str(chunk.valid()); + if !chunk.invalid().is_empty() { + text.push('\u{fffd}'); + } + } + debug_assert_eq!(text.len(), required); + Cow::Owned(text) +} -/// Shared handler invoked on per-message state transitions. pub type MessageCallback = Arc; - -/// A native LXMF audio field borrowed from its enclosing message. -/// -/// LXMF represents audio as `[mode, bytes]`, where `mode` is one of the -/// `AM_*` constants and `bytes` is the encoded audio payload. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AudioField<'a> { pub mode: u8, pub bytes: &'a [u8], } - -/// Per-message delivery and failure callbacks. -/// -/// Invoked by [`LxMessage::notify_delivered`] / [`LxMessage::notify_failed`] when the router -/// observes a state transition for a tracked outbound message. #[derive(Clone, Default)] pub struct MessageCallbacks { pub on_delivered: Option, pub on_failed: Option, } - impl std::fmt::Debug for MessageCallbacks { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MessageCallbacks") @@ -63,145 +63,390 @@ impl std::fmt::Debug for MessageCallbacks { .finish() } } - -/// An LXMF message. +/// Mutable delivery observations; none can change a message's authenticated bytes. #[derive(Debug, Clone)] -pub struct LxMessage { - pub destination_hash: [u8; 16], - pub source_hash: [u8; 16], - pub title: String, - pub content: String, - /// Application-level fields keyed by field ID. - pub fields: BTreeMap>, - /// Field IDs whose values are already msgpack-encoded LXMF values. - /// - /// Most custom fields are byte strings and must serialize as msgpack `bin`. - /// Native structured fields such as `FIELD_IMAGE = [format, bytes]` and - /// `FIELD_FILE_ATTACHMENTS = [[name, bytes], ...]` must serialize as their - /// contained msgpack value instead. - pub msgpack_field_ids: BTreeSet, - /// Unix epoch seconds. - pub timestamp: f64, - pub signature: Option<[u8; 64]>, - pub signature_validated: bool, +pub struct MessageMetadata { pub state: MessageState, pub method: DeliveryMethod, - /// Message stamp, if present. - /// - /// LXMF uses 32-byte PoW stamps and 16-byte ticket stamps, so this must stay - /// byte-sized instead of forcing the PoW length. - pub stamp: Option>, - /// Propagation PoW stamp, if present (32 bytes). - pub propagation_stamp: Option<[u8; 32]>, pub ratchet_id: Option<[u8; 32]>, pub delivery_attempts: u32, - /// Unix timestamp of the last delivery attempt; 0.0 means never attempted. pub last_delivery_attempt: f64, - /// Absolute Unix timestamp before which the message must not be re-attempted. - /// Mirrors Python LXMF `LXMessage.next_delivery_attempt`: set to - /// `now + PATH_REQUEST_WAIT` after a path request, `now + DELIVERY_RETRY_WAIT` - /// after a link attempt. 0.0 = no explicit deadline (router falls back to - /// `last_delivery_attempt + DELIVERY_RETRY_WAIT`). pub next_delivery_attempt: f64, - /// SHA-256 of the packed message. - pub hash: Option<[u8; 32]>, - /// Alias for [`hash`](Self::hash) set after packing. - pub message_id: Option<[u8; 32]>, - /// Full hash used by the propagation offer/get protocol. - pub transient_id: Option, - /// Destination-required stamp cost for outbound stamp generation. - pub stamp_cost: Option, - /// Outbound ticket for stamp bypass (16 bytes). - pub outbound_ticket: Option<[u8; 16]>, - /// Ask the router to include a reply ticket before this message is signed. - /// - /// Python reference: `LXMessage.include_ticket`. - pub include_ticket: bool, - /// Computed stamp value: leading zero bits, or `COST_TICKET`. - pub stamp_value: Option, pub unverified_reason: Option, pub representation: DeliveryRepresentation, pub transport_encrypted: bool, - /// Original msgpack payload bytes, stored on inbound messages so signature verification - /// can use the exact bytes that were signed. Avoids re-serialization mismatches for fields - /// with complex types (arrays, maps). - pub wire_payload: Option>, pub transport_encryption: Option, pub incoming: bool, - /// True when the source identity is blackholed at the transport layer. - /// - /// Python sets this during `unpack_from_bytes` via `Reticulum.is_blackholed` - /// (LXMessage.py:172, 803-805); `LXMRouter.lxmf_delivery` then drops such - /// messages before processing (LXMRouter.py:1739-1741). Rust unpacking has - /// no transport access, so embedders set it from the blackhole query - /// surface before processing. pub source_blackholed: bool, - /// Delivery progress in `0.0..=1.0`. pub progress: f64, - /// Whether the direct-delivery resource should be bz2-compressed by the RNS layer. - /// - /// Set optimistically to `true` on outbound construction to mirror Python's - /// `LXMessage.auto_compress`. Gets cleared by - /// [`determine_compression_support`](Self::determine_compression_support) when a peer's - /// announce indicates no `SF_COMPRESSION` capability. pub auto_compress: bool, - /// Optional per-message delivery / failure callbacks. pub callbacks: MessageCallbacks, } - -impl LxMessage { - /// Construct a new outbound message. - pub fn new( - destination_hash: [u8; 16], - source_hash: [u8; 16], - title: &str, - content: &str, - method: DeliveryMethod, - ) -> Self { - let timestamp = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs_f64(); - +impl Default for MessageMetadata { + fn default() -> Self { Self { - destination_hash, - source_hash, - title: title.to_string(), - content: content.to_string(), - fields: BTreeMap::new(), - msgpack_field_ids: BTreeSet::new(), - timestamp, - signature: None, - signature_validated: false, state: MessageState::Generating, - method, - stamp: None, - propagation_stamp: None, + method: DeliveryMethod::Direct, ratchet_id: None, delivery_attempts: 0, - last_delivery_attempt: 0.0, - next_delivery_attempt: 0.0, - hash: None, - message_id: None, - transient_id: None, - stamp_cost: None, - outbound_ticket: None, - include_ticket: false, - stamp_value: None, + last_delivery_attempt: 0., + next_delivery_attempt: 0., unverified_reason: None, representation: DeliveryRepresentation::Unknown, transport_encrypted: false, transport_encryption: None, - wire_payload: None, incoming: false, source_blackholed: false, - progress: 0.0, + progress: 0., auto_compress: true, callbacks: MessageCallbacks::default(), } } - - /// Update [`auto_compress`](Self::auto_compress) based on a peer's cached announce app_data. +} +/// Local parser/construction profile, independent of transport size admission. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MessageDecodeLimits { + pub max_wire_bytes: usize, + pub max_top_level_fields: usize, +} +impl Default for MessageDecodeLimits { + fn default() -> Self { + Self { + max_wire_bytes: 134_217_727, + max_top_level_fields: 4096, + } + } +} +impl MessageDecodeLimits { + fn check_wire(self, length: usize) -> Result<(), MessageError> { + if length > self.max_wire_bytes { + Err(MessageError::TooLarge { + size: length, + limit: self.max_wire_bytes, + }) + } else { + Ok(()) + } + } +} +/// Recipient stamp bytes. Construction does not itself authenticate the stamp. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RecipientStamp { + Ticket([u8; 16]), + ProofOfWork([u8; 32]), +} +impl RecipientStamp { + pub fn as_bytes(&self) -> &[u8] { + match self { + Self::Ticket(b) => b, + Self::ProofOfWork(b) => b, + } + } + pub fn from_bytes(bytes: &[u8]) -> Option { + match bytes.len() { + 16 => Some(Self::Ticket(bytes.try_into().ok()?)), + 32 => Some(Self::ProofOfWork(bytes.try_into().ok()?)), + _ => None, + } + } +} +/// One finalized or received image. All clones share the image and field indexes. +/// +/// Signed content cannot be assigned after finalization: +/// ```compile_fail +/// use lxmf_core::message::LxMessage; +/// fn change(message: &mut LxMessage) { message.message_id = [0; 32]; } +/// ``` +/// Recipient stamps must be supplied before the complete image is frozen: +/// ```compile_fail +/// use lxmf_core::message::{LxMessage, RecipientStamp}; +/// fn change(message: &mut LxMessage) { +/// message.stamp = Some(RecipientStamp::Ticket([0; 16])); +/// } +/// ``` +#[derive(Debug, Clone)] +pub struct LxMessage { + wire: Bytes, + indexes: Arc<[FieldIndex]>, + title: Range, + content: Range, + timestamp: f64, + message_id: [u8; 32], + stamp: Option, + limits: MessageDecodeLimits, + pub metadata: MessageMetadata, +} +impl Deref for LxMessage { + type Target = MessageMetadata; + fn deref(&self) -> &Self::Target { + &self.metadata + } +} +impl DerefMut for LxMessage { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.metadata + } +} +/// Source-bound authentication of an immutable message; cannot be constructed by callers. +/// ```compile_fail +/// use lxmf_core::message::{LxMessage, VerifiedLxMessage}; +/// fn counterfeit(message: &LxMessage) { +/// let _ = VerifiedLxMessage { message, source_public_key: [0; 64] }; +/// } +/// ``` +#[derive(Debug)] +pub struct VerifiedLxMessage<'a> { + message: &'a LxMessage, + source_public_key: [u8; 64], +} +/// Authentication retained across an asynchronous handoff. The frozen message +/// clone shares its original wire image and field index; callers cannot replace +/// either the authenticated bytes or the source key. +#[derive(Debug)] +pub struct OwnedVerifiedLxMessage { + message: LxMessage, + source_public_key: [u8; 64], +} +impl OwnedVerifiedLxMessage { + pub fn as_verified(&self) -> VerifiedLxMessage<'_> { + VerifiedLxMessage { + message: &self.message, + source_public_key: self.source_public_key, + } + } +} +impl<'a> VerifiedLxMessage<'a> { + pub fn message(&self) -> &'a LxMessage { + self.message + } + pub fn source_public_key(&self) -> &[u8; 64] { + &self.source_public_key + } + pub fn to_owned(&self) -> OwnedVerifiedLxMessage { + OwnedVerifiedLxMessage { + message: self.message.clone(), + source_public_key: self.source_public_key, + } + } +} +impl LxMessage { + pub fn destination_hash(&self) -> [u8; 16] { + self.wire[..16].try_into().expect("parsed header") + } + pub fn source_hash(&self) -> [u8; 16] { + self.wire[16..32].try_into().expect("parsed header") + } + pub fn signature(&self) -> [u8; 64] { + self.wire[32..96].try_into().expect("parsed header") + } + pub fn message_id(&self) -> [u8; 32] { + self.message_id + } + pub fn timestamp(&self) -> f64 { + self.timestamp + } + pub fn title_bytes(&self) -> &[u8] { + &self.wire[self.title.clone()] + } + pub fn content_bytes(&self) -> &[u8] { + &self.wire[self.content.clone()] + } + pub fn title_text(&self) -> Cow<'_, str> { + bounded_lossy_text(self.title_bytes()) + } + pub fn content_text(&self) -> Cow<'_, str> { + bounded_lossy_text(self.content_bytes()) + } + pub fn fields(&self) -> Fields<'_> { + Fields { + wire: &self.wire, + indexes: &self.indexes, + } + } + pub fn get_field(&self, id: impl Into) -> Option> { + self.fields().get(id) + } + pub fn recipient_stamp(&self) -> Option<&RecipientStamp> { + self.stamp.as_ref() + } + pub fn wire_bytes(&self) -> &[u8] { + &self.wire + } + /// Shared ownership for asynchronous storage without copying the message. + pub fn wire_owned(&self) -> Bytes { + self.wire.clone() + } + pub fn decode_limits(&self) -> MessageDecodeLimits { + self.limits + } + pub fn packed_len(&self) -> Result { + Ok(self.wire.len()) + } + pub fn pack(&self) -> Result, MessageError> { + Ok(self.wire.to_vec()) + } + pub fn pack_payload(&self) -> Result, MessageError> { + Ok(self.wire[96..].to_vec()) + } + pub fn compute_hash(&self) -> Result<[u8; 32], MessageError> { + Ok(self.message_id) + } + pub fn pack_propagated(&self) -> Result, MessageError> { + self.pack() + } + pub fn unpack_propagated(data: &[u8]) -> Result { + Self::unpack(data) + } + pub fn pack_opportunistic_encrypted(&self, encrypt: F) -> Result, MessageError> + where + F: FnOnce(&[u8]) -> Result, MessageError>, + { + encrypt(&self.wire[16..]) + } + /// Check a detached signature only; this grants no source-identity authority. + pub fn verify_signature(&self, key: &rns_crypto::ed25519::Ed25519PublicKey) -> bool { + let mut signed = Vec::with_capacity(self.wire.len() + 32); + signed.extend_from_slice(&self.wire[..32]); + if let Some(body) = first_four_msgpack_array_body(&self.wire[96..]) { + signed.push(0x94); + signed.extend_from_slice(body); + } else { + signed.extend_from_slice(&self.wire[96..]); + } + signed.extend_from_slice(&self.message_id); + key.verify(&signed, &self.signature()).is_ok() + } + /// Verify both the claimed LXMF source and its signature, without mutation. + pub fn verify( + &self, + source_public_key: &[u8; 64], + ) -> Result, MessageError> { + let identity = rns_identity::identity::Identity::from_public_key(source_public_key) + .map_err(|_| MessageError::InvalidSignature)?; + let expected = rns_identity::destination::Destination::hash_from_name_and_identity( + "lxmf.delivery", + Some(&identity.hash), + ); + if expected != self.source_hash() { + return Err(MessageError::SourceMismatch); + } + let key = rns_crypto::ed25519::Ed25519PublicKey::from_bytes( + source_public_key[32..].try_into().expect("public key half"), + ) + .map_err(|_| MessageError::InvalidSignature)?; + if !self.verify_signature(&key) { + return Err(MessageError::InvalidSignature); + } + Ok(VerifiedLxMessage { + message: self, + source_public_key: *source_public_key, + }) + } + pub fn unpack(data: &[u8]) -> Result { + let limits = MessageDecodeLimits::default(); + limits.check_wire(data.len())?; + Self::unpack_owned(Bytes::copy_from_slice(data), limits) + } + pub fn unpack_owned(wire: Bytes, limits: MessageDecodeLimits) -> Result { + limits.check_wire(wire.len())?; + if wire.len() < 97 { + return Err(MessageError::TooShort(wire.len())); + } + let mut input = &wire[96..]; + let count = read_msgpack_array_len(&mut input)?; + if count < 4 { + return Err(MessageError::UnpackFailed("payload array too short".into())); + } + let timestamp = read_msgpack_float(&mut input)?; + let title = read_text_range(&wire, &mut input)?; + let content = read_text_range(&wire, &mut input)?; + let mut indexes = Vec::new(); + if input.first().is_some_and(|m| msgpack_marker_is_map(*m)) { + let count = read_msgpack_map_len(&mut input)? as usize; + if count > limits.max_top_level_fields { + return Err(MessageError::TooManyFields); + } + if count > input.len() / 2 { + return Err(MessageError::UnpackFailed("impossible field count".into())); + } + count + .checked_mul(std::mem::size_of::()) + .ok_or(MessageError::TooManyFields)?; + indexes + .try_reserve_exact(count) + .map_err(|_| MessageError::TooManyFields)?; + for _ in 0..count { + let id = FieldId::try_from(read_msgpack_integer(&mut input)?)?; + let start = wire.len() - input.len(); + skip_msgpack_value(&mut input, 0)?; + indexes.push(FieldIndex { + id, + range: start..wire.len() - input.len(), + }); + } + indexes.sort_unstable_by_key(|entry| entry.id); + if indexes.windows(2).any(|pair| pair[0].id == pair[1].id) { + return Err(MessageError::DuplicateField); + } + } else { + skip_msgpack_value(&mut input, 0)?; + } + let stamp = if count > 4 { + read_recipient_stamp(&mut input)? + } else { + None + }; + let destination = wire[..16].try_into().expect("header"); + let source = wire[16..32].try_into().expect("header"); + let message_id = Self::message_id_from_payload(&destination, &source, &wire[96..]); + Ok(Self { + wire, + indexes: indexes.into(), + title, + content, + timestamp, + message_id, + stamp, + limits, + metadata: MessageMetadata { + incoming: true, + ..MessageMetadata::default() + }, + }) + } + /// Stamp checking is pure; the returned value is valid only for this request's policy. + pub fn validate_stamp_with_tickets( + &self, + target_cost: u8, + tickets: Option<&[Vec]>, + ) -> bool { + self.validated_stamp_value(target_cost, tickets).is_some() + } + pub fn validated_stamp_value( + &self, + target_cost: u8, + tickets: Option<&[Vec]>, + ) -> Option { + let stamp = self.stamp.as_ref()?.as_bytes(); + if let Some(tickets) = tickets { + for ticket in tickets { + if ticket.len() != TICKET_LENGTH { + continue; + } + let mut material = [0u8; 48]; + material[..16].copy_from_slice(ticket); + material[16..].copy_from_slice(&self.message_id); + if stamp == truncated_hash(&material) { + return Some(COST_TICKET); + } + } + } + let stamp = <&[u8; 32]>::try_from(stamp).ok()?; + let work = crate::stamper::stamp_workblock(&self.message_id, STAMP_WORKBLOCK_EXPAND_ROUNDS); + crate::stamper::stamp_valid(stamp, target_cost, &work) + .then(|| crate::stamper::stamp_value(&work, stamp) as u16) + } + /// Update [`auto_compress`](MessageMetadata::auto_compress) based on a peer's cached announce app_data. /// /// Matches Python `LXMessage.determine_compression_support` — LXMessage.py:510-513. /// Fail-open: no cached app_data and legacy peers without a feature list @@ -247,96 +492,13 @@ impl LxMessage { } } - pub fn set_field(&mut self, field_id: u8, data: Vec) { - self.fields.insert(field_id, data); - self.msgpack_field_ids.remove(&field_id); - } - - /// Set a field value that is already encoded as one complete msgpack value. - /// - /// Use this for native structured LXMF fields. For example, Python/Sideband - /// encode `FIELD_IMAGE` as the value `["webp", image_bytes]`, not as a - /// binary blob containing the bytes of that msgpack array. - pub fn set_msgpack_field(&mut self, field_id: u8, data: Vec) -> Result<(), MessageError> { - let mut cursor = std::io::Cursor::new(&data); - rmpv::decode::read_value(&mut cursor) - .map_err(|e| MessageError::PackFailed(format!("invalid msgpack field: {e}")))?; - if cursor.position() != data.len() as u64 { - return Err(MessageError::PackFailed( - "invalid msgpack field: trailing bytes".to_string(), - )); - } - self.fields.insert(field_id, data); - self.msgpack_field_ids.insert(field_id); - Ok(()) - } - - /// Encode and install the native LXMF image field without first cloning - /// `image_bytes` into an intermediate `rmpv::Value` tree. - /// - /// The wire value remains exactly `[format, image_bytes]`. - pub fn set_image_field( - &mut self, - format: &str, - image_bytes: &[u8], - ) -> Result<(), MessageError> { - let encoded = rmp_serde::to_vec(&ImageFieldRef { - format, - bytes: image_bytes, - }) - .map_err(|error| MessageError::PackFailed(error.to_string()))?; - self.fields.insert(FIELD_IMAGE, encoded); - self.msgpack_field_ids.insert(FIELD_IMAGE); - Ok(()) - } - - /// Encode and install the native LXMF audio field without cloning - /// `audio_bytes` into an intermediate `rmpv::Value` tree. - /// - /// The wire value is exactly `[mode, audio_bytes]`. Audio is independent - /// of [`FIELD_FILE_ATTACHMENTS`]; this method never adds or changes a file - /// attachment field. - pub fn set_audio_field(&mut self, mode: u8, audio_bytes: &[u8]) -> Result<(), MessageError> { - let encoded = rmp_serde::to_vec(&AudioFieldRef { - mode, - bytes: audio_bytes, - }) - .map_err(|error| MessageError::PackFailed(error.to_string()))?; - self.fields.insert(FIELD_AUDIO, encoded); - self.msgpack_field_ids.insert(FIELD_AUDIO); - Ok(()) - } - - /// Encode and install one native LXMF file attachment without first - /// cloning `file_bytes` into an intermediate `rmpv::Value` tree. - /// - /// The wire value remains exactly `[[file_name, file_bytes]]`. - pub fn set_file_attachment_field( - &mut self, - file_name: &str, - file_bytes: &[u8], - ) -> Result<(), MessageError> { - let encoded = rmp_serde::to_vec(&FileAttachmentsFieldRef { - file_name, - bytes: file_bytes, - }) - .map_err(|error| MessageError::PackFailed(error.to_string()))?; - self.fields.insert(FIELD_FILE_ATTACHMENTS, encoded); - self.msgpack_field_ids.insert(FIELD_FILE_ATTACHMENTS); - Ok(()) - } - - pub fn get_field(&self, field_id: u8) -> Option<&Vec> { - self.fields.get(&field_id) - } - /// Decode the first native LXMF file attachment while borrowing its bytes /// from this message. Only the small filename is allocated. pub fn first_file_attachment(&self) -> Result, MessageError> { - let Some(field) = self.fields.get(&FIELD_FILE_ATTACHMENTS) else { + let Some(field) = self.fields().get(FIELD_FILE_ATTACHMENTS) else { return Ok(None); }; - let mut input = field.as_slice(); + let mut input = field.encoded(); if read_msgpack_array_len(&mut input)? == 0 { return Ok(None); } @@ -345,8 +507,7 @@ impl LxMessage { "file attachment entry requires name and data".to_string(), )); } - let file_name = - String::from_utf8_lossy(read_msgpack_string_or_binary(&mut input)?).into_owned(); + let file_name = bounded_lossy_text(read_msgpack_string_or_binary(&mut input)?).into_owned(); let data = read_msgpack_binary(&mut input)?; Ok(Some((file_name, data))) } @@ -354,17 +515,16 @@ impl LxMessage { /// Decode the native LXMF image field while borrowing its image bytes /// from this message. Only the short format string is allocated. pub fn image_attachment(&self) -> Result, MessageError> { - let Some(field) = self.fields.get(&FIELD_IMAGE) else { + let Some(field) = self.fields().get(FIELD_IMAGE) else { return Ok(None); }; - let mut input = field.as_slice(); + let mut input = field.encoded(); if read_msgpack_array_len(&mut input)? < 2 { return Err(MessageError::UnpackFailed( "image field requires format and data".to_string(), )); } - let format = - String::from_utf8_lossy(read_msgpack_string_or_binary(&mut input)?).into_owned(); + let format = bounded_lossy_text(read_msgpack_string_or_binary(&mut input)?).into_owned(); let data = read_msgpack_binary(&mut input)?; Ok(Some((format, data))) } @@ -376,10 +536,10 @@ impl LxMessage { /// reported only by this accessor; it does not invalidate the enclosing /// message or its other fields. pub fn audio_field(&self) -> Result>, MessageError> { - let Some(field) = self.fields.get(&FIELD_AUDIO) else { + let Some(field) = self.fields().get(FIELD_AUDIO) else { return Ok(None); }; - let mut input = field.as_slice(); + let mut input = field.encoded(); let item_count = read_msgpack_array_len(&mut input)?; if item_count != 2 { return Err(MessageError::UnpackFailed( @@ -396,124 +556,6 @@ impl LxMessage { Ok(Some(AudioField { mode, bytes })) } - /// Pack the payload as `msgpack([timestamp, title, content, fields, ?stamp])`. - pub fn pack_payload(&self) -> Result, MessageError> { - self.pack_payload_inner(self.stamp.as_deref()) - } - - /// Pack the payload for signing, always as a 4-element array with `stamp = None`. - /// - /// Python strips the stamp element before verification and re-packs as 4 elements - /// (LXMessage.py:742-745). Matching that here keeps sign/verify bytes stable. - fn pack_payload_for_signing(&self) -> Result, MessageError> { - self.pack_payload_inner(None) - } - - /// Stream the payload directly into one output buffer. Structured LXMF - /// fields are already complete MessagePack values, so writing their bytes - /// verbatim avoids decoding a potentially large attachment into an owned - /// `rmpv::Value` tree merely to encode it again. - fn pack_payload_inner(&self, stamp: Option<&[u8]>) -> Result, MessageError> { - let capacity = self - .title - .len() - .checked_add(self.content.len()) - .and_then(|length| { - self.fields - .values() - .try_fold(length, |total, field| total.checked_add(field.len())) - }) - .and_then(|length| length.checked_add(stamp.map_or(0, <[u8]>::len))) - .and_then(|length| length.checked_add(64)) - .ok_or_else(|| MessageError::PackFailed("packed length overflow".to_string()))?; - let mut output = Vec::with_capacity(capacity); - self.write_payload(&mut output, stamp)?; - Ok(output) - } - - fn packed_payload_len(&self, stamp: Option<&[u8]>) -> Result { - let mut counter = CountingWriter::default(); - self.write_payload(&mut counter, stamp)?; - Ok(counter.bytes) - } - - fn write_payload( - &self, - writer: &mut W, - stamp: Option<&[u8]>, - ) -> Result<(), MessageError> { - fn length(value: usize, what: &str) -> Result { - u32::try_from(value) - .map_err(|_| MessageError::PackFailed(format!("{what} exceeds MessagePack limits"))) - } - - fn packed(error: impl std::fmt::Display) -> MessageError { - MessageError::PackFailed(error.to_string()) - } - - rmp::encode::write_array_len(writer, if stamp.is_some() { 5 } else { 4 }) - .map_err(packed)?; - rmp::encode::write_f64(writer, self.timestamp).map_err(packed)?; - rmp::encode::write_bin_len(writer, length(self.title.len(), "title")?).map_err(packed)?; - writer.write_all(self.title.as_bytes()).map_err(packed)?; - rmp::encode::write_bin_len(writer, length(self.content.len(), "content")?) - .map_err(packed)?; - writer.write_all(self.content.as_bytes()).map_err(packed)?; - rmp::encode::write_map_len(writer, length(self.fields.len(), "field count")?) - .map_err(packed)?; - for (field_id, field) in &self.fields { - rmp::encode::write_uint(writer, u64::from(*field_id)).map_err(packed)?; - if self.msgpack_field_ids.contains(field_id) { - writer.write_all(field).map_err(packed)?; - } else { - rmp::encode::write_bin_len(writer, length(field.len(), "field")?) - .map_err(packed)?; - writer.write_all(field).map_err(packed)?; - } - } - if let Some(stamp) = stamp { - rmp::encode::write_bin_len(writer, length(stamp.len(), "stamp")?).map_err(packed)?; - writer.write_all(stamp).map_err(packed)?; - } - Ok(()) - } - - /// Exact full wire length without allocating the packed message. This is - /// used for application envelope admission before the router constructs - /// the one contiguous signing/Resource buffer. - pub fn packed_len(&self) -> Result { - self.signature.ok_or(MessageError::NotSigned)?; - let payload = self.packed_payload_len(self.stamp.as_deref())?; - (DESTINATION_LENGTH * 2 + SIGNATURE_LENGTH) - .checked_add(payload) - .ok_or_else(|| MessageError::PackFailed("packed length overflow".to_string())) - } - - /// Pack the full message for wire transmission as - /// `dest_hash || src_hash || signature || payload` (Python/C++ Propagated format). - pub fn pack(&self) -> Result, MessageError> { - let sig = self.signature.ok_or(MessageError::NotSigned)?; - let payload_len = self.packed_payload_len(self.stamp.as_deref())?; - let mut packed = - Vec::with_capacity(DESTINATION_LENGTH * 2 + SIGNATURE_LENGTH + payload_len); - packed.extend_from_slice(&self.destination_hash); - packed.extend_from_slice(&self.source_hash); - packed.extend_from_slice(&sig); - self.write_payload(&mut packed, self.stamp.as_deref())?; - Ok(packed) - } - - fn signed_data_for_signing(&self) -> Result<(Vec, [u8; 32]), MessageError> { - let payload_len = self.packed_payload_len(None)?; - let mut signed_data = Vec::with_capacity(DESTINATION_LENGTH * 2 + payload_len + 32); - signed_data.extend_from_slice(&self.destination_hash); - signed_data.extend_from_slice(&self.source_hash); - self.write_payload(&mut signed_data, None)?; - let message_hash = sha256(&signed_data); - signed_data.extend_from_slice(&message_hash); - Ok((signed_data, message_hash)) - } - fn message_id_from_payload( destination_hash: &[u8; 16], source_hash: &[u8; 16], @@ -531,129 +573,6 @@ impl LxMessage { hasher.finalize().into() } - /// Pack a message for propagation delivery. - /// - /// Encrypts everything after the destination hash using `encrypt_fn` (ECIES against the - /// destination identity's public key, matching Python `destination.encrypt()`), then wraps - /// as `msgpack([timestamp, [lxmf_data]])`. Returns `(propagation_packed, transient_id)`. - /// - /// Python reference: LXMessage.py:434-441. - pub fn pack_propagated_encrypted( - &mut self, - encrypt_fn: F, - ) -> Result<(Vec, PropagationTransientId), MessageError> - where - F: FnOnce(&[u8]) -> Result, MessageError>, - { - let (packed, transient_id, _) = self.pack_propagated_encrypted_inner(encrypt_fn, None)?; - Ok((packed, transient_id)) - } - - /// Pack a propagated message and always append a propagation-node stamp. - /// - /// Python always generates a propagation stamp for `PROPAGATED` messages, - /// even when the target cost is zero. A zero-cost stamp is the all-zero - /// 32-byte value, which still gives propagation nodes the expected wire - /// layout for validation and storage. - pub fn pack_propagated_encrypted_with_stamp( - &mut self, - encrypt_fn: F, - target_cost: u8, - ) -> Result<(Vec, PropagationTransientId, u32), MessageError> - where - F: FnOnce(&[u8]) -> Result, MessageError>, - { - self.pack_propagated_encrypted_inner(encrypt_fn, Some(target_cost)) - } - - /// Pack the payload that Reticulum carries for Opportunistic delivery. - /// - /// Python `LXMessage.__as_packet()` encrypts the complete LXMF packet after - /// the leading destination hash because the RNS packet header already - /// carries that destination. Keeping this helper in core prevents callers - /// from reimplementing the destination-prefix stripping differently. - pub fn pack_opportunistic_encrypted(&self, encrypt_fn: F) -> Result, MessageError> - where - F: FnOnce(&[u8]) -> Result, MessageError>, - { - let packed = self.pack()?; - if packed.len() <= DESTINATION_LENGTH { - return Err(MessageError::PackFailed( - "packed LXMF message missing opportunistic payload tail".to_string(), - )); - } - encrypt_fn(&packed[DESTINATION_LENGTH..]) - } - - fn pack_propagated_encrypted_inner( - &mut self, - encrypt_fn: F, - propagation_stamp_cost: Option, - ) -> Result<(Vec, PropagationTransientId, u32), MessageError> - where - F: FnOnce(&[u8]) -> Result, MessageError>, - { - let packed = self.pack()?; - - let encrypted_data = encrypt_fn(&packed[DESTINATION_LENGTH..])?; - - let mut lxmf_data = Vec::with_capacity(DESTINATION_LENGTH + encrypted_data.len()); - lxmf_data.extend_from_slice(&packed[..DESTINATION_LENGTH]); - lxmf_data.extend_from_slice(&encrypted_data); - - // transient_id is computed before the propagation stamp is appended. - let tid = full_hash(&lxmf_data); - self.transient_id = Some(tid); - - let mut stamp_value = 0; - if let Some(target_cost) = propagation_stamp_cost - && self.propagation_stamp.is_none() - { - let (stamp, value) = crate::stamper::generate_stamp( - &tid, - target_cost, - crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, - ) - .ok_or_else(|| { - MessageError::PackFailed("failed to generate propagation stamp".to_string()) - })?; - self.propagation_stamp = Some(stamp); - stamp_value = value; - } - - if let Some(ref prop_stamp) = self.propagation_stamp { - if stamp_value == 0 { - let workblock = crate::stamper::stamp_workblock( - &tid, - crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, - ); - stamp_value = crate::stamper::stamp_value(&workblock, prop_stamp); - } - lxmf_data.extend_from_slice(prop_stamp); - } - - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs_f64(); - let entries: [&[u8]; 1] = [&lxmf_data]; - let wrapper = PropagationWrapperRef { - timestamp: now, - entries: &entries, - }; - let propagation_packed = - rmp_serde::to_vec(&wrapper).map_err(|e| MessageError::PackFailed(e.to_string()))?; - - Ok((propagation_packed, tid, stamp_value)) - } - - /// Backward-compatible propagation pack when no destination identity is available. Produces - /// the same wire format as [`Self::pack`]; prefer [`Self::pack_propagated_encrypted`] when - /// encryption is possible. - pub fn pack_propagated(&self) -> Result, MessageError> { - self.pack() - } - /// Unpack a propagation wrapper `msgpack([timestamp, [lxmf_data, ...]])`, where each entry is /// `dest_hash(16) + encrypted_data + ?propagation_stamp`. The caller must decrypt and then /// call [`Self::unpack`] on the decrypted bytes. @@ -682,34 +601,31 @@ impl LxMessage { data: &[u8], max_transfer_bytes: usize, ) -> Result<(f64, Vec>), MessageError> { - if data.len() > max_transfer_bytes { - return Err(MessageError::UnpackFailed(format!( - "propagation wrapper: {} bytes exceeds transfer limit {}", - data.len(), - max_transfer_bytes - ))); - } - - let (timestamp, entries) = Self::unpack_propagation_wrapper(data)?; - - let max_entries = max_transfer_bytes / Self::MIN_PROPAGATION_ENTRY_SIZE; - if entries.len() > max_entries { - return Err(MessageError::UnpackFailed(format!( - "propagation wrapper: {} entries exceeds maximum {} for transfer limit", - entries.len(), - max_entries - ))); - } - if let Some(undersized) = entries - .iter() - .position(|e| e.len() < Self::MIN_PROPAGATION_ENTRY_SIZE) - { - return Err(MessageError::UnpackFailed(format!( - "propagation wrapper: entry {} below minimum message size", - undersized - ))); - } + let (timestamp, entries) = parse_propagation_wrapper(data, max_transfer_bytes)?; + Ok(( + timestamp, + entries + .into_iter() + .map(std::borrow::Cow::into_owned) + .collect(), + )) + } + /// Bounded propagation parsing that shares canonical binary entries with + /// the received wire image. Legacy arrays of bytes remain accepted, with + /// their length checked before allocating the decoded entry. + pub fn unpack_propagation_wrapper_owned( + data: Bytes, + max_transfer_bytes: usize, + ) -> Result<(f64, Vec), MessageError> { + let (timestamp, entries) = parse_propagation_wrapper(&data, max_transfer_bytes)?; + let entries = entries + .into_iter() + .map(|entry| match entry { + std::borrow::Cow::Borrowed(entry) => data.slice_ref(entry), + std::borrow::Cow::Owned(entry) => Bytes::from(entry), + }) + .collect(); Ok((timestamp, entries)) } @@ -722,356 +638,6 @@ impl LxMessage { full_hash(lxmf_data) } - /// Unpack a wire message: `dest_hash(16) + src_hash(16) + signature(64) + msgpack_payload`. - pub fn unpack(data: &[u8]) -> Result { - let min_size = DESTINATION_LENGTH * 2 + SIGNATURE_LENGTH; - if data.len() < min_size + 1 { - return Err(MessageError::TooShort(data.len())); - } - - let mut dest_hash = [0u8; 16]; - dest_hash.copy_from_slice(&data[..16]); - - let mut src_hash = [0u8; 16]; - src_hash.copy_from_slice(&data[16..32]); - - let mut signature = [0u8; 64]; - signature.copy_from_slice(&data[32..96]); - - let payload_data = &data[96..]; - let payload = Self::unpack_payload_streamed(payload_data)?; - - let hash = Self::message_id_from_payload(&dest_hash, &src_hash, payload_data); - - let mut msg = Self { - destination_hash: dest_hash, - source_hash: src_hash, - title: payload.title, - content: payload.content, - fields: payload.fields, - msgpack_field_ids: payload.msgpack_field_ids, - timestamp: payload.timestamp, - signature: Some(signature), - signature_validated: false, - state: MessageState::Generating, - method: DeliveryMethod::Direct, - stamp: payload.stamp, - propagation_stamp: None, - ratchet_id: None, - delivery_attempts: 0, - last_delivery_attempt: 0.0, - next_delivery_attempt: 0.0, - hash: Some(hash), - message_id: Some(hash), - transient_id: None, - stamp_cost: None, - outbound_ticket: None, - include_ticket: false, - stamp_value: None, - unverified_reason: None, - representation: DeliveryRepresentation::Unknown, - transport_encrypted: false, - transport_encryption: None, - wire_payload: Some(payload_data.to_vec()), - incoming: true, - source_blackholed: false, - progress: 0.0, - auto_compress: true, - callbacks: MessageCallbacks::default(), - }; - - // Default to the message hash for direct messages. Propagation callers - // overwrite via [`compute_propagation_transient_id`]. - msg.transient_id = Some(hash); - - Ok(msg) - } - - /// Parse the payload without constructing an owned `rmpv::Value` tree. - /// Complex field values are copied once from their exact encoded range; - /// large attachment bytes are never duplicated during structural decode. - fn unpack_payload_streamed(payload_data: &[u8]) -> Result { - let mut input = payload_data; - let item_count = read_msgpack_array_len(&mut input)?; - if item_count < 4 { - return Err(MessageError::UnpackFailed(format!( - "payload array too short: {item_count}" - ))); - } - - let timestamp = read_msgpack_float(&mut input)?; - let title = read_msgpack_text_or_empty(&mut input)?; - let content = read_msgpack_text_or_empty(&mut input)?; - - let mut fields = BTreeMap::new(); - let mut msgpack_field_ids = BTreeSet::new(); - if input - .first() - .is_some_and(|marker| msgpack_marker_is_map(*marker)) - { - let field_count = read_msgpack_map_len(&mut input)?; - for _ in 0..field_count { - let key = read_msgpack_integer_u8(&mut input)?; - let value_bytes = if input - .first() - .is_some_and(|marker| matches!(*marker, 0xc4..=0xc6)) - { - read_msgpack_binary(&mut input)?.to_vec() - } else { - let encoded = input; - skip_msgpack_value(&mut input, 0)?; - let consumed = encoded.len() - input.len(); - msgpack_field_ids.insert(key); - encoded[..consumed].to_vec() - }; - fields.insert(key, value_bytes); - } - } else { - skip_msgpack_value(&mut input, 0)?; - } - - let stamp = if item_count > 4 { - match input.first().copied() { - Some(0xc4..=0xc6) => { - let bytes = read_msgpack_binary(&mut input)?; - (bytes.len() == TICKET_LENGTH || bytes.len() == 32).then(|| bytes.to_vec()) - } - Some(0x90..=0x9f | 0xdc | 0xdd) => { - let count = read_msgpack_array_len(&mut input)? as usize; - if count == TICKET_LENGTH || count == 32 { - let mut bytes = Vec::with_capacity(count); - for _ in 0..count { - bytes.push(read_msgpack_integer_u8(&mut input)?); - } - Some(bytes) - } else { - for _ in 0..count { - skip_msgpack_value(&mut input, 0)?; - } - None - } - } - Some(0xc0) => { - take_msgpack(&mut input, 1)?; - None - } - Some(_) => { - skip_msgpack_value(&mut input, 0)?; - None - } - None => { - return Err(MessageError::UnpackFailed( - "missing MessagePack stamp".to_string(), - )); - } - } - } else { - None - }; - - Ok(MessagePayload { - timestamp, - title, - content, - fields, - msgpack_field_ids, - stamp, - }) - } - - /// Alias for [`Self::unpack`]; all formats share the same - /// `dest_hash + src_hash + sig + payload` layout. - pub fn unpack_propagated(data: &[u8]) -> Result { - Self::unpack(data) - } - - pub fn compute_hash(&mut self) -> Result<[u8; 32], MessageError> { - let payload = self.pack_payload_for_signing()?; - let hash = - Self::message_id_from_payload(&self.destination_hash, &self.source_hash, &payload); - self.hash = Some(hash); - self.message_id = Some(hash); - self.transient_id = Some(hash); - Ok(hash) - } - - /// Sign the message with an identity's signing key. - /// - /// Signed blob: `dest_hash + src_hash + payload + SHA256(dest_hash + src_hash + payload)` - /// (Python LXMessage.py:380-383, shared with C++ ratcom/ratdeck). - pub fn sign( - &mut self, - signing_key: &rns_crypto::ed25519::Ed25519PrivateKey, - ) -> Result<(), MessageError> { - let (signed_data, message_hash) = self.signed_data_for_signing()?; - - self.signature = Some(signing_key.sign(&signed_data)); - self.hash = Some(message_hash); - self.message_id = Some(message_hash); - self.transient_id = Some(message_hash); - self.state = MessageState::Outbound; - Ok(()) - } - - /// Sign the message via an external signing function (hardware-identity variant of - /// [`Self::sign`]). The signed blob is the same as [`Self::sign`]; `sign_fn` must return a - /// 64-byte Ed25519 signature. - pub fn sign_with(&mut self, sign_fn: F) -> Result<(), MessageError> - where - F: FnOnce(&[u8]) -> Result<[u8; 64], E>, - E: std::fmt::Display, - { - let (signed_data, message_hash) = self.signed_data_for_signing()?; - - let signature = sign_fn(&signed_data) - .map_err(|e| MessageError::PackFailed(format!("signing failed: {e}")))?; - - self.signature = Some(signature); - self.hash = Some(message_hash); - self.message_id = Some(message_hash); - self.transient_id = Some(message_hash); - self.state = MessageState::Outbound; - Ok(()) - } - - /// Verify the signature against `verify_key`. Signed blob matches [`Self::sign`]. - pub fn verify(&mut self, verify_key: &rns_crypto::ed25519::Ed25519PublicKey) -> bool { - let sig = match self.signature { - Some(s) => s, - None => return false, - }; - - // Build the signed bytes once. Inbound wire payloads are borrowed and - // their fifth stamp element is omitted by slicing the first four - // encoded elements, avoiding an owned MessagePack value tree. - let payload_capacity = self - .wire_payload - .as_ref() - .map_or_else(|| self.packed_payload_len(None).unwrap_or(0), Vec::len); - let mut signed_data = Vec::with_capacity(64 + payload_capacity); - signed_data.extend_from_slice(&self.destination_hash); - signed_data.extend_from_slice(&self.source_hash); - if let Some(wire_payload) = self.wire_payload.as_deref() { - if let Some(body) = first_four_msgpack_array_body(wire_payload) { - signed_data.push(0x94); - signed_data.extend_from_slice(body); - } else { - signed_data.extend_from_slice(wire_payload); - } - } else if self.write_payload(&mut signed_data, None).is_err() { - return false; - } - let message_hash = sha256(&signed_data); - signed_data.extend_from_slice(&message_hash); - - let valid = verify_key.verify(&signed_data, &sig).is_ok(); - self.signature_validated = valid; - if valid { - // Fields now own the canonical values needed by the application; - // the full duplicate wire payload is no longer needed. - self.wire_payload = None; - } - valid - } - - /// Generate or retrieve the PoW stamp for this message. - /// - /// Priority: - /// 1. If an outbound ticket is set, derive a ticket-based stamp - /// `stamp = truncated_hash(ticket || message_id)`. - /// 2. If no [`stamp_cost`](Self::stamp_cost) is set, no stamp is needed. - /// 3. If a stamp is already cached, return it. - /// 4. Otherwise, generate a PoW stamp matching the required cost. - /// - /// Python reference: LXMessage.py:301-332. - pub fn get_stamp(&mut self) -> Option> { - if let (Some(ticket), Some(message_id)) = (self.outbound_ticket, self.message_id) { - let mut material = Vec::with_capacity(TICKET_LENGTH + 32); - material.extend_from_slice(&ticket); - material.extend_from_slice(&message_id); - let hash = truncated_hash(&material).to_vec(); - self.stamp_value = Some(COST_TICKET); - self.stamp = Some(hash.clone()); - return Some(hash); - } - - // 2. No stamp cost required - if self.stamp_cost.is_none() { - self.stamp_value = None; - return None; - } - - // 3. Stamp already generated - if let Some(stamp) = self.stamp.as_ref() { - return Some(stamp.clone()); - } - - // 4. Generate PoW stamp - let cost = self.stamp_cost.unwrap(); - if let Some(message_id) = self.message_id - && let Some((stamp, value)) = - crate::stamper::generate_stamp(&message_id, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS) - { - self.stamp_value = Some(value as u16); - self.stamp = Some(stamp.to_vec()); - return Some(stamp.to_vec()); - } - - None - } - - /// Validate a stamp on this message. - /// - /// Python reference: LXMessage.py:278-299 - /// - /// Priority order: - /// 1. Check against tickets first: `stamp == truncated_hash(ticket + message_id)` - /// 2. If no ticket match, validate as PoW stamp - pub fn validate_stamp_with_tickets( - &mut self, - target_cost: u8, - tickets: Option<&[Vec]>, - ) -> bool { - let message_id = match self.message_id.or(self.hash) { - Some(id) => id, - None => return false, - }; - - // A missing stamp can never match a ticket hash or a PoW workblock, - // so it is always invalid (Python `validate_stamp`: the ticket loop - // compares `self.stamp == hash`, which is False when stamp is None, - // then `if self.stamp == None: return False`). - let stamp = match self.stamp.as_deref() { - Some(s) => s, - None => return false, - }; - - // Ticket-based stamps take precedence over PoW. - if let Some(ticket_list) = tickets { - for ticket in ticket_list { - let mut material = Vec::with_capacity(ticket.len() + 32); - material.extend_from_slice(ticket); - material.extend_from_slice(&message_id); - let expected = truncated_hash(&material); - if stamp == expected.as_ref() { - self.stamp_value = Some(COST_TICKET); - return true; - } - } - } - - let Ok(stamp) = <&[u8; 32]>::try_from(stamp) else { - return false; - }; - let workblock = crate::stamper::stamp_workblock(&message_id, STAMP_WORKBLOCK_EXPAND_ROUNDS); - if crate::stamper::stamp_valid(stamp, target_cost, &workblock) { - self.stamp_value = Some(crate::stamper::stamp_value(&workblock, stamp) as u16); - return true; - } - - false - } - pub fn cancel(&mut self) { if self.state == MessageState::Outbound || self.state == MessageState::Sending { self.state = MessageState::Cancelled; @@ -1122,7 +688,7 @@ impl LxMessage { )); } - let packed = self.pack()?; + let packed = self.wire_bytes(); let encrypted = encrypt_fn(&packed[DESTINATION_LENGTH..])?; let mut paper_packed = Vec::with_capacity(DESTINATION_LENGTH + encrypted.len()); paper_packed.extend_from_slice(&packed[..DESTINATION_LENGTH]); @@ -1199,12 +765,11 @@ impl LxMessage { /// Layout is a msgpack map `{state: u8, lxmf_bytes: bin, transport_encrypted: bool, /// transport_encryption: str?, method: u8}`. pub fn pack_container(&self) -> Result, MessageError> { - let packed = self.pack()?; - let container = MessageContainer { + let container = MessageContainerRef { state: self.state as u8, - lxmf_bytes: packed, + lxmf_bytes: self.wire_bytes(), transport_encrypted: self.transport_encrypted, - transport_encryption: self.transport_encryption.clone(), + transport_encryption: self.transport_encryption.as_deref(), method: self.method as u8, }; rmp_serde::to_vec(&container).map_err(|e| MessageError::PackFailed(e.to_string())) @@ -1212,10 +777,16 @@ impl LxMessage { /// Unpack a message from a container (Python parity: `unpack_from_file` in LXMessage.py). pub fn unpack_container(data: &[u8]) -> Result { + if data.len() > MessageDecodeLimits::default().max_wire_bytes + 65_536 { + return Err(MessageError::UnpackFailed( + "container exceeds size limit".into(), + )); + } let container: MessageContainer = rmp_serde::from_slice(data).map_err(|e| MessageError::UnpackFailed(e.to_string()))?; - let mut msg = Self::unpack(&container.lxmf_bytes)?; + let mut msg = + Self::unpack_owned(container.lxmf_bytes.into(), MessageDecodeLimits::default())?; msg.state = match container.state { 0x00 => MessageState::Generating, @@ -1252,7 +823,7 @@ impl LxMessage { /// message are already exclusive-borrow serialized or hit unique tmp /// files, with the rename as the atomic last-writer-wins step. pub fn write_to_directory(&self, directory_path: &str) -> Result { - let hash = self.hash.ok_or(MessageError::NotSigned)?; + let hash = self.message_id(); let file_name = rns_crypto::hex_encode(&hash); let file_path = format!("{directory_path}/{file_name}"); @@ -1265,12 +836,91 @@ impl LxMessage { /// Read a message from a container file (Python parity: `unpack_from_file`). pub fn read_from_file(file_path: &str) -> Result { - let data = std::fs::read(file_path) + use std::io::Read; + let file = std::fs::File::open(file_path) .map_err(|e| MessageError::UnpackFailed(format!("read failed: {e}")))?; - Self::unpack_container(&data) + let maximum = MessageDecodeLimits::default().max_wire_bytes + 65_536; + let mut data = Vec::new(); + file.take((maximum + 1) as u64) + .read_to_end(&mut data) + .map_err(|e| MessageError::UnpackFailed(format!("read failed: {e}")))?; + let message = Self::unpack_container(&data)?; + if let Some(name) = std::path::Path::new(file_path) + .file_name() + .and_then(|n| n.to_str()) + && name.len() == 64 + && name.bytes().all(|b| b.is_ascii_hexdigit()) + && !name.eq_ignore_ascii_case(&hex::encode(message.message_id())) + { + return Err(MessageError::HistoricalHashMismatch); + } + Ok(message) } } +type ParsedPropagationWrapper<'a> = (f64, Vec>); + +fn parse_propagation_wrapper( + data: &[u8], + max_transfer_bytes: usize, +) -> Result, MessageError> { + let invalid = + |reason: &str| MessageError::UnpackFailed(format!("propagation wrapper: {reason}")); + if data.len() > max_transfer_bytes { + return Err(invalid("wire image exceeds transfer limit")); + } + let mut input = data; + if read_msgpack_array_len(&mut input)? != 2 { + return Err(invalid("expected timestamp and entries")); + } + let timestamp = if matches!(input.first(), Some(0xca | 0xcb)) { + read_msgpack_float(&mut input)? + } else { + read_msgpack_integer(&mut input)? as f64 + }; + let count = usize::try_from(read_msgpack_array_len(&mut input)?) + .map_err(|_| invalid("entry count overflow"))?; + // Each accepted entry must be present in this image and meet the size + // floor. Refuse forged array lengths before reserving the entry index. + let maximum = input.len().min(max_transfer_bytes) / LxMessage::MIN_PROPAGATION_ENTRY_SIZE; + if count > maximum { + return Err(invalid("entry count exceeds possible transfer size")); + } + let mut entries = Vec::new(); + entries + .try_reserve_exact(count) + .map_err(|_| invalid("entry index allocation failed"))?; + for _ in 0..count { + let entry = if matches!(input.first(), Some(0xc4..=0xc6)) { + std::borrow::Cow::Borrowed(read_msgpack_binary(&mut input)?) + } else { + let len = usize::try_from(read_msgpack_array_len(&mut input)?) + .map_err(|_| invalid("entry length overflow"))?; + if len < LxMessage::MIN_PROPAGATION_ENTRY_SIZE || len > input.len() { + return Err(invalid("invalid legacy byte-array length")); + } + let mut decoded = Vec::new(); + decoded + .try_reserve_exact(len) + .map_err(|_| invalid("entry allocation failed"))?; + for _ in 0..len { + decoded.push(read_msgpack_integer_u8_strict(&mut input)?); + } + std::borrow::Cow::Owned(decoded) + }; + if entry.len() < LxMessage::MIN_PROPAGATION_ENTRY_SIZE { + return Err(invalid("entry below minimum message size")); + } + entries.push(entry); + } + // rmp-serde's historical convenience API permits trailing bytes. The + // bounded ingress API requires one complete wrapper, without hidden data. + if !input.is_empty() { + return Err(invalid("trailing wrapper data")); + } + Ok((timestamp, entries)) +} + fn read_msgpack_array_len(input: &mut &[u8]) -> Result { let marker = take_msgpack(input, 1)?[0]; match marker { @@ -1366,17 +1016,6 @@ fn read_msgpack_float(input: &mut &[u8]) -> Result { } } -fn read_msgpack_text_or_empty(input: &mut &[u8]) -> Result { - if input - .first() - .is_some_and(|marker| matches!(*marker, 0xa0..=0xbf | 0xc4..=0xc6 | 0xd9..=0xdb)) - { - return Ok(String::from_utf8_lossy(read_msgpack_string_or_binary(input)?).into_owned()); - } - skip_msgpack_value(input, 0)?; - Ok(String::new()) -} - const fn msgpack_marker_is_map(marker: u8) -> bool { matches!(marker, 0x80..=0x8f | 0xde | 0xdf) } @@ -1396,46 +1035,7 @@ fn read_msgpack_map_len(input: &mut &[u8]) -> Result { } } -fn read_msgpack_integer_u8(input: &mut &[u8]) -> Result { - let marker = take_msgpack(input, 1)?[0]; - let value = match marker { - 0x00..=0x7f => u64::from(marker), - 0xe0..=0xff => i64::from(marker as i8) as u64, - 0xcc => u64::from(take_msgpack(input, 1)?[0]), - 0xcd => u64::from(u16::from_be_bytes( - take_msgpack(input, 2)?.try_into().expect("exact length"), - )), - 0xce => u64::from(u32::from_be_bytes( - take_msgpack(input, 4)?.try_into().expect("exact length"), - )), - 0xcf => u64::from_be_bytes(take_msgpack(input, 8)?.try_into().expect("exact length")), - 0xd0 => i64::from(i8::from_be_bytes( - take_msgpack(input, 1)?.try_into().expect("exact length"), - )) as u64, - 0xd1 => i64::from(i16::from_be_bytes( - take_msgpack(input, 2)?.try_into().expect("exact length"), - )) as u64, - 0xd2 => i64::from(i32::from_be_bytes( - take_msgpack(input, 4)?.try_into().expect("exact length"), - )) as u64, - 0xd3 => { - i64::from_be_bytes(take_msgpack(input, 8)?.try_into().expect("exact length")) as u64 - } - _ => { - return Err(MessageError::UnpackFailed( - "expected MessagePack integer".to_string(), - )); - } - }; - Ok(value as u8) -} - -/// Read any MessagePack integer representation whose value is in `0..=255`. -/// -/// The general payload decoder retains its historical narrowing behaviour in -/// `read_msgpack_integer_u8`; native audio modes need strict range validation -/// so malformed or future wider values cannot alias a known `AM_*` mode. -fn read_msgpack_integer_u8_strict(input: &mut &[u8]) -> Result { +fn read_msgpack_integer(input: &mut &[u8]) -> Result { let marker = take_msgpack(input, 1)?[0]; let value = match marker { 0x00..=0x7f => i128::from(marker), @@ -1464,15 +1064,16 @@ fn read_msgpack_integer_u8_strict(input: &mut &[u8]) -> Result )), _ => { return Err(MessageError::UnpackFailed( - "audio mode is not a MessagePack integer".to_string(), + "expected MessagePack integer".to_string(), )); } }; - u8::try_from(value).map_err(|_| { - MessageError::UnpackFailed("audio mode is outside the range 0..=255".to_string()) - }) + Ok(value) } +fn read_msgpack_integer_u8_strict(input: &mut &[u8]) -> Result { + u8::try_from(read_msgpack_integer(input)?).map_err(|_| MessageError::InvalidByte) +} fn skip_msgpack_value(input: &mut &[u8], depth: usize) -> Result<(), MessageError> { if depth >= 64 { return Err(MessageError::UnpackFailed( @@ -1603,6 +1204,16 @@ fn skip_msgpack_values(input: &mut &[u8], depth: usize, count: u32) -> Result<() Ok(()) } +#[derive(Serialize)] +struct MessageContainerRef<'a> { + state: u8, + #[serde(serialize_with = "serialize_bytes")] + lxmf_bytes: &'a [u8], + transport_encrypted: bool, + transport_encryption: Option<&'a str>, + method: u8, +} + /// Container format for on-disk message storage. Python parity: `packed_container` dict. #[derive(Debug, Clone, Serialize, Deserialize)] struct MessageContainer { @@ -1773,11 +1384,13 @@ impl serde::Serialize for FileAttachmentsFieldRef<'_> { } } +#[cfg(test)] struct PropagationWrapperRef<'a> { timestamp: f64, entries: &'a [&'a [u8]], } +#[cfg(test)] impl serde::Serialize for PropagationWrapperRef<'_> { fn serialize(&self, serializer: S) -> Result { use serde::ser::SerializeTuple; @@ -1788,8 +1401,10 @@ impl serde::Serialize for PropagationWrapperRef<'_> { } } +#[cfg(test)] struct PropagationEntriesRef<'a>(&'a [&'a [u8]]); +#[cfg(test)] impl serde::Serialize for PropagationEntriesRef<'_> { fn serialize(&self, serializer: S) -> Result { use serde::ser::SerializeSeq; @@ -1801,8 +1416,7 @@ impl serde::Serialize for PropagationEntriesRef<'_> { } } -/// Msgpack payload. Title and content serialize as `bin` (not `str`) to match Python's -/// `msgpack.packb(bytes_obj)` and C++'s `mpPackBin()`. +/// Semantic DTO for explicitly constructing payloads, never an archival authority. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MessagePayload { pub timestamp: f64, @@ -1816,10 +1430,8 @@ pub struct MessagePayload { deserialize_with = "deserialize_bin_or_str" )] pub content: String, - #[serde(with = "field_map_serde")] - pub fields: BTreeMap>, - #[serde(skip)] - pub msgpack_field_ids: BTreeSet, + #[serde(with = "field::map_serde")] + pub fields: BTreeMap, #[serde( default, skip_serializing_if = "Option::is_none", @@ -1828,7 +1440,6 @@ pub struct MessagePayload { )] pub stamp: Option>, } - fn serialize_as_bin(s: &String, serializer: S) -> Result { serializer.serialize_bytes(s.as_bytes()) } @@ -1853,79 +1464,27 @@ fn deserialize_bin_or_str<'de, D: serde::Deserializer<'de>>( deserializer.deserialize_any(BinOrStrVisitor) } -/// Custom serde for `BTreeMap>` so field values serialize as msgpack `bin` rather -/// than arrays of ints, matching Python's `msgpack.packb(bytes_obj)`. -mod field_map_serde { - use super::*; - use serde::de::{self, MapAccess, Visitor}; - use serde::ser::SerializeMap; - use serde::{Deserializer, Serializer}; - use std::fmt; - - struct BytesWrapper<'a>(&'a [u8]); - - impl serde::Serialize for BytesWrapper<'_> { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_bytes(self.0) - } - } - - pub fn serialize(map: &BTreeMap>, serializer: S) -> Result - where - S: Serializer, - { - let mut m = serializer.serialize_map(Some(map.len()))?; - for (k, v) in map { - m.serialize_entry(k, &BytesWrapper(v))?; - } - m.end() - } - - pub fn deserialize<'de, D>(deserializer: D) -> Result>, D::Error> - where - D: Deserializer<'de>, - { - struct FieldMapVisitor; - - impl<'de> Visitor<'de> for FieldMapVisitor { - type Value = BTreeMap>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a map with u8 keys and byte values") - } - - fn visit_map(self, mut access: M) -> Result - where - M: MapAccess<'de>, - { - const MAX_FIELD_SIZE: usize = 256 * 1024; // 256 KiB per field - const MAX_TOTAL_FIELDS_SIZE: usize = 1024 * 1024; // 1 MiB total - - let mut map = BTreeMap::new(); - let mut total_size = 0usize; - while let Some((key, value)) = access - .next_entry::>() - .map_err(de::Error::custom)? - { - if value.len() > MAX_FIELD_SIZE { - return Err(de::Error::custom("field exceeds maximum size")); - } - total_size += value.len(); - if total_size > MAX_TOTAL_FIELDS_SIZE { - return Err(de::Error::custom("total fields size exceeds maximum")); - } - map.insert(key, value); - } - Ok(map) - } - } - - deserializer.deserialize_map(FieldMapVisitor) - } -} - #[derive(Debug, thiserror::Error)] pub enum MessageError { + #[error("stored message hash differs from its historical filename; original retained")] + HistoricalHashMismatch, + #[error("reply ticket has not been durably committed")] + TicketNotCommitted, + #[error("message exceeds local profile: {size} > {limit}")] + TooLarge { size: usize, limit: usize }, + #[error("too many LXMF fields")] + TooManyFields, + #[error("field ID outside MessagePack integer domain")] + InvalidFieldId, + #[error("duplicate LXMF field ID")] + DuplicateField, + #[error("integer outside byte range")] + InvalidByte, + #[error("invalid message signature")] + InvalidSignature, + #[error("public key does not bind claimed source")] + SourceMismatch, + #[error("message too short: {0} bytes")] TooShort(usize), #[error("pack failed: {0}")] @@ -1938,1253 +1497,71 @@ pub enum MessageError { InvalidUri(String), } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_new_message() { - let msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Hello", - "World", - DeliveryMethod::Direct, - ); - assert_eq!(msg.state, MessageState::Generating); - assert_eq!(msg.method, DeliveryMethod::Direct); - assert!(msg.timestamp > 0.0); - assert!(msg.signature.is_none()); - assert!(!msg.signature_validated); - // Mirror Python LXMessage.py:145 default. - assert!(msg.auto_compress); - } - - #[test] - fn test_register_delivery_callback() { - use std::sync::Arc; - use std::sync::atomic::{AtomicBool, Ordering}; - - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); - let delivered = Arc::new(AtomicBool::new(false)); - let delivered_clone = delivered.clone(); - msg.register_delivery_callback(move |_m| { - delivered_clone.store(true, Ordering::Relaxed); - }); - - msg.mark_delivered(); - assert_eq!(msg.state, MessageState::Delivered); - assert!(delivered.load(Ordering::Relaxed)); - } - - #[test] - fn test_register_failed_callback() { - use std::sync::Arc; - use std::sync::atomic::{AtomicBool, Ordering}; - - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); - let failed = Arc::new(AtomicBool::new(false)); - let failed_clone = failed.clone(); - msg.register_failed_callback(move |_m| { - failed_clone.store(true, Ordering::Relaxed); - }); - - msg.mark_failed(); - assert_eq!(msg.state, MessageState::Failed); - assert!(failed.load(Ordering::Relaxed)); - } - - #[test] - fn test_determine_compression_support() { - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); - - let supported = { - use rmpv::Value; - let arr = Value::Array(vec![ - Value::Binary(b"Peer".to_vec()), - Value::from(8u64), - Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]), - ]); - crate::encode_value(&arr) - }; - msg.determine_compression_support(Some(&supported)); - assert!(msg.auto_compress); - - // Explicit feature list omitting SF_COMPRESSION disables compression. - let no_compression = { - use rmpv::Value; - let arr = Value::Array(vec![ - Value::Binary(b"Peer".to_vec()), - Value::from(8u64), - Value::Array(vec![]), - ]); - crate::encode_value(&arr) - }; - msg.determine_compression_support(Some(&no_compression)); - assert!(!msg.auto_compress); - - // Legacy <=0.9.8 2-element announce has no feature list — fail-open - // (Python compression_support_from_app_data returns True, LXMF.py:160). - let python_098 = { - use rmpv::Value; - let arr = Value::Array(vec![Value::Binary(b"Peer".to_vec()), Value::from(8u64)]); - crate::encode_value(&arr) - }; - msg.determine_compression_support(Some(&python_098)); - assert!(msg.auto_compress); - - // No peer data at all — defaults to compression on (LXMessage.py:513). - msg.auto_compress = false; - msg.determine_compression_support(None); - assert!(msg.auto_compress); - } - - #[test] - fn test_source_blackholed_defaults_false() { - // LXMessage.py:172 — source_blackholed initialises false; embedders - // flip it from the transport blackhole tables after unpacking. - let msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); - assert!(!msg.source_blackholed); - - let mut outbound = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Title", - "Content", - DeliveryMethod::Direct, - ); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - outbound.sign(&key).unwrap(); - let packed = outbound.pack().unwrap(); - let unpacked = LxMessage::unpack(&packed).unwrap(); - assert!(!unpacked.source_blackholed); - } - - #[test] - fn test_pack_payload() { - let msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Test", - "Content", - DeliveryMethod::Direct, - ); - let payload = msg.pack_payload().unwrap(); - assert!(!payload.is_empty()); - } - - #[test] - fn test_streamed_payload_byte_identical_to_owned() { - // The direct writer must produce the same bytes as the serde model for - // every ordinary-field stamp variant the protocol emits. - let mut fields = BTreeMap::new(); - fields.insert(FIELD_IMAGE, b"\x00\x01\x02\x03".to_vec()); - fields.insert(FIELD_AUDIO, b"audio-bytes".to_vec()); - - let cases = [None, Some(vec![0xAB; 32]), Some(vec![0xCD; TICKET_LENGTH])]; - for stamp in cases.iter() { - let owned = MessagePayload { - timestamp: 1700000000.0, - title: "title".to_string(), - content: "content body \u{1F600}".to_string(), - fields: fields.clone(), - msgpack_field_ids: BTreeSet::new(), - stamp: stamp.clone(), - }; - let owned_bytes = rmp_serde::to_vec(&owned).unwrap(); - let mut message = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "title", - "content body \u{1F600}", - DeliveryMethod::Direct, - ); - message.timestamp = 1700000000.0; - message.fields = fields.clone(); - message.stamp = stamp.clone(); - let streamed_bytes = message.pack_payload().unwrap(); - assert_eq!( - owned_bytes, - streamed_bytes, - "streamed serializer drifted for stamp={:?}", - stamp.is_some() - ); - } - } - - #[test] - fn test_sign_and_verify() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let pub_key = key.public_key(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Signed Message", - "Content here", - DeliveryMethod::Direct, - ); - - msg.sign(&key).unwrap(); - assert!(msg.signature.is_some()); - assert_eq!(msg.state, MessageState::Outbound); - - assert!(msg.verify(&pub_key)); - assert!(msg.signature_validated); - } - - #[test] - fn test_sign_verify_wrong_key() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let wrong_key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let wrong_pub = wrong_key.public_key(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Test", - "Content", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - assert!(!msg.verify(&wrong_pub)); - } - - #[test] - fn test_pack_unpack_roundtrip() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Round Trip", - "Full content test", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - - let packed = msg.pack().unwrap(); - assert!(packed.len() > 96); - let unpacked = LxMessage::unpack(&packed).unwrap(); - - assert_eq!(unpacked.destination_hash, msg.destination_hash); - assert_eq!(unpacked.source_hash, msg.source_hash); - assert_eq!(unpacked.title, msg.title); - assert_eq!(unpacked.content, msg.content); - assert_eq!(unpacked.signature, msg.signature); - assert!(unpacked.hash.is_some()); - assert!(unpacked.transient_id.is_some()); - } - - #[test] - fn test_pack_propagated_unpack_roundtrip() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Propagated Round Trip", - "Full content test", - DeliveryMethod::Propagated, - ); - msg.sign(&key).unwrap(); - - let packed = msg.pack_propagated().unwrap(); - let unpacked = LxMessage::unpack_propagated(&packed).unwrap(); - - assert_eq!(unpacked.destination_hash, [0xAA; 16]); - assert_eq!(unpacked.source_hash, [0xBB; 16]); - assert_eq!(unpacked.title, msg.title); - assert_eq!(unpacked.content, msg.content); - } - - #[test] - fn test_fields() { - let mut msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - msg.set_field(FIELD_IMAGE, vec![1, 2, 3]); - assert_eq!(msg.get_field(FIELD_IMAGE), Some(&vec![1, 2, 3])); - assert_eq!(msg.get_field(FIELD_AUDIO), None); - } - - #[test] - fn test_msgpack_field_serializes_as_native_value() { - use std::io::Cursor; - - let image_value = rmpv::Value::Array(vec![ - rmpv::Value::String("png".into()), - rmpv::Value::Binary(vec![0x89, b'P', b'N', b'G']), - ]); - let mut image_bytes = Vec::new(); - rmpv::encode::write_value(&mut image_bytes, &image_value).unwrap(); - - let mut msg = LxMessage::new( - [0x11; 16], - [0x22; 16], - "Image", - "Has image", - DeliveryMethod::Direct, - ); - msg.set_msgpack_field(FIELD_IMAGE, image_bytes.clone()) - .unwrap(); - - let payload = msg.pack_payload().unwrap(); - let value = rmpv::decode::read_value(&mut Cursor::new(&payload)).unwrap(); - let arr = value.as_array().unwrap(); - let fields = arr[3].as_map().unwrap(); - let (_, field_value) = fields - .iter() - .find(|(k, _)| k.as_u64() == Some(FIELD_IMAGE as u64)) - .expect("FIELD_IMAGE present"); - assert!( - field_value.as_array().is_some(), - "FIELD_IMAGE must be an LXMF array value, not a bin-wrapped msgpack blob" - ); - - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - msg.sign(&key).unwrap(); - let packed = msg.pack().unwrap(); - let unpacked = LxMessage::unpack(&packed).unwrap(); - assert_eq!(unpacked.get_field(FIELD_IMAGE), Some(&image_bytes)); - assert!(unpacked.msgpack_field_ids.contains(&FIELD_IMAGE)); - } - - #[test] - fn test_file_attachment_field_serializes_as_native_lxmf_shape() { - use std::io::Cursor; - - let attachment_value = rmpv::Value::Array(vec![rmpv::Value::Array(vec![ - rmpv::Value::String("note.txt".into()), - rmpv::Value::Binary(b"hello".to_vec()), - ])]); - let mut attachment_bytes = Vec::new(); - rmpv::encode::write_value(&mut attachment_bytes, &attachment_value).unwrap(); - - let mut msg = LxMessage::new( - [0x11; 16], - [0x22; 16], - "File", - "Has file", - DeliveryMethod::Direct, - ); - msg.set_msgpack_field(FIELD_FILE_ATTACHMENTS, attachment_bytes.clone()) - .unwrap(); - - let payload = msg.pack_payload().unwrap(); - let value = rmpv::decode::read_value(&mut Cursor::new(&payload)).unwrap(); - let arr = value.as_array().unwrap(); - let fields = arr[3].as_map().unwrap(); - let (_, field_value) = fields - .iter() - .find(|(k, _)| k.as_u64() == Some(FIELD_FILE_ATTACHMENTS as u64)) - .expect("FIELD_FILE_ATTACHMENTS present"); - let attachment = field_value.as_array().unwrap()[0].as_array().unwrap(); - assert_eq!(attachment[0].as_str(), Some("note.txt")); - assert_eq!(attachment[1].as_slice(), Some(&b"hello"[..])); - - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - msg.sign(&key).unwrap(); - let packed = msg.pack().unwrap(); - let unpacked = LxMessage::unpack(&packed).unwrap(); - assert_eq!( - unpacked.get_field(FIELD_FILE_ATTACHMENTS), - Some(&attachment_bytes) - ); - assert!(unpacked.msgpack_field_ids.contains(&FIELD_FILE_ATTACHMENTS)); - } - - #[test] - fn typed_image_field_matches_existing_msgpack_wire_value() { - let image_bytes = [0x89, b'P', b'N', b'G']; - let expected_value = rmpv::Value::Array(vec![ - rmpv::Value::String("png".into()), - rmpv::Value::Binary(image_bytes.to_vec()), - ]); - let mut expected = Vec::new(); - rmpv::encode::write_value(&mut expected, &expected_value).unwrap(); - - let mut msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - msg.set_image_field("png", &image_bytes).unwrap(); - - assert_eq!(msg.get_field(FIELD_IMAGE), Some(&expected)); - assert!(msg.msgpack_field_ids.contains(&FIELD_IMAGE)); - } - - #[test] - fn typed_audio_field_has_exact_native_wire_value_and_borrows_bytes() { - let audio_bytes = [0x4f, 0x67, 0x67, 0x53]; - let expected = vec![ - 0x92, - AM_OPUS_OGG, - 0xc4, - audio_bytes.len() as u8, - audio_bytes[0], - audio_bytes[1], - audio_bytes[2], - audio_bytes[3], - ]; - - let mut msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - msg.set_audio_field(AM_OPUS_OGG, &audio_bytes).unwrap(); - - assert_eq!(msg.get_field(FIELD_AUDIO), Some(&expected)); - assert!(msg.msgpack_field_ids.contains(&FIELD_AUDIO)); - assert!(!msg.fields.contains_key(&FIELD_FILE_ATTACHMENTS)); - - let encoded = msg.get_field(FIELD_AUDIO).unwrap(); - let encoded_start = encoded.as_ptr() as usize; - let encoded_end = encoded_start + encoded.len(); - let audio = msg.audio_field().unwrap().unwrap(); - assert_eq!(audio.mode, AM_OPUS_OGG); - assert_eq!(audio.bytes, audio_bytes); - assert!((encoded_start..encoded_end).contains(&(audio.bytes.as_ptr() as usize))); - } - - #[test] - fn typed_audio_field_survives_signed_pack_and_unpack() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let audio_bytes = b"OggS\0typed-audio"; - let mut outbound = LxMessage::new( - [0x11; 16], - [0x22; 16], - "", - "Voice message", - DeliveryMethod::Direct, - ); - outbound.set_audio_field(AM_OPUS_OGG, audio_bytes).unwrap(); - outbound.sign(&key).unwrap(); - - let packed = outbound.pack().unwrap(); - let inbound = LxMessage::unpack(&packed).unwrap(); - let audio = inbound.audio_field().unwrap().unwrap(); - assert_eq!(audio.mode, AM_OPUS_OGG); - assert_eq!(audio.bytes, audio_bytes); - assert_eq!(inbound.content, "Voice message"); - assert!(inbound.msgpack_field_ids.contains(&FIELD_AUDIO)); - assert!(!inbound.fields.contains_key(&FIELD_FILE_ATTACHMENTS)); - assert_eq!(inbound.hash, outbound.hash); - } - - #[test] - fn audio_field_strictly_validates_shape_mode_and_binary_data() { - let malformed = [ - ("not an array", vec![0xc0]), - ("too few elements", vec![0x91, AM_OPUS_OGG]), - ( - "too many elements", - vec![0x93, AM_OPUS_OGG, 0xc4, 0x00, 0xc0], - ), - ("negative mode", vec![0x92, 0xff, 0xc4, 0x00]), - ("mode above u8", vec![0x92, 0xcd, 0x01, 0x00, 0xc4, 0x00]), - ("mode is not integer", vec![0x92, 0xc0, 0xc4, 0x00]), - ("data is not binary", vec![0x92, AM_OPUS_OGG, 0xa0]), - ("truncated data", vec![0x92, AM_OPUS_OGG, 0xc4]), - ("trailing bytes", vec![0x92, AM_OPUS_OGG, 0xc4, 0x00, 0xc0]), - ]; - - for (case, encoded) in malformed { - let mut msg = LxMessage::new( - [0; 16], - [0; 16], - "", - "message remains usable", - DeliveryMethod::Direct, - ); - msg.fields.insert(FIELD_AUDIO, encoded); - assert!(msg.audio_field().is_err(), "accepted {case}"); - assert_eq!(msg.content, "message remains usable", "changed {case}"); - } - - // Any integer encoding is accepted when its value is in range; audio - // modes are value-constrained, not encoding-canonicalized. - let mut msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - msg.fields - .insert(FIELD_AUDIO, vec![0x92, 0xcd, 0x00, 0xff, 0xc4, 0x00]); - assert_eq!( - msg.audio_field().unwrap(), - Some(AudioField { - mode: u8::MAX, - bytes: &[] - }) - ); - } - - #[test] - fn malformed_audio_field_does_not_invalidate_enclosing_wire_message() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let malformed = vec![0x93, AM_OPUS_OGG, 0xc4, 0x00, 0xc0]; - let mut outbound = LxMessage::new( - [0x11; 16], - [0x22; 16], - "", - "still delivered", - DeliveryMethod::Direct, - ); - outbound - .set_msgpack_field(FIELD_AUDIO, malformed.clone()) - .unwrap(); - outbound.sign(&key).unwrap(); - - let packed = outbound.pack().unwrap(); - let mut inbound = LxMessage::unpack(&packed).unwrap(); - assert_eq!(inbound.content, "still delivered"); - assert_eq!(inbound.get_field(FIELD_AUDIO), Some(&malformed)); - assert!(inbound.audio_field().is_err()); - assert!(inbound.verify(&key.public_key())); - } - - #[test] - fn typed_file_attachment_matches_existing_msgpack_wire_value() { - let file_bytes = b"hello"; - let expected_value = rmpv::Value::Array(vec![rmpv::Value::Array(vec![ - rmpv::Value::String("note.txt".into()), - rmpv::Value::Binary(file_bytes.to_vec()), - ])]); - let mut expected = Vec::new(); - rmpv::encode::write_value(&mut expected, &expected_value).unwrap(); - - let mut msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - msg.set_file_attachment_field("note.txt", file_bytes) - .unwrap(); - - assert_eq!(msg.get_field(FIELD_FILE_ATTACHMENTS), Some(&expected)); - assert!(msg.msgpack_field_ids.contains(&FIELD_FILE_ATTACHMENTS)); - } - - #[test] - fn native_attachment_decoders_borrow_large_payload_bytes() { - let file_bytes = vec![0x5a; 2 * 1024 * 1024]; - let mut msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - msg.set_file_attachment_field("large.bin", &file_bytes) - .unwrap(); - let encoded = msg.get_field(FIELD_FILE_ATTACHMENTS).unwrap(); - let encoded_start = encoded.as_ptr() as usize; - let encoded_end = encoded_start + encoded.len(); - let (name, borrowed) = msg.first_file_attachment().unwrap().unwrap(); - assert_eq!(name, "large.bin"); - assert_eq!(borrowed, file_bytes); - assert!((encoded_start..encoded_end).contains(&(borrowed.as_ptr() as usize))); - - msg.set_image_field("webp", &file_bytes).unwrap(); - let encoded = msg.get_field(FIELD_IMAGE).unwrap(); - let encoded_start = encoded.as_ptr() as usize; - let encoded_end = encoded_start + encoded.len(); - let (format, borrowed) = msg.image_attachment().unwrap().unwrap(); - assert_eq!(format, "webp"); - assert_eq!(borrowed, file_bytes); - assert!((encoded_start..encoded_end).contains(&(borrowed.as_ptr() as usize))); - } - - #[test] - fn verified_inbound_attachment_releases_duplicate_wire_payload() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut outbound = LxMessage::new( - [0x11; 16], - [0x22; 16], - "", - "large inbound", - DeliveryMethod::Direct, - ); - outbound - .set_file_attachment_field("large.bin", &vec![0x77; 2 * 1024 * 1024]) - .unwrap(); - outbound.sign(&key).unwrap(); - outbound.stamp = Some(vec![0x44; TICKET_LENGTH]); - let packed = outbound.pack().unwrap(); - - let mut inbound = LxMessage::unpack(&packed).unwrap(); - assert!(inbound.wire_payload.is_some()); - assert!(inbound.verify(&key.public_key())); - assert!(inbound.wire_payload.is_none()); - let (name, data) = inbound.first_file_attachment().unwrap().unwrap(); - assert_eq!(name, "large.bin"); - assert_eq!(data.len(), 2 * 1024 * 1024); - } - - #[test] - fn exact_packed_len_matches_wire_without_allocating_a_second_message() { - let mut msg = LxMessage::new( - [0x11; 16], - [0x22; 16], - "title", - "content", - DeliveryMethod::Direct, - ); - msg.set_file_attachment_field("large.bin", &vec![0x5a; 2 * 1024 * 1024]) - .unwrap(); - msg.signature = Some([0x33; 64]); - assert_eq!(msg.packed_len().unwrap(), msg.pack().unwrap().len()); - } - - #[test] - fn test_state_transitions() { - let mut msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - assert_eq!(msg.state, MessageState::Generating); - - msg.state = MessageState::Outbound; - msg.cancel(); - assert_eq!(msg.state, MessageState::Cancelled); - } - - #[test] - fn test_base64url_roundtrip() { - use base64::Engine; - let data = b"Hello, LXMF World! This is a test message."; - let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(data); - let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(&encoded) - .unwrap(); - assert_eq!(decoded, data); - } - - #[test] - fn test_paper_uri() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - - let mut msg = LxMessage::new( - [0x11; 16], - [0x22; 16], - "Paper", - "Message", - DeliveryMethod::Paper, - ); - msg.sign(&key).unwrap(); - - let uri = msg - .to_paper_uri(|plaintext| Ok(plaintext.to_vec())) - .unwrap(); - assert!(uri.starts_with("lxm://")); - - let decoded = - LxMessage::from_paper_uri(&uri, |ciphertext| Ok(ciphertext.to_vec())).unwrap(); - assert_eq!(decoded.destination_hash, msg.destination_hash); - assert_eq!(decoded.title, "Paper"); - assert_eq!(decoded.method, DeliveryMethod::Paper); - assert_eq!(decoded.representation, DeliveryRepresentation::Paper); - } - - #[test] - fn test_paper_uri_uses_identity_encryption() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let recipient = rns_identity::identity::Identity::new(); - - let mut msg = LxMessage::new( - recipient.hash, - [0xBB; 16], - "Paper", - "encrypted", - DeliveryMethod::Paper, - ); - msg.sign(&key).unwrap(); - let plaintext_tail = msg.pack().unwrap()[DESTINATION_LENGTH..].to_vec(); - - let uri = msg - .to_paper_uri(|plaintext| { - recipient - .encrypt(plaintext, None) - .map_err(|e| MessageError::PackFailed(e.to_string())) - }) - .unwrap(); - let (dest_hash, encrypted_tail) = LxMessage::decode_paper_uri(&uri).unwrap(); - assert_eq!(dest_hash, recipient.hash); - assert_ne!(encrypted_tail, plaintext_tail); - - let decoded = LxMessage::from_paper_uri(&uri, |ciphertext| { - recipient - .decrypt(ciphertext, None, false) - .map_err(|e| MessageError::UnpackFailed(e.to_string())) - }) - .unwrap(); - assert_eq!(decoded.destination_hash, recipient.hash); - assert_eq!(decoded.content, "encrypted"); - } - - #[test] - fn test_sign_sets_hash() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Hash", - "Content", - DeliveryMethod::Direct, - ); - assert!(msg.hash.is_none()); - msg.sign(&key).unwrap(); - assert!(msg.hash.is_some()); - // SHA-256(dest_hash || src_hash || payload) - let payload = msg.pack_payload().unwrap(); - let mut hashed_part = Vec::new(); - hashed_part.extend_from_slice(&msg.destination_hash); - hashed_part.extend_from_slice(&msg.source_hash); - hashed_part.extend_from_slice(&payload); - let expected = rns_crypto::sha::sha256(&hashed_part); - assert_eq!(msg.hash.unwrap(), expected); - } - - #[test] - fn test_unpack_sets_python_message_id() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Hash", - "Content", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - let expected = msg.hash.unwrap(); - - let unpacked = LxMessage::unpack(&msg.pack().unwrap()).unwrap(); - - assert_eq!(unpacked.hash, Some(expected)); - assert_eq!(unpacked.message_id, Some(expected)); - } - - #[test] - fn test_unpack_hash_strips_stamp() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Stamped", - "Content", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - let expected = msg.hash.unwrap(); - msg.stamp = Some(vec![0x42; 32]); - - let unpacked = LxMessage::unpack(&msg.pack().unwrap()).unwrap(); - - assert_eq!(unpacked.hash, Some(expected)); - assert_eq!(unpacked.message_id, Some(expected)); - } - - #[test] - fn test_sign_verify_with_message_hash_appended() { - // Signed data = dest_hash || src_hash || payload || SHA256(dest_hash || src_hash || payload) - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let pub_key = key.public_key(); - - let mut msg = LxMessage::new( - [0x11; 16], - [0x22; 16], - "Test", - "Body", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - - let payload = msg.pack_payload().unwrap(); - let mut hashed_part = Vec::new(); - hashed_part.extend_from_slice(&msg.destination_hash); - hashed_part.extend_from_slice(&msg.source_hash); - hashed_part.extend_from_slice(&payload); - let message_hash = rns_crypto::sha::sha256(&hashed_part); - let mut signed_data = hashed_part; - signed_data.extend_from_slice(&message_hash); - - let sig = msg.signature.unwrap(); - assert!(pub_key.verify(&signed_data, &sig).is_ok()); - assert!(msg.verify(&pub_key)); - } - - #[test] - fn test_unpack_bin_encoded_title_content() { - // Interop: C++/Python senders emit title/content as msgpack `bin`, not `str`. - // Hand-build a 4-element payload: [timestamp, title(bin), content(bin), fields(map)]. - let mut payload = Vec::new(); - - // fixarray of 4 elements - payload.push(0x94); - - // float64 timestamp - payload.push(0xCB); - payload.extend_from_slice(&1700000000.0_f64.to_be_bytes()); - - // bin8 "Hello" - payload.push(0xC4); - payload.push(5); - payload.extend_from_slice(b"Hello"); - - // bin8 "World body" - payload.push(0xC4); - payload.push(10); - payload.extend_from_slice(b"World body"); - - // fixmap of 0 elements - payload.push(0x80); - - let mut wire = Vec::new(); - wire.extend_from_slice(&[0xAA; 16]); - wire.extend_from_slice(&[0xBB; 16]); - wire.extend_from_slice(&[0x00; 64]); - wire.extend_from_slice(&payload); - - let msg = LxMessage::unpack(&wire).unwrap(); - assert_eq!(msg.title, "Hello"); - assert_eq!(msg.content, "World body"); - assert_eq!(msg.destination_hash, [0xAA; 16]); - assert_eq!(msg.source_hash, [0xBB; 16]); - } - - #[test] - fn test_unpack_too_short() { - assert!(LxMessage::unpack(&[0; 10]).is_err()); - // 96-byte header alone is too short -- payload is required - assert!(LxMessage::unpack(&[0; 96]).is_err()); - } - - #[test] - fn test_pack_unpack_container_roundtrip() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Container Test", - "Content for container", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - msg.state = MessageState::Delivered; - msg.transport_encrypted = true; - msg.transport_encryption = Some("Curve25519".to_string()); - - let container_data = msg.pack_container().unwrap(); - assert!(!container_data.is_empty()); - - let unpacked = LxMessage::unpack_container(&container_data).unwrap(); - assert_eq!(unpacked.state, MessageState::Delivered); - assert_eq!(unpacked.method, DeliveryMethod::Direct); - assert!(unpacked.transport_encrypted); - assert_eq!(unpacked.transport_encryption.as_deref(), Some("Curve25519")); - assert_eq!(unpacked.title, "Container Test"); - assert_eq!(unpacked.content, "Content for container"); - } - - #[test] - fn test_pack_unpack_container_method_variants() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - for method in [ - DeliveryMethod::Paper, - DeliveryMethod::Direct, - DeliveryMethod::Propagated, - ] { - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", method); - msg.sign(&key).unwrap(); - let unpacked = LxMessage::unpack_container(&msg.pack_container().unwrap()).unwrap(); - assert_eq!( - unpacked.method, method, - "method round-trip for {:?}", - method - ); - } - } - - #[test] - fn test_new_message_fields() { - let msg = LxMessage::new([0; 16], [0; 16], "", "", DeliveryMethod::Direct); - assert_eq!(msg.representation, DeliveryRepresentation::Unknown); - assert!(msg.unverified_reason.is_none()); - assert!(!msg.transport_encrypted); - assert!(!msg.incoming); - assert_eq!(msg.progress, 0.0); - } - - #[test] - fn test_compute_hash() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Hash Test", - "Content", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - let hash = msg.compute_hash().unwrap(); - assert_ne!(hash, [0u8; 32]); - assert!(msg.transient_id.is_some()); - } - - #[test] - fn test_sign_sets_message_id() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Test", - "Content", - DeliveryMethod::Direct, - ); - assert!(msg.message_id.is_none()); - msg.sign(&key).unwrap(); - assert!(msg.message_id.is_some()); - assert_eq!(msg.message_id, msg.hash); - } - - #[test] - fn test_pack_propagated_encrypted() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Propagated Encrypted", - "Content body here", - DeliveryMethod::Propagated, - ); - msg.sign(&key).unwrap(); - - let (propagation_packed, tid) = msg - .pack_propagated_encrypted(|plaintext| { - // Marker-byte prepend stands in for real encryption - let mut out = vec![0xFF]; - out.extend_from_slice(plaintext); - Ok(out) - }) - .unwrap(); - - assert!(!propagation_packed.is_empty()); - assert_eq!(msg.transient_id, Some(tid)); - assert_ne!(tid, [0u8; 32]); - - let (ts, entries) = LxMessage::unpack_propagation_wrapper(&propagation_packed).unwrap(); - assert!(ts > 0.0); - assert_eq!(entries.len(), 1); - - let raw_wrapper = - rmpv::decode::read_value(&mut std::io::Cursor::new(&propagation_packed)).unwrap(); - match raw_wrapper { - rmpv::Value::Array(items) => match &items[1] { - rmpv::Value::Array(entries) => { - assert!(matches!(entries.first(), Some(rmpv::Value::Binary(_)))); - } - other => panic!("propagation entries should be msgpack array, got {other:?}"), - }, - other => panic!("propagation wrapper should be msgpack array, got {other:?}"), - } - - let lxmf_data = &entries[0]; - assert_eq!(&lxmf_data[..16], &[0xAA; 16]); - } - - /// T0-7: the bounded wrapper decode must reject CPU-amplification shapes - /// (junk-stuffed entry lists) cheaply, before per-entry stamp validation - /// could build any ~256 KB workblocks; legitimate transfers still pass. - #[test] - fn test_unpack_propagation_wrapper_bounded() { - let entry_floor = LxMessage::MIN_PROPAGATION_ENTRY_SIZE; - let limit = 16 * 1024; - - // Hostile: thousands of tiny entries in a small blob. - let junk: Vec> = (0..2000).map(|_| vec![0xAB; 3]).collect(); - let hostile = rmp_serde::to_vec(&(1000.0f64, junk)).unwrap(); - assert!(hostile.len() <= limit, "test blob must fit the limit"); - assert!(LxMessage::unpack_propagation_wrapper_bounded(&hostile, limit).is_err()); - - // Hostile: a single under-floor entry hidden among valid-sized ones. - let mixed: Vec> = vec![vec![0xAB; entry_floor], vec![0xAB; entry_floor - 1]]; - let mixed_blob = rmp_serde::to_vec(&(1000.0f64, mixed)).unwrap(); - assert!(LxMessage::unpack_propagation_wrapper_bounded(&mixed_blob, limit).is_err()); - - // Hostile: blob bigger than the configured transfer limit. - let oversize: Vec> = vec![vec![0xAB; 2 * limit]]; - let oversize_blob = rmp_serde::to_vec(&(1000.0f64, oversize)).unwrap(); - assert!(LxMessage::unpack_propagation_wrapper_bounded(&oversize_blob, limit).is_err()); - - // Legitimate multi-entry sync passes and round-trips. - let good: Vec> = (0..8).map(|i| vec![i as u8; entry_floor + 64]).collect(); - let good_blob = rmp_serde::to_vec(&(1000.0f64, good.clone())).unwrap(); - let (ts, entries) = - LxMessage::unpack_propagation_wrapper_bounded(&good_blob, limit).unwrap(); - assert_eq!(ts, 1000.0); - assert_eq!(entries, good); - } - - #[test] - fn test_pack_opportunistic_encrypted_strips_destination_hash() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Opportunistic", - "Content body here", - DeliveryMethod::Opportunistic, - ); - msg.sign(&key).unwrap(); - let packed = msg.pack().unwrap(); - let expected_tail = packed[DESTINATION_LENGTH..].to_vec(); - - let encrypted = msg - .pack_opportunistic_encrypted(|plaintext| { - assert_eq!(plaintext, expected_tail.as_slice()); - let mut out = vec![0xEE]; - out.extend_from_slice(plaintext); - Ok(out) - }) - .unwrap(); - - assert_eq!(encrypted[0], 0xEE); - assert_eq!(&encrypted[1..], expected_tail.as_slice()); - } - - #[test] - fn test_propagation_transient_id() { - let lxmf_data = vec![0xAA; 100]; - let tid = LxMessage::compute_propagation_transient_id(&lxmf_data); - assert_eq!(tid.len(), 32); - - let tid2 = LxMessage::compute_propagation_transient_id(&lxmf_data); - assert_eq!(tid, tid2); - - let other_data = vec![0xBB; 100]; - let tid3 = LxMessage::compute_propagation_transient_id(&other_data); - assert_ne!(tid, tid3); - } - - #[test] - fn test_propagation_transient_id_matches_full_hash() { - use rns_crypto::sha::full_hash; - - let lxmf_data = vec![0x42; 200]; - let tid = LxMessage::compute_propagation_transient_id(&lxmf_data); - let expected_full = full_hash(&lxmf_data); - assert_eq!(tid, expected_full); - } - - #[test] - fn test_get_stamp_with_ticket() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Ticket", - "Test", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - - let ticket = [0x42; 16]; - msg.outbound_ticket = Some(ticket); - - let stamp = msg.get_stamp(); - assert!(stamp.is_some()); - assert_eq!(msg.stamp_value, Some(COST_TICKET)); - - // stamp = truncated_hash(ticket || message_id) - let message_id = msg.message_id.unwrap(); - let mut material = Vec::new(); - material.extend_from_slice(&ticket); - material.extend_from_slice(&message_id); - let expected = truncated_hash(&material).to_vec(); - assert_eq!(stamp.unwrap(), expected); - } - - #[test] - fn test_get_stamp_no_cost() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "NoCost", - "Test", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - msg.stamp_cost = None; - - let stamp = msg.get_stamp(); - assert!(stamp.is_none()); - assert!(msg.stamp_value.is_none()); - } - - #[test] - fn test_validate_stamp_with_ticket() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Validate Ticket", - "Test", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - - let ticket = vec![0x42; 16]; - let message_id = msg.message_id.unwrap(); - let mut material = Vec::new(); - material.extend_from_slice(&ticket); - material.extend_from_slice(&message_id); - let stamp = truncated_hash(&material).to_vec(); - msg.stamp = Some(stamp); - - let valid = msg.validate_stamp_with_tickets(16, Some(std::slice::from_ref(&ticket))); - assert!(valid); - assert_eq!(msg.stamp_value, Some(COST_TICKET)); - } - - #[test] - fn test_validate_stamp_wrong_ticket() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Wrong Ticket", - "Test", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - msg.stamp = Some(vec![0xFF; 32]); - - let valid = msg.validate_stamp_with_tickets(16, Some(&[vec![0x42; 16]])); - // Must fail both the ticket check and the PoW check - assert!(!valid); - } - - #[test] - fn test_validate_stamp_no_stamp() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "No Stamp", - "Test", - DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - msg.stamp = None; - - let valid = msg.validate_stamp_with_tickets(16, None); - assert!(!valid); - } - - #[test] - fn test_pack_propagated_encrypted_with_prop_stamp() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Prop Stamp", - "Content", - DeliveryMethod::Propagated, - ); - msg.sign(&key).unwrap(); - msg.propagation_stamp = Some([0xDD; 32]); - - let (propagation_packed, _tid) = msg - .pack_propagated_encrypted(|plaintext| Ok(plaintext.to_vec())) - .unwrap(); - - let (_, entries) = LxMessage::unpack_propagation_wrapper(&propagation_packed).unwrap(); - assert_eq!(entries.len(), 1); - - // lxmf_data = dest_hash(16) || encrypted_data || propagation_stamp(32) - let lxmf_entry = &entries[0]; - assert_eq!(&lxmf_entry[..16], &[0xAA; 16]); - let last_32 = &lxmf_entry[lxmf_entry.len() - 32..]; - assert_eq!(last_32, &[0xDD; 32]); - } - - #[test] - fn test_pack_propagated_encrypted_with_zero_cost_stamp() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Prop Stamp", - "Content", - DeliveryMethod::Propagated, - ); - msg.sign(&key).unwrap(); - - let (propagation_packed, _tid, _value) = msg - .pack_propagated_encrypted_with_stamp(|plaintext| Ok(plaintext.to_vec()), 0) - .unwrap(); - - let (_, entries) = LxMessage::unpack_propagation_wrapper(&propagation_packed).unwrap(); - let lxmf_entry = &entries[0]; - assert_eq!(lxmf_entry.len(), msg.pack().unwrap().len() + 32); - assert_eq!(&lxmf_entry[lxmf_entry.len() - 32..], &[0u8; 32]); - assert!(crate::stamper::validate_pn_stamp(lxmf_entry, 0).is_some()); - } - - #[test] - fn test_uri_roundtrip() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( - [0xAA; 16], - [0xBB; 16], - "Test", - "Hello via paper", - DeliveryMethod::Paper, - ); - msg.sign(&key).unwrap(); - - let uri = msg.as_uri(|plaintext| Ok(plaintext.to_vec())).unwrap(); - assert!(uri.starts_with("lxm://")); - - let decoded = LxMessage::from_uri(&uri, |ciphertext| Ok(ciphertext.to_vec())).unwrap(); - assert_eq!(decoded.content, "Hello via paper"); - assert_eq!(decoded.title, "Test"); - assert_eq!(decoded.destination_hash, [0xAA; 16]); - assert_eq!(decoded.source_hash, [0xBB; 16]); - } - - #[test] - fn test_from_uri_invalid_prefix() { - let result = - LxMessage::from_uri("https://example.com", |ciphertext| Ok(ciphertext.to_vec())); - assert!(result.is_err()); - } - - #[test] - fn test_from_uri_invalid_base64() { - let result = LxMessage::from_uri("lxm://not-valid-base64!!!", |ciphertext| { - Ok(ciphertext.to_vec()) - }); - assert!(result.is_err()); - } - - use proptest::prelude::*; - - proptest! { - /// Full LxMessage pack → unpack round-trip over the reasonable - /// input space. Explicit `test_pack_unpack_roundtrip` uses one - /// hand-picked case; proptest widens to arbitrary title/content - /// strings, arbitrary dest/source hashes, and all sendable - /// delivery methods. Catches msgpack/serde drift + unicode - /// normalization bugs in the title/content payload. - #[test] - fn proptest_message_pack_unpack_roundtrip( - destination_hash: [u8; 16], - source_hash: [u8; 16], - // Cap string length to keep the test fast; long content is - // already covered by test_pack_unpack_container_roundtrip. - title in ".{0,128}", - content in ".{0,512}", - method_idx in 0u8..=2, - ) { - let method = match method_idx { - 0 => DeliveryMethod::Opportunistic, - 1 => DeliveryMethod::Direct, - _ => DeliveryMethod::Propagated, - }; - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new(destination_hash, source_hash, &title, &content, method); - msg.sign(&key).unwrap(); - - let packed = msg.pack().unwrap(); - let unpacked = LxMessage::unpack(&packed).unwrap(); - - prop_assert_eq!(unpacked.destination_hash, destination_hash); - prop_assert_eq!(unpacked.source_hash, source_hash); - prop_assert_eq!(&unpacked.title, &title); - prop_assert_eq!(&unpacked.content, &content); - prop_assert_eq!(unpacked.signature, msg.signature); - } +fn read_text_range(wire: &[u8], input: &mut &[u8]) -> Result, MessageError> { + if input + .first() + .is_some_and(|marker| matches!(*marker,0xa0..=0xbf|0xc4..=0xc6|0xd9..=0xdb)) + { + let bytes = read_msgpack_string_or_binary(input)?; + let start = bytes.as_ptr() as usize - wire.as_ptr() as usize; + Ok(start..start + bytes.len()) + } else { + skip_msgpack_value(input, 0)?; + Ok(0..0) } } +fn read_recipient_stamp(input: &mut &[u8]) -> Result, MessageError> { + match input.first().copied() { + Some(0xc4..=0xc6) => Ok(RecipientStamp::from_bytes(read_msgpack_binary(input)?)), + Some(0x90..=0x9f | 0xdc | 0xdd) => { + let count = read_msgpack_array_len(input)? as usize; + if count != 16 && count != 32 { + for _ in 0..count { + skip_msgpack_value(input, 0)?; + } + return Ok(None); + } + let mut bytes = [0u8; 32]; + let mut valid = true; + for slot in &mut bytes[..count] { + match u8::try_from(read_msgpack_integer(input)?) { + Ok(byte) => *slot = byte, + Err(_) => valid = false, + } + } + Ok(if valid { + RecipientStamp::from_bytes(&bytes[..count]) + } else { + None + }) + } + Some(_) => { + skip_msgpack_value(input, 0)?; + Ok(None) + } + None => Err(MessageError::UnpackFailed( + "missing MessagePack stamp".into(), + )), + } +} +#[cfg(test)] +mod tests; + +/// Test fixtures still cross the production signing/finalization boundary. +#[cfg(test)] +pub(crate) fn test_message( + destination: [u8; 16], + source: [u8; 16], + title: &str, + content: &str, + method: DeliveryMethod, +) -> LxMessage { + LxMessageDraft::new(destination, source, title, content, method) + .unwrap() + .sign(&rns_crypto::ed25519::Ed25519PrivateKey::from_bytes( + &[1; 32], + )) + .unwrap() + .finalize(None) + .unwrap() +} diff --git a/crates/lxmf-core/src/message/draft.rs b/crates/lxmf-core/src/message/draft.rs new file mode 100644 index 0000000..aade30a --- /dev/null +++ b/crates/lxmf-core/src/message/draft.rs @@ -0,0 +1,404 @@ +//! Checked mutable construction followed by consuming signature/finalization. +use super::*; +use rns_crypto::ed25519::Ed25519PrivateKey; +/// Mutable outbound semantics. This type cannot be submitted as a wire message. +/// ```compile_fail +/// use lxmf_core::message::LxMessageDraft; +/// fn send_unsigned(draft: LxMessageDraft) { let _ = draft.wire_bytes(); } +/// ``` +#[derive(Debug, Clone)] +pub struct LxMessageDraft { + destination: [u8; 16], + source: [u8; 16], + title: Bytes, + content: Bytes, + timestamp: f64, + fields: BTreeMap, + limits: MessageDecodeLimits, + pub metadata: MessageMetadata, + pub include_ticket: bool, + pub outbound_ticket: Option<[u8; 16]>, + pub stamp_cost: Option, + ticket_barrier: Option>, +} +impl Deref for LxMessageDraft { + type Target = MessageMetadata; + fn deref(&self) -> &Self::Target { + &self.metadata + } +} +impl DerefMut for LxMessageDraft { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.metadata + } +} +/// Frozen signed body awaiting its optional recipient stamp. Not a sendable type. +#[derive(Debug)] +pub struct SignedLxMessage { + message: LxMessage, + outbound_ticket: Option<[u8; 16]>, + stamp_cost: Option, +} +impl Deref for SignedLxMessage { + type Target = MessageMetadata; + fn deref(&self) -> &Self::Target { + &self.message.metadata + } +} +impl DerefMut for SignedLxMessage { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.message.metadata + } +} +impl LxMessageDraft { + pub fn new( + destination: [u8; 16], + source: [u8; 16], + title: &str, + content: &str, + method: DeliveryMethod, + ) -> Result { + Self::new_with_limits( + destination, + source, + title, + content, + method, + MessageDecodeLimits::default(), + ) + } + pub fn new_with_limits( + destination: [u8; 16], + source: [u8; 16], + title: &str, + content: &str, + method: DeliveryMethod, + limits: MessageDecodeLimits, + ) -> Result { + limits.check_wire( + title + .len() + .checked_add(content.len()) + .and_then(|n| n.checked_add(110)) + .ok_or_else(|| MessageError::PackFailed("length overflow".into()))?, + )?; + let draft = Self { + destination, + source, + title: Bytes::copy_from_slice(title.as_bytes()), + content: Bytes::copy_from_slice(content.as_bytes()), + timestamp: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(), + fields: BTreeMap::new(), + limits, + metadata: MessageMetadata { + method, + ..MessageMetadata::default() + }, + include_ticket: false, + outbound_ticket: None, + stamp_cost: None, + ticket_barrier: None, + }; + draft.checked_wire_len()?; + Ok(draft) + } + pub fn destination_hash(&self) -> [u8; 16] { + self.destination + } + pub fn source_hash(&self) -> [u8; 16] { + self.source + } + pub fn timestamp(&self) -> f64 { + self.timestamp + } + pub fn title_bytes(&self) -> &[u8] { + &self.title + } + pub fn content_bytes(&self) -> &[u8] { + &self.content + } + pub fn fields(&self) -> &BTreeMap { + &self.fields + } + pub(crate) fn mark_ticket_pending(&mut self, owner: Arc<()>) { + self.ticket_barrier = Some(owner); + } + pub(crate) fn release_ticket_barrier(&mut self, owner: &Arc<()>) -> bool { + if self + .ticket_barrier + .as_ref() + .is_some_and(|pending| Arc::ptr_eq(pending, owner)) + { + self.ticket_barrier = None; + true + } else { + false + } + } + pub fn get_field(&self, id: impl Into) -> Option<&FieldValue> { + self.fields.get(&id.into()) + } + pub fn set_timestamp(&mut self, value: f64) -> Result<(), MessageError> { + if !value.is_finite() { + return Err(MessageError::PackFailed( + "nonfinite outbound timestamp".into(), + )); + } + self.timestamp = value; + Ok(()) + } + pub fn set_title(&mut self, value: &str) -> Result<(), MessageError> { + self.set_text(value, true) + } + pub fn set_content(&mut self, value: &str) -> Result<(), MessageError> { + self.set_text(value, false) + } + fn set_text(&mut self, value: &str, title: bool) -> Result<(), MessageError> { + self.limits.check_wire(value.len())?; + let next = Bytes::copy_from_slice(value.as_bytes()); + let old = if title { + std::mem::replace(&mut self.title, next) + } else { + std::mem::replace(&mut self.content, next) + }; + if let Err(e) = self.checked_wire_len() { + if title { + self.title = old + } else { + self.content = old + }; + return Err(e); + } + Ok(()) + } + pub fn set_field( + &mut self, + id: impl Into, + bytes: impl Into, + ) -> Result<(), MessageError> { + self.set_field_value(id, FieldValue::Binary(bytes.into())) + } + pub fn set_msgpack_field( + &mut self, + id: impl Into, + bytes: impl Into, + ) -> Result<(), MessageError> { + self.set_field_value( + id, + FieldValue::MessagePack(EncodedFieldValue::new(bytes.into())?), + ) + } + pub fn set_field_value( + &mut self, + id: impl Into, + value: FieldValue, + ) -> Result<(), MessageError> { + let id = id.into(); + if !self.fields.contains_key(&id) && self.fields.len() >= self.limits.max_top_level_fields { + return Err(MessageError::TooManyFields); + } + let old = self.fields.insert(id, value); + if let Err(e) = self.checked_wire_len() { + match old { + Some(v) => { + self.fields.insert(id, v); + } + None => { + self.fields.remove(&id); + } + }; + return Err(e); + } + Ok(()) + } + pub fn remove_field(&mut self, id: impl Into) -> Option { + self.fields.remove(&id.into()) + } + pub fn set_image_field(&mut self, format: &str, bytes: &[u8]) -> Result<(), MessageError> { + self.limits.check_wire(bytes.len())?; + let encoded = rmp_serde::to_vec(&ImageFieldRef { format, bytes }).map_err(packed)?; + self.set_msgpack_field(FIELD_IMAGE, encoded) + } + pub fn set_audio_field(&mut self, mode: u8, bytes: &[u8]) -> Result<(), MessageError> { + self.limits.check_wire(bytes.len())?; + let encoded = rmp_serde::to_vec(&AudioFieldRef { mode, bytes }).map_err(packed)?; + self.set_msgpack_field(FIELD_AUDIO, encoded) + } + pub fn set_file_attachment_field( + &mut self, + file_name: &str, + bytes: &[u8], + ) -> Result<(), MessageError> { + self.limits.check_wire(bytes.len())?; + let encoded = + rmp_serde::to_vec(&FileAttachmentsFieldRef { file_name, bytes }).map_err(packed)?; + self.set_msgpack_field(FIELD_FILE_ATTACHMENTS, encoded) + } + /// Exact unsigned payload, for diagnostics; it is not a transmittable message. + pub fn pack_payload(&self) -> Result, MessageError> { + let size = self.checked_wire_len()?; + let mut out = Vec::with_capacity(size - 96); + self.write_payload(&mut out)?; + Ok(out) + } + pub fn checked_wire_len(&self) -> Result { + if self.fields.len() > self.limits.max_top_level_fields { + return Err(MessageError::TooManyFields); + } + let mut counter = CountingWriter::default(); + self.write_payload(&mut counter)?; + let len = counter + .bytes + .checked_add(96) + .ok_or_else(|| packed("length overflow"))?; + self.limits.check_wire(len)?; + Ok(len) + } + fn write_payload(&self, out: &mut W) -> Result<(), MessageError> { + rmp::encode::write_array_len(out, 4).map_err(packed)?; + rmp::encode::write_f64(out, self.timestamp).map_err(packed)?; + write_bin(out, &self.title)?; + write_bin(out, &self.content)?; + rmp::encode::write_map_len(out, length(self.fields.len())?).map_err(packed)?; + for (id, value) in &self.fields { + if id.as_i128() >= 0 { + rmp::encode::write_uint(out, u64::try_from(id.as_i128()).map_err(packed)?) + .map_err(packed)?; + } else { + rmp::encode::write_sint(out, i64::try_from(id.as_i128()).map_err(packed)?) + .map_err(packed)?; + } + match value { + FieldValue::Binary(b) => write_bin(out, b)?, + FieldValue::MessagePack(v) => out.write_all(v.encoded()).map_err(packed)?, + } + } + Ok(()) + } + pub fn sign(self, key: &Ed25519PrivateKey) -> Result { + self.sign_with(|bytes| Ok::<_, std::convert::Infallible>(key.sign(bytes))) + } + pub fn sign_with(self, sign: F) -> Result + where + F: FnOnce(&[u8]) -> Result<[u8; 64], E>, + E: std::fmt::Display, + { + if self.ticket_barrier.is_some() { + return Err(MessageError::TicketNotCommitted); + } + let size = self.checked_wire_len()?; + let mut signed = Vec::with_capacity(size); + signed.extend_from_slice(&self.destination); + signed.extend_from_slice(&self.source); + self.write_payload(&mut signed)?; + let id = sha256(&signed); + signed.extend_from_slice(&id); + let signature = sign(&signed).map_err(packed)?; + let mut wire = Vec::with_capacity(size); + wire.extend_from_slice(&self.destination); + wire.extend_from_slice(&self.source); + wire.extend_from_slice(&signature); + wire.extend_from_slice(&signed[32..signed.len() - 32]); + drop(signed); + let mut message = LxMessage::unpack_owned(wire.into(), self.limits)?; + message.metadata = self.metadata; + message.incoming = false; + message.state = MessageState::Outbound; + Ok(SignedLxMessage { + message, + outbound_ticket: self.outbound_ticket, + stamp_cost: self.stamp_cost, + }) + } +} +impl SignedLxMessage { + pub fn timestamp(&self) -> f64 { + self.message.timestamp() + } + /// Complete no-stamp wire length; finalization can add a recipient stamp. + pub fn packed_len(&self) -> Result { + self.message.packed_len() + } + /// Signed payload length, without exposing sendable bytes before finalization. + pub fn payload_len(&self) -> usize { + self.message.wire_bytes().len() - 96 + } + pub fn title_bytes(&self) -> &[u8] { + self.message.title_bytes() + } + pub fn content_bytes(&self) -> &[u8] { + self.message.content_bytes() + } + pub fn title_text(&self) -> std::borrow::Cow<'_, str> { + self.message.title_text() + } + pub fn content_text(&self) -> std::borrow::Cow<'_, str> { + self.message.content_text() + } + pub fn message_id(&self) -> [u8; 32] { + self.message.message_id() + } + pub fn destination_hash(&self) -> [u8; 16] { + self.message.destination_hash() + } + pub fn source_hash(&self) -> [u8; 16] { + self.message.source_hash() + } + pub fn fields(&self) -> Fields<'_> { + self.message.fields() + } + pub fn stamp_cost(&self) -> Option { + self.stamp_cost + } + pub fn outbound_ticket(&self) -> Option<[u8; 16]> { + self.outbound_ticket + } + /// Compute the optional recipient stamp without changing the signed body. + pub fn generate_recipient_stamp(&self) -> Result, MessageError> { + if let Some(ticket) = self.outbound_ticket { + let mut material = [0u8; 48]; + material[..16].copy_from_slice(&ticket); + material[16..].copy_from_slice(&self.message_id()); + return Ok(Some(RecipientStamp::Ticket(truncated_hash(&material)))); + } + let Some(cost) = self.stamp_cost else { + return Ok(None); + }; + crate::stamper::generate_stamp(&self.message_id(), cost, STAMP_WORKBLOCK_EXPAND_ROUNDS) + .map(|(stamp, _)| Some(RecipientStamp::ProofOfWork(stamp))) + .ok_or_else(|| packed("recipient stamp generation failed")) + } + pub fn finalize(self, stamp: Option) -> Result { + let Some(stamp) = stamp else { + return Ok(self.message); + }; + let size = self + .message + .wire + .len() + .checked_add(2 + stamp.as_bytes().len()) + .ok_or_else(|| packed("length overflow"))?; + self.message.limits.check_wire(size)?; + let mut wire = Vec::with_capacity(size); + wire.extend_from_slice(&self.message.wire); + wire[96] = 0x95; + write_bin(&mut wire, stamp.as_bytes())?; + let mut message = LxMessage::unpack_owned(wire.into(), self.message.limits)?; + debug_assert_eq!(message.message_id, self.message.message_id); + message.metadata = self.message.metadata; + Ok(message) + } +} +fn packed(error: impl std::fmt::Display) -> MessageError { + MessageError::PackFailed(error.to_string()) +} +fn length(value: usize) -> Result { + u32::try_from(value).map_err(packed) +} +fn write_bin(out: &mut W, bytes: &[u8]) -> Result<(), MessageError> { + rmp::encode::write_bin_len(out, length(bytes.len())?).map_err(packed)?; + out.write_all(bytes).map_err(packed) +} diff --git a/crates/lxmf-core/src/message/field.rs b/crates/lxmf-core/src/message/field.rs new file mode 100644 index 0000000..8be5eb2 --- /dev/null +++ b/crates/lxmf-core/src/message/field.rs @@ -0,0 +1,341 @@ +//! Full-width LXMF field keys and coherent binary/structured values. +use super::{MessageError, read_msgpack_binary, skip_msgpack_value}; +use bytes::Bytes; +use serde::{Deserialize, Serialize}; +use std::{fmt, ops::Range}; + +/// A MessagePack integer field key, preserving the complete signed/unsigned domain. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct FieldId(i128); +impl FieldId { + pub const fn as_i128(self) -> i128 { + self.0 + } + pub fn as_standard(self) -> Option { + u8::try_from(self.0).ok() + } +} +macro_rules! field_from { ($($t:ty),*) => { $(impl From<$t> for FieldId { fn from(v:$t)->Self { Self(i128::from(v)) } })* }; } +field_from!(u8, u16, u32, u64, i8, i16, i32, i64); +impl TryFrom for FieldId { + type Error = MessageError; + fn try_from(v: i128) -> Result { + if v < i128::from(i64::MIN) || v > i128::from(u64::MAX) { + return Err(MessageError::InvalidFieldId); + } + Ok(Self(v)) + } +} +impl Serialize for FieldId { + fn serialize(&self, s: S) -> Result { + if self.0 >= 0 { + s.serialize_u64(u64::try_from(self.0).map_err(serde::ser::Error::custom)?) + } else { + s.serialize_i64(i64::try_from(self.0).map_err(serde::ser::Error::custom)?) + } + } +} +impl<'de> Deserialize<'de> for FieldId { + fn deserialize>(d: D) -> Result { + struct V; + impl serde::de::Visitor<'_> for V { + type Value = FieldId; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a signed or unsigned 64-bit integer") + } + fn visit_i64(self, v: i64) -> Result { + Ok(v.into()) + } + fn visit_u64(self, v: u64) -> Result { + Ok(v.into()) + } + fn visit_i128(self, v: i128) -> Result { + FieldId::try_from(v).map_err(E::custom) + } + fn visit_u128(self, v: u128) -> Result { + u64::try_from(v).map(FieldId::from).map_err(E::custom) + } + } + d.deserialize_any(V) + } +} + +/// One structurally valid encoded MessagePack value. Storage cannot be mutated. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodedFieldValue(Bytes); +impl EncodedFieldValue { + pub fn new(bytes: Bytes) -> Result { + let mut remaining = bytes.as_ref(); + skip_msgpack_value(&mut remaining, 0)?; + if !remaining.is_empty() { + return Err(MessageError::UnpackFailed("trailing field bytes".into())); + } + Ok(Self(bytes)) + } + pub fn encoded(&self) -> &[u8] { + &self.0 + } +} +/// A binary byte string or a native structured MessagePack value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FieldValue { + Binary(Bytes), + MessagePack(EncodedFieldValue), +} +impl Serialize for FieldValue { + fn serialize(&self, s: S) -> Result { + match self { + Self::Binary(b) => s.serialize_bytes(b), + Self::MessagePack(v) => { + let value = rmpv::decode::read_value(&mut v.encoded()) + .map_err(serde::ser::Error::custom)?; + value.serialize(s) + } + } + } +} +impl<'de> Deserialize<'de> for FieldValue { + fn deserialize>(d: D) -> Result { + let value = rmpv::Value::deserialize(d)?; + if let rmpv::Value::Binary(b) = value { + return Ok(Self::Binary(b.into())); + } + let mut bytes = Vec::new(); + rmpv::encode::write_value(&mut bytes, &value).map_err(serde::de::Error::custom)?; + EncodedFieldValue::new(bytes.into()) + .map(Self::MessagePack) + .map_err(serde::de::Error::custom) + } +} + +/// Borrowed exact encoded field value. Binary is never inferred to be structure. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FieldValueRef<'a> { + pub(super) encoded: &'a [u8], +} +impl<'a> FieldValueRef<'a> { + /// Borrow exactly one structurally valid value without decoding or copying it. + /// Duplicate map keys remain opaque until a recognized schema asks for + /// `unique_map`; binary payloads are never interpreted implicitly. + pub fn from_encoded(encoded: &'a [u8]) -> Result { + let mut remaining = encoded; + skip_msgpack_value(&mut remaining, 0)?; + if !remaining.is_empty() { + return Err(MessageError::UnpackFailed("trailing field bytes".into())); + } + Ok(Self { encoded }) + } + /// Exact UTF-8 MessagePack text, without accepting a binary value as text. + pub fn as_text(self) -> Option<&'a str> { + if !matches!(self.encoded.first(), Some(0xa0..=0xbf | 0xd9..=0xdb)) { + return None; + } + let mut input = self.encoded; + let bytes = super::read_msgpack_string_or_binary(&mut input).ok()?; + if !input.is_empty() { + return None; + } + std::str::from_utf8(bytes).ok() + } + pub fn encoded(self) -> &'a [u8] { + self.encoded + } + pub fn as_binary(self) -> Option<&'a [u8]> { + let mut value = self.encoded; + let bytes = read_msgpack_binary(&mut value).ok()?; + value.is_empty().then_some(bytes) + } + /// Owned explicit copy, for constructing a new message deliberately. + pub fn to_owned(self) -> FieldValue { + match self.as_binary() { + Some(b) => FieldValue::Binary(Bytes::copy_from_slice(b)), + None => { + FieldValue::MessagePack(EncodedFieldValue(Bytes::copy_from_slice(self.encoded))) + } + } + } +} +#[derive(Debug, Clone)] +pub(super) struct FieldIndex { + pub id: FieldId, + pub range: Range, +} +const _: () = assert!(std::mem::size_of::() <= 32); +/// Numeric-key ordered view; original field wire order stays in the message. +#[derive(Debug, Clone, Copy)] +pub struct Fields<'a> { + pub(super) wire: &'a [u8], + pub(super) indexes: &'a [FieldIndex], +} +impl<'a> Fields<'a> { + pub fn get(self, id: impl Into) -> Option> { + let id = id.into(); + self.indexes + .binary_search_by_key(&id, |entry| entry.id) + .ok() + .map(|i| FieldValueRef { + encoded: &self.wire[self.indexes[i].range.clone()], + }) + } + pub fn contains(self, id: impl Into) -> bool { + self.get(id).is_some() + } + pub fn len(self) -> usize { + self.indexes.len() + } + pub fn is_empty(self) -> bool { + self.indexes.is_empty() + } + pub fn iter(self) -> impl ExactSizeIterator)> { + self.indexes.iter().map(move |entry| { + ( + entry.id, + FieldValueRef { + encoded: &self.wire[entry.range.clone()], + }, + ) + }) + } +} + +pub(super) mod map_serde { + use super::*; + use std::collections::BTreeMap; + pub fn serialize( + map: &BTreeMap, + s: S, + ) -> Result { + map.serialize(s) + } + pub fn deserialize<'de, D: serde::Deserializer<'de>>( + d: D, + ) -> Result, D::Error> { + struct V; + impl<'de> serde::de::Visitor<'de> for V { + type Value = BTreeMap; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("unique integer fields") + } + fn visit_map>( + self, + mut access: A, + ) -> Result { + let mut map = BTreeMap::new(); + while let Some(key) = access.next_key::()? { + if map.len() + >= super::super::MessageDecodeLimits::default().max_top_level_fields + { + return Err(serde::de::Error::custom("too many fields")); + } + if map.contains_key(&key) { + return Err(serde::de::Error::custom("duplicate field ID")); + } + let value = access.next_value()?; + map.insert(key, value); + } + Ok(map) + } + } + d.deserialize_map(V) + } +} + +/// Validated schema-map keys. Integer encodings normalize; text is exact UTF-8. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum FieldMapKey<'a> { + Integer(FieldId), + Text(&'a str), +} +/// Borrowed map values with a compact sorted key-offset index. +/// +/// Intended for recognized reaction/chat/game schemas. Unknown structured fields +/// remain opaque and need not request this semantic validation. The index uses +/// four bytes per entry (at most twice the encoded field size), with no value copies. +#[derive(Debug)] +pub struct UniqueFieldMap<'a> { + encoded: &'a [u8], + offsets: Vec, +} +impl<'a> FieldValueRef<'a> { + pub fn unique_map(self) -> Result, MessageError> { + let mut input = self.encoded; + let count = super::read_msgpack_map_len(&mut input)? as usize; + if count > input.len() / 2 { + return Err(MessageError::UnpackFailed( + "impossible nested map count".into(), + )); + } + let mut offsets = Vec::new(); + offsets + .try_reserve_exact(count) + .map_err(|_| MessageError::UnpackFailed("nested map index allocation".into()))?; + for _ in 0..count { + offsets.push( + u32::try_from(self.encoded.len() - input.len()) + .map_err(|_| MessageError::InvalidFieldId)?, + ); + read_map_key(&mut input)?; + skip_msgpack_value(&mut input, 0)?; + } + if !input.is_empty() { + return Err(MessageError::UnpackFailed( + "trailing nested map bytes".into(), + )); + } + let key_at = |offset: &u32| { + read_map_key(&mut &self.encoded[*offset as usize..]) + .expect("validated immutable map key") + }; + offsets.sort_unstable_by(|a, b| key_at(a).cmp(&key_at(b))); + if offsets + .windows(2) + .any(|pair| key_at(&pair[0]) == key_at(&pair[1])) + { + return Err(MessageError::DuplicateField); + } + Ok(UniqueFieldMap { + encoded: self.encoded, + offsets, + }) + } +} +impl<'a> UniqueFieldMap<'a> { + pub fn len(&self) -> usize { + self.offsets.len() + } + pub fn is_empty(&self) -> bool { + self.offsets.is_empty() + } + pub fn get(&self, key: FieldMapKey<'_>) -> Option> { + let index = self + .offsets + .binary_search_by(|offset| { + read_map_key(&mut &self.encoded[*offset as usize..]) + .expect("validated map key") + .cmp(&key) + }) + .ok()?; + let mut input = &self.encoded[self.offsets[index] as usize..]; + read_map_key(&mut input).ok()?; + let value = input; + skip_msgpack_value(&mut input, 0).ok()?; + Some(FieldValueRef { + encoded: &value[..value.len() - input.len()], + }) + } +} +fn read_map_key<'a>(input: &mut &'a [u8]) -> Result, MessageError> { + if input + .first() + .is_some_and(|marker| matches!(*marker,0xa0..=0xbf|0xd9..=0xdb)) + { + let text = super::read_msgpack_string_or_binary(input)?; + Ok(FieldMapKey::Text(std::str::from_utf8(text).map_err( + |_| MessageError::UnpackFailed("map key is not UTF-8".into()), + )?)) + } else { + Ok(FieldMapKey::Integer(FieldId::try_from( + super::read_msgpack_integer(input)?, + )?)) + } +} diff --git a/crates/lxmf-core/src/message/fixtures/python-reordered-public.bin b/crates/lxmf-core/src/message/fixtures/python-reordered-public.bin new file mode 100644 index 0000000..0639b10 --- /dev/null +++ b/crates/lxmf-core/src/message/fixtures/python-reordered-public.bin @@ -0,0 +1 @@ +/�äxîÒÝfPpVJך�*uÁ”qPp÷_I#D‰H®8 \ No newline at end of file diff --git a/crates/lxmf-core/src/message/fixtures/python-reordered.bin b/crates/lxmf-core/src/message/fixtures/python-reordered.bin new file mode 100644 index 0000000000000000000000000000000000000000..f9e56a92f9ed565e4cc3aedcf0fa51188d3f9efe GIT binary patch literal 165 zcmXSUDEYqf4zI&Zt*hTzcx%d^ysY(TPG(wet(Ne9{>=J!hm=Bj1-ALGpZ#6INPAwy z@n8?z88v)WKaYi6+myg7Z_+AY^Tg*x)*PnYf|tVNWwNDvOjcNyuQDwB_wUm^m&rU+ zPTPNA0D~h8N5q3OQ&N)>^HLP@i&9dHQd1PtGE;L>iktYEcqW~8yn8kkr1FSBIT`=} Dz;8v` literal 0 HcmV?d00001 diff --git a/crates/lxmf-core/src/message/tests.rs b/crates/lxmf-core/src/message/tests.rs new file mode 100644 index 0000000..7774411 --- /dev/null +++ b/crates/lxmf-core/src/message/tests.rs @@ -0,0 +1,733 @@ +use super::*; +use rns_crypto::ed25519::Ed25519PrivateKey; +fn key() -> Ed25519PrivateKey { + Ed25519PrivateKey::from_bytes(&[7; 32]) +} +fn draft() -> LxMessageDraft { + LxMessageDraft::new([1; 16], [2; 16], "title", "content", DeliveryMethod::Direct).unwrap() +} +fn freeze(draft: LxMessageDraft) -> LxMessage { + draft.sign(&key()).unwrap().finalize(None).unwrap() +} +fn payload(fields: &[u8], stamp: Option<&[u8]>) -> Vec { + let mut p = vec![if stamp.is_some() { 0x95 } else { 0x94 }]; + rmp::encode::write_f64(&mut p, 1_700_000_000.).unwrap(); + p.extend_from_slice(&[0xc4, 1, b'T', 0xc4, 1, b'C']); + p.extend_from_slice(fields); + if let Some(s) = stamp { + p.extend_from_slice(s); + } + p +} +fn wire(payload: &[u8]) -> Vec { + let mut signed = vec![1; 16]; + signed.extend_from_slice(&[2; 16]); + if let Some(body) = first_four_msgpack_array_body(payload) { + signed.push(0x94); + signed.extend_from_slice(body); + } else { + signed.extend_from_slice(payload); + } + let hash = sha256(&signed); + signed.extend_from_slice(&hash); + let mut out = vec![1; 16]; + out.extend_from_slice(&[2; 16]); + out.extend_from_slice(&key().sign(&signed)); + out.extend_from_slice(payload); + out +} +#[test] +fn signed_body_finalization_defaults_and_states() { + let d = draft(); + assert!(d.timestamp() > 0.); + assert_eq!(d.state, MessageState::Generating); + assert!(d.auto_compress); + assert!(!d.source_blackholed); + let signed = d.sign(&key()).unwrap(); + let id = signed.message_id(); + let mut m = signed.finalize(None).unwrap(); + assert_eq!(m.state, MessageState::Outbound); + assert_eq!(m.message_id(), id); + let before = m.wire_owned(); + m.mark_sending(); + m.mark_sent(); + m.mark_delivered(); + assert_eq!(m.state, MessageState::Delivered); + m.mark_failed(); + assert_eq!(m.state, MessageState::Failed); + m.mark_rejected(); + assert_eq!(m.state, MessageState::Rejected); + assert_eq!(m.wire_bytes(), before.as_ref()); +} +#[test] +fn received_wire_identity_repeated_verification_and_ownership() { + let mut p = payload(&[0x82, 0x0f, 0x01, 0x0c, 0x92, 0x00, 0xc4, 0x00], None); + // A retained noncanonical f32 timestamp cannot be reencoded as f64. + p.splice(1..10, [0xca, 0x3f, 0x80, 0x00, 0x00]); + let wire = Bytes::from(wire(&p)); + let ptr = wire.as_ptr(); + let mut m = LxMessage::unpack_owned(wire.clone(), MessageDecodeLimits::default()).unwrap(); + assert_eq!(m.wire_bytes().as_ptr(), ptr); + let id = m.message_id(); + assert!(m.verify_signature(&key().public_key())); + assert!(m.verify_signature(&key().public_key())); + assert_eq!(m.pack().unwrap(), wire); + assert_eq!(m.pack_payload().unwrap(), p); + assert_eq!(m.message_id(), id); + m.method = DeliveryMethod::Propagated; + m.progress = 0.8; + assert_eq!(m.clone().wire_bytes().as_ptr(), ptr); + assert_eq!(m.pack().unwrap(), wire); + let restored = LxMessage::unpack_container(&m.pack_container().unwrap()).unwrap(); + assert_eq!(restored.wire_bytes(), wire); + assert_eq!(restored.message_id(), id); + assert!(restored.verify_signature(&key().public_key())); +} +#[test] +fn received_wire_identity_real_python_reordered_vector() { + // Emitted by Python LXMF 1.0.1: renderer precedes the subsequently added reply ticket. + let raw = include_bytes!("fixtures/python-reordered.bin"); + let public = include_bytes!("fixtures/python-reordered-public.bin"); + let key = + rns_crypto::ed25519::Ed25519PublicKey::from_bytes(public.as_slice().try_into().unwrap()) + .unwrap(); + let m = LxMessage::unpack(raw).unwrap(); + assert!(m.verify_signature(&key)); + assert!(m.verify_signature(&key)); + assert_eq!(m.pack().unwrap(), raw); + let restored = LxMessage::unpack_container(&m.pack_container().unwrap()).unwrap(); + assert_eq!(restored.wire_bytes(), raw); + assert_eq!(restored.message_id(), m.message_id()); + assert!(restored.verify_signature(&key)); +} +#[test] +fn received_wire_identity_source_binding() { + let identity = rns_identity::identity::Identity::from_private_key(&[7; 64]).unwrap(); + let source = rns_identity::destination::Destination::hash_from_name_and_identity( + "lxmf.delivery", + Some(&identity.hash), + ); + let d = LxMessageDraft::new([1; 16], source, "", "", DeliveryMethod::Direct).unwrap(); + let m = freeze(d); + assert!(m.verify(&identity.get_public_key()).is_ok()); + assert!(m.verify(&identity.get_public_key()).is_ok()); + let mut altered = identity.get_public_key(); + altered[..32].fill(8); + assert!(matches!( + m.verify(&altered), + Err(MessageError::SourceMismatch) + )); + let wrong_source = freeze(draft()); + assert!(wrong_source.verify_signature(&key().public_key())); + assert!(matches!( + wrong_source.verify(&identity.get_public_key()), + Err(MessageError::SourceMismatch) + )); + assert!(!m.verify_signature(&Ed25519PrivateKey::from_bytes(&[9; 32]).public_key())); +} +#[test] +fn owned_verification_retains_exact_source_and_shared_wire_after_handoff() { + let identity = rns_identity::identity::Identity::from_private_key(&[7; 64]).unwrap(); + let source = rns_identity::destination::Destination::hash_from_name_and_identity( + "lxmf.delivery", + Some(&identity.hash), + ); + let message = freeze( + LxMessageDraft::new([1; 16], source, "title", "content", DeliveryMethod::Direct).unwrap(), + ); + let pointer = message.wire_bytes().as_ptr(); + let hash = message.message_id(); + let owned = message + .verify(&identity.get_public_key()) + .unwrap() + .to_owned(); + drop(message); + let verified = owned.as_verified(); + assert_eq!(verified.message().wire_bytes().as_ptr(), pointer); + assert_eq!(verified.message().message_id(), hash); + assert_eq!(verified.source_public_key(), &identity.get_public_key()); + assert_eq!(verified.message().source_hash(), source); +} +#[test] +fn field_id_entire_domain_and_serde_roundtrip() { + let values = [ + i64::MIN as i128, + -1, + 0, + 255, + 256, + i64::MAX as i128, + i64::MAX as i128 + 1, + u64::MAX as i128, + ]; + let mut d = draft(); + for v in values { + let id = FieldId::try_from(v).unwrap(); + let bytes = rmp_serde::to_vec(&id).unwrap(); + let decoded: FieldId = rmp_serde::from_slice(&bytes).unwrap(); + assert_eq!(decoded, id); + d.set_field(id, vec![42]).unwrap(); + } + let m = freeze(d); + for v in values { + assert_eq!( + m.get_field(FieldId::try_from(v).unwrap()) + .unwrap() + .as_binary(), + Some(&[42][..]) + ); + } + assert!(FieldId::try_from(i64::MIN as i128 - 1).is_err()); + assert!(FieldId::try_from(u64::MAX as i128 + 1).is_err()); + assert!(FieldId::from(256u64).as_standard().is_none()); + assert_eq!(FieldId::from(1u64), FieldId::from(1i64)); +} +#[test] +fn field_id_never_aliases_native_ids() { + let mut d = draft(); + d.set_field(0x105u64, vec![1]).unwrap(); + d.set_field(0x10cu64, vec![2]).unwrap(); + d.set_field(-1i64, vec![3]).unwrap(); + let m = freeze(d); + assert!(!m.fields().contains(5u8)); + assert!(!m.fields().contains(12u8)); + assert!(!m.fields().contains(255u8)); + assert_eq!(m.fields().len(), 3); +} +#[test] +fn field_id_duplicate_numeric_encodings_rejected() { + for map in [ + vec![0x82, 1, 0xc0, 1, 0xc0], + vec![0x82, 1, 0xc0, 0xd1, 0, 1, 0xc0], + vec![0x82, 0xcf, 0, 0, 0, 0, 0, 0, 0, 1, 0xc0, 0xcc, 1, 0xc0], + ] { + assert!(matches!( + LxMessage::unpack(&wire(&payload(&map, None))), + Err(MessageError::DuplicateField) + )); + let mut dto = vec![0x94, 0xcb]; + dto.extend_from_slice(&0f64.to_be_bytes()); + dto.extend_from_slice(&[0xc4, 0, 0xc4, 0]); + dto.extend_from_slice(&map); + assert!(rmp_serde::from_slice::(&dto).is_err()); + } +} +#[test] +fn field_id_coherent_replacement_and_binary_is_not_structure() { + let mut d = draft(); + d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0]) + .unwrap(); + d.set_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0]).unwrap(); + let m = freeze(d); + let value = m.get_field(FIELD_AUDIO).unwrap(); + assert_eq!(value.as_binary(), Some(&[0x92, 0x10, 0xc4, 0][..])); + assert!(m.audio_field().is_err()); + assert!(LxMessage::unpack(m.wire_bytes()).is_ok()); + let mut d = draft(); + d.set_field(FIELD_AUDIO, vec![0]).unwrap(); + d.set_audio_field(0x10, &[1, 2]).unwrap(); + assert_eq!(freeze(d).audio_field().unwrap().unwrap().bytes, &[1, 2]); +} +#[test] +fn field_id_opaque_nested_duplicate_map_is_preserved() { + let raw = vec![0x82, 1, 0x01, 0xd1, 0, 1, 0x02]; + let mut d = draft(); + d.set_msgpack_field(300u64, raw.clone()).unwrap(); + let m = freeze(d); + assert_eq!(m.get_field(300u64).unwrap().encoded(), raw); + assert_eq!( + LxMessage::unpack(m.wire_bytes()).unwrap().pack().unwrap(), + m.wire_bytes() + ); +} +#[test] +fn field_id_profile_counts_inbound_and_outbound() { + let mut d = draft(); + for i in 0..4096u64 { + d.set_field(i, Bytes::new()).unwrap(); + } + d.set_field(0u64, vec![1]).unwrap(); + assert!(matches!( + d.set_field(4096u64, Bytes::new()), + Err(MessageError::TooManyFields) + )); + let m = freeze(d); + assert_eq!(m.fields().len(), 4096); + let smaller = MessageDecodeLimits { + max_top_level_fields: 4095, + ..MessageDecodeLimits::default() + }; + assert!(matches!( + LxMessage::unpack_owned(m.wire_owned(), smaller), + Err(MessageError::TooManyFields) + )); + let profile = MessageDecodeLimits { + max_top_level_fields: 1, + ..MessageDecodeLimits::default() + }; + let mut d = + LxMessageDraft::new_with_limits([1; 16], [2; 16], "", "", DeliveryMethod::Direct, profile) + .unwrap(); + d.set_field(1u8, vec![]).unwrap(); + assert!(d.set_field(FIELD_TICKET, vec![]).is_err()); + d.set_field(1u8, vec![2]).unwrap(); + assert_eq!(freeze(d).fields().len(), 1); + let map = [0xdf, 0xff, 0xff, 0xff, 0xff]; + assert!(LxMessage::unpack(&wire(&payload(&map, None))).is_err()); +} +#[test] +fn signed_body_finalization_enforces_exact_stamp_limit() { + let base = freeze(draft()).wire_bytes().len(); + let mut profile = MessageDecodeLimits { + max_wire_bytes: base, + max_top_level_fields: 4096, + }; + let d = LxMessageDraft::new_with_limits( + [1; 16], + [2; 16], + "title", + "content", + DeliveryMethod::Direct, + profile, + ) + .unwrap(); + assert!(matches!( + d.sign(&key()) + .unwrap() + .finalize(Some(RecipientStamp::Ticket([1; 16]))), + Err(MessageError::TooLarge { .. }) + )); + profile.max_wire_bytes = base + 18; + let d = LxMessageDraft::new_with_limits( + [1; 16], + [2; 16], + "title", + "content", + DeliveryMethod::Direct, + profile, + ) + .unwrap(); + assert_eq!( + d.sign(&key()) + .unwrap() + .finalize(Some(RecipientStamp::Ticket([1; 16]))) + .unwrap() + .wire_bytes() + .len(), + base + 18 + ); +} +#[test] +fn signed_body_finalization_stamp_preserves_id_and_signature() { + let mut d = draft(); + d.set_timestamp(1700000000.).unwrap(); + let no_stamp = freeze(d.clone()); + for stamp in [ + RecipientStamp::Ticket([3; 16]), + RecipientStamp::ProofOfWork([4; 32]), + ] { + let m = d + .clone() + .sign(&key()) + .unwrap() + .finalize(Some(stamp)) + .unwrap(); + assert_eq!(m.message_id(), no_stamp.message_id()); + assert_eq!(m.signature(), no_stamp.signature()); + assert!(m.verify_signature(&key().public_key())); + assert_eq!(m.recipient_stamp(), Some(&stamp)); + assert_eq!( + LxMessage::unpack(m.wire_bytes()).unwrap().message_id(), + no_stamp.message_id() + ); + } +} +#[test] +fn recipient_stamp_array_range_and_malformed_dispositions() { + for (element, valid) in [ + (vec![0], true), + (vec![0xcc, 255], true), + (vec![0xd1, 0, 255], true), + (vec![0xff], false), + (vec![0xcd, 1, 0], false), + (vec![0xcf, 255, 255, 255, 255, 255, 255, 255, 255], false), + ] { + let mut stamp = vec![0xdc, 0, 16]; + for _ in 0..16 { + stamp.extend_from_slice(&element); + } + let bytes = wire(&payload(&[0x80], Some(&stamp))); + let m = LxMessage::unpack(&bytes).unwrap(); + assert_eq!(m.recipient_stamp().is_some(), valid); + assert_eq!(m.wire_bytes(), bytes); + assert!(m.verify_signature(&key().public_key())); + if !valid { + assert!(!m.validate_stamp_with_tickets(0, None)); + } + } + for stamp in [vec![0xc0], vec![0x91, 0], vec![0xc4, 1, 0], vec![0xa0]] { + let m = LxMessage::unpack(&wire(&payload(&[0x80], Some(&stamp)))).unwrap(); + assert!(m.recipient_stamp().is_none()); + } + for stamp in [vec![], vec![0xc4], { + let mut s = vec![0xdc, 0, 16]; + s.extend_from_slice(&[0xc0; 16]); + s + }] { + assert!(LxMessage::unpack(&wire(&payload(&[0x80], Some(&stamp)))).is_err()); + } +} +#[test] +fn recipient_ticket_stamp_and_missing_stamp_policy() { + let mut d = draft(); + d.outbound_ticket = Some([3; 16]); + let signed = d.sign(&key()).unwrap(); + let stamp = signed.generate_recipient_stamp().unwrap(); + let m = signed.finalize(stamp).unwrap(); + assert!(m.validate_stamp_with_tickets(255, Some(&[vec![3; 16]]))); + assert_eq!( + m.validated_stamp_value(255, Some(&[vec![3; 16]])), + Some(COST_TICKET) + ); + assert!(!m.validate_stamp_with_tickets(1, Some(&[vec![4; 16]]))); + assert!(!freeze(draft()).validate_stamp_with_tickets(0, None)); + let signed = draft().sign(&key()).unwrap(); + assert_eq!(signed.generate_recipient_stamp().unwrap(), None); +} +#[test] +fn signed_body_finalization_matches_semantic_dto() { + let mut d = draft(); + d.set_timestamp(1700000000.).unwrap(); + d.set_field(256u64, vec![1, 2]).unwrap(); + d.set_msgpack_field(-1i64, vec![0x92, 1, 0xc4, 0]).unwrap(); + let dto = MessagePayload { + timestamp: d.timestamp(), + title: "title".into(), + content: "content".into(), + fields: d.fields().clone(), + stamp: None, + }; + let encoded = rmp_serde::to_vec(&dto).unwrap(); + assert_eq!(d.pack_payload().unwrap(), encoded); + let decoded: MessagePayload = rmp_serde::from_slice(&encoded).unwrap(); + assert_eq!(decoded.fields, dto.fields); +} +#[test] +fn native_attachments_borrow_exact_image_and_clone() { + let data = vec![0xa5; 2 * 1024 * 1024]; + let mut d = draft(); + d.set_audio_field(AM_OPUS_OGG, &data).unwrap(); + d.set_image_field("webp", &[2, 3]).unwrap(); + d.set_file_attachment_field("test.bin", &[4, 5]).unwrap(); + let m = freeze(d); + let audio = m.audio_field().unwrap().unwrap(); + assert_eq!(audio.bytes, data); + let start = m.wire_bytes().as_ptr() as usize; + assert!((start..start + m.wire_bytes().len()).contains(&(audio.bytes.as_ptr() as usize))); + assert_eq!(m.clone().wire_bytes().as_ptr(), m.wire_bytes().as_ptr()); + assert_eq!( + m.image_attachment().unwrap(), + Some(("webp".into(), &[2, 3][..])) + ); + assert_eq!( + m.first_file_attachment().unwrap(), + Some(("test.bin".into(), &[4, 5][..])) + ); + assert_eq!(m.packed_len().unwrap(), m.pack().unwrap().len()); + assert!(m.verify_signature(&key().public_key())); + assert_eq!( + m.audio_field().unwrap().unwrap().bytes.as_ptr(), + audio.bytes.as_ptr() + ); +} +#[test] +fn native_audio_shape_and_optional_failure() { + for malformed in [ + vec![0xc0], + vec![0x91, 0x10], + vec![0x93, 0x10, 0xc4, 0, 0xc0], + vec![0x92, 0xff, 0xc4, 0], + vec![0x92, 0xcd, 1, 0, 0xc4, 0], + vec![0x92, 0xc0, 0xc4, 0], + vec![0x92, 0x10, 0xa0], + ] { + let mut d = draft(); + d.set_msgpack_field(FIELD_AUDIO, malformed).unwrap(); + let m = freeze(d); + assert!(m.audio_field().is_err()); + assert_eq!(m.content_text(), "content"); + assert!(m.verify_signature(&key().public_key())); + } + let mut d = draft(); + assert!( + d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4]) + .is_err() + ); + assert!( + d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0, 0xc0]) + .is_err() + ); + d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0xcd, 0, 255, 0xc4, 0]) + .unwrap(); + assert_eq!(freeze(d).audio_field().unwrap().unwrap().mode, 255); +} +#[test] +fn received_wire_identity_paper_and_opportunistic_use_exact_tail() { + let mut m = freeze(draft()); + m.method = DeliveryMethod::Paper; + let uri = m.to_paper_uri(|tail| Ok(tail.to_vec())).unwrap(); + assert!(uri.starts_with("lxm://")); + let read = LxMessage::from_paper_uri(&uri, |tail| Ok(tail.to_vec())).unwrap(); + assert_eq!(read.wire_bytes(), m.wire_bytes()); + assert!(read.verify_signature(&key().public_key())); + assert_eq!( + m.pack_opportunistic_encrypted(|tail| Ok(tail.to_vec())) + .unwrap(), + m.wire_bytes()[16..] + ); + assert!(LxMessage::decode_paper_uri("not-uri").is_err()); + assert!(LxMessage::decode_paper_uri("lxm://!!").is_err()); + m.method = DeliveryMethod::Direct; + assert!(m.to_paper_uri(|b| Ok(b.to_vec())).is_err()); +} +#[test] +fn received_wire_identity_file_and_method_roundtrips() { + let dir = tempfile::tempdir().unwrap(); + let mut m = freeze(draft()); + m.state = MessageState::Delivered; + m.transport_encrypted = true; + m.transport_encryption = Some("ECIES".into()); + for method in [ + DeliveryMethod::Direct, + DeliveryMethod::Propagated, + DeliveryMethod::Paper, + DeliveryMethod::Opportunistic, + ] { + m.method = method; + let path = m.write_to_directory(dir.path().to_str().unwrap()).unwrap(); + let read = LxMessage::read_from_file(&path).unwrap(); + assert_eq!(read.method, method); + assert_eq!(read.state, MessageState::Delivered); + assert_eq!(read.wire_bytes(), m.wire_bytes()); + assert_eq!(read.transport_encryption, m.transport_encryption); + assert!(read.verify_signature(&key().public_key())); + } +} +#[test] +fn message_callbacks_and_compression_metadata_do_not_mutate_wire() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut m = freeze(draft()); + let before = m.wire_owned(); + let calls = Arc::new(AtomicUsize::new(0)); + let c = calls.clone(); + m.register_delivery_callback(move |_| { + c.fetch_add(1, Ordering::SeqCst); + }); + let c = calls.clone(); + m.register_failed_callback(move |_| { + c.fetch_add(10, Ordering::SeqCst); + }); + m.mark_delivered(); + m.mark_failed(); + assert_eq!(calls.load(Ordering::SeqCst), 11); + m.determine_compression_support(None); + assert!(m.auto_compress); + m.determine_compression_support(Some(&[0x93, 0xc0, 0xc0, 0x90])); + assert!(!m.auto_compress); + assert_eq!(m.wire_bytes(), before); +} +#[test] +fn propagation_wrapper_compatibility_and_bounds() { + let entry = vec![1; LxMessage::MIN_PROPAGATION_ENTRY_SIZE]; + let entries = [entry.as_slice()]; + let encoded = rmp_serde::to_vec(&PropagationWrapperRef { + timestamp: 1., + entries: &entries, + }) + .unwrap(); + assert_eq!( + LxMessage::unpack_propagation_wrapper(&encoded).unwrap().1, + vec![entry] + ); + assert!(LxMessage::unpack_propagation_wrapper_bounded(&encoded, encoded.len()).is_ok()); + assert!(LxMessage::unpack_propagation_wrapper_bounded(&encoded, encoded.len() - 1).is_err()); + assert_eq!( + LxMessage::compute_propagation_transient_id(&encoded), + full_hash(&encoded) + ); +} +#[test] +fn received_wire_identity_bounds_and_invalid_utf8_preserved() { + for len in 0..97 { + assert!(LxMessage::unpack(&vec![0; len]).is_err()); + } + let mut p = payload(&[0x80], None); + p[12] = 255; + let raw = wire(&p); + let m = LxMessage::unpack(&raw).unwrap(); + assert_eq!(m.title_bytes(), &[255]); + assert_eq!(m.title_text(), "\u{fffd}"); + assert_eq!(m.wire_bytes(), raw); + assert!(m.verify_signature(&key().public_key())); + let limits = MessageDecodeLimits { + max_wire_bytes: raw.len() - 1, + ..MessageDecodeLimits::default() + }; + assert!(LxMessage::unpack_owned(raw.into(), limits).is_err()); +} + +#[test] +fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() { + for encoded in [ + vec![0x82, 0xa1, b'a', 1, 0xa1, b'a', 2], + vec![0x82, 1, 0, 0xd1, 0, 1, 1], + vec![0x81, 0xc3, 0], + ] { + let mut d = draft(); + d.set_msgpack_field(300u64, encoded).unwrap(); + let m = freeze(d); + assert!(m.get_field(300u64).unwrap().unique_map().is_err()); + assert!(m.verify_signature(&key().public_key())); + } + let mut d = draft(); + d.set_msgpack_field(300u64, vec![0x82, 0xa1, b'a', 0xc4, 1, 7, 0x01, 0x02]) + .unwrap(); + let m = freeze(d); + let map = m.get_field(300u64).unwrap().unique_map().unwrap(); + assert_eq!(map.len(), 2); + assert_eq!( + map.get(FieldMapKey::Text("a")).unwrap().as_binary(), + Some(&[7][..]) + ); + assert_eq!( + map.get(FieldMapKey::Integer(1u8.into())).unwrap().encoded(), + &[2] + ); +} +#[test] +fn signed_body_finalization_ticket_barrier_blocks_signer() { + let owner = Arc::new(()); + let mut d = draft(); + d.mark_ticket_pending(owner.clone()); + assert!(!d.release_ticket_barrier(&Arc::new(()))); + assert!(matches!( + d.clone() + .sign_with(|_| -> Result<[u8; 64], &str> { panic!("uncommitted signer called") }), + Err(MessageError::TicketNotCommitted) + )); + assert!(d.release_ticket_barrier(&owner)); + assert!(!d.release_ticket_barrier(&owner)); + assert!(d.sign(&key()).is_ok()); +} + +#[test] +fn lossy_projection_uses_exact_capacity_and_preserves_utf8_replacement() { + for bytes in [ + b"".as_slice(), + b"valid \xf0\x9f\xa6\x80".as_slice(), + b"\xff\xff\xff".as_slice(), + b"a\xf0\x90\x80".as_slice(), + b"a\xed\xa0\x80b\xc0\x80c".as_slice(), + ] { + let actual = bounded_lossy_text(bytes); + assert_eq!(actual, String::from_utf8_lossy(bytes)); + match actual { + Cow::Borrowed(text) => assert_eq!(text.as_ptr(), bytes.as_ptr()), + Cow::Owned(text) => assert_eq!(text.capacity(), text.len()), + } + } + let bytes = vec![0xff; 1024 * 1024]; + let repaired = bounded_lossy_text(&bytes).into_owned(); + assert_eq!(repaired.len(), bytes.len() * 3); + assert_eq!(repaired.capacity(), repaired.len()); +} + +proptest::proptest! { + #[test] + fn bounded_lossy_projection_matches_standard(bytes in proptest::collection::vec(proptest::prelude::any::(), 0..4096)) { + let actual = bounded_lossy_text(&bytes); + proptest::prop_assert_eq!(&actual, &String::from_utf8_lossy(&bytes)); + if let Cow::Owned(text) = actual { + proptest::prop_assert_eq!(text.capacity(), text.len()); + proptest::prop_assert!(text.len() <= 3 * bytes.len()); + } + } +} + +#[test] +fn borrowed_encoded_field_validates_shape_without_copy_or_implicit_conversion() { + let encoded = b"\xa4text"; + let field = FieldValueRef::from_encoded(encoded).unwrap(); + assert_eq!(field.encoded().as_ptr(), encoded.as_ptr()); + assert_eq!(field.as_text(), Some("text")); + assert!(field.as_binary().is_none()); + assert!( + FieldValueRef::from_encoded(b"\xc4\x04text") + .unwrap() + .as_text() + .is_none() + ); + assert!( + FieldValueRef::from_encoded(b"\xa1\xff") + .unwrap() + .as_text() + .is_none() + ); + for invalid in [b"".as_slice(), b"\xa5text", b"\xa4text\xc0", b"\x81\x01"] { + assert!(FieldValueRef::from_encoded(invalid).is_err()); + } + let duplicate = FieldValueRef::from_encoded(b"\x82\x01\x02\xcc\x01\x03").unwrap(); + assert!(matches!( + duplicate.unique_map(), + Err(MessageError::DuplicateField) + )); +} + +#[test] +fn owned_propagation_wrapper_shares_binary_and_preserves_legacy_byte_arrays() { + let entry = vec![0xff; LxMessage::MIN_PROPAGATION_ENTRY_SIZE]; + let entries = [entry.as_slice()]; + let binary = Bytes::from( + rmp_serde::to_vec(&PropagationWrapperRef { + timestamp: 1., + entries: &entries, + }) + .unwrap(), + ); + let (_, decoded) = + LxMessage::unpack_propagation_wrapper_owned(binary.clone(), binary.len()).unwrap(); + assert_eq!(decoded[0].as_ref(), entry); + assert_eq!( + decoded[0].as_ptr(), + binary[binary.len() - entry.len()..].as_ptr() + ); + drop(binary); + assert_eq!(decoded[0].as_ref(), entry); + let legacy = rmp_serde::to_vec(&(1.0, vec![entry.clone()])).unwrap(); + assert_eq!( + LxMessage::unpack_propagation_wrapper_bounded(&legacy, legacy.len()) + .unwrap() + .1, + vec![entry] + ); +} + +#[test] +fn bounded_propagation_wrapper_rejects_forged_counts_and_lengths_before_allocation() { + let forged_count = [0x92, 0x01, 0xdd, 0xff, 0xff, 0xff, 0xff]; + assert!( + LxMessage::unpack_propagation_wrapper_owned( + Bytes::copy_from_slice(&forged_count), + usize::MAX + ) + .is_err() + ); + for marker in [0xdd, 0xc6] { + let mut forged_length = vec![0x92, 0x01, 0x91, marker, 0xff, 0xff, 0xff, 0xff]; + forged_length.resize(1024, 0); + assert!(LxMessage::unpack_propagation_wrapper_bounded(&forged_length, 1024).is_err()); + } + let mut trailing = rmp_serde::to_vec(&(1.0, Vec::>::new())).unwrap(); + trailing.push(0); + assert!(LxMessage::unpack_propagation_wrapper_bounded(&trailing, trailing.len()).is_err()); +} diff --git a/crates/lxmf-core/src/persist.rs b/crates/lxmf-core/src/persist.rs index 786a005..f03e46c 100644 --- a/crates/lxmf-core/src/persist.rs +++ b/crates/lxmf-core/src/persist.rs @@ -34,52 +34,75 @@ pub struct PersistedNodeStats { pub unpeered_propagation_rx_bytes: u64, } -/// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename. -/// -/// Tmp name is `.tmp..<16 random hex>` so concurrent writers (or -/// other processes) never collide; the tmp file is unlinked on error. An fsync -/// failure is logged as a warning and is non-fatal, matching Python -/// `LXMessage.write_to_directory` — LXMessage.py:674-696 (1.0.1). +/// Publish exact bytes through the strict platform durability boundary. +/// CommitUncertain remains an error: readback alone cannot authorize a receipt. pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> { - use std::io::Write; + rns_identity::persistence::durable_write(path, data) + .map(|_| ()) + .map_err(io::Error::other) +} - let random: [u8; 8] = rand::random(); - let tmp_name = format!( - "{}.tmp.{}.{}", - path.file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default(), - std::process::id(), - hex::encode(random) - ); - let tmp = path.with_file_name(tmp_name); +/// Suppression state cannot authorize a remote purge. Adapters nevertheless +/// persist it before allowing the next automatic wants selection. +pub fn save_suppression( + dir: &Path, + ledger: &crate::admission::SuppressionLedger, +) -> io::Result<()> { + write_mpk(&dir.join("propagation_suppression_v1"), ledger) +} - let result = (|| { - let mut file = fs::File::create(&tmp)?; - file.write_all(data)?; - file.flush()?; - if let Err(e) = file.sync_all() { - tracing::warn!( - "Error while waiting for persist fsync for {}: {e}", - tmp.display() - ); - } - drop(file); - fs::rename(&tmp, path) - })(); - - if result.is_err() - && tmp.exists() - && let Err(e) = fs::remove_file(&tmp) - { - tracing::error!( - "Error while cleaning temporary file {} for {}: {e}", - tmp.display(), - path.display() - ); +pub fn load_suppression(dir: &Path) -> io::Result { + // Preserve the existing one-field wrapper while rejecting duplicate keys, + // mismatched embedded scope and quota violations before hydration. + #[derive(serde::Deserialize)] + struct Wire { + #[serde(deserialize_with = "suppression_records")] + records: Vec, } + let wire: Option = + read_mpk_bounded(&dir.join("propagation_suppression_v1"), 65536 * 512 + 4096)?; + crate::admission::SuppressionLedger::from_records( + wire.map_or_else(Vec::new, |wire| wire.records), + ) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} +fn suppression_records<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + struct Records; + impl<'de> serde::de::Visitor<'de> for Records { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("bounded unique suppression map") + } + fn visit_map>( + self, + mut map: M, + ) -> Result { + let mut seen = std::collections::HashSet::new(); + let mut records = Vec::new(); + while let Some((scope,record))=map.next_entry::()? { + if scope!=record.scope || !seen.insert(scope) || records.len()>=crate::admission::SuppressionLedger::GLOBAL { + return Err(serde::de::Error::custom("invalid suppression scope or capacity")); + } + records.push(record); + } + Ok(records) + } + } + deserializer.deserialize_map(Records) +} - result +pub fn save_node_policies( + dir: &Path, + policies: &HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>, +) -> io::Result<()> { + write_mpk(&dir.join("propagation_node_policies_v1"), policies) +} +pub fn load_node_policies( + dir: &Path, +) -> io::Result> { + Ok(read_mpk(&dir.join("propagation_node_policies_v1"))?.unwrap_or_default()) } fn write_mpk(path: &Path, value: &T) -> io::Result<()> { @@ -92,15 +115,33 @@ fn write_mpk(path: &Path, value: &T) -> io::Result<()> { } fn read_mpk(path: &Path) -> io::Result> { - match fs::read(path) { - Ok(bytes) => { - let value = rmp_serde::from_slice(&bytes) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; - Ok(Some(value)) - } - Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), - Err(e) => Err(e), + read_mpk_bounded(path, 64 * 1024 * 1024) +} +fn read_mpk_bounded( + path: &Path, + limit: usize, +) -> io::Result> { + use std::io::Read; + let file = match fs::File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + let mut bytes = Vec::new(); + file.take(limit as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > limit { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "router state exceeds bounded capacity", + )); } + // Allocation-free structural walk precedes serde's collection size hints. + // It also rejects trailing roots, deep nesting and truncated huge lengths. + let encoded = crate::message::EncodedFieldValue::new(bytes.into()) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + rmp_serde::from_slice(encoded.encoded()) + .map(Some) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) } pub fn save_stamp_costs(dir: &Path, costs: &HashMap<[u8; 16], StampCostEntry>) -> io::Result<()> { @@ -111,8 +152,83 @@ pub fn load_stamp_costs(dir: &Path) -> io::Result, +} +impl TicketPersistenceSnapshot { + pub(crate) fn capture(snapshot: TicketStoreSnapshot) -> Self { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(1); + // Rust 1.99 renamed this operation; keep the identical Rust 1.89 API. + #[allow(deprecated)] + let revision = NEXT + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)) + .expect("ticket checkpoint revision exhausted"); + Self { + revision, + snapshot: std::sync::Arc::new(snapshot), + } + } + pub(crate) fn save(&self, dir: &Path, required: Option<&Ticket>) -> io::Result<()> { + use std::sync::{Mutex, OnceLock}; + struct Latest { + revision: u64, + committed: bool, + } + static WRITERS: OnceLock>> = OnceLock::new(); + fs::create_dir_all(dir)?; + let path = fs::canonicalize(dir)?.join(TICKETS_FILE); + let mut writers = WRITERS + .get_or_init(|| Mutex::new(HashMap::new())) + .lock() + .map_err(|_| io::Error::other("ticket persistence coordinator unavailable"))?; + if !writers.contains_key(&path) && writers.len() >= 4096 { + return Err(io::Error::other("ticket persistence path quota exhausted")); + } + let latest = writers.entry(path.clone()).or_insert(Latest { + revision: self.revision, + committed: false, + }); + if self.revision < latest.revision { + if !latest.committed { + return Err(io::Error::other( + "newer ticket checkpoint is uncertain and must be retried", + )); + } + if let Some(required) = required { + let (stored, _) = load_tickets(dir)?; + if !stored.inbound.contains(required) { + return Err(io::Error::other( + "newer ticket state no longer contains this signing intent", + )); + } + } + return Ok(()); + } + if required.is_some_and(|required| !self.snapshot.inbound.contains(required)) { + return Err(io::Error::other( + "ticket snapshot does not contain this signing intent", + )); + } + latest.revision = self.revision; + latest.committed = false; + // Even an uncertain publication raises the revision floor. Older + // snapshots fail closed until this or a newly captured current state + // reestablishes the strict barrier. No failed payload is retained by + // this bounded process-wide metadata coordinator. + write_mpk(&path, &*self.snapshot)?; + latest.committed = true; + Ok(()) + } +} + pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> { - write_mpk(&dir.join(TICKETS_FILE), tickets) + TicketPersistenceSnapshot::capture(tickets.clone()).save(dir, None) } #[derive(serde::Deserialize)] diff --git a/crates/lxmf-core/src/presentation.rs b/crates/lxmf-core/src/presentation.rs index 126e907..d824fc0 100644 --- a/crates/lxmf-core/src/presentation.rs +++ b/crates/lxmf-core/src/presentation.rs @@ -11,6 +11,23 @@ pub const MAX_ADVERTISED_NAME_CHARS: usize = 128; /// codepoints, collapses all Unicode whitespace to one ASCII space, and is /// truncated by Unicode scalar values rather than UTF-8 bytes. pub fn sanitize_name(input: &str, max_chars: usize) -> String { + let mut output = sanitize_name_pass(input, max_chars); + let rounds = output.nfkd().count().saturating_add(2); + for _ in 0..rounds { + let next = sanitize_name_pass(&output, max_chars); + if next == output { + return output; + } + output = next; + } + debug_assert!( + false, + "name normalization exceeded its derived stabilization bound" + ); + String::new() +} + +fn sanitize_name_pass(input: &str, max_chars: usize) -> String { if max_chars == 0 { return String::new(); } @@ -146,6 +163,22 @@ mod tests { assert_eq!(sanitize_name("A B", 3), "A B"); } + #[test] + fn normalization_reaches_fixed_point_after_filtered_separators() { + for input in [ + "A\u{0000}\u{030A}", + "e\u{034f}\u{0301}", + "o\u{200d}\u{0308}", + ] { + for limit in 0..8 { + let once = sanitize_name(input, limit); + assert_eq!(sanitize_name(&once, limit), once); + assert_eq!(once.nfkc().collect::(), once); + } + } + assert_eq!(sanitize_name("™", 128), "TM"); + } + proptest! { #[test] fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) { diff --git a/crates/lxmf-core/src/propagation_client.rs b/crates/lxmf-core/src/propagation_client.rs index ca1d7a4..986bb99 100644 --- a/crates/lxmf-core/src/propagation_client.rs +++ b/crates/lxmf-core/src/propagation_client.rs @@ -13,6 +13,10 @@ //! 8. `/get` with `[None, received_ids]` purges each downloaded batch before the next chunk. use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{ + Arc, + atomic::{AtomicU64, Ordering}, +}; use std::time::{Duration, Instant}; use bytes::Bytes; @@ -31,6 +35,11 @@ use rns_transport::messages::{ }; use tokio::sync::{mpsc, oneshot}; +use crate::admission::{ + AdmissionEpochs, AdmissionResolution, AdmissionScope, DownloadAdmissionOutcome, + DownloadAdmissionToken, DownloadedPropagationMessage, MAX_DOWNLOAD_ITEMS, SuppressionLedger, + SuppressionRecord, retain_response, +}; use crate::constants::*; use crate::propagation::hex_encode; use crate::types::PropagationTransientId; @@ -48,18 +57,48 @@ pub enum PropagationClientState { Receiving, /// `/get` with `[None, received_ids]` sent. PurgeRequested, + /// Download bytes await a durable local application decision. + AwaitingAdmission, + /// At least one item was retained remotely for retry/revalidation. + Partial, Complete, Failed, } +/// Local admission/backoff status; none of these records authorize purge. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PropagationAdmissionStatus { + pub suppressed_count: usize, + pub deferred_count: usize, + pub next_retry: Option, + pub node_records: usize, + pub node_capacity: usize, + pub ledger_full: bool, + pub admission_paused: bool, +} + +/// Per-cycle outcomes distinguish received ciphertext from durable local effects. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PropagationAdmissionCounts { + pub downloaded: usize, + pub committed: usize, + pub duplicate: usize, + pub policy_discarded: usize, + pub user_deleted: usize, + pub rejected: usize, + /// Subset of rejected items eligible for transient backoff retry. + pub retryable: usize, +} + /// One coherent public snapshot of a propagation-node download. #[derive(Debug, Clone, Copy, PartialEq)] pub struct PropagationTransferStatus { pub state: PropagationClientState, pub progress: f64, pub data_size: Option, - /// Number of message blobs decoded from the completed response. + /// Number of durably accepted decisions, including duplicates/discards. pub result: Option, + pub admission: PropagationAdmissionCounts, } impl Default for PropagationTransferStatus { @@ -69,6 +108,7 @@ impl Default for PropagationTransferStatus { progress: 0.0, data_size: None, result: None, + admission: PropagationAdmissionCounts::default(), } } } @@ -164,6 +204,9 @@ pub struct PropagationClient { outbound_propagation_node: Option<[u8; 16]>, link: Option, link_id: Option<[u8; 16]>, + link_request_result: Option< + oneshot::Receiver>, + >, attached_interface: Option, endpoint_release_queued: bool, pending_endpoint_bind: Option, @@ -180,8 +223,23 @@ pub struct PropagationClient { available_messages: Vec>, /// Messages we already have locally. local_messages: HashSet>, + local_message_expiry: HashMap, u64>, /// Phase 2 response: downloaded LXMF message data. - received_messages: Vec>, + received_messages: Vec, + admission_tx: mpsc::UnboundedSender, + admission_rx: mpsc::UnboundedReceiver, + admission_generation: u64, + current_admission_generation: Arc, + pending_admissions: HashSet, + admission_started: Option, + admission_progress: Option, + admission_failures: usize, + suppression: SuppressionLedger, + admission_epochs: AdmissionEpochs, + suppression_updates: Vec, + suppression_persist_failed: bool, + suppression_dirty: bool, + suppression_revision: u64, /// IDs of messages successfully received (drives the Phase 3 purge). received_ids: Vec>, pending_haves: VecDeque>, @@ -212,6 +270,7 @@ impl PropagationClient { identity_key: Option, ) -> Self { let (event_tx, event_rx) = mpsc::channel(256); + let (admission_tx, admission_rx) = mpsc::unbounded_channel(); let (endpoint_lifecycle_tx, endpoint_lifecycle_rx) = mpsc::unbounded_channel(); Self { transport_tx, @@ -220,6 +279,7 @@ impl PropagationClient { outbound_propagation_node: None, link: None, link_id: None, + link_request_result: None, attached_interface: None, endpoint_release_queued: false, pending_endpoint_bind: None, @@ -233,7 +293,22 @@ impl PropagationClient { identity_key, available_messages: Vec::new(), local_messages: HashSet::new(), + local_message_expiry: HashMap::new(), received_messages: Vec::new(), + admission_tx, + admission_rx, + admission_generation: 0, + current_admission_generation: Arc::new(AtomicU64::new(0)), + pending_admissions: HashSet::new(), + admission_started: None, + admission_progress: None, + admission_failures: 0, + suppression: SuppressionLedger::default(), + admission_epochs: AdmissionEpochs::default(), + suppression_updates: Vec::new(), + suppression_persist_failed: false, + suppression_dirty: false, + suppression_revision: 0, received_ids: Vec::new(), pending_haves: VecDeque::new(), pending_wants: VecDeque::new(), @@ -264,10 +339,12 @@ impl PropagationClient { } pub fn add_local_message(&mut self, transient_id: PropagationTransientId) { + self.local_message_expiry.remove(transient_id.as_slice()); self.local_messages.insert(transient_id.to_vec()); } pub fn add_local_message_id(&mut self, transient_id: Vec) { + self.local_message_expiry.remove(&transient_id); self.local_messages.insert(transient_id); } @@ -276,6 +353,49 @@ impl PropagationClient { I: IntoIterator>, { self.local_messages = transient_ids.into_iter().collect(); + self.local_message_expiry.clear(); + } + + pub fn replace_durable_haves( + &mut self, + haves: impl IntoIterator, + ) { + self.local_messages.clear(); + self.local_message_expiry.clear(); + for have in haves { + self.remember_durable_have(have); + } + self.prune_expired_haves(crate::now_f64() as u64); + } + fn remember_durable_have(&mut self, have: crate::admission::DurableHave) { + self.local_messages.insert(have.transient_id.to_vec()); + match have.expires_at { + Some(expiry) => { + self.local_message_expiry + .insert(have.transient_id.to_vec(), expiry); + } + None => { + self.local_message_expiry + .remove(have.transient_id.as_slice()); + } + } + } + fn prune_expired_haves(&mut self, now: u64) { + self.local_message_expiry.retain(|id, expiry| { + if now >= *expiry { + self.local_messages.remove(id); + false + } else { + true + } + }); + // Recheck immediately before the next purge, including long cycles. + if self.request.is_none() { + self.pending_haves + .retain(|id| self.local_messages.contains(id)); + self.received_ids + .retain(|id| self.local_messages.contains(id)); + } } pub fn set_retain_synced_on_node(&mut self, retain: bool) { @@ -286,11 +406,106 @@ impl PropagationClient { &self.available_messages } - pub fn take_received_messages(&mut self) -> Vec> { + /// Move payloads and their single-use admission tokens into the durable + /// adapter. Raw-byte credit follows every Bytes clone across cancellation. + pub fn take_downloaded_messages(&mut self) -> Vec { self.unread_bytes = 0; std::mem::take(&mut self.received_messages) } + /// Install only persisted suppression state. It never supplies purge authority. + pub fn set_suppression_ledger(&mut self, ledger: SuppressionLedger, epochs: AdmissionEpochs) { + self.suppression = ledger; + self.suppression_revision = self.suppression_revision.wrapping_add(1); + self.admission_epochs = epochs; + self.suppression_persist_failed = false; + self.suppression_dirty = false; + self.suppression_updates.clear(); + } + pub fn update_admission_epochs(&mut self, epochs: AdmissionEpochs) { + if self.admission_epochs != epochs { + self.suppression_revision = self.suppression_revision.wrapping_add(1); + } + self.admission_epochs = epochs; + self.prune_suppression(); + } + fn prune_suppression(&mut self) { + let before = self.suppression.records().count(); + self.suppression + .prune(crate::now_f64() as u64, self.admission_epochs); + if self.suppression.records().count() != before { + self.suppression_dirty = true; + self.suppression_revision = self.suppression_revision.wrapping_add(1); + } + } + pub fn admission_status(&self) -> PropagationAdmissionStatus { + let identity = self.identity_hash(); + let node = self.outbound_propagation_node.unwrap_or([0; 16]); + let now = crate::now_f64() as u64; + let mut status = PropagationAdmissionStatus { + node_capacity: SuppressionLedger::PER_NODE, + ledger_full: self.suppression.saturated(identity, node), + ..Default::default() + }; + for record in self + .suppression + .records() + .filter(|record| record.scope.identity == identity && record.scope.node == node) + { + status.node_records += 1; + if record.active(now, self.admission_epochs) { + if record.reason.is_transient() { + status.deferred_count += 1; + } else { + status.suppressed_count += 1; + } + status.next_retry = Some( + status + .next_retry + .map_or(record.next_retry, |n| n.min(record.next_retry)), + ); + } + } + status.admission_paused = + self.suppression_persist_failed || self.suppression_dirty || status.ledger_full; + status + } + pub fn suppression_ledger(&self) -> &SuppressionLedger { + &self.suppression + } + /// Covers inserts, removals, expiry, epoch changes and restored snapshots. + pub fn suppression_revision(&self) -> u64 { + self.suppression_revision + } + /// A slow checkpoint must never reinstall an older ledger over new state. + pub fn acknowledge_suppression_persistence(&mut self, revision: u64) -> bool { + if revision != self.suppression_revision { + return false; + } + self.suppression_dirty = false; + self.suppression_persist_failed = false; + self.suppression_updates.clear(); + true + } + pub fn suppression_persistence_pending(&self) -> bool { + self.suppression_dirty + } + pub fn take_suppression_updates(&mut self) -> Vec { + std::mem::take(&mut self.suppression_updates) + } + /// The adapter must report a failed durable suppression update. Automatic + /// new wants pause until persisted state is installed after recovery. + pub fn suppression_persistence_failed(&mut self) { + self.suppression_persist_failed = true; + } + + fn identity_hash(&self) -> [u8; 16] { + self.identity_pub + .as_ref() + .map(|key| rns_crypto::sha::truncated_hash(key)) + .unwrap_or([0; 16]) + } + pub const fn state(&self) -> PropagationClientState { self.status.state } @@ -304,7 +519,9 @@ impl PropagationClient { pub fn acknowledge_transfer(&mut self) -> bool { if !matches!( self.status.state, - PropagationClientState::Complete | PropagationClientState::Failed + PropagationClientState::Complete + | PropagationClientState::Partial + | PropagationClientState::Failed ) { return false; } @@ -319,10 +536,15 @@ impl PropagationClient { /// Start a propagation download, limiting newly requested messages. /// `None` and zero mirror Python's `PR_ALL_MESSAGES`. - /// Drain previously received messages before restarting, including after a - /// failed purge or cancellation. A refused start never discards results. + /// Move live downloads into the durable adapter before restarting. Failure + /// or cancellation drops the client-owned queue and revokes its tokens; + /// already moved payload/worker owners retain their memory leases. pub fn start_download_with_limit(&mut self, max_messages: Option) -> bool { - if !self.received_messages.is_empty() { + self.prune_suppression(); + if !self.received_messages.is_empty() + || self.suppression_persist_failed + || self.suppression_dirty + { return false; } let node_hash = match self.outbound_propagation_node { @@ -333,13 +555,16 @@ impl PropagationClient { self.status.state, PropagationClientState::Idle | PropagationClientState::Complete + | PropagationClientState::Partial | PropagationClientState::Failed ) { return false; } if matches!( self.status.state, - PropagationClientState::Complete | PropagationClientState::Failed + PropagationClientState::Complete + | PropagationClientState::Partial + | PropagationClientState::Failed ) { self.cleanup(); } @@ -377,15 +602,21 @@ impl PropagationClient { let mut raw = header.pack(); raw.extend_from_slice(&request_data); - if !self.queue_transport(TransportMessage::Outbound(OutboundRequest { - raw: Bytes::from(raw), - destination_hash: node_hash, - })) { + let (request_tx, request_rx) = oneshot::channel(); + if !self.queue_transport(TransportMessage::SendLinkRequest { + request: OutboundRequest { + raw: Bytes::from(raw), + destination_hash: node_hash, + }, + result_tx: request_tx, + }) { tracing::warn!("failed to stage propagation client Link request"); self.pending_transport.clear(); return false; } + self.link_request_result = Some(request_rx); + self.status = PropagationTransferStatus { state: PropagationClientState::LinkEstablishing, ..PropagationTransferStatus::default() @@ -401,6 +632,13 @@ impl PropagationClient { self.identified = false; self.available_messages.clear(); self.received_messages.clear(); + self.admission_generation = self.admission_generation.wrapping_add(1); + self.current_admission_generation + .store(self.admission_generation, Ordering::Release); + self.pending_admissions.clear(); + self.admission_failures = 0; + self.admission_started = None; + self.admission_progress = None; self.received_ids.clear(); self.pending_haves.clear(); self.pending_wants.clear(); @@ -447,7 +685,7 @@ impl PropagationClient { } Err(mpsc::error::TrySendError::Closed(_)) => { self.pending_transport.clear(); - self.status.state = PropagationClientState::Failed; + self.fail(); break; } } @@ -588,7 +826,7 @@ impl PropagationClient { "propagation client Link endpoint send rejected" ); if current { - self.status.state = PropagationClientState::Failed; + self.fail(); } if pending.final_send { self.queue_endpoint_cleanup(pending.link_id); @@ -596,12 +834,12 @@ impl PropagationClient { } Err(oneshot::error::TryRecvError::Closed) => { if current { - self.status.state = PropagationClientState::Failed; + self.fail(); } } Err(oneshot::error::TryRecvError::Empty) => { if current && pending.queued_at.elapsed() >= Duration::from_secs(120) { - self.status.state = PropagationClientState::Failed; + self.fail(); } else if current || pending.final_send { still_pending.push(pending); } @@ -648,7 +886,7 @@ impl PropagationClient { ); self.attached_interface = None; self.pending_endpoint_bind = None; - self.status.state = PropagationClientState::Failed; + self.fail(); } } @@ -662,7 +900,7 @@ impl PropagationClient { self.status.state = PropagationClientState::LinkEstablished; self.started_at = Some(Instant::now()); } else { - self.status.state = PropagationClientState::Failed; + self.fail(); } } Ok( @@ -670,7 +908,7 @@ impl PropagationClient { | LinkEndpointBindResult::InterfaceUnavailable, ) | Err(oneshot::error::TryRecvError::Closed) => { - self.status.state = PropagationClientState::Failed; + self.fail(); } Err(oneshot::error::TryRecvError::Empty) => { self.pending_endpoint_bind = Some(pending); @@ -678,7 +916,25 @@ impl PropagationClient { } } + fn poll_link_request(&mut self) { + let Some(mut receiver) = self.link_request_result.take() else { + return; + }; + match receiver.try_recv() { + Ok(Ok(())) => {} + Ok(Err(error)) => { + tracing::warn!(%error,"Link request rejected by transport"); + self.fail(); + } + Err(oneshot::error::TryRecvError::Closed) => { + self.fail(); + } + Err(oneshot::error::TryRecvError::Empty) => self.link_request_result = Some(receiver), + } + } + pub fn drain_events(&mut self, known_identities: &std::collections::HashMap) { + self.poll_link_request(); self.poll_endpoint_control(); let mut events = Vec::new(); while let Ok(event) = self.event_rx.try_recv() { @@ -694,7 +950,10 @@ impl PropagationClient { self.handle_link_closed(link_id, None); } DestinationEvent::InboundPacket { - raw, interface_id, .. + raw, + interface_id, + interface_owner, + .. } => { let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) { Ok(h) => h, @@ -753,11 +1012,12 @@ impl PropagationClient { .expect("known_identities values are [u8; 64]; slice [32..64] is always 32 bytes"); if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes) { - self.handle_link_proof( + self.handle_link_proof_with_owner( data, &verify_key, &ed25519_bytes, interface_id, + interface_owner, ); } } @@ -766,7 +1026,7 @@ impl PropagationClient { if let Some(plaintext) = self.link.as_ref().and_then(|link| link.decrypt(data).ok()) { - self.handle_response_plaintext(&plaintext); + self.handle_response_owned(Bytes::from(plaintext)); } } rns_wire::context::PacketContext::ResourceReq => { @@ -820,18 +1080,29 @@ impl PropagationClient { self.inbound_resources.clear(); self.inbound_split_resources.clear(); self.segment_routing.clear(); - self.status.state = PropagationClientState::Failed; + self.fail(); } verified } + #[cfg(test)] fn handle_link_proof( &mut self, proof_data: &[u8], verify_key: &Ed25519PublicKey, ed25519_pub: &[u8; 32], interface_id: InterfaceId, + ) { + self.handle_link_proof_with_owner(proof_data, verify_key, ed25519_pub, interface_id, None) + } + fn handle_link_proof_with_owner( + &mut self, + proof_data: &[u8], + verify_key: &Ed25519PublicKey, + ed25519_pub: &[u8; 32], + interface_id: InterfaceId, + interface_owner: Option, ) { let link = match self.link.as_mut() { Some(l) => l, @@ -864,6 +1135,7 @@ impl PropagationClient { let (result_tx, result_rx) = oneshot::channel(); if !self.queue_transport(TransportMessage::BindLinkEndpoint { binding: LinkEndpointBinding { + interface_owner, link_id, interface_id, role: LinkEndpointRole::Initiator, @@ -871,7 +1143,7 @@ impl PropagationClient { lifecycle_tx: self.endpoint_lifecycle_tx.clone(), result_tx, }) { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } self.pending_endpoint_bind = Some(PendingEndpointBind { @@ -899,7 +1171,7 @@ impl PropagationClient { self.handle_list_response(response_data); } PropagationClientState::GetRequested => { - self.handle_get_response(response_data); + self.handle_get_response_owned(Bytes::copy_from_slice(response_data)); } PropagationClientState::PurgeRequested => { self.handle_purge_response(response_data); @@ -937,7 +1209,7 @@ impl PropagationClient { || (adv.total_segments > 1 && !adv.flags.split) || adv.random_hash.len() != RANDOM_HASH_SIZE { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } let logical_hash = if adv.flags.split { @@ -950,7 +1222,7 @@ impl PropagationClient { || response.total_segments != adv.total_segments || response.data_size != adv.data_size { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } if adv.segment_index < response.next_segment @@ -959,11 +1231,11 @@ impl PropagationClient { return; } if adv.segment_index != response.next_segment || response.current_segment.is_some() { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } } else if adv.segment_index != 1 { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } @@ -978,7 +1250,7 @@ impl PropagationClient { } self.receiving_for = Some(self.status.state); } else if self.receiving_for.is_none() { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } self.status.state = PropagationClientState::Receiving; @@ -989,7 +1261,7 @@ impl PropagationClient { || adv.segment_index == 0 || adv.segment_index > adv.total_segments { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } @@ -998,7 +1270,7 @@ impl PropagationClient { .entry(adv.original_hash) .or_insert_with(|| MultiSegmentInbound::new(adv.total_segments, adv.original_hash)); if entry.total_segments != adv.total_segments { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } self.segment_routing.insert( @@ -1030,7 +1302,7 @@ impl PropagationClient { map_hashes, rtt, ) else { - self.status.state = PropagationClientState::Failed; + self.fail(); return; }; @@ -1080,7 +1352,7 @@ impl PropagationClient { control_actions.push((rns_wire::context::PacketContext::ResourceReq, req)); } TransferAction::Failed(_) => { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } _ => {} @@ -1166,7 +1438,7 @@ impl PropagationClient { ); } TransferAction::Failed(_) => { - self.status.state = PropagationClientState::Failed; + self.fail(); } _ => {} } @@ -1207,7 +1479,7 @@ impl PropagationClient { if let Some(link) = self.link.as_mut() { link.untrack_resource(&resource_hash); } - self.status.state = PropagationClientState::Failed; + self.fail(); } fn complete_resource(&mut self, resource_hash: [u8; 32]) { @@ -1225,13 +1497,13 @@ impl PropagationClient { match transfer.complete(Some(&decrypt_fn)) { Ok(result) => result, Err(_) => { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } } }; if !self.send_resource_proof(&proof) { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } let route = self.segment_routing.remove(&resource_hash); @@ -1254,7 +1526,7 @@ impl PropagationClient { } let Some(pending) = self.pending_endpoint_sends.last_mut() else { - self.status.state = PropagationClientState::Failed; + self.fail(); return; }; pending.success = EndpointSendSuccess::ResourceProof { @@ -1282,7 +1554,7 @@ impl PropagationClient { .checked_add(assembled.len()) .filter(|total| *total <= MAX_RESOURCE_SIZE && *total <= response.data_size) else { - self.status.state = PropagationClientState::Failed; + self.fail(); return; }; response.assembled_bytes = total; @@ -1290,7 +1562,7 @@ impl PropagationClient { response.next_segment += 1; response.waiting_since = Instant::now(); if response.next_segment > response.total_segments && total != response.data_size { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } if let Some(route) = route { @@ -1300,7 +1572,7 @@ impl PropagationClient { .set_segment_data(route.segment_index, assembled) .is_err() { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } if let Some(meta) = metadata { @@ -1310,7 +1582,7 @@ impl PropagationClient { match coord.reassemble() { Ok(payload) => complete_payload = Some(payload), Err(_) => { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } } @@ -1318,26 +1590,17 @@ impl PropagationClient { } if let Some(payload) = complete_payload { self.inbound_split_resources.remove(&route.original_hash); - self.handle_resource_response_payload(&payload); + self.handle_resource_response_owned(Bytes::from(payload)); } } else { - self.handle_resource_response_payload(&assembled); + self.handle_resource_response_owned(Bytes::from(assembled)); } } - fn handle_resource_response_payload(&mut self, payload: &[u8]) { - if !Link::parse_response_plaintext(payload) - .ok() - .is_some_and(|(id, _)| { - self.request - .as_ref() - .is_some_and(|request| request.id == id) - }) - { - self.status.state = PropagationClientState::Failed; - return; + fn handle_resource_response_owned(&mut self, payload: Bytes) { + if !self.handle_response_owned(payload) { + self.fail(); } - self.handle_response_plaintext(payload); } fn send_encrypted_resource_control( @@ -1376,7 +1639,7 @@ impl PropagationClient { raw: Bytes::from(raw), destination_hash: link_id, }) { - self.status.state = PropagationClientState::Failed; + self.fail(); false } else if let Some(link) = self.link.as_mut() { link.record_tx(payload.len()); @@ -1445,7 +1708,7 @@ impl PropagationClient { let value: rmpv::Value = match Self::decode_response_value(response_data) { Ok(v) => v, Err(_) => { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } }; @@ -1469,63 +1732,184 @@ impl PropagationClient { self.send_get_request(); } } else { - self.status.state = PropagationClientState::Failed; + self.fail(); } } - /// Validate and reserve the complete batch before publishing any result or - /// purge ID. A node may return a subset (or nothing) for a requested chunk. - fn handle_get_response(&mut self, response_data: &[u8]) { - let Ok(rmpv::Value::Array(items)) = Self::decode_response_value(response_data) else { - self.status.state = PropagationClientState::Failed; - return; - }; + /// Validate type/count, exact requested TID membership, duplicates and full + /// byte budget before publishing any item. Payload ranges borrow one owner. + fn handle_get_response_owned(&mut self, response_data: Bytes) { let count = match self.request.as_ref().map(|request| request.kind) { Some(RequestKind::Get(count)) => count, - _ => 0, + _ => { + self.fail(); + return; + } }; - if count > 0 && items.len() > count { - self.status.state = PropagationClientState::Failed; - return; - } - let mut batch_bytes = 0usize; - for item in &items { - let rmpv::Value::Binary(data) = item else { - self.status.state = PropagationClientState::Failed; - return; - }; - let Some(bytes) = batch_bytes.checked_add(data.len()) else { - self.status.state = PropagationClientState::Failed; - return; - }; - batch_bytes = bytes; - } - let Some(unread_bytes) = self - .unread_bytes - .checked_add(batch_bytes) - .filter(|bytes| *bytes <= self.unread_limit) - else { - tracing::warn!( - reason = "result_capacity", - "propagation downloaded batch exceeds unread result capacity" - ); - self.status.state = PropagationClientState::Failed; + let parsed = (|| { + let mut cursor = std::io::Cursor::new(response_data.as_ref()); + let n = rmp::decode::read_array_len(&mut cursor).map_err(|_| ())? as usize; + if n > count || n > MAX_DOWNLOAD_ITEMS { + return Err(()); + } + let wanted: HashSet<_> = self + .pending_wants + .iter() + .take(count) + .map(Vec::as_slice) + .collect(); + let mut seen = HashSet::new(); + let mut ranges = Vec::with_capacity(n); + for _ in 0..n { + let len = rmp::decode::read_bin_len(&mut cursor).map_err(|_| ())? as usize; + let start = cursor.position() as usize; + let end = start + .checked_add(len) + .filter(|end| *end <= response_data.len()) + .ok_or(())?; + let tid = rns_crypto::sha::full_hash(&response_data[start..end]); + if !wanted.contains(tid.as_slice()) || !seen.insert(tid) { + return Err(()); + } + ranges.push((start..end, tid)); + cursor.set_position(end as u64); + } + if cursor.position() as usize != response_data.len() { + return Err(()); + } + Ok(ranges) + })(); + let Ok(ranges) = parsed else { + self.fail(); return; }; - self.unread_bytes = unread_bytes; - self.finish_request(response_data); + let Ok(data) = retain_response(response_data, self.unread_limit) else { + self.fail(); + return; + }; + self.finish_request(&[]); self.pending_wants.drain(..count); - self.status.result = Some(self.status.result.unwrap_or(0).saturating_add(items.len())); - for item in items { - let rmpv::Value::Binary(data) = item else { - unreachable!("batch validated above") + self.admission_generation = self.admission_generation.wrapping_add(1); + self.current_admission_generation + .store(self.admission_generation, Ordering::Release); + let identity = self.identity_hash(); + let node = self.outbound_propagation_node.unwrap_or([0; 16]); + self.unread_bytes = data.len(); + self.status.admission.downloaded = self + .status + .admission + .downloaded + .saturating_add(ranges.len()); + for (range, transient_id) in ranges { + let scope = AdmissionScope { + identity, + node, + transient_id, }; - self.received_ids - .push(rns_crypto::sha::full_hash(&data).to_vec()); - self.received_messages.push(data); + self.pending_admissions.insert(scope); + let token = DownloadAdmissionToken::new( + scope, + self.admission_generation, + self.current_admission_generation.clone(), + self.admission_tx.clone(), + ); + self.received_messages + .push(DownloadedPropagationMessage::new(data.slice(range), token)); + } + if self.pending_admissions.is_empty() { + self.send_next_chunk(); + } else { + self.status.state = PropagationClientState::AwaitingAdmission; + self.admission_started = Some(Instant::now()); + self.admission_progress = self.admission_started; + } + } + + #[cfg(test)] + fn handle_get_response(&mut self, data: &[u8]) { + self.handle_get_response_owned(Bytes::copy_from_slice(data)); + } + + fn poll_admissions(&mut self) { + while let Ok(result) = self.admission_rx.try_recv() { + if result.generation != self.admission_generation + || !self.pending_admissions.remove(&result.scope) + { + continue; + } + self.admission_progress = Some(Instant::now()); + match result.outcome { + DownloadAdmissionOutcome::Accepted(receipt) => { + match receipt.record().disposition { + crate::admission::DurableDisposition::Committed => { + self.status.admission.committed += 1 + } + crate::admission::DurableDisposition::Duplicate => { + self.status.admission.duplicate += 1 + } + crate::admission::DurableDisposition::PolicyDiscard => { + self.status.admission.policy_discarded += 1 + } + crate::admission::DurableDisposition::UserDeleted => { + self.status.admission.user_deleted += 1 + } + } + self.remember_durable_have(crate::admission::DurableHave::from_record( + receipt.record(), + )); + self.received_ids.push(result.scope.transient_id.to_vec()); + self.status.result = Some(self.status.result.unwrap_or(0).saturating_add(1)); + if self.suppression.get(&receipt.record().scope).is_some() { + self.suppression.remove(&receipt.record().scope); + self.suppression_dirty = true; + self.suppression_revision = self.suppression_revision.wrapping_add(1); + } + } + DownloadAdmissionOutcome::Rejected(reason) => { + self.admission_failures += 1; + self.status.admission.rejected += 1; + self.status.admission.retryable += usize::from(reason.is_transient()); + let now = crate::now_f64() as u64; + match self.suppression.record_failure( + result.scope, + reason, + self.admission_epochs, + now, + ) { + Ok(record) => { + self.suppression_updates.push(record.clone()); + self.suppression_dirty = true; + self.suppression_revision = self.suppression_revision.wrapping_add(1); + } + Err(_) => self.suppression_persist_failed = true, + } + } + } + } + if self.status.state == PropagationClientState::AwaitingAdmission { + if self.pending_admissions.is_empty() { + self.admission_started = None; + self.admission_progress = None; + self.send_next_chunk(); + } else if self + .admission_started + .is_some_and(|t| t.elapsed() >= Duration::from_secs(600)) + || self + .admission_progress + .is_some_and(|t| t.elapsed() >= Duration::from_secs(120)) + { + // Revokes authority only. External payload/worker leases remain live. + self.admission_generation = self.admission_generation.wrapping_add(1); + self.current_admission_generation + .store(self.admission_generation, Ordering::Release); + self.admission_failures += self.pending_admissions.len(); + self.status.admission.rejected += self.pending_admissions.len(); + self.status.admission.retryable += self.pending_admissions.len(); + self.pending_admissions.clear(); + self.received_messages.clear(); + self.send_next_chunk(); + } } - self.status.progress = 1.0; - self.send_next_chunk(); } fn decode_response_value(data: &[u8]) -> Result { @@ -1542,7 +1926,7 @@ impl PropagationClient { fn handle_purge_response(&mut self, response_data: &[u8]) { if !matches!(Self::decode_response_value(response_data), Ok(rmpv::Value::Array(items)) if items.is_empty()) { - self.status.state = PropagationClientState::Failed; + self.fail(); return; } match self.finish_request(response_data) { @@ -1558,19 +1942,22 @@ impl PropagationClient { } pub fn tick(&mut self) { + self.prune_suppression(); + self.poll_link_request(); self.flush_pending_transport(); self.poll_endpoint_control(); if self.status.state == PropagationClientState::Failed { self.cleanup(); return; } + self.poll_admissions(); if let Some(started) = self.started_at && started.elapsed() > self.timeout && self.status.state == PropagationClientState::LinkEstablishing { self.cleanup(); - self.status.state = PropagationClientState::Failed; + self.fail(); return; } @@ -1583,7 +1970,7 @@ impl PropagationClient { && response.waiting_since.elapsed() > request.timeout }) }) { - self.status.state = PropagationClientState::Failed; + self.fail(); self.cleanup(); return; } @@ -1603,9 +1990,9 @@ impl PropagationClient { rns_wire::flags::PacketType::Data, &payload, ); - self.status.state = PropagationClientState::Failed; + self.fail(); } - Some(LinkAction::Closed(_)) => self.status.state = PropagationClientState::Failed, + Some(LinkAction::Closed(_)) => self.fail(), Some(LinkAction::None) | None => {} } @@ -1619,7 +2006,7 @@ impl PropagationClient { match transfer.check_timeout() { TransferAction::SendRequest(request) => retry_requests.push(request), TransferAction::Failed(_) => { - self.status.state = PropagationClientState::Failed; + self.fail(); break; } _ => {} @@ -1649,8 +2036,11 @@ impl PropagationClient { PropagationClientState::ListRequested | PropagationClientState::GetRequested | PropagationClientState::Receiving - | PropagationClientState::PurgeRequested => {} - PropagationClientState::Complete | PropagationClientState::Failed => { + | PropagationClientState::PurgeRequested + | PropagationClientState::AwaitingAdmission => {} + PropagationClientState::Complete + | PropagationClientState::Partial + | PropagationClientState::Failed => { self.cleanup(); } } @@ -1691,7 +2081,7 @@ impl PropagationClient { if let Some(outbound) = outbound && !self.queue_link_endpoint(outbound) { - self.status.state = PropagationClientState::Failed; + self.fail(); } } @@ -1704,6 +2094,7 @@ impl PropagationClient { /// Snapshot selection once per cycle. Haves are purged before any wants; /// the configured message count limits the entire cycle, not each chunk. fn send_get_request(&mut self) { + self.prune_expired_haves(crate::now_f64() as u64); self.pending_haves.clear(); self.pending_wants.clear(); let mut seen = HashSet::new(); @@ -1716,6 +2107,23 @@ impl PropagationClient { self.pending_haves.push_back(id.clone()); } } else if self.pending_wants.len() < self.max_messages.unwrap_or(usize::MAX) { + let Ok(transient_id) = <[u8; 32]>::try_from(id.as_slice()) else { + continue; + }; + let scope = AdmissionScope { + identity: self.identity_hash(), + node: self.outbound_propagation_node.unwrap_or([0; 16]), + transient_id, + }; + if self.suppression_persist_failed + || self.suppression.saturated(scope.identity, scope.node) + || self + .suppression + .get(&scope) + .is_some_and(|r| r.active(crate::now_f64() as u64, self.admission_epochs)) + { + continue; + } self.pending_wants.push_back(id.clone()); } } @@ -1751,7 +2159,10 @@ impl PropagationClient { - 1; let mut low = 0; // Every valid transient ID consumes at least its 32 payload bytes. - let mut high = ids.len().min(MAX_EFFICIENT_SIZE / 32); + let mut high = ids + .len() + .min(MAX_DOWNLOAD_ITEMS) + .min(MAX_EFFICIENT_SIZE / 32); while low < high { let count = low + (high - low).div_ceil(2); if self.chunk_body(&ids[..count], get).len() <= MAX_EFFICIENT_SIZE - overhead { @@ -1764,9 +2175,13 @@ impl PropagationClient { } fn send_next_chunk(&mut self) { - if self.request.is_some() || self.status.state == PropagationClientState::Failed { + if self.request.is_some() + || !self.pending_admissions.is_empty() + || self.status.state == PropagationClientState::Failed + { return; } + self.prune_expired_haves(crate::now_f64() as u64); if !self.received_ids.is_empty() { self.send_purge_request(); } else if !self.pending_haves.is_empty() { @@ -1778,6 +2193,8 @@ impl PropagationClient { .collect(); let (count, data) = self.bounded_chunk(&ids, false); self.send_get_path_request(&data, RequestKind::Haves(count)); + } else if self.suppression_dirty || self.suppression_persist_failed { + self.status.state = PropagationClientState::AwaitingAdmission; } else if !self.pending_wants.is_empty() { let ids: Vec<_> = self .pending_wants @@ -1790,7 +2207,11 @@ impl PropagationClient { self.status.data_size = None; self.send_get_path_request(&data, RequestKind::Get(count)); } else { - self.status.state = PropagationClientState::Complete; + self.status.state = if self.admission_failures == 0 { + PropagationClientState::Complete + } else { + PropagationClientState::Partial + }; self.status.progress = 1.0; self.status.result.get_or_insert(0); } @@ -1803,27 +2224,27 @@ impl PropagationClient { fn send_get_path_request(&mut self, request_data: &[u8], kind: RequestKind) -> bool { if self.request.is_some() { - self.status.state = PropagationClientState::Failed; + self.fail(); return false; } let Some(link) = self.link.as_mut() else { - self.status.state = PropagationClientState::Failed; + self.fail(); return false; }; let timeout = link.default_request_timeout().max(Duration::from_secs(60)); let Ok((packed, id)) = link.prepare_request(MESSAGE_GET_PATH, Some(request_data), timeout) else { - self.status.state = PropagationClientState::Failed; + self.fail(); return false; }; if packed.len() > MAX_EFFICIENT_SIZE { link.fail_pending_request(&id); - self.status.state = PropagationClientState::Failed; + self.fail(); return false; } let Some(generation) = self.next_request_generation.checked_add(1) else { link.fail_pending_request(&id); - self.status.state = PropagationClientState::Failed; + self.fail(); return false; }; self.next_request_generation = generation; @@ -1832,7 +2253,7 @@ impl PropagationClient { let outbound = if resource { let Some(keys) = link.session_keys() else { link.fail_pending_request(&id); - self.status.state = PropagationClientState::Failed; + self.fail(); return false; }; let Ok(mut transfer) = OutboundTransfer::new_encrypted( @@ -1842,7 +2263,7 @@ impl PropagationClient { keys, ) else { link.fail_pending_request(&id); - self.status.state = PropagationClientState::Failed; + self.fail(); return false; }; transfer.resource.flags.is_request = true; @@ -1861,7 +2282,7 @@ impl PropagationClient { Ok(data) => Some(data), Err(_) => { link.fail_pending_request(&id); - self.status.state = PropagationClientState::Failed; + self.fail(); return false; } } @@ -1917,7 +2338,7 @@ impl PropagationClient { &data, ); } - Some(TransferAction::Failed(_)) => self.status.state = PropagationClientState::Failed, + Some(TransferAction::Failed(_)) => self.fail(), _ => {} } } @@ -1961,9 +2382,9 @@ impl PropagationClient { rns_wire::context::PacketContext::ResourceIcl, &hash, ); - self.status.state = PropagationClientState::Failed; + self.fail(); } - TransferAction::Failed(_) => self.status.state = PropagationClientState::Failed, + TransferAction::Failed(_) => self.fail(), _ => {} } if self.status.state == PropagationClientState::Failed { @@ -2039,26 +2460,56 @@ impl PropagationClient { Some(request.kind) } - fn handle_response_plaintext(&mut self, data: &[u8]) { - let Ok((id, response)) = Link::parse_response_plaintext(data) else { - return; + fn handle_response_owned(&mut self, data: Bytes) -> bool { + let mut cursor = std::io::Cursor::new(data.as_ref()); + if rmp::decode::read_array_len(&mut cursor).ok() != Some(2) + || rmp::decode::read_bin_len(&mut cursor).ok() != Some(16) + { + return false; + } + let start = cursor.position() as usize; + let Some(id) = data.get(start..start + 16) else { + return false; }; - if !self - .request - .as_ref() - .is_some_and(|request| request.id == id && Some(request.link_id) == self.link_id) - { - return; + if !self.request.as_ref().is_some_and(|request| { + request.id.as_slice() == id && Some(request.link_id) == self.link_id + }) { + return false; } - if !matches!(Self::decode_response_value(data), Ok(rmpv::Value::Array(fields)) if fields.len() == 2 && matches!(&fields[0], rmpv::Value::Binary(_)) && fields[1].is_array()) - { - self.status.state = PropagationClientState::Failed; - return; + let payload = data.slice(start + 16..); + if matches!( + self.request.as_ref().map(|r| r.kind), + Some(RequestKind::Get(_)) + ) { + self.handle_get_response_owned(payload); + } else { + self.handle_response_data(&payload); } - self.handle_response_data(&response); + true + } + + fn revoke_admissions(&mut self) { + self.admission_generation = self.admission_generation.wrapping_add(1); + self.current_admission_generation + .store(self.admission_generation, Ordering::Release); + self.pending_admissions.clear(); + self.received_messages.clear(); + self.unread_bytes = 0; + self.admission_started = None; + self.admission_progress = None; + } + fn fail(&mut self) { + // Revoke at the failure observation, before an adapter or later tick + // could accept a completed blocking worker under the old generation. + self.revoke_admissions(); + self.status.state = PropagationClientState::Failed; } fn cleanup(&mut self) { + self.link_request_result = None; + self.pending_transport + .retain(|message| !matches!(message, TransportMessage::SendLinkRequest { .. })); + self.revoke_admissions(); self.request = None; if let Some(link_id) = self.link_id { self.pending_transport.retain(|message| { @@ -2115,12 +2566,59 @@ impl PropagationClient { #[cfg(test)] mod tests { use super::*; + pub(super) fn fixture_download( + client: &PropagationClient, + data: Vec, + ) -> DownloadedPropagationMessage { + let scope = AdmissionScope { + identity: client.identity_hash(), + node: client.outbound_propagation_node.unwrap_or([0; 16]), + transient_id: rns_crypto::sha::full_hash(&data), + }; + let token = DownloadAdmissionToken::new( + scope, + client.admission_generation, + client.current_admission_generation.clone(), + client.admission_tx.clone(), + ); + DownloadedPropagationMessage::new( + retain_response(data.into(), client.unread_limit).unwrap(), + token, + ) + } + pub(super) fn downloaded_bytes(messages: &[DownloadedPropagationMessage]) -> Vec> { + messages.iter().map(|m| m.data().to_vec()).collect() + } + use rns_protocol::resource::OutboundTransfer; + fn prime_get(client: &mut PropagationClient, messages: &[Vec]) { + client.pending_wants = messages + .iter() + .map(|bytes| rns_crypto::sha::full_hash(bytes).to_vec()) + .collect(); + client.status.state = PropagationClientState::GetRequested; + client.request = Some(PendingRequest { + link_id: [1; 16], + generation: 1, + id: [2; 16], + kind: RequestKind::Get(messages.len()), + sender_active: false, + outbound: None, + response: None, + waiting_since: Some(Instant::now()), + timeout: Duration::from_secs(60), + }); + } fn next_link_request(rx: &mut mpsc::Receiver) -> OutboundRequest { while let Ok(message) = rx.try_recv() { match message { TransportMessage::Outbound(request) => return request, + TransportMessage::SendLinkRequest { request, result_tx } => { + let _ = result_tx.send(Ok(())); + return request; + } + TransportMessage::SendLinkEndpoint { request, result_tx, .. } => { @@ -2235,7 +2733,10 @@ mod tests { TransportMessage::RegisterDestination { .. } )); let outbound = rx.try_recv(); - assert!(matches!(outbound.unwrap(), TransportMessage::Outbound(_))); + assert!(matches!( + outbound.unwrap(), + TransportMessage::SendLinkRequest { .. } + )); } #[test] @@ -2273,7 +2774,7 @@ mod tests { client.tick(); assert!(matches!( rx.try_recv().unwrap(), - TransportMessage::Outbound(_) + TransportMessage::SendLinkRequest { .. } )); assert!(client.pending_transport.is_empty()); } @@ -2388,11 +2889,15 @@ mod tests { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.received_messages.push(vec![0x01, 0x02]); - client.received_messages.push(vec![0x03, 0x04]); + client + .received_messages + .push(fixture_download(&client, vec![0x01, 0x02])); + client + .received_messages + .push(fixture_download(&client, vec![0x03, 0x04])); assert_eq!(client.received_count(), 2); - let messages = client.take_received_messages(); + let messages = client.take_downloaded_messages(); assert_eq!(messages.len(), 2); assert_eq!(client.received_count(), 0); } @@ -2470,18 +2975,21 @@ mod tests { let mut buf = Vec::new(); rmpv::encode::write_value(&mut buf, &response).unwrap(); + prime_get(&mut client, &[msg1.clone(), msg2.clone()]); client.handle_get_response(&buf); assert_eq!(client.received_messages.len(), 2); - assert_eq!(client.received_messages[0], msg1); - assert_eq!(client.received_messages[1], msg2); - assert_eq!(client.received_ids.len(), 2); - assert_eq!( - client.received_ids[0], - rns_crypto::sha::full_hash(&msg1).to_vec() + assert_eq!(client.received_messages[0].data().as_ref(), msg1); + assert_eq!(client.received_messages[1].data().as_ref(), msg2); + assert!( + client.received_ids.is_empty(), + "uncommitted bytes grant no purge authority" ); - assert_eq!(client.received_ids[0].len(), 32); - assert_eq!(client.transfer_status().progress, 1.0); - assert_eq!(client.transfer_status().result, Some(2)); + assert_eq!( + client.received_messages[0].scope().transient_id, + rns_crypto::sha::full_hash(&msg1) + ); + assert_eq!(client.state(), PropagationClientState::AwaitingAdmission); + assert_eq!(client.transfer_status().result, None); } #[test] @@ -2490,6 +2998,7 @@ mod tests { let mut client = PropagationClient::new(tx, None, None); client.status.state = PropagationClientState::GetRequested; + prime_get(&mut client, &[]); let response = rmpv::Value::Array(vec![]); let mut buf = Vec::new(); rmpv::encode::write_value(&mut buf, &response).unwrap(); @@ -2505,9 +3014,11 @@ mod tests { client.status.state = PropagationClientState::Receiving; client.receiving_for = Some(PropagationClientState::GetRequested); + prime_get(&mut client, &[]); let response = rmpv::Value::Array(vec![]); let mut buf = Vec::new(); rmpv::encode::write_value(&mut buf, &response).unwrap(); + client.status.state = PropagationClientState::Receiving; client.handle_response_data(&buf); assert_eq!(client.status.state, PropagationClientState::Complete); @@ -2825,6 +3336,7 @@ mod tests { client .event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::LinkClose, @@ -2862,6 +3374,7 @@ mod tests { client .event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]), interface_id: 0, metrics: Default::default(), @@ -2890,6 +3403,7 @@ mod tests { client .event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::LinkClose, @@ -2909,3 +3423,10 @@ mod tests { #[cfg(test)] #[path = "propagation_client_tests.rs"] mod lifecycle_tests; + +impl Drop for PropagationClient { + fn drop(&mut self) { + self.current_admission_generation + .fetch_add(1, Ordering::AcqRel); + } +} diff --git a/crates/lxmf-core/src/propagation_client_tests.rs b/crates/lxmf-core/src/propagation_client_tests.rs index 02e6349..c27d94a 100644 --- a/crates/lxmf-core/src/propagation_client_tests.rs +++ b/crates/lxmf-core/src/propagation_client_tests.rs @@ -1,4 +1,5 @@ //! In-process encrypted peers: every emitted packet is checked at the real MTU. +use super::tests::{downloaded_bytes, fixture_download}; use super::*; use rmpv::Value; use rns_wire::{context::PacketContext as Context, flags::PacketType}; @@ -15,6 +16,8 @@ struct Peer { drop_hmu: bool, drop_request: bool, retries: usize, + admission_dir: tempfile::TempDir, + admitted: Vec>, } impl Peer { @@ -44,9 +47,52 @@ impl Peer { drop_hmu: false, drop_request: false, retries: 0, + admission_dir: tempfile::tempdir().unwrap(), + admitted: Vec::new(), } } + /// Protocol-unit-test recipient seam. The simulated decryptor maps each + /// opaque response to distinct actually signed bytes; FileAdmissionStore + /// must commit them before the client is allowed to send its purge. + fn accept_downloads(&mut self) { + use crate::admission::{ + AdmissionRecord, DownloadAdmissionOutcome, DurableAdmissionReceipt, DurableDisposition, + }; + let store = crate::admission_store::FileAdmissionStore::open( + self.admission_dir.path(), + &self.admission_dir.path().join("messages"), + ) + .unwrap(); + for downloaded in self.client.take_downloaded_messages() { + let (data, token) = downloaded.into_parts(); + let scope = token.scope(); + let message = crate::message::test_message( + [1; 16], + [2; 16], + &hex::encode(scope.transient_id), + "simulated recipient decryption", + crate::constants::DeliveryMethod::Propagated, + ); + let record = AdmissionRecord { + scope, + message_id: message.message_id(), + received_wire_hash: rns_crypto::sha::full_hash(message.wire_bytes()), + stored_message_wire_hash: None, + disposition: DurableDisposition::Committed, + committed_at: 100, + }; + let receipt = + DurableAdmissionReceipt::commit(store.prepare(record, message.wire_owned(), false)) + .unwrap(); + self.admitted.push(data.to_vec()); + token + .resolve(DownloadAdmissionOutcome::Accepted(receipt)) + .unwrap(); + } + self.client.poll_admissions(); + } + fn inject(&mut self, context: Context, payload: &[u8]) { let raw = PropagationClient::link_packet_bytes( self.link.link_id, @@ -65,6 +111,7 @@ impl Peer { self.client .event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: raw.into(), interface_id: 7, metrics: Default::default(), @@ -279,19 +326,20 @@ impl Peer { } } +fn blob(index: usize) -> Vec { + let mut data = (0u64..5) + .flat_map(|v| rns_crypto::sha::full_hash(&v.to_be_bytes())) + .collect::>(); + data[..8].copy_from_slice(&(index as u64).to_be_bytes()); + data +} fn ids(n: usize) -> Vec> { (0..n) - .map(|i| rns_crypto::sha::full_hash(&(i as u64).to_be_bytes()).to_vec()) + .map(|i| rns_crypto::sha::full_hash(&blob(i)).to_vec()) .collect() } fn blobs(n: usize) -> Vec> { - (0..n) - .map(|i| { - let mut data = ids(5).concat(); - data[..8].copy_from_slice(&(i as u64).to_be_bytes()); - data - }) - .collect() + (0..n).map(blob).collect() } fn binary_list(items: &[Vec]) -> Value { Value::Array(items.iter().cloned().map(Value::Binary).collect()) @@ -353,12 +401,22 @@ fn fifty_downloaded_messages_survive_get_and_purge_resource_round_trip() { assert_eq!(request.as_array().unwrap()[0], binary_list(&wants)); peer.response(get_id, binary_list(&messages), true); assert_eq!(peer.client.received_count(), 50); + assert_eq!( + peer.client.state(), + PropagationClientState::AwaitingAdmission + ); + peer.accept_downloads(); let (purge_id, request, _) = peer.request(true); assert_eq!(request, Value::Array(vec![Value::Nil, binary_list(&wants)])); peer.response(purge_id, empty(), true); assert_eq!(peer.client.state(), PropagationClientState::Complete); assert_eq!(peer.client.transfer_status().result, Some(50)); - assert_eq!(peer.client.take_received_messages(), messages); + let counts = peer.client.transfer_status().admission; + assert_eq!(counts.downloaded, 50); + assert_eq!(counts.committed, 50); + assert_eq!(counts.rejected, 0); + assert_eq!(counts.retryable, 0); + assert_eq!(peer.admitted, messages); assert_eq!(peer.resource_requests, 2); assert_eq!(peer.client.unread_bytes, 0); } @@ -381,6 +439,7 @@ fn early_response_retires_sender_and_ignores_late_proof_cancel_and_receipt() { .resource .resource_hash; peer.response(old_id, binary_list(&blobs(1)), false); + peer.accept_downloads(); let new_request = peer.client.request.as_ref().unwrap(); assert_ne!(old_id, new_request.id); let generation = new_request.generation; @@ -450,23 +509,23 @@ fn purge_errors_never_complete_or_advance_chunk() { #[test] fn capacity_failure_precedes_publication_purge_and_cursor_advance() { let mut peer = Peer::new(); - peer.client.unread_limit = 100; - peer.client.received_messages.push(vec![1; 20]); - peer.client.unread_bytes = 20; - peer.client.available_messages = ids(2); + peer.client.unread_limit = 80; + let retained = vec![fixture_download(&peer.client, vec![1; 20])]; + let over_limit = vec![vec![2; 60], vec![3; 30]]; + peer.client.available_messages = over_limit + .iter() + .map(|bytes| rns_crypto::sha::full_hash(bytes).to_vec()) + .collect(); peer.client.send_get_request(); let (id, _, _) = peer.request(true); - peer.response(id, binary_list(&[vec![2; 60], vec![3; 30]]), false); + peer.response(id, binary_list(&over_limit), false); assert_eq!(peer.client.state(), PropagationClientState::Failed); assert_eq!(peer.client.pending_wants.len(), 2); assert!(peer.client.received_ids.is_empty()); - assert_eq!(peer.client.received_messages, vec![vec![1; 20]]); - assert_eq!(peer.client.unread_bytes, 20); + assert!(peer.client.received_messages.is_empty()); + assert_eq!(peer.client.unread_bytes, 0); + assert_eq!(downloaded_bytes(&retained), vec![vec![1; 20]]); assert!(peer.rx.try_recv().is_err(), "overflow must not queue purge"); - assert!(!peer.client.start_download()); - peer.client.cancel_download(); - assert!(!peer.client.start_download()); - assert_eq!(peer.client.take_received_messages(), vec![vec![1; 20]]); } #[test] @@ -525,33 +584,37 @@ fn oversized_logical_sets_advance_after_empty_and_partial_chunks() { peer.client.available_messages = selected.clone(); peer.client.available_messages.push(selected[0].clone()); peer.client.send_get_request(); - let first = peer.client.request.as_ref().unwrap(); - let RequestKind::Get(first_count) = first.kind else { - panic!() - }; - assert!(first_count < 30_840); - assert!( - first - .outbound - .as_ref() - .unwrap() - .resource - .advertisement_data_size - <= MAX_EFFICIENT_SIZE - ); - let id = first.id; - // Correlated early empty response skips the complete requested chunk. - peer.response(id, empty(), false); - let RequestKind::Get(tail_count) = peer.client.request.as_ref().unwrap().kind else { - panic!() - }; - assert_eq!(first_count + tail_count, 30_840); - let tail = peer.client.request.as_ref().unwrap().id; - peer.response(tail, binary_list(&blobs(1)), false); + let mut consumed = 0; + loop { + let request = peer.client.request.as_ref().unwrap(); + let RequestKind::Get(count) = request.kind else { + panic!("get chunk expected") + }; + assert!(count <= crate::admission::MAX_DOWNLOAD_ITEMS); + assert!(count > 0); + if let Some(transfer) = &request.outbound { + assert!(transfer.resource.advertisement_data_size <= MAX_EFFICIENT_SIZE); + } + let id = request.id; + if consumed + count < 30_840 { + peer.response(id, empty(), false); + consumed += count; + continue; + } + assert_eq!(consumed + count, 30_840); + peer.response(id, binary_list(&[blob(consumed)]), false); + break; + } assert!(peer.client.pending_wants.is_empty()); + assert!(peer.client.received_ids.is_empty()); + assert_eq!( + peer.client.state(), + PropagationClientState::AwaitingAdmission + ); + peer.accept_downloads(); assert_eq!(peer.client.received_ids.len(), 1); - let purge = peer.client.request.as_ref().unwrap().id; - peer.response(purge, empty(), false); + let id = peer.client.request.as_ref().unwrap().id; + peer.response(id, empty(), false); assert_eq!(peer.client.state(), PropagationClientState::Complete); assert_eq!(peer.client.transfer_status().result, Some(1)); } @@ -563,18 +626,20 @@ fn known_haves_chunks_complete_and_retain_policy_skips_only_known_haves() { peer.client.available_messages = selected.clone(); peer.client.replace_local_message_ids(selected); peer.client.send_get_request(); - let RequestKind::Haves(first) = peer.client.request.as_ref().unwrap().kind else { - panic!() - }; - assert!(first < 30_840); - let id = peer.client.request.as_ref().unwrap().id; - peer.response(id, empty(), false); - assert_eq!(peer.client.pending_haves.len(), 30_840 - first); - let id = peer.client.request.as_ref().unwrap().id; - peer.response(id, empty(), false); - assert!(peer.client.pending_haves.is_empty()); + let mut chunks = 0; + while !peer.client.pending_haves.is_empty() { + let request = peer.client.request.as_ref().unwrap(); + let RequestKind::Haves(count) = request.kind else { + panic!("haves chunk expected") + }; + assert!(count > 0 && count <= crate::admission::MAX_DOWNLOAD_ITEMS); + let id = request.id; + peer.response(id, empty(), false); + chunks += 1; + assert!(chunks <= 8); + } + assert_eq!(chunks, 8); assert_eq!(peer.client.state(), PropagationClientState::Complete); - let mut peer = Peer::new(); peer.client.available_messages = ids(2); peer.client.replace_local_message_ids(ids(1)); @@ -583,7 +648,12 @@ fn known_haves_chunks_complete_and_retain_policy_skips_only_known_haves() { let (id, data, _) = peer.request(true); assert_eq!(data.as_array().unwrap()[0], binary_list(&ids(2)[1..])); assert_eq!(data.as_array().unwrap()[1], empty()); - peer.response(id, binary_list(&blobs(1)), false); + peer.response(id, binary_list(&[blob(1)]), false); + assert_eq!( + peer.client.state(), + PropagationClientState::AwaitingAdmission + ); + peer.accept_downloads(); assert!(matches!( peer.client.request.as_ref().unwrap().kind, RequestKind::Purge(1) @@ -604,15 +674,21 @@ fn hashmap_updates_and_split_responses_keep_exact_request_identity() { assert_eq!(peer.client.state(), PropagationClientState::Complete); let mut peer = Peer::new(); - peer.client.available_messages = ids(1); + let blob = vec![0x5a; MAX_EFFICIENT_SIZE + 100]; + peer.client.available_messages = vec![rns_crypto::sha::full_hash(&blob).to_vec()]; peer.client.set_delivery_limit(2000.0); peer.client.send_get_request(); let (id, _, _) = peer.request(true); let blob = vec![0x5a; MAX_EFFICIENT_SIZE + 100]; peer.response(id, binary_list(std::slice::from_ref(&blob)), true); - assert_eq!(peer.client.received_messages, vec![blob]); - assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested); + assert_eq!(downloaded_bytes(&peer.client.received_messages), vec![blob]); + assert_eq!( + peer.client.state(), + PropagationClientState::AwaitingAdmission + ); assert!(peer.client.inbound_split_resources.is_empty()); + peer.accept_downloads(); + assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested); } #[test] @@ -777,10 +853,9 @@ fn advertisement_requires_matching_request_id_and_response_direction() { } #[test] -fn malformed_batch_is_atomic_and_preserves_prior_results() { +fn malformed_batch_is_atomic_and_preserves_external_payload_owners() { let mut peer = Peer::new(); - peer.client.received_messages.push(vec![0xab; 20]); - peer.client.unread_bytes = 20; + let retained = vec![fixture_download(&peer.client, vec![0xab; 20])]; peer.client.available_messages = ids(2); peer.client.send_get_request(); let (id, _, _) = peer.request(true); @@ -790,14 +865,15 @@ fn malformed_batch_is_atomic_and_preserves_prior_results() { false, ); assert_eq!(peer.client.state(), PropagationClientState::Failed); - assert_eq!(peer.client.received_messages, vec![vec![0xab; 20]]); - assert_eq!(peer.client.unread_bytes, 20); + assert_eq!(downloaded_bytes(&retained), vec![vec![0xab; 20]]); + assert!(peer.client.received_messages.is_empty()); + assert_eq!(peer.client.unread_bytes, 0); assert!(peer.client.received_ids.is_empty()); assert_eq!(peer.client.pending_wants.len(), 2); } #[test] -fn accepted_results_survive_purge_failure_cancel_and_disconnect_until_drained() { +fn durable_results_survive_purge_failure_and_external_owners_survive_cancellation() { for failure in 0..3 { let mut peer = Peer::new(); let messages = blobs(50); @@ -806,31 +882,55 @@ fn accepted_results_survive_purge_failure_cancel_and_disconnect_until_drained() let (id, _, _) = peer.request(true); peer.response(id, binary_list(&messages), true); assert_eq!(peer.client.received_count(), 50); - match failure { - 0 => { - let (id, _, _) = peer.request(true); - peer.response(id, Value::from(0xf0), false); - peer.client.tick(); - } - 1 => peer.client.cancel_download(), - _ => { + assert_eq!( + peer.client.state(), + PropagationClientState::AwaitingAdmission + ); + if failure == 0 { + peer.accept_downloads(); + let (id, _, _) = peer.request(true); + peer.response(id, Value::from(0xf0), false); + peer.client.tick(); + assert_eq!(peer.admitted, messages); + assert_eq!(peer.client.local_messages.len(), 50); + let store = crate::admission_store::FileAdmissionStore::open( + peer.admission_dir.path(), + &peer.admission_dir.path().join("messages"), + ) + .unwrap(); + assert_eq!(store.haves([0; 16], [0xe8; 16], 101).len(), 50); + } else { + let downloaded = peer.client.take_downloaded_messages(); + if failure == 1 { + peer.client.cancel_download(); + } else { let teardown = peer.link.teardown(CloseReason::DestinationClosed).unwrap(); peer.inject(Context::LinkClose, &teardown); } + assert!(peer.client.received_messages.is_empty()); + assert_eq!(downloaded_bytes(&downloaded), messages); + assert!( + downloaded + .iter() + .all(|item| !item.scope().transient_id.iter().all(|b| *b == 0)) + ); + for item in downloaded { + let (_, token) = item.into_parts(); + assert!(!token.is_current()); + } + peer.client.poll_admissions(); + assert!(peer.client.local_messages.is_empty()); + assert!(peer.client.received_ids.is_empty()); + assert!(peer.client.start_download()); + assert!(peer.client.take_downloaded_messages().is_empty()); } - assert!(!peer.client.start_download()); - assert_eq!(peer.client.take_received_messages(), messages); - assert_eq!(peer.client.unread_bytes, 0); - assert!(peer.client.start_download()); - assert!(peer.client.take_received_messages().is_empty()); } } #[test] fn transport_result_deadline_is_finite_and_retains_results() { let mut peer = Peer::new(); - peer.client.received_messages.push(vec![0x33; 10]); - peer.client.unread_bytes = 10; + let retained = vec![fixture_download(&peer.client, vec![0x33; 10])]; peer.client.received_ids = ids(50); peer.client.send_purge_request(); let pending = peer.client.pending_endpoint_sends.last_mut().unwrap(); @@ -838,8 +938,11 @@ fn transport_result_deadline_is_finite_and_retains_results() { peer.client.tick(); assert_eq!(peer.client.state(), PropagationClientState::Failed); assert!(peer.client.request.is_none()); - assert!(!peer.client.start_download()); - assert_eq!(peer.client.take_received_messages(), vec![vec![0x33; 10]]); + assert_eq!(downloaded_bytes(&retained), vec![vec![0x33; 10]]); + for item in retained { + let (_, token) = item.into_parts(); + assert!(!token.is_current()); + } } #[test] @@ -924,7 +1027,7 @@ fn slow_segment_gets_a_fresh_proof_admission_deadline() { let (context, proof, _) = peer.packet(); assert_eq!(context, Context::ResourcePrf); assert!(sender.handle_proof(&proof)); - assert_eq!(peer.client.received_messages, messages); + assert_eq!(downloaded_bytes(&peer.client.received_messages), messages); } #[test] @@ -934,6 +1037,7 @@ fn response_resource_before_request_proof_retires_only_its_sender() { peer.client.send_get_request(); let (id, _, proof) = peer.request(false); peer.response(id, binary_list(&blobs(50)), true); + peer.accept_downloads(); let successor = peer.client.request.as_ref().unwrap().id; let generation = peer.client.request.as_ref().unwrap().generation; peer.inject(Context::ResourcePrf, &proof.unwrap()); @@ -942,11 +1046,11 @@ fn response_resource_before_request_proof_retires_only_its_sender() { let (id, _, _) = peer.request(true); peer.response(id, empty(), false); assert_eq!(peer.client.state(), PropagationClientState::Complete); - assert_eq!(peer.client.received_count(), 50); + assert_eq!(peer.admitted.len(), 50); } #[test] -fn full_then_closed_transport_fails_request_without_losing_accepted_results() { +fn full_then_closed_transport_fails_request_without_releasing_external_payload() { let mut peer = Peer::new(); while peer .client @@ -954,8 +1058,7 @@ fn full_then_closed_transport_fails_request_without_losing_accepted_results() { .try_send(TransportMessage::DeregisterDestination { hash: [0; 16] }) .is_ok() {} - peer.client.received_messages.push(vec![1; 12]); - peer.client.unread_bytes = 12; + let retained = vec![fixture_download(&peer.client, vec![1; 12])]; peer.client.received_ids = ids(50); peer.client.send_purge_request(); assert_eq!(peer.client.pending_transport.len(), 1); @@ -964,5 +1067,207 @@ fn full_then_closed_transport_fails_request_without_losing_accepted_results() { peer.client.tick(); assert_eq!(peer.client.state(), PropagationClientState::Failed); assert!(peer.client.request.is_none()); - assert_eq!(peer.client.take_received_messages(), vec![vec![1; 12]]); + assert_eq!(downloaded_bytes(&retained), vec![vec![1; 12]]); +} + +#[test] +fn expired_durable_haves_are_downloaded_instead_of_purged() { + use crate::admission::DurableHave; + let mut peer = Peer::new(); + let expired = [0x81; 32]; + let visible = [0x82; 32]; + peer.client.replace_durable_haves([ + DurableHave { + transient_id: expired, + expires_at: Some(0), + }, + DurableHave { + transient_id: visible, + expires_at: None, + }, + ]); + peer.client.available_messages = vec![expired.to_vec(), visible.to_vec()]; + peer.client.send_get_request(); + let (id, request, _) = peer.request(true); + assert_eq!( + request, + Value::Array(vec![Value::Nil, binary_list(&[visible.to_vec()])]) + ); + assert!(!peer.client.local_messages.contains(expired.as_slice())); + peer.response(id, empty(), false); + let (_, request, _) = peer.request(true); + assert_eq!( + request.as_array().unwrap()[0], + binary_list(&[expired.to_vec()]) + ); +} + +#[test] +fn expiry_preserves_the_counted_request_and_prunes_the_next_purge() { + use crate::admission::DurableHave; + let mut peer = Peer::new(); + let all = ids(MAX_DOWNLOAD_ITEMS + 1); + let expires_later: [u8; 32] = all.last().unwrap().as_slice().try_into().unwrap(); + peer.client + .replace_durable_haves(all.iter().map(|id| DurableHave { + transient_id: id.as_slice().try_into().unwrap(), + expires_at: None, + })); + peer.client.available_messages = all.clone(); + peer.client.send_get_request(); + let (id, request, _) = peer.request(true); + assert_eq!( + request.as_array().unwrap()[1].as_array().unwrap().len(), + MAX_DOWNLOAD_ITEMS + ); + assert!(matches!( + peer.client.request.as_ref().unwrap().kind, + RequestKind::Haves(MAX_DOWNLOAD_ITEMS) + )); + peer.client + .local_message_expiry + .insert(expires_later.to_vec(), 1); + peer.client.prune_expired_haves(1); + // The in-flight response still accounts for exactly its original prefix. + assert_eq!( + peer.client + .pending_haves + .iter() + .cloned() + .collect::>(), + all + ); + assert!( + !peer + .client + .local_messages + .contains(expires_later.as_slice()) + ); + peer.response(id, empty(), false); + assert!(peer.client.pending_haves.is_empty()); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + assert!( + peer.rx.is_empty(), + "expired tail must not produce another purge" + ); + + // Fresh accepted receipts use the same last-moment check before purge. + peer.client.received_ids = vec![expires_later.to_vec()]; + peer.client.send_next_chunk(); + assert!(peer.client.received_ids.is_empty()); + assert!(peer.rx.is_empty()); +} + +#[test] +fn discard_receipts_expire_after_ninety_days_and_visible_receipts_do_not() { + use crate::admission::{AdmissionRecord, AdmissionScope, DurableDisposition, DurableHave}; + for disposition in [ + DurableDisposition::Committed, + DurableDisposition::Duplicate, + DurableDisposition::PolicyDiscard, + DurableDisposition::UserDeleted, + ] { + let record = AdmissionRecord { + scope: AdmissionScope { + identity: [1; 16], + node: [2; 16], + transient_id: [3; 32], + }, + message_id: [4; 32], + received_wire_hash: [5; 32], + stored_message_wire_hash: None, + disposition, + committed_at: 100, + }; + let have = DurableHave::from_record(&record); + if matches!( + disposition, + DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted + ) { + assert_eq!(have.expires_at, Some(100 + 90 * 86400)); + assert!(have.active(100 + 90 * 86400 - 1)); + assert!(!have.active(100 + 90 * 86400)); + } else { + assert_eq!(have.expires_at, None); + assert!(have.active(u64::MAX)); + } + } +} + +#[test] +fn stale_suppression_checkpoint_cannot_acknowledge_newer_pruning_or_epochs() { + use crate::admission::{AdmissionEpochs, AdmissionScope, SuppressionLedger, SuppressionReason}; + for expired in [true, false] { + let mut peer = Peer::new(); + let mut ledger = SuppressionLedger::default(); + let epochs = AdmissionEpochs::default(); + let at = if expired { 0 } else { crate::now_f64() as u64 }; + ledger + .record_failure( + AdmissionScope { + identity: [1; 16], + node: [2; 16], + transient_id: [3; 32], + }, + SuppressionReason::InvalidStamp, + epochs, + at, + ) + .unwrap(); + peer.client.set_suppression_ledger(ledger, epochs); + let checkpoint = peer.client.suppression_revision(); + if expired { + peer.client.prune_suppression(); + } else { + peer.client.update_admission_epochs(AdmissionEpochs { + policy: [1; 32], + ..epochs + }); + } + peer.client.suppression_persist_failed = true; + assert_eq!(peer.client.suppression_ledger().records().count(), 0); + assert_ne!(peer.client.suppression_revision(), checkpoint); + assert!(!peer.client.acknowledge_suppression_persistence(checkpoint)); + assert!(peer.client.suppression_persistence_pending()); + assert!(peer.client.suppression_persist_failed); + assert!( + peer.client + .acknowledge_suppression_persistence(peer.client.suppression_revision()) + ); + assert!(!peer.client.suppression_persistence_pending()); + assert!(!peer.client.suppression_persist_failed); + assert_eq!(peer.client.suppression_ledger().records().count(), 0); + } +} + +#[test] +fn rejected_and_retryable_download_counts_never_become_purge_authority() { + use crate::admission::{DownloadAdmissionOutcome, SuppressionReason}; + let mut peer = Peer::new(); + let messages = blobs(2); + peer.client.available_messages = ids(2); + peer.client.send_get_request(); + let (id, _, _) = peer.request(true); + peer.response(id, binary_list(&messages), false); + for (item, reason) in peer.client.take_downloaded_messages().into_iter().zip([ + SuppressionReason::InvalidSignature, + SuppressionReason::MissingKey, + ]) { + let (_, token) = item.into_parts(); + token + .resolve(DownloadAdmissionOutcome::Rejected(reason)) + .unwrap(); + } + peer.client.poll_admissions(); + let counts = peer.client.transfer_status().admission; + assert_eq!(counts.downloaded, 2); + assert_eq!(counts.rejected, 2); + assert_eq!(counts.retryable, 1); + assert_eq!( + counts.committed + counts.duplicate + counts.policy_discarded + counts.user_deleted, + 0 + ); + assert!(peer.client.local_messages.is_empty()); + assert!(peer.client.received_ids.is_empty()); + assert!(peer.rx.is_empty(), "no durable acceptance means no purge"); } diff --git a/crates/lxmf-core/src/propagation_node.rs b/crates/lxmf-core/src/propagation_node.rs index b91bb1a..46c0de9 100644 --- a/crates/lxmf-core/src/propagation_node.rs +++ b/crates/lxmf-core/src/propagation_node.rs @@ -9,7 +9,6 @@ use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use crate::constants::*; -use crate::message::LxMessage; use crate::peer::{LxmPeer, OutboundOfferPolicy}; use crate::propagation::{PropagationEntry, PropagationStore, hex_encode}; use crate::propagation_admission::PnOfferCandidate; @@ -55,6 +54,78 @@ pub struct OfferRequestContext<'a> { pub remote_identity_hash: Option<&'a [u8; 16]>, } +/// Borrow the validated ID lists; never expand untrusted GET input to a Value tree. +struct BorrowedGetRequest<'a> { + wants: Option<&'a [u8]>, + haves: Option<&'a [u8]>, + limit_bytes: Option, +} +fn parse_get_request(mut input: &[u8]) -> Option> { + let count = rmp::decode::read_array_len(&mut input).ok()?; + if !(2..=3).contains(&count) { + return None; + } + fn ids<'a>(input: &mut &'a [u8]) -> Option> { + if input.first() == Some(&0xc0) { + *input = &input[1..]; + return Some(None); + } + let count = rmp::decode::read_array_len(input).ok()? as usize; + if count > input.len() / 34 { + return None; + } + let start = *input; + for _ in 0..count { + if rmp::decode::read_bin_len(input).ok()? != 32 || input.len() < 32 { + return None; + } + *input = &input[32..]; + } + Some(Some(&start[..start.len() - input.len()])) + } + let wants = ids(&mut input)?; + let haves = ids(&mut input)?; + let limit_bytes = if count == 3 { + // Only one scalar number is decoded; containers and strings are refused + // before the general decoder can allocate. + if !matches!( + input.first(), + Some(0x00..=0x7f | 0xca..=0xcf | 0xd0..=0xd3 | 0xe0..=0xff) + ) { + return None; + } + let value = rmpv::decode::read_value(&mut input).ok()?; + let kb = value + .as_f64() + .or_else(|| value.as_u64().map(|v| v as f64)) + .or_else(|| value.as_i64().map(|v| v as f64))?; + let bytes = kb * BYTES_PER_KILOBYTE as f64; + if !kb.is_finite() || kb < 0.0 || !bytes.is_finite() { + return None; + } + Some(bytes) + } else { + None + }; + input.is_empty().then_some(BorrowedGetRequest { + wants, + haves, + limit_bytes, + }) +} +fn get_ids(input: Option<&[u8]>) -> impl Iterator + '_ { + let mut input = input.unwrap_or_default(); + std::iter::from_fn(move || { + if input.is_empty() { + return None; + } + rmp::decode::read_bin_len(&mut input).expect("validated ID"); + let id = input[..32].try_into().expect("validated ID length"); + input = &input[32..]; + Some(id) + }) +} + /// Outcome of [`PropagationNode::handle_get_request`]. Phases 1/3 (and /// malformed input) are answered from the store alone; phase 2 returns a /// read plan so the embedder performs blocking file I/O after releasing @@ -76,9 +147,16 @@ impl GetRequestAction { /// and admitted by the client's transfer limit. This lets the daemon keep /// Python-compatible served-message accounting without repeating I/O. pub fn into_response_with_served_count(self) -> (Vec, u64) { + self.into_response_with_served_count_bounded(rns_protocol::resource::MAX_RESOURCE_SIZE) + } + + /// Resolve on a blocking worker with its previously reserved local response + /// allowance. Complete messages are skipped when they cannot fit. + pub fn into_response_with_served_count_bounded(self, maximum: usize) -> (Vec, u64) { match self { - GetRequestAction::Respond(bytes) => (bytes, 0), - GetRequestAction::ServeFiles(plan) => plan.serve_with_count(), + GetRequestAction::Respond(bytes) if bytes.len() <= maximum => (bytes, 0), + GetRequestAction::Respond(_) => (vec![0xc0], 0), + GetRequestAction::ServeFiles(plan) => plan.serve_with_count_bounded(maximum), } } } @@ -88,6 +166,7 @@ impl GetRequestAction { #[derive(Debug)] pub struct GetServePlan { reads: Vec, + retirements: PropagationRetirementPlan, /// Client transfer limit in bytes (wire value is kB ×1000, Python parity). limit_bytes: Option, } @@ -96,6 +175,7 @@ pub struct GetServePlan { struct PlannedRead { path: PathBuf, stamped: bool, + stored_size: usize, } impl GetServePlan { @@ -109,31 +189,166 @@ impl GetServePlan { } fn serve_with_count(&self) -> (Vec, u64) { - use rmpv::Value; + self.serve_with_count_bounded(rns_protocol::resource::MAX_RESOURCE_SIZE) + } + fn serve_with_count_bounded(&self, maximum: usize) -> (Vec, u64) { + let maximum = maximum.min(rns_protocol::resource::MAX_RESOURCE_SIZE); + if maximum < 5 { + return (vec![0xc0], 0); + } + + if self.retirements.persist().is_err() { + return (vec![0xc0], 0); + } const PER_MESSAGE_OVERHEAD: f64 = 16.0; let mut cumulative_size: f64 = 24.0; - let mut messages: Vec = Vec::new(); + // Reserve one fixed-size output image. A single bounded verified file + // exists alongside it; no stripped copy or recursive Value tree does. + let mut response = Vec::new(); + let allocation = self + .reads + .iter() + .fold(5usize, |size, read| { + size.saturating_add(read.stored_size).saturating_add(5) + }) + .min(maximum); + if response.try_reserve_exact(allocation).is_err() { + return (vec![0xc0], 0); + } + let mut served = 0u32; for read in &self.reads { - let Ok(data) = std::fs::read(&read.path) else { + let Some(payload_size) = + read.stored_size + .checked_sub(if read.stamped { 32 } else { 0 }) + else { continue; }; - let next_size = cumulative_size + data.len() as f64 + PER_MESSAGE_OVERHEAD; + let prefix = if payload_size <= u8::MAX as usize { + 2 + } else if payload_size <= u16::MAX as usize { + 3 + } else { + 5 + }; + let array_prefix = if served + 1 < 16 { + 1 + } else if served < u16::MAX as u32 { + 3 + } else { + 5 + }; + if payload_size + .checked_add(prefix) + .and_then(|size| response.len().checked_add(size)) + .and_then(|size| size.checked_add(array_prefix)) + .is_none_or(|size| size > maximum) + { + continue; + } + let next_size = cumulative_size + read.stored_size as f64 + PER_MESSAGE_OVERHEAD; if self.limit_bytes.is_some_and(|limit| next_size > limit) { continue; } - cumulative_size = next_size; - let payload = if read.stamped && data.len() >= 32 { - data[..data.len() - 32].to_vec() - } else { - data + let Ok(data) = crate::propagation_store_v2::read_validated_file_bounded( + &read.path, + read.stored_size, + ) else { + continue; }; - messages.push(Value::Binary(payload)); + if data.len() != read.stored_size { + continue; + } + cumulative_size = next_size; + if prefix == 2 { + response.extend_from_slice(&[0xc4, payload_size as u8]); + } else if prefix == 3 { + response.push(0xc5); + response.extend_from_slice(&(payload_size as u16).to_be_bytes()); + } else { + response.push(0xc6); + response.extend_from_slice(&(payload_size as u32).to_be_bytes()); + } + response.extend_from_slice(&data[..payload_size]); + served += 1; } - let served = messages.len() as u64; - (crate::encode_value(&Value::Array(messages)), served) + // Prepend the canonical array header in the already reserved buffer. + let header: Vec = if served < 16 { + vec![0x90 | served as u8] + } else if served <= u16::MAX as u32 { + let mut h = vec![0xdc]; + h.extend_from_slice(&(served as u16).to_be_bytes()); + h + } else { + let mut h = vec![0xdd]; + h.extend_from_slice(&served.to_be_bytes()); + h + }; + let payload_len = response.len(); + let final_len = payload_len + header.len(); + response.resize(final_len, 0); + response.copy_within(0..payload_len, header.len()); + response[..header.len()].copy_from_slice(&header); + response.truncate(final_len); + (response, u64::from(served)) + } +} + +/// Committed retirements become invisible immediately, including to snapshots +/// captured while a blocking deletion worker was running. A node later reaps +/// counters under its short owner lock. +#[derive(Debug, Default)] +struct RetiredEntries { + ids: std::sync::Mutex>, + generation: std::sync::atomic::AtomicU64, +} +impl RetiredEntries { + fn contains(&self, id: &PathBuf) -> bool { + self.ids + .lock() + .unwrap_or_else(|e| e.into_inner()) + .contains(id) + } + fn commit(&self, id: PathBuf) { + if self + .ids + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(id) + { + // Rust 1.99 renamed this operation; keep the identical Rust 1.89 API. + #[allow(deprecated)] + let _ = self.generation.fetch_update( + std::sync::atomic::Ordering::AcqRel, + std::sync::atomic::Ordering::Acquire, + |v| Some(v.saturating_add(1)), + ); + } + } +} +/// Blocking durable cull/purge work. Capture under the node lock; run on a +/// bounded blocking worker after releasing it. Failed publication retains the +/// active entry and cannot authorize a successful remote purge response. +#[derive(Debug)] +pub struct PropagationRetirementPlan { + entries: Vec, + retired: std::sync::Arc, +} +impl PropagationRetirementPlan { + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + pub fn persist(&self) -> std::io::Result<()> { + for path in &self.entries { + if self.retired.contains(path) { + continue; + } + crate::propagation_store_v2::retire_object(path)?; + self.retired.commit(path.clone()); + } + Ok(()) } } @@ -152,19 +367,113 @@ pub fn read_planned_messages( ) -> Vec<(PropagationTransientId, Vec)> { plan.iter() .filter_map(|read| { - std::fs::read(&read.path) + crate::propagation_store_v2::read_validated_file(&read.path) .ok() .map(|data| (read.transient_id, data)) }) .collect() } +/// An opaque stamped deposit with validated stamp work. Construction does not +/// claim the relay can decrypt or mathematically identify ciphertext. +#[derive(Debug)] +pub struct ValidatedOpaquePropagationBlob { + bytes: bytes::Bytes, + transient_id: PropagationTransientId, + stamp_value: u8, +} +impl ValidatedOpaquePropagationBlob { + pub fn validate(bytes: bytes::Bytes, minimum_stamp_cost: u8) -> Option { + if bytes.len() < DESTINATION_LENGTH + 1 + 32 + || bytes.len() > rns_protocol::resource::MAX_RESOURCE_SIZE + { + return None; + } + let body = &bytes[..bytes.len() - 32]; + let stamp: &[u8; 32] = bytes[bytes.len() - 32..].try_into().ok()?; + let transient_id = rns_crypto::sha::full_hash(body); + let workblock = + crate::stamper::stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN); + let stamp_value = crate::stamper::stamp_value(&workblock, stamp).min(255) as u8; + (stamp_value >= minimum_stamp_cost).then_some(Self { + bytes, + transient_id, + stamp_value, + }) + } + pub fn transient_id(&self) -> PropagationTransientId { + self.transient_id + } + pub fn stamp_value(&self) -> u8 { + self.stamp_value + } +} +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PropagationAdmissionOutcome { + Pending, + Committed, + Failed, +} +#[derive(Debug)] +struct AdmissionReservation { + content_hash: [u8; 32], + size: usize, + result: tokio::sync::watch::Sender, +} +impl Drop for AdmissionReservation { + fn drop(&mut self) { + if *self.result.borrow() == PropagationAdmissionOutcome::Pending { + self.result + .send_replace(PropagationAdmissionOutcome::Failed); + } + } +} +/// Await only outside validation/storage worker slots. This observer cannot +/// persist, commit, revoke, or manufacture another admission's authority. +#[derive(Debug)] +pub struct PropagationAdmissionWaiter { + result: tokio::sync::watch::Receiver, +} +impl PropagationAdmissionWaiter { + pub async fn wait(mut self) -> PropagationAdmissionOutcome { + loop { + let current = *self.result.borrow_and_update(); + if current != PropagationAdmissionOutcome::Pending { + return current; + } + if self.result.changed().await.is_err() { + return PropagationAdmissionOutcome::Failed; + } + } + } +} +/// Revalidate retained ciphertext and its committed provenance off the actor +/// before a duplicate can earn a proof. +#[derive(Debug)] +pub struct PropagationDuplicateCheck { + path: PathBuf, +} +impl PropagationDuplicateCheck { + pub fn verify(self) -> std::io::Result<()> { + crate::propagation_store_v2::verify_committed_object(&self.path) + } +} +#[derive(Debug)] +pub enum PropagationAdmission { + Reserved(Box), + CommittedDuplicate(PropagationDuplicateCheck), + Pending(PropagationAdmissionWaiter), + Rejected, +} + /// One propagation-store admission reserved under the node lock. Persist it /// on a blocking worker, then commit the returned value under a short lock. #[derive(Debug)] pub struct PropagationStoreWritePlan { entry: PropagationEntry, data: Vec, + manifest: crate::propagation_store_v2::EntryManifest, + reservation: std::sync::Arc, path: Option, } @@ -178,14 +487,22 @@ impl PropagationStoreWritePlan { } /// Perform the potentially blocking durable write. Disk-backed nodes use - /// atomic temp-file replacement; in-memory nodes complete immediately. + /// strict platform publication; volatile nodes cannot acknowledge storage. pub fn persist(self) -> std::io::Result { - if let Some(ref path) = self.path { - crate::persist::write_file_atomic(path, &self.data)?; + let path = self.path.as_ref().ok_or_else(|| { + std::io::Error::other("volatile propagation nodes cannot issue durable admission") + })?; + if crate::propagation_store_v2::deletion_path(path).exists() { + return Err(std::io::Error::other( + "prior relay deletion needs reconciliation before readmission", + )); } + let (manifest, path) = + crate::propagation_store_v2::publish_object(path, &self.manifest, &self.data)?; Ok(PersistedPropagationStoreWrite { - entry: self.entry, - path: self.path, + entry: manifest.entry(), + path: Some(path), + reservation: self.reservation, }) } } @@ -196,6 +513,7 @@ impl PropagationStoreWritePlan { pub struct PersistedPropagationStoreWrite { entry: PropagationEntry, path: Option, + reservation: std::sync::Arc, } #[derive(Debug, Clone)] @@ -327,6 +645,8 @@ pub struct PropagationNode { sync_sessions: HashMap<[u8; 16], SyncSession>, pub dest_hash: [u8; 16], storage_path: Option, + object_paths: HashMap, + _store_lock: Option, /// Transitional pre-1.1 behavior; removed when the daemon-lifetime /// `PnInboundAdmission` becomes the live throttle owner. last_offer_times: HashMap<[u8; 16], f64>, @@ -338,7 +658,9 @@ pub struct PropagationNode { /// duplicate acceptance and storage-cap oversubscription while I/O is in /// flight. pending_write_ids: HashSet, + pending_admissions: HashMap>, pending_write_bytes: usize, + retired: std::sync::Arc, } impl PropagationNode { @@ -350,13 +672,21 @@ impl PropagationNode { sync_sessions: HashMap::new(), dest_hash, storage_path: None, + object_paths: HashMap::new(), + _store_lock: None, last_offer_times: HashMap::new(), offer_generation: 0, pending_write_ids: HashSet::new(), + pending_admissions: HashMap::new(), pending_write_bytes: 0, + retired: std::sync::Arc::new(RetiredEntries::default()), } } + pub fn is_durable(&self) -> bool { + self.storage_path.is_some() + } + pub fn min_stamp_cost(&self) -> u8 { self.config.min_stamp_cost } @@ -366,7 +696,11 @@ impl PropagationNode { } pub fn offer_generation(&self) -> u64 { - self.offer_generation + self.offer_generation.saturating_add( + self.retired + .generation + .load(std::sync::atomic::Ordering::Acquire), + ) } /// Apply the daemon's destination deny policy to the authoritative hosted @@ -404,17 +738,21 @@ impl PropagationNode { dest_hash: [u8; 16], storage_path: PathBuf, ) -> std::io::Result { - std::fs::create_dir_all(&storage_path)?; + let (storage_path, lock) = crate::propagation_store_v2::open_locked_store(&storage_path)?; let mut node = Self { config, store: PropagationStore::new(), sync_sessions: HashMap::new(), dest_hash, storage_path: Some(storage_path), + object_paths: HashMap::new(), + _store_lock: Some(lock), last_offer_times: HashMap::new(), offer_generation: 0, pending_write_ids: HashSet::new(), + pending_admissions: HashMap::new(), pending_write_bytes: 0, + retired: std::sync::Arc::new(RetiredEntries::default()), }; node.load_from_disk()?; Ok(node) @@ -425,6 +763,7 @@ impl PropagationNode { entry: PropagationEntry, data: Vec, ) -> Option { + self.reap_retired(); let transient_id = entry.transient_id; if self.store.contains(&transient_id) || self.pending_write_ids.contains(&transient_id) { return None; @@ -441,17 +780,40 @@ impl PropagationNode { return None; } + let (result, _) = tokio::sync::watch::channel(PropagationAdmissionOutcome::Pending); + let reservation = std::sync::Arc::new(AdmissionReservation { + content_hash: rns_crypto::sha::full_hash(&data), + size: data.len(), + result, + }); + self.pending_admissions + .insert(transient_id, std::sync::Arc::downgrade(&reservation)); self.pending_write_ids.insert(transient_id); self.pending_write_bytes = self.pending_write_bytes.saturating_add(data.len()); + let manifest = crate::propagation_store_v2::EntryManifest::from_entry(&entry, &data); let path = self .storage_path .as_ref() - .map(|dir| dir.join(entry.filename())); - Some(PropagationStoreWritePlan { entry, data, path }) + .map(|dir| dir.join("objects").join(manifest.filename())); + Some(PropagationStoreWritePlan { + entry, + data, + manifest, + reservation, + path, + }) } /// Release a reservation after a failed blocking write. pub fn abort_store_write(&mut self, transient_id: &PropagationTransientId, size: usize) { + if self + .pending_admissions + .get(transient_id) + .is_some_and(|weak| weak.upgrade().is_some()) + { + return; + } + self.pending_admissions.remove(transient_id); if self.pending_write_ids.remove(transient_id) { self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size); } @@ -462,22 +824,31 @@ impl PropagationNode { pub fn commit_store_write(&mut self, persisted: PersistedPropagationStoreWrite) -> bool { let transient_id = persisted.entry.transient_id; let size = persisted.entry.size; + if self + .pending_admissions + .get(&transient_id) + .and_then(|weak| weak.upgrade()) + .is_none_or(|owner| !std::sync::Arc::ptr_eq(&owner, &persisted.reservation)) + { + return false; + } + self.pending_admissions.remove(&transient_id); if !self.pending_write_ids.remove(&transient_id) { - if let Some(path) = persisted.path { - let _ = std::fs::remove_file(path); - } return false; } self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size); - - let inserted = self.store.insert(persisted.entry); + let inserted = !self.store.contains(&transient_id) && self.store.insert(persisted.entry); if inserted { + if let Some(path) = persisted.path { + self.object_paths.insert(transient_id, path); + } self.advance_offer_generation(); - } else if let Some(path) = persisted.path { - // Reservation loss/duplicate commit is exceptional; cleanup is a - // short best-effort operation and never occurs on normal traffic. - let _ = std::fs::remove_file(path); } + persisted.reservation.result.send_replace(if inserted { + PropagationAdmissionOutcome::Committed + } else { + PropagationAdmissionOutcome::Failed + }); inserted } @@ -498,117 +869,6 @@ impl PropagationNode { } } - /// Returns `true` if the message was stored, `false` on duplicate, overflow, - /// pack failure, oversized message, or insufficient stamp. - #[tracing::instrument( - level = "debug", - name = "propagation.accept_message", - skip_all, - fields( - transient_id = message.transient_id.as_ref().map(|tid| hex::encode(&tid[..8])), - size = message.content.len(), - ), - )] - pub fn plan_accept_message( - &mut self, - message: &LxMessage, - ) -> Option { - let hash = message.hash?; - - let transient_id = message.transient_id.unwrap_or(hash); - if self.store.contains(&transient_id) { - return None; - } - - let packed = message.pack().ok()?; - let msg_size = packed.len(); - - if msg_size > self.config.max_message_size { - return None; - } - - // Compute stamp value via HKDF workblock over full_hash(packed) using - // PN expand rounds. Matches Python LXStamper.validate_pn_stamp(). - let sv = if let Some(ref stamp) = message.stamp { - let transient_id_full = rns_crypto::sha::full_hash(&packed); - let workblock = crate::stamper::stamp_workblock( - &transient_id_full, - crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, - ); - if let Ok(stamp) = <&[u8; 32]>::try_from(stamp.as_slice()) { - crate::stamper::stamp_value(&workblock, stamp) as u8 - } else { - 0 - } - } else { - 0 - }; - - if self.config.min_stamp_cost > 0 && sv < self.config.min_stamp_cost { - return None; - } - - let mut entry = - PropagationEntry::new(transient_id, hash, message.destination_hash, msg_size, sv); - entry.stored_at = message.timestamp; - - self.reserve_store_write(entry, packed) - } - - pub fn accept_message(&mut self, message: &LxMessage) -> bool { - let Some(plan) = self.plan_accept_message(message) else { - return false; - }; - self.persist_reserved(plan) - } - - /// Store an already propagation-packed LXMF blob (`dest_hash || encrypted_data`). - /// - /// This is the normal client -> propagation-node ingress path. Unlike - /// [`Self::accept_message`], the node cannot decrypt or unpack this data; - /// it indexes by the transient ID and serves the raw blob back to the - /// destination client during `/get`. - pub fn plan_accept_propagated_blob( - &mut self, - lxmf_data: &[u8], - stamp_value: u8, - ) -> Option { - if lxmf_data.len() < DESTINATION_LENGTH + 1 { - return None; - } - if self.config.min_stamp_cost > 0 && stamp_value < self.config.min_stamp_cost { - return None; - } - - let transient_id = rns_crypto::sha::full_hash(lxmf_data); - if self.store.contains(&transient_id) { - return None; - } - if lxmf_data.len() > self.config.max_message_size { - return None; - } - - let mut destination_hash = [0u8; 16]; - destination_hash.copy_from_slice(&lxmf_data[..DESTINATION_LENGTH]); - - let entry = PropagationEntry::new( - transient_id, - transient_id, - destination_hash, - lxmf_data.len(), - stamp_value, - ); - - self.reserve_store_write(entry, lxmf_data.to_vec()) - } - - pub fn accept_propagated_blob(&mut self, lxmf_data: &[u8], stamp_value: u8) -> bool { - let Some(plan) = self.plan_accept_propagated_blob(lxmf_data, stamp_value) else { - return false; - }; - self.persist_reserved(plan) - } - /// Store a validated propagated LXMF blob with its propagation-node stamp. /// /// Canonical propagation-node storage mirrors upstream Python: keep @@ -621,38 +881,86 @@ impl PropagationNode { stamp_data: &[u8; 32], stamp_value: u8, ) -> Option { - if lxmf_data.len() < DESTINATION_LENGTH + 1 { + let mut bytes = Vec::with_capacity(lxmf_data.len().checked_add(32)?); + if lxmf_data.len().checked_add(32)? > self.config.max_message_size { return None; } - if self.config.min_stamp_cost > 0 && stamp_value < self.config.min_stamp_cost { + bytes.extend_from_slice(lxmf_data); + bytes.extend_from_slice(stamp_data); + let blob = + ValidatedOpaquePropagationBlob::validate(bytes.into(), self.config.min_stamp_cost)?; + if blob.stamp_value() != stamp_value { return None; } - - let transient_id = rns_crypto::sha::full_hash(lxmf_data); - if self.store.contains(&transient_id) { - return None; + match self.plan_opaque_admission(blob) { + PropagationAdmission::Reserved(plan) => Some(*plan), + _ => None, } - - let mut stored_data = Vec::with_capacity(lxmf_data.len() + stamp_data.len()); - stored_data.extend_from_slice(lxmf_data); - stored_data.extend_from_slice(stamp_data); - - if stored_data.len() > self.config.max_message_size { - return None; + } + /// Preferred network admission API. Same-TID exact-image duplicates share + /// the original completion and never perform a second disk write. + pub fn plan_opaque_admission( + &mut self, + blob: ValidatedOpaquePropagationBlob, + ) -> PropagationAdmission { + self.reap_retired(); + // Clear cancelled reservation accounting only after its actual owner + // has exited; a weak observer never prolongs ownership or byte leases. + let stale = self + .pending_admissions + .iter() + .filter_map(|(id, weak)| weak.upgrade().is_none().then_some(*id)) + .collect::>(); + for id in stale { + self.pending_admissions.remove(&id); + self.pending_write_ids.remove(&id); } - - let mut destination_hash = [0u8; 16]; - destination_hash.copy_from_slice(&lxmf_data[..DESTINATION_LENGTH]); - + self.pending_write_bytes = self + .pending_admissions + .values() + .filter_map(|w| w.upgrade()) + .fold(0usize, |n, r| n.saturating_add(r.size)); + if !self.is_durable() + || blob.stamp_value < self.config.min_stamp_cost + || blob.bytes.len() > self.config.max_message_size + { + return PropagationAdmission::Rejected; + } + if self.contains(&blob.transient_id) { + return self + .object_paths + .get(&blob.transient_id) + .cloned() + .map(|path| { + PropagationAdmission::CommittedDuplicate(PropagationDuplicateCheck { path }) + }) + .unwrap_or(PropagationAdmission::Rejected); + } + if let Some(owner) = self + .pending_admissions + .get(&blob.transient_id) + .and_then(|w| w.upgrade()) + { + if owner.content_hash != rns_crypto::sha::full_hash(&blob.bytes) { + return PropagationAdmission::Rejected; + } + return PropagationAdmission::Pending(PropagationAdmissionWaiter { + result: owner.result.subscribe(), + }); + } + let mut destination = [0; 16]; + destination.copy_from_slice(&blob.bytes[..16]); let entry = PropagationEntry::new_stamped( - transient_id, - transient_id, - destination_hash, - stored_data.len(), - stamp_value, + blob.transient_id, + blob.transient_id, + destination, + blob.bytes.len(), + blob.stamp_value, ); - - self.reserve_store_write(entry, stored_data) + match self.reserve_store_write(entry, blob.bytes.to_vec()) { + Some(plan) => PropagationAdmission::Reserved(Box::new(plan)), + None => PropagationAdmission::Rejected, + } } pub fn accept_stamped_propagated_blob( @@ -670,155 +978,104 @@ impl PropagationNode { } fn load_from_disk(&mut self) -> std::io::Result<()> { - let dir = match &self.storage_path { - Some(d) => d, - None => return Ok(()), - }; - - if !dir.exists() { + let Some(root) = self.storage_path.as_ref() else { return Ok(()); - } - - let mut loaded = 0; - let mut quarantined = 0; - for entry in std::fs::read_dir(dir)? { - // One unreadable directory entry or file must not abort the whole - // store load — quarantine it and keep loading the rest. - let entry = match entry { - Ok(e) => e, - Err(e) => { - tracing::warn!(error = %e, "skipping unreadable messagestore entry"); - quarantined += 1; - continue; - } - }; - let path = entry.path(); - if !path.is_file() { + }; + crate::propagation_store_v2::reconcile_deletions(root)?; + let objects = root.join("objects"); + for file in std::fs::read_dir(&objects)? { + let path = file?.path(); + if path.extension().and_then(|s| s.to_str()) != Some("active") { continue; } - - let filename = match path.file_name().and_then(|f| f.to_str()) { - Some(f) => f.to_string(), - None => continue, - }; - - if filename.ends_with(".peer") - || filename.ends_with(".msgpack") - || filename.ends_with(".corrupt") - { + let object = crate::propagation_store_v2::indexed_object(&path)?; + if crate::propagation_store_v2::deletion_path(&object).exists() { continue; } - - if let Some((tid, ts, sv)) = PropagationEntry::parse_filename(&filename) { - let data = match std::fs::read(&path) { - Ok(d) => d, - Err(e) => { - tracing::warn!( - file = %path.display(), - error = %e, - "quarantining unreadable propagation message" - ); - let _ = std::fs::rename(&path, path.with_extension("corrupt")); - quarantined += 1; - continue; - } - }; - let size = data.len(); - - if self.store.contains(&tid) { - continue; - } - - let mut message_hash = [0u8; 32]; - message_hash.copy_from_slice(&rns_crypto::sha::full_hash(&data)); - - // Opaque propagated blobs are stored as `dest_hash || encrypted_data` - // and cannot be unpacked by the node. Recover the routing key from - // the first 16 bytes before trying the legacy full-message path. - let mut destination_hash = [0u8; 16]; - if data.len() >= DESTINATION_LENGTH { - destination_hash.copy_from_slice(&data[..DESTINATION_LENGTH]); - } - - let mut pe = - PropagationEntry::new_stamped(tid, message_hash, destination_hash, size, sv); - pe.stored_at = ts; - - // Older app hosts persisted opaque blobs without their PN - // stamp. Their filename TID hashes the entire file, whereas - // canonical stamped storage hashes the file before its final - // 32-byte stamp. Recover that exact legacy representation so - // client /get cannot truncate ciphertext after a restart. - // This distinguishes storage format, not stamp authenticity; - // retain the existing policy for other opaque/malformed files. - if data.len() > DESTINATION_LENGTH && message_hash == tid { - pe.stamped = false; - } - - if let Ok(msg) = LxMessage::unpack(&data) { - pe.message_hash = msg.hash.unwrap_or([0u8; 32]); - pe.destination_hash = msg.destination_hash; - pe.stamped = false; - } - - if self.store.insert(pe) { - loaded += 1; - } + let (meta, _) = crate::propagation_store_v2::read_manifest(&object)?; + crate::propagation_store_v2::verify_committed_object(&object)?; + if self.store.contains(&meta.transient_id) { + return Err(std::io::Error::other("duplicate relay TID")); } + self.object_paths.insert(meta.transient_id, object); + self.store.insert(meta.entry()); } - - if loaded > 0 || quarantined > 0 { - tracing::info!(loaded, quarantined, "loaded propagation messages from disk"); - } - if loaded > 0 { + if !self.store.is_empty() { self.advance_offer_generation(); } - Ok(()) } - - /// Periodic maintenance: cull expired entries, enforce the storage cap by - /// weight (Python `clean_message_store` parity — makes room for new - /// messages instead of wedging at the ingest reject), and clean up - /// orphaned files. - pub fn tick(&mut self) { - let before = self.store.len(); - self.store.cull_expired(self.config.max_message_age); - self.store.cull_by_weight(self.config.max_storage); - let after = self.store.len(); - - if before != after { - self.advance_offer_generation(); - } - - if before > after - && let Some(ref dir) = self.storage_path - { - self.cleanup_orphaned_files(dir); + fn eligible(&self, id: &PropagationTransientId) -> bool { + self.object_paths + .get(id) + .is_none_or(|path| !self.retired.contains(path)) + } + fn reap_retired(&mut self) { + let removed = + std::mem::take(&mut *self.retired.ids.lock().unwrap_or_else(|e| e.into_inner())); + let ids = self + .object_paths + .iter() + .filter_map(|(id, path)| removed.contains(path).then_some(*id)) + .collect::>(); + for id in ids { + self.store.remove(&id); + self.object_paths.remove(&id); } } - - fn cleanup_orphaned_files(&self, dir: &std::path::Path) { - if let Ok(entries) = std::fs::read_dir(dir) { - for entry in entries.flatten() { - let path = entry.path(); - if !path.is_file() { - continue; - } - let filename = match path.file_name().and_then(|f| f.to_str()) { - Some(f) => f.to_string(), - None => continue, - }; - if filename.ends_with(".peer") || filename.ends_with(".msgpack") { - continue; - } - if let Some((tid, _, _)) = PropagationEntry::parse_filename(&filename) - && !self.store.contains(&tid) - { - let _ = std::fs::remove_file(&path); - } + fn retirement_plan( + &self, + ids: impl IntoIterator, + ) -> PropagationRetirementPlan { + let entries = ids + .into_iter() + .filter(|id| self.eligible(id)) + .filter_map(|id| self.object_paths.get(&id).cloned()) + .collect(); + PropagationRetirementPlan { + entries, + retired: std::sync::Arc::clone(&self.retired), + } + } + /// Select maintenance without filesystem IO. The caller runs persist off + /// the actor and drops this plan after actual completion. + pub fn plan_maintenance(&mut self) -> PropagationRetirementPlan { + self.reap_retired(); + let now = crate::now_f64(); + let cutoff = now - self.config.max_message_age as f64; + let mut ids = Vec::new(); + let mut remaining = self.store.total_size(); + let mut weighted = Vec::new(); + for entry in self.store.entries() { + if entry.stored_at < cutoff { + ids.push(entry.transient_id); + remaining = remaining.saturating_sub(entry.size); + } else { + weighted.push(( + entry.transient_id, + self.store.compute_weight(entry, now), + entry.size, + )); } } + weighted.sort_by(|a, b| b.1.total_cmp(&a.1)); + for (id, _, size) in weighted { + if remaining <= self.config.max_storage { + break; + } + ids.push(id); + remaining = remaining.saturating_sub(size); + } + self.retirement_plan(ids) + } + /// Blocking compatibility wrapper. Async hosts use plan_maintenance and + /// execute its durable operations on their bounded storage worker. + pub fn tick(&mut self) { + let plan = self.plan_maintenance(); + if let Err(error) = plan.persist() { + tracing::warn!(%error,"relay maintenance remains pending"); + } + self.reap_retired(); } /// When `peer_min_stamp_cost` is `Some`, include only messages whose stamp @@ -833,10 +1090,15 @@ impl PropagationNode { Some(min_cost) if min_cost > 0 => self .store .entries() - .filter(|e| e.stamp_value >= min_cost) + .filter(|e| self.eligible(&e.transient_id) && e.stamp_value >= min_cost) + .map(|e| e.transient_id) + .collect(), + _ => self + .store + .entries() + .filter(|e| self.eligible(&e.transient_id)) .map(|e| e.transient_id) .collect(), - _ => self.store.transient_ids(), } } @@ -853,7 +1115,10 @@ impl PropagationNode { } pub fn message_count(&self) -> usize { - self.store.len() + self.store + .entries() + .filter(|e| self.eligible(&e.transient_id)) + .count() } /// Count live store entries not yet handled by one peer. The daemon's @@ -866,16 +1131,22 @@ impl PropagationNode { ) -> usize { self.store .entries() - .filter(|entry| !handled_messages.contains(&entry.transient_id)) + .filter(|entry| { + self.eligible(&entry.transient_id) + && !handled_messages.contains(&entry.transient_id) + }) .count() } pub fn total_size(&self) -> usize { - self.store.total_size() + self.store + .entries() + .filter(|e| self.eligible(&e.transient_id)) + .fold(0usize, |n, e| n.saturating_add(e.size)) } pub fn contains(&self, transient_id: &PropagationTransientId) -> bool { - self.store.contains(transient_id) + self.eligible(transient_id) && self.store.contains(transient_id) } pub fn get_session(&self, peer_hash: &[u8; 16]) -> Option<&SyncSession> { @@ -1005,7 +1276,7 @@ impl PropagationNode { local_hash, remote_hash, self.config.peering_cost, - |transient_id| self.store.contains(transient_id), + |transient_id| self.contains(transient_id), ) { Ok(evaluation) => evaluation.into_wire_response(), Err(error) => error.wire_response(), @@ -1032,7 +1303,7 @@ impl PropagationNode { &remote_identity_hash, self.config.peering_cost, self.config.max_offer_size, - |transient_id| self.store.contains(transient_id), + |transient_id| self.contains(transient_id), ) } @@ -1051,113 +1322,115 @@ impl PropagationNode { request_data: &[u8], client_dest_hash: &[u8; 16], ) -> GetRequestAction { - use rmpv::Value; - - let value: rmpv::Value = match rmpv::decode::read_value(&mut &request_data[..]) { - Ok(v) => v, - Err(_) => return GetRequestAction::Respond(crate::encode_value(&Value::Nil)), - }; - - let arr = match value.as_array() { - Some(a) if a.len() >= 2 => a, - _ => return GetRequestAction::Respond(crate::encode_value(&Value::Nil)), - }; - - let wants_is_nil = arr[0].is_nil(); - let haves_is_nil = arr[1].is_nil(); - - fn parse_store_id(value: &rmpv::Value) -> Option { - let id_bytes = value.as_slice()?; - match id_bytes.len() { - 32 => { - let mut tid = [0u8; 32]; - tid.copy_from_slice(id_bytes); - Some(tid) - } - _ => None, - } - } - - if wants_is_nil && haves_is_nil { - // Phase 1: list available messages for this client, smallest first. - let mut available = self.store.entries_for_destination(client_dest_hash); - available.sort_by_key(|e| e.size); - let id_list: Vec = available - .iter() - .map(|e| Value::Binary(e.transient_id.to_vec())) - .collect(); - GetRequestAction::Respond(crate::encode_value(&Value::Array(id_list))) - } else if wants_is_nil && !haves_is_nil { - // Phase 3: purge messages the client already received. Python - // returns the (empty) response_messages list here. - if let Some(haves_arr) = arr[1].as_array() { - for have_val in haves_arr { - if let Some(tid) = parse_store_id(have_val) { - self.purge_client_entry(&tid, client_dest_hash); - } - } - } - GetRequestAction::Respond(crate::encode_value(&Value::Array(Vec::new()))) - } else { - // Phase 2: purge haves first (Python order — an ID in both wants - // and haves is purged, not served), then resolve wants into a - // read plan executed after the node lock is released. - if let Some(haves_arr) = arr[1].as_array() { - for have_val in haves_arr { - if let Some(tid) = parse_store_id(have_val) { - self.purge_client_entry(&tid, client_dest_hash); - } - } - } - - let mut reads = Vec::new(); - if let Some(wants_arr) = arr[0].as_array() { - for want_val in wants_arr { - if let (Some(tid), Some(dir)) = - (parse_store_id(want_val), self.storage_path.as_ref()) - && let Some(entry) = self.store.get(&tid) - { - // Ownership gate (Python LXMRouter.py:1479): a client - // may only download messages addressed to itself. - if entry.destination_hash == *client_dest_hash { - reads.push(PlannedRead { - path: dir.join(entry.filename()), - stamped: entry.stamped, - }); - } - } - } - } - - // Wire value is decimal kilobytes (Python LXMRouter.py:1471). - let limit_bytes = if arr.len() > 2 { - arr[2].as_f64().map(|kb| kb * BYTES_PER_KILOBYTE as f64) - } else { - None - }; - - GetRequestAction::ServeFiles(GetServePlan { reads, limit_bytes }) - } + self.handle_get_request_bounded( + request_data, + client_dest_hash, + rns_protocol::resource::MAX_RESOURCE_SIZE, + ) } - /// Remove a store entry on a client's behalf — only when the entry is - /// addressed to that client (Python LXMRouter.py:1454 ownership gate); - /// foreign transient IDs are ignored. - fn purge_client_entry(&mut self, tid: &PropagationTransientId, client_dest_hash: &[u8; 16]) { - let owned = self - .store - .get(tid) - .is_some_and(|entry| entry.destination_hash == *client_dest_hash); - if !owned { - return; + /// Plan a GET under a caller-reserved transfer budget. No native I/O occurs + /// here; resolve the plan on the worker retaining that reservation. + pub fn handle_get_request_bounded( + &mut self, + request_data: &[u8], + client_dest_hash: &[u8; 16], + maximum_response_bytes: usize, + ) -> GetRequestAction { + let Some(request) = parse_get_request(request_data) else { + return GetRequestAction::Respond(vec![0xc0]); + }; + let maximum_response_bytes = + maximum_response_bytes.min(rns_protocol::resource::MAX_RESOURCE_SIZE); + if maximum_response_bytes < 5 { + return GetRequestAction::Respond(vec![0xc0]); } - if let Some(entry) = self.store.remove(tid) { - self.advance_offer_generation(); - if let Some(ref dir) = self.storage_path { - let path = dir.join(entry.filename()); - let _ = std::fs::remove_file(&path); + if request.wants.is_none() && request.haves.is_none() { + // Select only the smallest IDs that fit. A list request cannot + // allocate an index proportional to the entire retained store. + let count = maximum_response_bytes.saturating_sub(5) / 34; + let mut available = std::collections::BinaryHeap::new(); + for entry in self.store.entries() { + if entry.destination_hash != *client_dest_hash + || !self.eligible(&entry.transient_id) + { + continue; + } + if available.len() < count { + available.push((entry.size, entry.transient_id)); + } else if available + .peek() + .is_some_and(|largest| (entry.size, entry.transient_id) < *largest) + { + available.pop(); + available.push((entry.size, entry.transient_id)); + } + } + let available = available.into_sorted_vec(); + let mut response = Vec::with_capacity(5 + 34 * available.len()); + rmp::encode::write_array_len(&mut response, available.len() as u32).expect("Vec write"); + for (_, id) in available { + response.extend_from_slice(&[0xc4, 32]); + response.extend_from_slice(&id); + } + return GetRequestAction::Respond(response); + } + // The deferred owner charges 16×raw input and 16 MiB scratch. Charge + // every retained ID/path before cloning it; unusual long local paths + // cannot exceed that reservation. Failure creates no retirement plan. + let mut planning_left = request_data + .len() + .saturating_mul(8) + .saturating_add(8 * 1024 * 1024); + let mut retired_ids = HashSet::new(); + for tid in get_ids(request.haves) { + if self + .store + .get(&tid) + .is_some_and(|e| e.destination_hash == *client_dest_hash) + && !retired_ids.contains(&tid) + { + let path_len = self + .object_paths + .get(&tid) + .map_or(0, |p| p.as_os_str().len()); + let charge = 256usize.saturating_add(path_len.saturating_mul(2)); + let Some(left) = planning_left.checked_sub(charge) else { + return GetRequestAction::Respond(vec![0xc0]); + }; + planning_left = left; + retired_ids.insert(tid); } } + let mut reads = Vec::new(); + let mut seen = HashSet::new(); + for tid in get_ids(request.wants) { + if let Some(entry) = self.store.get(&tid) + && entry.destination_hash == *client_dest_hash + && self.eligible(&tid) + && !retired_ids.contains(&tid) + && !seen.contains(&tid) + && let Some(path) = self.object_paths.get(&tid) + { + let charge = 256usize.saturating_add(path.as_os_str().len().saturating_mul(2)); + let Some(left) = planning_left.checked_sub(charge) else { + return GetRequestAction::Respond(vec![0xc0]); + }; + planning_left = left; + seen.insert(tid); + reads.push(PlannedRead { + path: path.clone(), + stamped: entry.stamped, + stored_size: entry.size, + }); + } + } + let retirements = self.retirement_plan(retired_ids); + GetRequestAction::ServeFiles(GetServePlan { + reads, + retirements, + limit_bytes: request.limit_bytes, + }) } /// Resolve requested transient IDs into store-file read plans (no I/O). @@ -1167,7 +1440,7 @@ impl PropagationNode { &self, requested_ids: &[PropagationTransientId], ) -> Vec { - let dir = match &self.storage_path { + let _dir = match &self.storage_path { Some(d) => d, None => return Vec::new(), }; @@ -1175,10 +1448,13 @@ impl PropagationNode { requested_ids .iter() .filter_map(|tid| { - self.store.get(tid).map(|entry| PlannedMessageRead { - transient_id: *tid, - path: dir.join(entry.filename()), - }) + self.store + .get(tid) + .filter(|_| self.eligible(tid)) + .map(|_entry| PlannedMessageRead { + transient_id: *tid, + path: self.object_paths[tid].clone(), + }) }) .collect() } @@ -1216,6 +1492,7 @@ impl PropagationNode { let candidates = self .store .entries() + .filter(|entry| self.eligible(&entry.transient_id)) .map(|entry| SyncOfferCandidateSnapshot { transient_id: entry.transient_id, weight: self.store.compute_weight(entry, now), @@ -1230,7 +1507,7 @@ impl PropagationNode { SyncOfferPreparationSnapshot { policy: policy.clone(), - generation: self.offer_generation, + generation: self.offer_generation(), peer_path, candidates, } @@ -1243,11 +1520,11 @@ impl PropagationNode { &mut self, prepared: PreparedSyncOffer, ) -> InstallPreparedSyncOffer { - if prepared.generation != self.offer_generation + if prepared.generation != self.offer_generation() || prepared .selected_ids .iter() - .any(|transient_id| !self.store.contains(transient_id)) + .any(|transient_id| !self.contains(transient_id)) { return InstallPreparedSyncOffer::Stale; } @@ -1421,7 +1698,7 @@ impl PropagationNode { /// through on every sync — grow with total propagated volume forever. /// Files converge lazily: the next `mark_peer_handled` saves the pruned set. fn prune_handled_against_store(&self, peer: &mut LxmPeer) { - peer.handled_messages.retain(|id| self.store.contains(id)); + peer.handled_messages.retain(|id| self.contains(id)); } } @@ -1438,15 +1715,113 @@ impl std::fmt::Debug for PropagationNode { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::constants::DeliveryMethod; - fn make_signed_message(dest: [u8; 16], src: [u8; 16], title: &str, content: &str) -> LxMessage { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new(dest, src, title, content, DeliveryMethod::Propagated); - msg.sign(&key).unwrap(); - msg + // Real opaque relay fixtures: ID derives from ciphertext, and stamp value is + // measured from the exact retained blob. Timestamp below is a test arrival + // clock, never a mutation of the signed message. + #[derive(Clone)] + pub(crate) struct OpaqueFixture { + pub(crate) data: Vec, + pub(crate) stamp: [u8; 32], + pub(crate) value: u8, + pub(crate) transient_id: Option<[u8; 32]>, + pub(crate) hash: Option<[u8; 32]>, + pub(crate) timestamp: f64, + } + impl OpaqueFixture { + pub(crate) fn message_id(&self) -> [u8; 32] { + self.transient_id.unwrap() + } + } + pub(crate) fn fixture_stamp(data: &[u8], cost: u8) -> ([u8; 32], u32) { + let id = rns_crypto::sha::full_hash(data); + let block = crate::stamper::stamp_workblock( + &id, + crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, + ); + // Exact value makes filtering fixtures deterministic (cost zero's public + // generator shortcut is not a measured stamp strength). + for counter in 0..u64::MAX { + let mut stamp = [0; 32]; + stamp[..8].copy_from_slice(&counter.to_be_bytes()); + let value = crate::stamper::stamp_value(&block, &stamp); + if value == u32::from(cost) { + return (stamp, value); + } + } + unreachable!() + } + pub(crate) fn opaque_message( + dest: [u8; 16], + src: [u8; 16], + title: &str, + content: &str, + method: DeliveryMethod, + ) -> OpaqueFixture { + let message = crate::message::test_message(dest, src, title, content, method); + let identity = rns_identity::identity::Identity::new(); + let mut data = dest.to_vec(); + data.extend(identity.encrypt(&message.wire_bytes()[16..], None).unwrap()); + let transient_id = rns_crypto::sha::full_hash(&data); + let (stamp, value) = fixture_stamp(&data, 0); + OpaqueFixture { + data, + stamp, + value: value.min(255) as u8, + transient_id: Some(transient_id), + hash: Some(transient_id), + timestamp: crate::now_f64(), + } + } + pub(crate) fn make_signed_message( + dest: [u8; 16], + src: [u8; 16], + title: &str, + content: &str, + ) -> OpaqueFixture { + opaque_message(dest, src, title, content, DeliveryMethod::Propagated) + } + thread_local! { static FIXTURE_DIRECTORIES: std::cell::RefCell>=const {std::cell::RefCell::new(Vec::new())}; } + pub(crate) fn durable_test_node( + config: PropagationNodeConfig, + dest: [u8; 16], + ) -> PropagationNode { + let dir = tempfile::tempdir().unwrap(); + let node = PropagationNode::with_storage(config, dest, dir.path().join("store")).unwrap(); + FIXTURE_DIRECTORIES.with(|dirs| dirs.borrow_mut().push(dir)); + node + } + impl PropagationNode { + pub(crate) fn plan_fixture( + &mut self, + fixture: &OpaqueFixture, + ) -> Option { + let mut plan = self.plan_accept_stamped_propagated_blob( + &fixture.data, + &fixture.stamp, + fixture.value, + )?; + plan.entry.stored_at = fixture.timestamp; + plan.manifest.stored_at = fixture.timestamp; + plan.path = self + .storage_path + .as_ref() + .map(|root| root.join("objects").join(plan.manifest.filename())); + Some(plan) + } + pub(crate) fn accept_fixture(&mut self, fixture: &OpaqueFixture) -> bool { + let Some(plan) = self.plan_fixture(fixture) else { + return false; + }; + self.persist_reserved(plan) + } + pub(crate) fn accept_blob_fixture(&mut self, data: &[u8], cost: u8) -> bool { + let (stamp, value) = fixture_stamp(data, cost); + self.accept_stamped_propagated_blob(data, &stamp, value.min(255) as u8) + } } fn tid(byte: u8) -> PropagationTransientId { @@ -1511,20 +1886,20 @@ mod tests { #[test] fn test_accept_message() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); assert!(msg.hash.is_some()); - assert!(node.accept_message(&msg)); + assert!(node.accept_fixture(&msg)); assert_eq!(node.message_count(), 1); } #[test] fn store_write_reservation_blocks_duplicates_until_durable_commit() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "reserved"); - let plan = node.plan_accept_message(&msg).expect("first reservation"); + let plan = node.plan_fixture(&msg).expect("first reservation"); assert_eq!(node.message_count(), 0, "reservation is not served state"); - assert!(node.plan_accept_message(&msg).is_none()); + assert!(node.plan_fixture(&msg).is_none()); let persisted = plan.persist().unwrap(); assert!(node.commit_store_write(persisted)); @@ -1533,51 +1908,47 @@ mod tests { #[test] fn failed_store_write_is_not_inserted_and_releases_reservation() { - let root = tempfile::tempdir().unwrap(); - let store_dir = root.path().join("store"); - let mut node = PropagationNode::with_storage( - PropagationNodeConfig::default(), - [0xAA; 16], - store_dir.clone(), - ) - .unwrap(); - let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "durable"); - let plan = node.plan_accept_message(&msg).expect("reservation"); - let transient_id = plan.transient_id(); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); + let message = + make_signed_message([0xBB; 16], [0xCC; 16], "write failure", "preserve retry"); + let plan = node.plan_fixture(&message).unwrap(); + let id = plan.transient_id(); let size = plan.size(); - std::fs::remove_dir(&store_dir).unwrap(); - + let objects = node.storage_path.as_ref().unwrap().join("objects"); + let saved = objects.with_extension("temporarily-unavailable"); + std::fs::rename(&objects, &saved).unwrap(); + std::fs::write(&objects, b"temporary non-directory").unwrap(); assert!(plan.persist().is_err()); - node.abort_store_write(&transient_id, size); + node.abort_store_write(&id, size); assert_eq!(node.message_count(), 0); - - std::fs::create_dir(&store_dir).unwrap(); - assert!(node.accept_message(&msg)); + std::fs::remove_file(&objects).unwrap(); + std::fs::rename(&saved, &objects).unwrap(); + assert!(node.accept_fixture(&message)); assert_eq!(node.message_count(), 1); } #[test] fn hosted_node_applies_ignored_destination_policy() { let destination = [0x44; 16]; - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); node.ignore_destination(destination); assert!(node.is_destination_ignored(&destination)); let mut blob = destination.to_vec(); blob.extend_from_slice(b"encrypted-lxmf"); - assert!(!node.accept_stamped_propagated_blob(&blob, &[0; 32], 0)); + assert!(!node.accept_blob_fixture(&blob, 0)); assert_eq!(node.message_count(), 0); node.unignore_destination(&destination); - assert!(node.accept_stamped_propagated_blob(&blob, &[0; 32], 0)); + assert!(node.accept_blob_fixture(&blob, 0)); } #[test] fn unhandled_count_is_derived_from_live_store_and_peer_handled_set() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); let transient_id = msg.transient_id.or(msg.hash).unwrap(); - assert!(node.accept_message(&msg)); + assert!(node.accept_fixture(&msg)); let mut handled = HashSet::new(); assert_eq!(node.unhandled_message_count(&handled), 1); @@ -1587,25 +1958,18 @@ mod tests { #[test] fn test_reject_duplicate() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "duplicate"); - assert!(node.accept_message(&msg)); - assert!(!node.accept_message(&msg)); + assert!(node.accept_fixture(&msg)); + assert!(!node.accept_fixture(&msg)); assert_eq!(node.message_count(), 1); } #[test] fn test_reject_no_hash() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let msg = LxMessage::new( - [0xBB; 16], - [0xCC; 16], - "Test", - "no hash", - DeliveryMethod::Propagated, - ); - assert!(msg.hash.is_none()); - assert!(!node.accept_message(&msg)); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); + assert!(!node.accept_stamped_propagated_blob(&[0; 16], &[0; 32], 0)); + assert_eq!(node.message_count(), 0); } #[test] @@ -1614,22 +1978,22 @@ mod tests { max_storage: 1, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xAA; 16]); + let mut node = durable_test_node(config, [0xAA; 16]); let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg1"); - assert!(node.accept_message(&msg1)); + assert!(node.accept_fixture(&msg1)); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg2"); - assert!(!node.accept_message(&msg2)); + assert!(!node.accept_fixture(&msg2)); } #[test] fn test_create_offer() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg1"); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg2"); - node.accept_message(&msg1); - node.accept_message(&msg2); + node.accept_fixture(&msg1); + node.accept_fixture(&msg2); let offer = node.create_offer([0xFF; 16], None); assert_eq!(offer.len(), 2); @@ -1637,14 +2001,14 @@ mod tests { #[test] fn test_create_offer_filtered() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg1"); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg2"); let tid1 = msg1.transient_id.unwrap(); - node.accept_message(&msg1); - node.accept_message(&msg2); + node.accept_fixture(&msg1); + node.accept_fixture(&msg2); let all = node.create_offer([0xFF; 16], None); assert_eq!(all.len(), 2); @@ -1658,7 +2022,7 @@ mod tests { #[test] fn authoritative_offer_policy_combines_all_filters_and_real_key() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); insert_offer_entry(&mut node, tid(0x01), 100, 20); // handled insert_offer_entry(&mut node, tid(0x02), 100, 12); // low stamp insert_offer_entry(&mut node, tid(0x03), 100, 13); // accepted @@ -1687,7 +2051,7 @@ mod tests { #[test] fn offer_cumulative_limit_is_decimal_and_excludes_exact_boundary() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); insert_offer_entry(&mut node, tid(0x01), 50, 0); insert_offer_entry(&mut node, tid(0x02), 50, 0); let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); @@ -1702,7 +2066,7 @@ mod tests { #[test] fn prepared_offer_distinguishes_terminal_filters_from_cumulative_deferral() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); insert_offer_entry(&mut node, tid(0x01), 10, 9); // terminal low stamp insert_offer_entry(&mut node, tid(0x02), 100, 20); // selected insert_offer_entry(&mut node, tid(0x03), 100, 20); // cumulative deferred @@ -1724,7 +2088,7 @@ mod tests { #[test] fn all_cumulatively_deferred_candidates_exhaust_unchanged_generation() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); insert_offer_entry(&mut node, tid(0x01), 50, 20); insert_offer_entry(&mut node, tid(0x02), 50, 20); let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); @@ -1744,16 +2108,16 @@ mod tests { #[test] fn prepared_offer_revalidates_store_generation_before_install() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let mut first = vec![0x11; DESTINATION_LENGTH + 1]; first[0] = 0x01; - assert!(node.accept_propagated_blob(&first, 0)); + assert!(node.accept_blob_fixture(&first, 0)); let policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); let snapshot = node.snapshot_sync_offer_preparation(&policy); let mut second = vec![0x22; DESTINATION_LENGTH + 1]; second[0] = 0x02; - assert!(node.accept_propagated_blob(&second, 0)); + assert!(node.accept_blob_fixture(&second, 0)); let prepared = prepare_sync_offer_snapshot(snapshot); assert!(matches!( @@ -1764,7 +2128,8 @@ mod tests { #[test] fn passed_and_persisted_handled_sets_are_unioned() { - let dir = std::env::temp_dir().join("lxmf_test_offer_handled_union"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( PropagationNodeConfig::default(), @@ -1792,7 +2157,8 @@ mod tests { #[test] fn test_propagation_disk_persistence() { - let dir = std::env::temp_dir().join("lxmf_test_prop_persist"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); { @@ -1804,7 +2170,7 @@ mod tests { .unwrap(); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "persistent content"); - assert!(node.accept_message(&msg)); + assert!(node.accept_fixture(&msg)); assert_eq!(node.message_count(), 1); } @@ -1824,24 +2190,17 @@ mod tests { #[test] fn test_disk_load_ignores_pre_fix_16_byte_transient_id_filenames() { - let dir = std::env::temp_dir().join("lxmf_test_prop_reject_16_byte_ids"); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - - let old_filename = "aabbccddaabbccddaabbccddaabbccdd_1234567890_0"; - let mut lxmf_data = vec![0xBB; 16]; - lxmf_data.extend_from_slice(&[0xCC; 64]); - std::fs::write(dir.join(old_filename), &lxmf_data).unwrap(); - - let node = PropagationNode::with_storage( - PropagationNodeConfig::default(), - [0xAA; 16], - dir.clone(), - ) - .unwrap(); - assert_eq!(node.message_count(), 0); - - let _ = std::fs::remove_dir_all(&dir); + let dir = tempfile::tempdir().unwrap(); + let legacy = dir.path().join("store"); + std::fs::create_dir(&legacy).unwrap(); + let path = legacy.join("aabbccddaabbccddaabbccddaabbccdd_1234567890_0"); + let evidence = vec![0xCC; 80]; + std::fs::write(&path, &evidence).unwrap(); + let error = + PropagationNode::with_storage(PropagationNodeConfig::default(), [0xAA; 16], legacy) + .unwrap_err(); + assert!(error.to_string().contains("MigrationRequired")); + assert_eq!(std::fs::read(path).unwrap(), evidence); } /// T0-1: `/get` ownership gating — a client may only list, download, and @@ -1850,7 +2209,8 @@ mod tests { fn test_get_request_ownership_gating() { use rmpv::Value; - let dir = std::env::temp_dir().join("lxmf_test_get_ownership"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( PropagationNodeConfig::default(), @@ -1863,8 +2223,8 @@ mod tests { let client_b = [0xDD; 16]; let msg_a = make_signed_message(client_a, [0xBB; 16], "Test", "for A"); let msg_b = make_signed_message(client_b, [0xBB; 16], "Test", "for B"); - assert!(node.accept_message(&msg_a)); - assert!(node.accept_message(&msg_b)); + assert!(node.accept_fixture(&msg_a)); + assert!(node.accept_fixture(&msg_b)); let tid_a = node.store.entries_for_destination(&client_a)[0].transient_id; let tid_b = node.store.entries_for_destination(&client_b)[0].transient_id; @@ -1893,14 +2253,14 @@ mod tests { assert!(node.store.get(&tid_b).is_some()); // A's haves cannot purge B's entry (Phase 3). - node.handle_get_request(&encode_req(None, Some(&[tid_b])), &client_a); + node.handle_get_request(&encode_req(None, Some(&[tid_b])), &client_a) + .into_response(); assert!( node.store.get(&tid_b).is_some(), "foreign purge must be ignored" ); assert!( - dir.join(node.store.get(&tid_b).unwrap().filename()) - .exists(), + node.object_paths[&tid_b].exists(), "B's file must survive A's purge attempt" ); @@ -1911,8 +2271,9 @@ mod tests { assert_eq!(decode_msgs(&resp), 1); // ...and purge it. - node.handle_get_request(&encode_req(None, Some(&[tid_a])), &client_a); - assert!(node.store.get(&tid_a).is_none(), "own purge must work"); + node.handle_get_request(&encode_req(None, Some(&[tid_a])), &client_a) + .into_response(); + assert!(!node.contains(&tid_a), "own purge must work"); let _ = std::fs::remove_dir_all(&dir); } @@ -1922,52 +2283,44 @@ mod tests { /// remaining entries load. #[cfg(unix)] #[test] - fn test_disk_load_quarantines_unreadable_file() { + fn test_disk_load_preserves_unreadable_evidence_and_blocks_hosting() { use std::os::unix::fs::PermissionsExt; - - let dir = std::env::temp_dir().join("lxmf_test_prop_quarantine"); - let _ = std::fs::remove_dir_all(&dir); - - { - let mut node = PropagationNode::with_storage( - PropagationNodeConfig::default(), - [0xAA; 16], - dir.clone(), - ) - .unwrap(); - let msg_a = make_signed_message([0xCC; 16], [0xBB; 16], "Test", "loads fine"); - let msg_b = make_signed_message([0xDD; 16], [0xBB; 16], "Test", "will corrupt"); - assert!(node.accept_message(&msg_a)); - assert!(node.accept_message(&msg_b)); - } - - // Make one stored file unreadable (read() will fail, parse_filename - // still succeeds — the load must skip + quarantine it). - let victim = std::fs::read_dir(&dir) - .unwrap() - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .find(|p| p.is_file() && !p.to_string_lossy().ends_with(".msgpack")) - .expect("expected a stored message file"); - std::fs::set_permissions(&victim, std::fs::Permissions::from_mode(0o000)).unwrap(); - - let node = PropagationNode::with_storage( + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("store"); + let mut node = PropagationNode::with_storage( PropagationNodeConfig::default(), [0xAA; 16], - dir.clone(), + path.clone(), ) .unwrap(); - assert_eq!( - node.message_count(), - 1, - "remaining entry must load despite the unreadable file" + let good = make_signed_message([0xCC; 16], [0xBB; 16], "healthy", "retained"); + let bad = make_signed_message([0xDD; 16], [0xBB; 16], "unreadable", "evidence"); + assert!(node.accept_fixture(&good)); + assert!(node.accept_fixture(&bad)); + let good_path = node.object_paths[&good.message_id()].clone(); + let bad_path = node.object_paths[&bad.message_id()].clone(); + let good_bytes = std::fs::read(&good_path).unwrap(); + let bad_bytes = std::fs::read(&bad_path).unwrap(); + drop(node); + std::fs::set_permissions(&bad_path, std::fs::Permissions::from_mode(0o000)).unwrap(); + let result = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [0xAA; 16], + path.clone(), ); + std::fs::set_permissions(&bad_path, std::fs::Permissions::from_mode(0o600)).unwrap(); assert!( - victim.with_extension("corrupt").exists(), - "unreadable file must be quarantined" + result.is_err(), + "authoritative committed corruption must block hosting" + ); + assert_eq!(std::fs::read(good_path).unwrap(), good_bytes); + assert_eq!(std::fs::read(bad_path).unwrap(), bad_bytes); + assert_eq!( + PropagationNode::with_storage(PropagationNodeConfig::default(), [0xAA; 16], path) + .unwrap() + .message_count(), + 2 ); - - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -1976,11 +2329,11 @@ mod tests { max_message_age: 1, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xAA; 16]); + let mut node = durable_test_node(config, [0xAA; 16]); let mut msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "will expire"); msg.timestamp = 1000.0; - node.accept_message(&msg); + node.accept_fixture(&msg); assert_eq!(node.message_count(), 1); node.tick(); @@ -1998,11 +2351,11 @@ mod tests { max_message_age: 1, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xAA; 16]); + let mut node = durable_test_node(config, [0xAA; 16]); let mut msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "cull then redeliver"); msg.timestamp = 1000.0; - assert!(node.accept_message(&msg), "first accept"); + assert!(node.accept_fixture(&msg), "first accept"); assert_eq!(node.message_count(), 1); node.tick(); @@ -2014,7 +2367,7 @@ mod tests { .unwrap() .as_secs_f64(); assert!( - node.accept_message(&msg), + node.accept_fixture(&msg), "same message re-accepted after cull" ); assert_eq!(node.message_count(), 1); @@ -2030,15 +2383,15 @@ mod tests { max_message_age: 1, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xAA; 16]); + let mut node = durable_test_node(config, [0xAA; 16]); let mut msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "first"); msg1.timestamp = 1000.0; // ancient so tick will cull it - assert!(node.accept_message(&msg1)); + assert!(node.accept_fixture(&msg1)); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "rejected-while-full"); assert!( - !node.accept_message(&msg2), + !node.accept_fixture(&msg2), "store full, second message must reject" ); @@ -2047,7 +2400,7 @@ mod tests { let msg3 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "accepted-after-cull"); assert!( - node.accept_message(&msg3), + node.accept_fixture(&msg3), "store has space after cull, next message accepted" ); assert_eq!(node.message_count(), 1); @@ -2055,7 +2408,7 @@ mod tests { #[test] fn test_tick_enforces_weight_cap() { - let mut node = PropagationNode::new( + let mut node = durable_test_node( PropagationNodeConfig { max_storage: 1, ..PropagationNodeConfig::default() @@ -2064,7 +2417,7 @@ mod tests { ); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "weight-cull"); assert!( - node.accept_message(&msg), + node.accept_fixture(&msg), "ingest cap checks size before insert, first message is admitted" ); assert_eq!(node.message_count(), 1); @@ -2078,7 +2431,8 @@ mod tests { #[test] fn test_peer_persistence() { - let dir = std::env::temp_dir().join("lxmf_test_peer_persist"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2092,7 +2446,7 @@ mod tests { // backed by a live store entry survives; one whose message is gone // from the store is dropped. let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "peer-persist"); - assert!(node.accept_message(&msg)); + assert!(node.accept_fixture(&msg)); let live_id = node.create_offer_filtered(&HashSet::new())[0]; let mut peer = LxmPeer::new([0xBB; 16]); @@ -2121,7 +2475,8 @@ mod tests { #[test] fn test_peer_persistence_multiple() { - let dir = std::env::temp_dir().join("lxmf_test_peer_persist_multi"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let node = PropagationNode::with_storage( @@ -2159,58 +2514,29 @@ mod tests { #[test] fn test_disk_cleanup_on_cull() { - let dir = std::env::temp_dir().join("lxmf_test_disk_cleanup"); - let _ = std::fs::remove_dir_all(&dir); - - let config = PropagationNodeConfig { - max_message_age: 1, - ..Default::default() - }; - let mut node = PropagationNode::with_storage(config, [0xAA; 16], dir.clone()).unwrap(); - - let mut msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "cleanup test"); - msg.timestamp = 1000.0; - node.accept_message(&msg); - - let file_count = std::fs::read_dir(&dir) - .unwrap() - .filter(|e| { - e.as_ref() - .ok() - .and_then(|e| { - e.path() - .file_name() - .map(|f| !f.to_str().unwrap_or("").ends_with(".peer")) - }) - .unwrap_or(false) - }) - .count(); - assert_eq!(file_count, 1); - + let mut node = durable_test_node( + PropagationNodeConfig { + max_message_age: 1, + ..Default::default() + }, + [0xAA; 16], + ); + let mut message = make_signed_message([0xBB; 16], [0xCC; 16], "cull", "cleanup"); + message.timestamp = 1000.; + assert!(node.accept_fixture(&message)); + let id = message.message_id(); + let object = node.object_paths[&id].clone(); + assert!(object.exists()); + assert!(object.with_extension("entry").exists()); node.tick(); assert_eq!(node.message_count(), 0); - - let remaining = std::fs::read_dir(&dir) - .unwrap() - .filter(|e| { - e.as_ref() - .ok() - .and_then(|e| { - e.path() - .file_name() - .map(|f| !f.to_str().unwrap_or("").ends_with(".peer")) - }) - .unwrap_or(false) - }) - .count(); - assert_eq!(remaining, 0); - - let _ = std::fs::remove_dir_all(&dir); + assert!(!object.exists()); + assert!(!object.with_extension("entry").exists()); } #[test] fn test_sync_session_management() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let peer_hash = [0xBB; 16]; assert!(node.get_session(&peer_hash).is_none()); @@ -2226,7 +2552,7 @@ mod tests { #[test] fn test_offer_request_returns_missing() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg1"); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg2"); @@ -2236,9 +2562,9 @@ mod tests { let tid2 = msg2.transient_id.unwrap(); let tid3 = msg3.transient_id.unwrap(); - node.accept_message(&msg1); - node.accept_message(&msg2); - node.accept_message(&msg3); + node.accept_fixture(&msg1); + node.accept_fixture(&msg2); + node.accept_fixture(&msg3); let peer_has = [tid1, tid2]; let missing = node.offer_request([0xDD; 16], &peer_has); @@ -2249,10 +2575,10 @@ mod tests { #[test] fn test_offer_request_peer_has_nothing() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); - node.accept_message(&msg); + node.accept_fixture(&msg); let missing = node.offer_request([0xDD; 16], &[]); assert_eq!(missing.len(), 1); @@ -2260,11 +2586,11 @@ mod tests { #[test] fn test_offer_request_peer_has_everything() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); let tid = msg.transient_id.unwrap(); - node.accept_message(&msg); + node.accept_fixture(&msg); let missing = node.offer_request([0xDD; 16], &[tid]); assert!(missing.is_empty()); @@ -2272,7 +2598,8 @@ mod tests { #[test] fn test_message_get_request_with_storage() { - let dir = std::env::temp_dir().join("lxmf_test_msg_get"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2284,22 +2611,24 @@ mod tests { let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "get request content"); let tid = msg.transient_id.unwrap(); - node.accept_message(&msg); + node.accept_fixture(&msg); let results = node.message_get_request(&[tid]); assert_eq!(results.len(), 1); assert_eq!(results[0].0, tid); assert!(!results[0].1.is_empty()); - let unpacked = LxMessage::unpack(&results[0].1); - assert!(unpacked.is_ok()); + let mut expected = msg.data.clone(); + expected.extend_from_slice(&msg.stamp); + assert_eq!(results[0].1, expected); let _ = std::fs::remove_dir_all(&dir); } #[test] fn test_message_get_request_unknown_id() { - let dir = std::env::temp_dir().join("lxmf_test_msg_get_unknown"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let node = PropagationNode::with_storage( @@ -2325,12 +2654,12 @@ mod tests { #[test] fn test_prepare_sync_offer() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "sync1"); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "sync2"); - node.accept_message(&msg1); - node.accept_message(&msg2); + node.accept_fixture(&msg1); + node.accept_fixture(&msg2); let peer_hash = [0xDD; 16]; let offer = node.prepare_sync_offer(peer_hash); @@ -2341,11 +2670,11 @@ mod tests { #[test] fn test_process_sync_offer_and_get() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "has_this"); let tid1 = msg1.transient_id.unwrap(); - node.accept_message(&msg1); + node.accept_fixture(&msg1); let peer_hash = [0xDD; 16]; let tid2 = tid(0xEE); @@ -2361,11 +2690,11 @@ mod tests { #[test] fn test_sync_lifecycle_complete() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let peer_hash = [0xDD; 16]; let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "lifecycle"); - node.accept_message(&msg); + node.accept_fixture(&msg); let _offer = node.prepare_sync_offer(peer_hash); assert!(node.get_session(&peer_hash).is_some()); @@ -2376,7 +2705,8 @@ mod tests { #[test] fn test_process_sync_get_with_storage() { - let dir = std::env::temp_dir().join("lxmf_test_sync_get"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2388,7 +2718,7 @@ mod tests { let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "sync get content"); let tid = msg.transient_id.unwrap(); - node.accept_message(&msg); + node.accept_fixture(&msg); let get = crate::sync::SyncGet { wanted_ids: vec![tid.to_vec()], @@ -2399,8 +2729,9 @@ mod tests { assert_eq!(messages.len(), 1); assert!(!messages[0].is_empty()); - let unpacked = LxMessage::unpack(&messages[0]); - assert!(unpacked.is_ok()); + let mut expected = msg.data.clone(); + expected.extend_from_slice(&msg.stamp); + assert_eq!(messages[0], expected); let _ = std::fs::remove_dir_all(&dir); } @@ -2443,7 +2774,7 @@ mod tests { peering_cost: cost, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xCC; 16]); + let mut node = durable_test_node(config, [0xCC; 16]); let key = peering_key(&local_identity, &remote_identity, cost); use rmpv::Value; @@ -2478,7 +2809,7 @@ mod tests { peering_cost: cost, ..Default::default() }; - let node = PropagationNode::new(config, [0xCC; 16]); + let node = durable_test_node(config, [0xCC; 16]); let mut admission = crate::propagation_admission::PnInboundAdmission::default(); let candidate = admission .preflight_offer([0xDD; 16], Some(remote_identity), std::time::Duration::ZERO) @@ -2497,7 +2828,7 @@ mod tests { #[test] fn test_handle_offer_request_rejects_empty_peering_key_when_cost_required() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let local_identity = [0xAA; 16]; let remote_identity = [0xBB; 16]; @@ -2533,8 +2864,30 @@ mod tests { peering_cost: cost, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xCC; 16]); - let key = peering_key(&remote_identity, &local_identity, cost); + let mut node = durable_test_node(config, [0xCC; 16]); + // A cost-8 stamp for the reverse order can also satisfy the forward + // order by chance. Select a deterministic witness for the distinction + // this regression asserts, and verify both preconditions explicitly. + let rounds = crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING; + let reverse = crate::stamper::stamp_workblock( + &[remote_identity.as_slice(), local_identity.as_slice()].concat(), + rounds, + ); + let forward = crate::stamper::stamp_workblock( + &[local_identity.as_slice(), remote_identity.as_slice()].concat(), + rounds, + ); + let key = (0u64..1_000_000) + .find_map(|counter| { + let mut candidate = [0u8; 32]; + candidate[..8].copy_from_slice(&counter.to_le_bytes()); + (crate::stamper::stamp_valid(&candidate, cost, &reverse) + && !crate::stamper::stamp_valid(&candidate, cost, &forward)) + .then_some(candidate) + }) + .expect("reverse-only deterministic peering stamp"); + assert!(crate::stamper::stamp_valid(&key, cost, &reverse)); + assert!(!crate::stamper::stamp_valid(&key, cost, &forward)); use rmpv::Value; let offer = Value::Array(vec![ @@ -2561,7 +2914,7 @@ mod tests { #[test] fn test_handle_offer_request_no_identity() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); use rmpv::Value; let offer = Value::Array(vec![Value::Binary(vec![]), Value::Array(vec![])]); @@ -2576,7 +2929,7 @@ mod tests { #[test] fn test_handle_offer_request_invalid_data() { - let mut node = PropagationNode::new( + let mut node = durable_test_node( PropagationNodeConfig { peering_cost: 0, ..Default::default() @@ -2621,7 +2974,8 @@ mod tests { #[test] fn test_handle_get_request_list_phase() { - let dir = std::env::temp_dir().join("lxmf_test_get_list"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2632,7 +2986,7 @@ mod tests { .unwrap(); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "get list content"); - node.accept_message(&msg); + node.accept_fixture(&msg); use rmpv::Value; let request = Value::Array(vec![Value::Nil, Value::Nil]); @@ -2650,7 +3004,7 @@ mod tests { #[test] fn test_handle_get_request_list_empty() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); use rmpv::Value; let request = Value::Array(vec![Value::Nil, Value::Nil]); @@ -2665,7 +3019,8 @@ mod tests { #[test] fn test_accept_propagated_blob_and_get_with_full_hash_id() { - let dir = std::env::temp_dir().join("lxmf_test_propagated_blob_get"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2677,7 +3032,7 @@ mod tests { let mut lxmf_data = vec![0xBB; 16]; lxmf_data.extend_from_slice(&[0xCC; 128]); - assert!(node.accept_propagated_blob(&lxmf_data, 0)); + assert!(node.accept_blob_fixture(&lxmf_data, 0)); let full_id = rns_crypto::sha::full_hash(&lxmf_data); use rmpv::Value; @@ -2709,7 +3064,8 @@ mod tests { #[test] fn test_stamped_propagated_blob_strips_only_for_client_download() { - let dir = std::env::temp_dir().join("lxmf_test_stamped_blob_get"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2724,7 +3080,20 @@ mod tests { let stamp = [0x5A; 32]; let full_id = rns_crypto::sha::full_hash(&lxmf_data); - assert!(node.accept_stamped_propagated_blob(&lxmf_data, &stamp, 0)); + assert!( + node.accept_stamped_propagated_blob( + &lxmf_data, + &stamp, + crate::stamper::stamp_value( + &crate::stamper::stamp_workblock( + &rns_crypto::sha::full_hash(&lxmf_data), + STAMP_WORKBLOCK_EXPAND_ROUNDS_PN + ), + &stamp + ) + .min(255) as u8 + ) + ); let peer_results = node.message_get_request(&[full_id]); assert_eq!(peer_results.len(), 1); @@ -2752,7 +3121,8 @@ mod tests { #[test] fn test_reloaded_stamped_blob_strips_for_client_download() { - let dir = std::env::temp_dir().join("lxmf_test_stamped_blob_reload_get"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut lxmf_data = vec![0xBB; 16]; @@ -2767,7 +3137,20 @@ mod tests { dir.clone(), ) .unwrap(); - assert!(node.accept_stamped_propagated_blob(&lxmf_data, &stamp, 0)); + assert!( + node.accept_stamped_propagated_blob( + &lxmf_data, + &stamp, + crate::stamper::stamp_value( + &crate::stamper::stamp_workblock( + &rns_crypto::sha::full_hash(&lxmf_data), + STAMP_WORKBLOCK_EXPAND_ROUNDS_PN + ), + &stamp + ) + .min(255) as u8 + ) + ); } let mut reloaded = PropagationNode::with_storage( @@ -2801,21 +3184,22 @@ mod tests { min_stamp_cost: 8, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xAA; 16]); + let mut node = durable_test_node(config, [0xAA; 16]); let mut lxmf_data = vec![0xBB; 16]; lxmf_data.extend_from_slice(&[0xCC; 128]); - assert!(!node.accept_propagated_blob(&lxmf_data, 7)); + assert!(!node.accept_blob_fixture(&lxmf_data, 7)); assert_eq!(node.message_count(), 0); - assert!(node.accept_propagated_blob(&lxmf_data, 8)); + assert!(node.accept_blob_fixture(&lxmf_data, 8)); assert_eq!(node.message_count(), 1); } #[test] fn test_opaque_propagated_blob_reload_preserves_destination() { - let dir = std::env::temp_dir().join("lxmf_test_propagated_blob_reload"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2827,7 +3211,7 @@ mod tests { let mut lxmf_data = vec![0xBB; 16]; lxmf_data.extend_from_slice(&[0xCC; 128]); - assert!(node.accept_propagated_blob(&lxmf_data, 0)); + assert!(node.accept_blob_fixture(&lxmf_data, 0)); drop(node); let mut reloaded = PropagationNode::with_storage( @@ -2870,120 +3254,76 @@ mod tests { #[test] fn test_opaque_blob_reload_preserves_bytes_and_accounting_at_minimum_lengths() { use rmpv::Value; - - // These are storage-format controls, not authenticated ciphertext or - // stamp-validation tests. Retain the existing public ingress minimum. - for stamped in [false, true] { - for len in [17, 31, 32, 33, 48, 49, 144] { - let dir = tempfile::tempdir().unwrap(); - let mut node = PropagationNode::with_storage( - PropagationNodeConfig::default(), - [0xAA; 16], - dir.path().to_path_buf(), - ) - .unwrap(); - assert!(!node.accept_propagated_blob(&[0xBB; 16], 0)); - assert!(!node.accept_stamped_propagated_blob(&[0xBB; 16], &[0; 32], 0)); - assert_eq!(node.message_count(), 0); - let mut blob = vec![0xBB; 16]; - blob.resize(len, 0xCC); - let stamp = [0x5A; 32]; - let full_id = rns_crypto::sha::full_hash(&blob); - let mut stored = blob.clone(); - if stamped { - stored.extend_from_slice(&stamp); - assert!(node.accept_stamped_propagated_blob(&blob, &stamp, 0)); - } else { - assert!(node.accept_propagated_blob(&blob, 0)); - } - assert_eq!(node.total_size(), stored.len()); - let path = dir - .path() - .join(node.store.get(&full_id).unwrap().filename()); - assert_eq!(std::fs::read(&path).unwrap(), stored); - drop(node); - - let mut node = PropagationNode::with_storage( - PropagationNodeConfig::default(), - [0xAA; 16], - dir.path().to_path_buf(), - ) - .unwrap(); - assert_eq!(node.message_count(), 1); - assert_eq!(node.total_size(), stored.len()); - assert_eq!(node.store.get(&full_id).unwrap().stamped, stamped); - // Duplicate admission must neither replace the known format - // nor grow the byte/accounting reservation after reload. - assert!(!node.accept_propagated_blob(&blob, 0)); - assert!(!node.accept_stamped_propagated_blob(&blob, &stamp, 0)); - assert_eq!(node.message_count(), 1); - assert_eq!(node.total_size(), stored.len()); - assert!(node.pending_write_ids.is_empty()); - assert_eq!(node.pending_write_bytes, 0); - let get = Value::Array(vec![ - Value::Array(vec![Value::Binary(full_id.to_vec())]), - Value::Array(vec![]), - ]); - let mut request = Vec::new(); - rmpv::encode::write_value(&mut request, &get).unwrap(); - let response = node - .handle_get_request(&request, &[0xBB; 16]) - .into_response(); - let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap(); - let messages = value.as_array().unwrap(); - assert_eq!(messages.len(), 1); - assert_eq!(messages[0].as_slice().unwrap(), blob); - assert_eq!( - node.message_get_request(&[full_id]), - vec![(full_id, stored.clone())] - ); - assert_eq!(std::fs::read(&path).unwrap(), stored); - } + for len in [17, 31, 32, 33, 48, 49, 144] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("store"); + let mut node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [0xAA; 16], + path.clone(), + ) + .unwrap(); + assert!(!node.accept_blob_fixture(&[0xBB; 16], 0)); + let mut blob = vec![0xBB; 16]; + blob.resize(len, 0xCC); + let (stamp, value) = fixture_stamp(&blob, 0); + let id = rns_crypto::sha::full_hash(&blob); + let mut stored = blob.clone(); + stored.extend_from_slice(&stamp); + assert!(node.accept_stamped_propagated_blob(&blob, &stamp, value as u8)); + let object = node.object_paths[&id].clone(); + assert_eq!(std::fs::read(&object).unwrap(), stored); + drop(node); + let mut node = + PropagationNode::with_storage(PropagationNodeConfig::default(), [0xAA; 16], path) + .unwrap(); + assert_eq!(node.message_count(), 1); + assert_eq!(node.total_size(), stored.len()); + assert!(node.store.get(&id).unwrap().stamped); + assert!(!node.accept_stamped_propagated_blob(&blob, &stamp, value as u8)); + assert!(node.pending_write_ids.is_empty()); + assert_eq!(node.pending_write_bytes, 0); + let request = crate::encode_value(&Value::Array(vec![ + Value::Array(vec![Value::Binary(id.to_vec())]), + Value::Array(vec![]), + ])); + let response = node + .handle_get_request(&request, &[0xBB; 16]) + .into_response(); + let decoded = rmpv::decode::read_value(&mut response.as_slice()).unwrap(); + assert_eq!(decoded.as_array().unwrap()[0].as_slice().unwrap(), blob); + assert_eq!(node.message_get_request(&[id]), vec![(id, stored.clone())]); + assert_eq!(std::fs::read(object).unwrap(), stored); } } #[test] fn test_reloaded_legacy_message_keeps_original_get_bytes() { - use rmpv::Value; - + // Ordinary startup never promotes a recognizable legacy plaintext LXMF + // file into relay provenance, even when its filename uses a real ID. let dir = tempfile::tempdir().unwrap(); - let message = make_signed_message([0xBB; 16], [0xCC; 16], "legacy", "full message"); - let packed = message.pack().unwrap(); - let full_id = message.transient_id.or(message.hash).unwrap(); - assert_ne!(full_id, rns_crypto::sha::full_hash(&packed)); - let mut node = PropagationNode::with_storage( - PropagationNodeConfig::default(), - [0xAA; 16], - dir.path().to_path_buf(), - ) - .unwrap(); - assert!(node.accept_message(&message)); - drop(node); - let mut node = PropagationNode::with_storage( - PropagationNodeConfig::default(), - [0xAA; 16], - dir.path().to_path_buf(), - ) - .unwrap(); - assert_eq!(node.message_count(), 1); - assert_eq!(node.total_size(), packed.len()); - assert!(!node.store.get(&full_id).unwrap().stamped); - let get = Value::Array(vec![ - Value::Array(vec![Value::Binary(full_id.to_vec())]), - Value::Array(vec![]), - ]); - let mut request = Vec::new(); - rmpv::encode::write_value(&mut request, &get).unwrap(); - let response = node - .handle_get_request(&request, &[0xBB; 16]) - .into_response(); - let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap(); - assert_eq!(value.as_array().unwrap()[0].as_slice().unwrap(), packed); + let legacy = dir.path().join("store"); + std::fs::create_dir(&legacy).unwrap(); + let message = crate::message::test_message( + [0xBB; 16], + [0xCC; 16], + "legacy", + "full message", + DeliveryMethod::Propagated, + ); + let file = legacy.join(format!("{}_100_0", hex::encode(message.message_id()))); + std::fs::write(&file, message.wire_bytes()).unwrap(); + assert!( + PropagationNode::with_storage(PropagationNodeConfig::default(), [0xAA; 16], legacy) + .is_err() + ); + assert_eq!(std::fs::read(file).unwrap(), message.wire_bytes()); } #[test] fn test_handle_get_request_purge_phase() { - let dir = std::env::temp_dir().join("lxmf_test_get_purge"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -2995,7 +3335,7 @@ mod tests { let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "purge content"); let tid = msg.transient_id.unwrap(); - node.accept_message(&msg); + node.accept_fixture(&msg); assert_eq!(node.message_count(), 1); use rmpv::Value; @@ -3014,7 +3354,8 @@ mod tests { #[test] fn test_handle_get_request_get_phase() { - let dir = std::env::temp_dir().join("lxmf_test_get_data"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( @@ -3026,7 +3367,7 @@ mod tests { let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "get data content"); let tid = msg.transient_id.unwrap(); - node.accept_message(&msg); + node.accept_fixture(&msg); use rmpv::Value; let request = Value::Array(vec![ @@ -3051,7 +3392,8 @@ mod tests { fn test_get_request_phase2_returns_serve_plan() { use rmpv::Value; - let dir = std::env::temp_dir().join("lxmf_test_get_serve_plan"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( PropagationNodeConfig::default(), @@ -3062,7 +3404,7 @@ mod tests { let mut blob = vec![0xBB; 16]; blob.extend_from_slice(&[0x11; 64]); - assert!(node.accept_propagated_blob(&blob, 0)); + assert!(node.accept_blob_fixture(&blob, 0)); let tid = rns_crypto::sha::full_hash(&blob); let list_req = crate::encode_value(&Value::Array(vec![Value::Nil, Value::Nil])); @@ -3077,7 +3419,7 @@ mod tests { ])); assert!(matches!( node.handle_get_request(&purge_req, &[0xBB; 16]), - GetRequestAction::Respond(_) + GetRequestAction::ServeFiles(_) )); let get_req = crate::encode_value(&Value::Array(vec![ @@ -3106,7 +3448,8 @@ mod tests { fn test_get_phase_purges_haves_before_serving_wants() { use rmpv::Value; - let dir = std::env::temp_dir().join("lxmf_test_get_purge_first"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( PropagationNodeConfig::default(), @@ -3117,7 +3460,7 @@ mod tests { let mut blob = vec![0xBB; 16]; blob.extend_from_slice(&[0x22; 48]); - assert!(node.accept_propagated_blob(&blob, 0)); + assert!(node.accept_blob_fixture(&blob, 0)); let tid = rns_crypto::sha::full_hash(&blob); let req = crate::encode_value(&Value::Array(vec![ @@ -3142,7 +3485,8 @@ mod tests { fn test_get_phase_transfer_limit_python_accounting() { use rmpv::Value; - let dir = std::env::temp_dir().join("lxmf_test_get_limit_accounting"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( PropagationNodeConfig::default(), @@ -3163,7 +3507,7 @@ mod tests { let blob_b = make_blob(0x02, 350); let blob_c = make_blob(0x03, 50); for blob in [&blob_a, &blob_b, &blob_c] { - assert!(node.accept_propagated_blob(blob, 0)); + assert!(node.accept_blob_fixture(blob, 0)); } let wants: Vec = [&blob_a, &blob_b, &blob_c] @@ -3192,7 +3536,8 @@ mod tests { fn test_get_list_phase_sorted_smallest_first() { use rmpv::Value; - let dir = std::env::temp_dir().join("lxmf_test_get_list_sorted"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let mut node = PropagationNode::with_storage( PropagationNodeConfig::default(), @@ -3210,7 +3555,7 @@ mod tests { let blob_small = make_blob(0x05, 100); let blob_mid = make_blob(0x06, 200); for blob in [&blob_large, &blob_small, &blob_mid] { - assert!(node.accept_propagated_blob(blob, 0)); + assert!(node.accept_blob_fixture(blob, 0)); } let list_req = crate::encode_value(&Value::Array(vec![Value::Nil, Value::Nil])); @@ -3239,10 +3584,10 @@ mod tests { min_stamp_cost: 8, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xAA; 16]); + let mut node = durable_test_node(config, [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "unstamped"); - assert!(!node.accept_message(&msg)); + assert!(!node.accept_fixture(&msg)); assert_eq!(node.message_count(), 0); } @@ -3252,16 +3597,16 @@ mod tests { min_stamp_cost: 0, ..Default::default() }; - let mut node = PropagationNode::new(config, [0xAA; 16]); + let mut node = durable_test_node(config, [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "no_cost"); - assert!(node.accept_message(&msg)); + assert!(node.accept_fixture(&msg)); assert_eq!(node.message_count(), 1); } #[test] fn test_create_offer_with_stamp_filter() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let entry1 = crate::propagation::PropagationEntry { transient_id: tid(0x01), @@ -3296,4 +3641,139 @@ mod tests { let all2 = node.create_offer([0xFF; 16], Some(0)); assert_eq!(all2.len(), 2); } + #[test] + fn bounded_get_schema_rejects_amplification_and_nonfinite_limits_before_purge() { + use rmpv::Value; + let temporary = tempfile::tempdir().unwrap(); + let mut node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [1; 16], + temporary.path().join("store"), + ) + .unwrap(); + let blob = vec![0xBB; 100]; + assert!(node.accept_blob_fixture(&blob, 0)); + let tid = rns_crypto::sha::full_hash(&blob); + for limit in [ + Value::F64(f64::NAN), + Value::F64(f64::INFINITY), + Value::F64(-1.), + Value::F64(f64::MAX), + Value::from("bad"), + Value::Nil, + ] { + let request = crate::encode_value(&Value::Array(vec![ + Value::Nil, + Value::Array(vec![Value::Binary(tid.to_vec())]), + limit, + ])); + assert_eq!( + node.handle_get_request_bounded(&request, &[0xBB; 16], 1024) + .into_response_with_served_count_bounded(1024), + (vec![0xc0], 0) + ); + assert_eq!(node.message_count(), 1); + } + for malformed in [ + vec![0x92, 0xdd, 0xff, 0xff, 0xff, 0xff], + vec![0x92, 0x91, 0x90, 0xc0], + vec![0x92, 0xc0, 0xc0, 0xc0], + ] { + assert!(parse_get_request(&malformed).is_none()); + assert_eq!(node.message_count(), 1); + } + // More than the historical packet-sized ID count remains valid. + let request = crate::encode_value(&Value::Array(vec![ + Value::Array(vec![Value::Binary(tid.to_vec()); 2048]), + Value::Array(vec![]), + ])); + assert_eq!( + get_ids(parse_get_request(&request).unwrap().wants).count(), + 2048 + ); + } + + #[test] + fn bounded_get_deduplicates_and_fits_exact_encoded_boundary() { + use rmpv::Value; + let temporary = tempfile::tempdir().unwrap(); + let mut node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [1; 16], + temporary.path().join("store"), + ) + .unwrap(); + let blob = vec![0xBB; 100]; + assert!(node.accept_blob_fixture(&blob, 0)); + let tid = rns_crypto::sha::full_hash(&blob); + let request = crate::encode_value(&Value::Array(vec![ + Value::Array(vec![Value::Binary(tid.to_vec()); 4]), + Value::Array(vec![]), + ])); + let (bytes, count) = node + .handle_get_request_bounded(&request, &[0xBB; 16], 103) + .into_response_with_served_count_bounded(103); + assert_eq!(count, 1); + assert_eq!(bytes.len(), 103); + assert!(bytes.capacity() <= 103); + assert_eq!( + rmpv::decode::read_value(&mut bytes.as_slice()).unwrap(), + Value::Array(vec![Value::Binary(blob)]) + ); + let (bytes, count) = node + .handle_get_request_bounded(&request, &[0xBB; 16], 102) + .into_response_with_served_count_bounded(102); + assert_eq!(count, 0); + assert_eq!(bytes, vec![0x90]); + assert!(bytes.capacity() <= 102); + } + + #[test] + fn bounded_get_skips_corrupt_or_grown_file_without_reading_past_plan() { + use rmpv::Value; + let temporary = tempfile::tempdir().unwrap(); + let mut node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [1; 16], + temporary.path().join("store"), + ) + .unwrap(); + let blob = vec![0xBB; 100]; + assert!(node.accept_blob_fixture(&blob, 0)); + let tid = rns_crypto::sha::full_hash(&blob); + let request = crate::encode_value(&Value::Array(vec![ + Value::Array(vec![Value::Binary(tid.to_vec())]), + Value::Array(vec![]), + ])); + let action = node.handle_get_request_bounded(&request, &[0xBB; 16], 103); + std::fs::write(&node.object_paths[&tid], vec![0; 4096]).unwrap(); + assert_eq!( + action.into_response_with_served_count_bounded(103), + (vec![0x90], 0) + ); + } + + #[test] + fn bounded_get_listing_stays_within_reserved_output_capacity() { + use rmpv::Value; + let temporary = tempfile::tempdir().unwrap(); + let mut node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [1; 16], + temporary.path().join("store"), + ) + .unwrap(); + for n in 0..4 { + let mut blob = vec![0xBB; 100 + n]; + blob[20] = n as u8; + assert!(node.accept_blob_fixture(&blob, 0)); + } + let (response, _) = node + .handle_get_request_bounded(&[0x92, 0xc0, 0xc0], &[0xBB; 16], 73) + .into_response_with_served_count_bounded(73); + assert!(response.capacity() <= 73); + assert!( + matches!(rmpv::decode::read_value(&mut response.as_slice()).unwrap(),Value::Array(ids) if ids.len()==2) + ); + } } diff --git a/crates/lxmf-core/src/propagation_send.rs b/crates/lxmf-core/src/propagation_send.rs new file mode 100644 index 0000000..3ca7b6b --- /dev/null +++ b/crates/lxmf-core/src/propagation_send.rs @@ -0,0 +1,292 @@ +//! Shared propagation preparation for daemon and embedding applications. +use crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN; +use crate::message::{LxMessage, MessageError}; +use bytes::Bytes; +use std::sync::atomic::AtomicBool; + +pub const NODE_METADATA_MAX_AGE: f64 = 45.0 * 86400.0; + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub struct AdvertisedNodePolicy { + pub stamp_cost: u8, + pub transfer_limit_kb: f64, + pub recorded_at: f64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MissingPropagationInput { + NodeIdentity, + NodePath, + NodePolicy, + RecipientIdentity, +} + +#[derive(Debug, Clone, Copy)] +pub struct PreparedNode { + pub node: [u8; 16], + pub policy: AdvertisedNodePolicy, +} + +/// Identity and policy freshness are required; the recipient itself may be +/// offline. Only a missing recipient key warrants recipient path discovery. +pub fn propagation_readiness( + node: [u8; 16], + node_identity_known: bool, + node_path_known: bool, + policy: Option, + recipient_identity_known: bool, + now: f64, +) -> Result { + if !node_identity_known { + return Err(MissingPropagationInput::NodeIdentity); + } + if !node_path_known { + return Err(MissingPropagationInput::NodePath); + } + let policy = policy + .filter(|p| { + p.recorded_at.is_finite() + && p.recorded_at <= now + && now - p.recorded_at < NODE_METADATA_MAX_AGE + && p.transfer_limit_kb.is_finite() + && p.transfer_limit_kb >= 0. + }) + .ok_or(MissingPropagationInput::NodePolicy)?; + if !recipient_identity_known { + return Err(MissingPropagationInput::RecipientIdentity); + } + Ok(PreparedNode { node, policy }) +} + +/// One send-owned encryption result. Retrying changes only the outer timestamp +/// and (when required cost rises) the PN stamp, never ciphertext or transient ID. +#[derive(Debug, Clone)] +pub struct PropagationEnvelope { + message: LxMessage, + ciphertext: Bytes, + transient_id: [u8; 32], + encryption_binding: [u8; 32], + stamp: [u8; 32], + stamp_value: u32, + required_cost: u8, +} + +impl PropagationEnvelope { + pub fn new( + message: LxMessage, + encryption_binding: [u8; 32], + required_cost: u8, + encrypt: F, + ) -> Result + where + F: FnOnce(&[u8]) -> Result, MessageError>, + { + Self::new_cancellable( + message, + encryption_binding, + required_cost, + encrypt, + &AtomicBool::new(false), + ) + } + pub fn new_cancellable( + message: LxMessage, + encryption_binding: [u8; 32], + required_cost: u8, + encrypt: F, + cancel: &AtomicBool, + ) -> Result + where + F: FnOnce(&[u8]) -> Result, MessageError>, + { + let encrypted = encrypt(&message.wire_bytes()[16..])?; + let mut ciphertext = Vec::with_capacity(16 + encrypted.len()); + ciphertext.extend_from_slice(&message.destination_hash()); + ciphertext.extend_from_slice(&encrypted); + let transient_id = rns_crypto::sha::full_hash(&ciphertext); + let (stamp, generated_value) = crate::stamper::generate_stamp_cancellable( + &transient_id, + required_cost, + STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, + cancel, + ) + .ok_or_else(|| MessageError::PackFailed("PN stamp generation failed".into()))?; + // The general stamper's cost-zero shortcut reports the required lower + // bound. Envelopes carry the measured value used by strict relay ingress. + let stamp_value = if required_cost == 0 { + crate::stamper::stamp_value( + &crate::stamper::stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN), + &stamp, + ) + } else { + generated_value + }; + if cancel.load(std::sync::atomic::Ordering::Acquire) { + return Err(MessageError::PackFailed( + "PN stamp generation cancelled".into(), + )); + } + Ok(Self { + message, + ciphertext: ciphertext.into(), + transient_id, + encryption_binding, + stamp, + stamp_value, + required_cost, + }) + } + pub fn message(&self) -> &LxMessage { + &self.message + } + pub fn transient_id(&self) -> [u8; 32] { + self.transient_id + } + pub fn ciphertext(&self) -> &Bytes { + &self.ciphertext + } + pub fn stamp(&self) -> &[u8; 32] { + &self.stamp + } + pub fn stamp_value(&self) -> u32 { + self.stamp_value + } + pub fn matches(&self, message: &LxMessage, encryption_binding: &[u8; 32]) -> bool { + self.message.wire_bytes() == message.wire_bytes() + && &self.encryption_binding == encryption_binding + } + /// Call immediately before dispatch with refreshed advertised policy. + pub fn pack_for( + &mut self, + node: PreparedNode, + timestamp: f64, + ) -> Result, MessageError> { + self.pack_for_cancellable(node, timestamp, &AtomicBool::new(false)) + } + pub fn pack_for_cancellable( + &mut self, + node: PreparedNode, + timestamp: f64, + cancel: &AtomicBool, + ) -> Result, MessageError> { + if !timestamp.is_finite() { + return Err(MessageError::PackFailed( + "propagation timestamp must be finite".into(), + )); + } + if self.stamp_value < u32::from(node.policy.stamp_cost) { + (self.stamp, self.stamp_value) = crate::stamper::generate_stamp_cancellable( + &self.transient_id, + node.policy.stamp_cost, + STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, + cancel, + ) + .ok_or_else(|| MessageError::PackFailed("PN stamp regeneration failed".into()))?; + } + self.required_cost = node.policy.stamp_cost; + let blob_len = self + .ciphertext + .len() + .checked_add(32) + .ok_or_else(|| MessageError::PackFailed("PN envelope size overflow".into()))?; + let bin_header = if blob_len < 256 { + 2 + } else if blob_len < 65536 { + 3 + } else { + 5 + }; + let packed_len = blob_len + .checked_add(11 + bin_header) + .ok_or_else(|| MessageError::PackFailed("PN wrapper size overflow".into()))?; + let limit = (node.policy.transfer_limit_kb * 1000.).floor(); + let resource_limit = rns_protocol::resource::MAX_EFFICIENT_SIZE + .checked_mul(rns_protocol::resource::MAX_SEGMENTS) + .unwrap_or(0); + if packed_len as f64 > limit || packed_len > resource_limit { + return Err(MessageError::TooLarge { + size: packed_len, + limit: (limit as usize).min(resource_limit), + }); + } + let mut out = Vec::with_capacity(packed_len); + rmp::encode::write_array_len(&mut out, 2).expect("Vec writer"); + rmp::encode::write_f64(&mut out, timestamp).expect("Vec writer"); + rmp::encode::write_array_len(&mut out, 1).expect("Vec writer"); + rmp::encode::write_bin_len( + &mut out, + u32::try_from(blob_len) + .map_err(|_| MessageError::PackFailed("PN blob too large".into()))?, + ) + .expect("Vec writer"); + out.extend_from_slice(&self.ciphertext); + out.extend_from_slice(&self.stamp); + debug_assert_eq!(out.len(), packed_len); + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constants::DeliveryMethod; + use crate::message::LxMessageDraft; + #[test] + fn offline_recipient_key_is_sufficient_and_zero_cost_is_explicit() { + let policy = AdvertisedNodePolicy { + stamp_cost: 0, + transfer_limit_kb: 256., + recorded_at: 100., + }; + assert!(propagation_readiness([1; 16], true, true, Some(policy), true, 101.).is_ok()); + assert_eq!( + propagation_readiness([1; 16], true, true, None, true, 101.).unwrap_err(), + MissingPropagationInput::NodePolicy + ); + assert_eq!( + propagation_readiness([1; 16], true, true, Some(policy), false, 101.).unwrap_err(), + MissingPropagationInput::RecipientIdentity + ); + } + #[test] + fn retry_and_cost_increase_keep_ciphertext_and_transient_id() { + let key = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[3; 32]); + let msg = LxMessageDraft::new([1; 16], [2; 16], "", "test", DeliveryMethod::Propagated) + .unwrap() + .sign(&key) + .unwrap() + .finalize(None) + .unwrap(); + let mut envelope = PropagationEnvelope::new(msg, [4; 32], 0, |p| Ok(p.to_vec())).unwrap(); + let before = envelope.ciphertext.clone(); + let tid = envelope.transient_id(); + assert_eq!( + envelope.stamp_value(), + crate::stamper::stamp_value( + &crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN), + envelope.stamp(), + ) + ); + let mut prepared = PreparedNode { + node: [5; 16], + policy: AdvertisedNodePolicy { + stamp_cost: 0, + transfer_limit_kb: 256., + recorded_at: 100., + }, + }; + let first = envelope.pack_for(prepared, 101.).unwrap(); + prepared.policy.stamp_cost = 4; + let next = envelope.pack_for(prepared, 102.).unwrap(); + assert_eq!(envelope.ciphertext(), &before); + assert_eq!(envelope.transient_id(), tid); + assert!(envelope.stamp_value() >= 4); + assert_ne!(first, next); + assert!( + crate::stamper::stamp_value( + &crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN), + envelope.stamp() + ) >= 4 + ); + } +} diff --git a/crates/lxmf-core/src/propagation_store_v2.rs b/crates/lxmf-core/src/propagation_store_v2.rs new file mode 100644 index 0000000..188cf7a --- /dev/null +++ b/crates/lxmf-core/src/propagation_store_v2.rs @@ -0,0 +1,456 @@ +//! Provenance-gated relay storage and conservative offline migration. +//! +//! Private local manifests record accepted opaque ingress. They are not an +//! encryption oracle, and old files acquire no authority from their names or +//! apparent envelope shape. Callers exclude external writers from these paths. +#[cfg(target_os = "android")] +mod android_container; +mod migration; +#[cfg(any(target_os = "ios", target_os = "android", test))] +mod mobile; +#[cfg(target_os = "android")] +pub use mobile::begin_android_container_migration; +#[cfg(target_os = "ios")] +pub use mobile::begin_ios_container_migration; +mod offline; +mod recovery; +pub(crate) use migration::open_locked_store; +pub use migration::{ + MigrationReport, QuarantineSummary, migrate_store_offline, open_store, quarantine_summary, +}; +pub use offline::{OfflineMigrationGuard, begin_offline_migration}; +pub use recovery::{ + RecoveryEntry, RecoveryPolicy, RecoveryReport, TrustedRecoveryManifest, + import_trusted_recovery_manifest, +}; + +use rns_identity::persistence::{durable_reconcile, durable_remove, durable_write}; +use serde::{Deserialize, Serialize}; +use std::fs::{self, File}; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +const TOMBSTONE: &[u8] = + b"LXMF relay store moved to v2; legacy hosting and sync must remain disabled.\n"; +const FORMAT: &[u8] = b"LXMF opaque relay store v2; objects and per-entry provenance\n"; +const MAX_MANIFEST_BYTES: usize = 4096; +static STORE_MUTATION_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[derive(Debug, thiserror::Error)] +#[error( + "MigrationRequired: stop all legacy relay writers and run explicit offline store migration" +)] +pub struct MigrationRequired; +pub fn is_migration_required(error: &io::Error) -> bool { + error + .get_ref() + .is_some_and(|inner| inner.is::()) +} +fn err(error: impl std::fmt::Display) -> io::Error { + io::Error::other(error.to_string()) +} +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} +fn sibling(path: &Path, suffix: &str) -> io::Result { + let mut name = path + .file_name() + .ok_or_else(|| invalid("store path has no file name"))? + .to_os_string(); + name.push(suffix); + Ok(path.with_file_name(name)) +} +fn read_bounded(path: &Path, maximum: usize) -> io::Result> { + let metadata = fs::symlink_metadata(path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > maximum as u64 { + return Err(invalid("store record is not a bounded regular file")); + } + let mut data = Vec::new(); + File::open(path)? + .take(maximum as u64 + 1) + .read_to_end(&mut data)?; + if data.len() > maximum { + return Err(invalid("store record grew beyond its bound")); + } + Ok(data) +} +fn canonical_legacy(path: &Path) -> io::Result { + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let parent = fs::canonicalize(parent)?; + let name = path + .file_name() + .ok_or_else(|| invalid("store path has no file name"))?; + if name == "." || name == ".." { + return Err(invalid("invalid store path")); + } + let path = parent.join(name); + if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(invalid("store root cannot be a symbolic link")); + } + Ok(path) +} +pub(crate) fn manifest_path(path: &Path) -> PathBuf { + sibling(path, ".entry").expect("validated object path") +} +pub(crate) fn deletion_path(path: &Path) -> PathBuf { + sibling(path, ".delete").expect("validated object path") +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +pub enum OpaqueIngress { + ValidatedPropagation, + TrustedRecovery, +} +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +enum AdmissionProtocol { + StampedPropagation, + ExplicitTrustedRecovery, +} +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +enum PublicationState { + Committed, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct EntryManifest { + pub version: u8, + admission_id: [u8; 16], + pub transient_id: [u8; 32], + pub content_hash: [u8; 32], + pub destination: [u8; 16], + pub size: usize, + pub stamp_value: u8, + pub stored_at: f64, + pub stamped: bool, + pub origin: OpaqueIngress, + protocol: AdmissionProtocol, + publication: PublicationState, +} +impl EntryManifest { + pub(crate) fn from_entry(entry: &crate::propagation::PropagationEntry, bytes: &[u8]) -> Self { + Self { + version: 2, + admission_id: rand::random(), + transient_id: entry.transient_id, + content_hash: rns_crypto::sha::full_hash(bytes), + destination: entry.destination_hash, + size: bytes.len(), + stamp_value: entry.stamp_value, + stored_at: entry.stored_at, + stamped: entry.stamped, + origin: OpaqueIngress::ValidatedPropagation, + protocol: AdmissionProtocol::StampedPropagation, + publication: PublicationState::Committed, + } + } + pub(crate) fn validate(&self, data: &[u8]) -> bool { + let tail = if self.stamped { 32 } else { 0 }; + self.version == 2 + && self.stored_at.is_finite() + && self.stored_at >= 0.0 + && self.size <= rns_protocol::resource::MAX_RESOURCE_SIZE + && data.len() == self.size + && data.len() > 16 + tail + && data[..16] == self.destination + && rns_crypto::sha::full_hash(data) == self.content_hash + && rns_crypto::sha::full_hash(&data[..data.len() - tail]) == self.transient_id + && matches!( + (self.origin, self.protocol), + ( + OpaqueIngress::ValidatedPropagation, + AdmissionProtocol::StampedPropagation + ) | ( + OpaqueIngress::TrustedRecovery, + AdmissionProtocol::ExplicitTrustedRecovery + ) + ) + && (self.origin == OpaqueIngress::TrustedRecovery || self.stamped) + } + pub(crate) fn filename(&self) -> String { + format!( + "{}_{}", + self.entry().filename(), + hex::encode(self.admission_id) + ) + } + pub(crate) fn entry(&self) -> crate::propagation::PropagationEntry { + let mut entry = crate::propagation::PropagationEntry::new( + self.transient_id, + self.transient_id, + self.destination, + self.size, + self.stamp_value, + ); + entry.stored_at = self.stored_at; + entry.stamped = self.stamped; + entry + } +} +pub(crate) fn read_manifest(path: &Path) -> io::Result<(EntryManifest, Vec)> { + let encoded = read_bounded(&manifest_path(path), MAX_MANIFEST_BYTES)?; + let meta: EntryManifest = rmp_serde::from_slice(&encoded).map_err(err)?; + if meta.filename() != path.file_name().and_then(|s| s.to_str()).unwrap_or("") { + return Err(invalid( + "relay object filename does not match its provenance record", + )); + } + Ok((meta, encoded)) +} +#[derive(Debug, Serialize, Deserialize)] +struct ActiveIndex { + version: u8, + object: String, + manifest_hash: [u8; 32], +} +fn index_path(object: &Path, id: &[u8; 32]) -> io::Result { + Ok(object + .parent() + .ok_or_else(|| invalid("object has no parent"))? + .join(format!("{}.active", hex::encode(id)))) +} +fn check_index(object: &Path, meta: &EntryManifest, encoded: &[u8]) -> io::Result<()> { + let index: ActiveIndex = rmp_serde::from_slice(&read_bounded( + &index_path(object, &meta.transient_id)?, + MAX_MANIFEST_BYTES, + )?) + .map_err(err)?; + if index.version != 2 + || index.object != meta.filename() + || index.manifest_hash != rns_crypto::sha::full_hash(encoded) + { + return Err(invalid( + "object is not the active committed relay admission", + )); + } + Ok(()) +} +pub(crate) fn indexed_object(index_path: &Path) -> io::Result { + let index: ActiveIndex = + rmp_serde::from_slice(&read_bounded(index_path, MAX_MANIFEST_BYTES)?).map_err(err)?; + if index.version != 2 + || Path::new(&index.object).components().count() != 1 + || !matches!( + Path::new(&index.object).components().next(), + Some(std::path::Component::Normal(_)) + ) + { + return Err(invalid("invalid relay active index")); + } + let object = index_path + .parent() + .ok_or_else(|| invalid("active index has no parent"))? + .join(index.object); + let (meta, encoded) = read_manifest(&object)?; + if self::index_path(&object, &meta.transient_id)? != index_path { + return Err(invalid("relay index TID mismatch")); + } + check_index(&object, &meta, &encoded)?; + Ok(object) +} +/// Publish object, provenance, then its per-TID commit index. A cancelled +/// in-memory callback cannot cause retry to replace the first committed image. +pub(crate) fn publish_object( + object: &Path, + meta: &EntryManifest, + data: &[u8], +) -> io::Result<(EntryManifest, PathBuf)> { + let _guard = STORE_MUTATION_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + let index = index_path(object, &meta.transient_id)?; + match fs::symlink_metadata(&index) { + Ok(_) => { + let existing = indexed_object(&index)?; + let (first, encoded) = read_manifest(&existing)?; + let retained = read_validated_file(&existing)?; + durable_reconcile(&existing, &retained).map_err(err)?; + durable_reconcile(&manifest_path(&existing), &encoded).map_err(err)?; + let index_bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?; + durable_reconcile(&index, &index_bytes).map_err(err)?; + return Ok((first, existing)); + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + if !meta.validate(data) + || object.file_name().and_then(|s| s.to_str()) != Some(meta.filename().as_str()) + { + return Err(invalid("invalid relay publication")); + } + let encoded = rmp_serde::to_vec_named(meta).map_err(err)?; + durable_write(object, data).map_err(err)?; + durable_write(&manifest_path(object), &encoded).map_err(err)?; + let active = ActiveIndex { + version: 2, + object: meta.filename(), + manifest_hash: rns_crypto::sha::full_hash(&encoded), + }; + durable_write(&index, &rmp_serde::to_vec_named(&active).map_err(err)?).map_err(err)?; + Ok((meta.clone(), object.to_owned())) +} + +/// Verify the complete indexed admission and renew all three publication +/// barriers. Serialize against retirement so successful return has a concrete +/// committed point, even when a purge was prepared concurrently. +pub(crate) fn verify_committed_object(path: &Path) -> io::Result<()> { + let _guard = STORE_MUTATION_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + let (meta, encoded) = read_manifest(path)?; + let data = read_validated_file(path)?; + durable_reconcile(path, &data).map_err(err)?; + durable_reconcile(&manifest_path(path), &encoded).map_err(err)?; + let index = index_path(path, &meta.transient_id)?; + let bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?; + durable_reconcile(&index, &bytes).map_err(err)?; + check_index(path, &meta, &encoded) +} + +/// Both the manifest and complete bytes are checked at the final read boundary. +/// An unresolved durable deletion always defeats a previously prepared read. +pub(crate) fn read_validated_file(path: &Path) -> io::Result> { + read_validated_file_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE) +} + +/// Refuse oversized metadata before allocating or opening the payload. The +/// caller can therefore reserve its complete GET response budget first. +pub(crate) fn read_validated_file_bounded(path: &Path, maximum: usize) -> io::Result> { + if fs::symlink_metadata(deletion_path(path)).is_ok() { + return Err(invalid("relay object has a pending durable deletion")); + } + let (meta, encoded) = read_manifest(path)?; + check_index(path, &meta, &encoded)?; + if meta.size > maximum.min(rns_protocol::resource::MAX_RESOURCE_SIZE) { + return Err(invalid("relay object exceeds Resource capacity")); + } + let data = read_bounded(path, meta.size)?; + if !meta.validate(&data) { + return Err(invalid("relay object changed after validated admission")); + } + if fs::symlink_metadata(deletion_path(path)).is_ok() { + return Err(invalid("relay object retired while being read")); + } + check_index(path, &meta, &encoded)?; + Ok(data) +} + +#[derive(Debug, Serialize, Deserialize)] +struct DeletionRecord { + version: u8, + object: String, + content_hash: [u8; 32], + transient_id: [u8; 32], +} +/// The durable deletion intent is committed before either indexed file is +/// removed. Keep it across every uncertain cleanup; startup resumes cleanup +/// before loading any active objects. +pub(crate) fn retire_object(path: &Path) -> io::Result<()> { + retire_object_inner(path, false) +} +fn retire_object_inner(path: &Path, fail_after_intent: bool) -> io::Result<()> { + let _guard = STORE_MUTATION_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + let marker = deletion_path(path); + let encoded = match read_bounded(&marker, MAX_MANIFEST_BYTES) { + Ok(encoded) => encoded, + Err(e) if e.kind() == io::ErrorKind::NotFound => { + let (meta, _) = read_manifest(path)?; + let record = DeletionRecord { + version: 2, + object: path + .file_name() + .and_then(|s| s.to_str()) + .ok_or_else(|| invalid("invalid object name"))? + .to_string(), + content_hash: meta.content_hash, + transient_id: meta.transient_id, + }; + rmp_serde::to_vec_named(&record).map_err(err)? + } + Err(e) => return Err(e), + }; + let record: DeletionRecord = rmp_serde::from_slice(&encoded).map_err(err)?; + if record.version != 2 + || Path::new(&record.object).components().count() != 1 + || path.file_name().and_then(|s| s.to_str()) != Some(&record.object) + { + return Err(invalid("deletion record path mismatch")); + } + let witness = durable_write(&marker, &encoded).map_err(err)?; + if fail_after_intent { + return Err(io::Error::other( + "injected interruption after durable deletion intent", + )); + } + let cleanup = (|| -> io::Result<()> { + let index = index_path(path, &record.transient_id)?; + if let Ok(active) = indexed_object(&index) + && active == path + { + durable_remove(&index, &witness).map_err(err)?; + } + durable_remove(path, &witness).map_err(err)?; + durable_remove(&manifest_path(path), &witness).map_err(err)?; + // A separate, retained FORMAT witness may retire the journal only once both + // removals have acknowledged barriers. Failure leaves the journal reusable. + let root = path + .parent() + .and_then(Path::parent) + .ok_or_else(|| invalid("object outside v2 objects directory"))?; + let format = durable_reconcile(&root.join("FORMAT"), FORMAT).map_err(err)?; + durable_remove(&marker, &format).map_err(err)?; + Ok(()) + })(); + if let Err(error) = cleanup { + tracing::warn!(%error, "committed relay deletion retains pending cleanup evidence"); + } + Ok(()) +} +pub(crate) fn reconcile_deletions(root: &Path) -> io::Result<()> { + for entry in fs::read_dir(root.join("objects"))? { + let path = entry?.path(); + if path.extension().and_then(|s| s.to_str()) != Some("delete") { + continue; + } + let object = path.with_extension(""); + retire_object(&object)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn deletion_intent_survives_interruption_and_revokes_all_read_authority() { + let temp = tempfile::tempdir().unwrap(); + let legacy = temp.path().join("store"); + let root = open_store(&legacy).unwrap(); + let mut data = [2; 16].to_vec(); + data.extend_from_slice( + &rns_identity::identity::Identity::new() + .encrypt(b"private payload", None) + .unwrap(), + ); + let tid = rns_crypto::sha::full_hash(&data); + data.extend_from_slice(&[0; 32]); + let mut entry = crate::propagation::PropagationEntry::new(tid, tid, [2; 16], data.len(), 0); + entry.stamped = true; + let meta = EntryManifest::from_entry(&entry, &data); + let object = root.join("objects").join(meta.filename()); + publish_object(&object, &meta, &data).unwrap(); + assert_eq!(read_validated_file(&object).unwrap(), data); + assert!(retire_object_inner(&object, true).is_err()); + assert!(object.exists()); + assert!(deletion_path(&object).exists()); + assert!(read_validated_file(&object).is_err()); + assert!(verify_committed_object(&object).is_err()); + open_store(&legacy).unwrap(); + assert!(!object.exists()); + assert!(!index_path(&object, &tid).unwrap().exists()); + assert!(!deletion_path(&object).exists()); + } +} diff --git a/crates/lxmf-core/src/propagation_store_v2/android_container.rs b/crates/lxmf-core/src/propagation_store_v2/android_container.rs new file mode 100644 index 0000000..e39a525 --- /dev/null +++ b/crates/lxmf-core/src/propagation_store_v2/android_container.rs @@ -0,0 +1,207 @@ +//! Android framework metadata, rather than process-list visibility or guessed +//! /data prefixes, establishes a single-package private-container boundary. +use super::*; +use jni::{ + JNIEnv, + objects::{JObject, JString, JValue}, +}; +use std::os::unix::fs::MetadataExt; + +fn take_string(env: &JNIEnv<'_>, value: JObject<'_>) -> io::Result { + if value.is_null() { + return Err(invalid("Android application metadata is missing")); + } + let result: String = env.get_string(JString::from(value)).map_err(err)?.into(); + env.delete_local_ref(value).map_err(err)?; + Ok(result) +} + +pub(super) fn private_root<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result { + let result = private_root_inner(env, context); + // Return a Rust failure without leaving an unrelated pending Java exception + // on the embedding application's worker thread. + if result.is_err() && env.exception_check().unwrap_or(true) { + let _ = env.exception_clear(); + } + result +} + +fn private_root_inner<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result { + if context.is_null() + || !env + .is_instance_of(context, "android/content/Context") + .map_err(err)? + { + return Err(invalid( + "an initialized Android application context is required", + )); + } + let uid = env + .call_static_method("android/os/Process", "myUid", "()I", &[]) + .map_err(err)? + .i() + .map_err(err)?; + if uid < 0 || uid % 100_000 < 10_000 { + return Err(invalid( + "relay recovery requires a private Android application UID", + )); + } + let manager = env + .call_method( + context, + "getPackageManager", + "()Landroid/content/pm/PackageManager;", + &[], + ) + .map_err(err)? + .l() + .map_err(err)?; + let packages = env + .call_method( + manager, + "getPackagesForUid", + "(I)[Ljava/lang/String;", + &[JValue::Int(uid)], + ) + .map_err(err)? + .l() + .map_err(err)?; + if packages.is_null() || env.get_array_length(packages.into_inner()).map_err(err)? != 1 { + return Err(invalid( + "shared or unknown Android UID cannot authorize relay migration", + )); + } + let package = take_string( + env, + env.get_object_array_element(packages.into_inner(), 0) + .map_err(err)?, + )?; + let context_package = take_string( + env, + env.call_method(context, "getPackageName", "()Ljava/lang/String;", &[]) + .map_err(err)? + .l() + .map_err(err)?, + )?; + if package != context_package { + return Err(invalid("Android context does not own this application UID")); + } + let mut cmdline = Vec::new(); + File::open("/proc/self/cmdline")? + .take(4097) + .read_to_end(&mut cmdline)?; + if cmdline.len() > 4096 || cmdline.split(|b| *b == 0).next() != Some(package.as_bytes()) { + return Err(invalid( + "relay migration is restricted to the default Android app process", + )); + } + let package_string = env.new_string(&package).map_err(err)?; + // Resolve all four component classes, including disabled declarations. A + // secondary process can own the same private UID even if it is not running. + const FLAGS: i32 = 1 | 2 | 4 | 8 | 512; + let info = env + .call_method( + manager, + "getPackageInfo", + "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;", + &[JValue::Object(package_string.into()), JValue::Int(FLAGS)], + ) + .map_err(err)? + .l() + .map_err(err)?; + if !env + .get_field(info, "sharedUserId", "Ljava/lang/String;") + .map_err(err)? + .l() + .map_err(err)? + .is_null() + { + return Err(invalid( + "sharedUserId applications cannot authorize relay migration", + )); + } + let application = env + .get_field( + info, + "applicationInfo", + "Landroid/content/pm/ApplicationInfo;", + ) + .map_err(err)? + .l() + .map_err(err)?; + if env + .get_field(application, "uid", "I") + .map_err(err)? + .i() + .map_err(err)? + != uid + { + return Err(invalid("Android application UID changed")); + } + let process = take_string( + env, + env.get_field(application, "processName", "Ljava/lang/String;") + .map_err(err)? + .l() + .map_err(err)?, + )?; + if process != package { + return Err(invalid( + "custom Android application process is not qualified", + )); + } + for (field, signature) in [ + ("activities", "[Landroid/content/pm/ActivityInfo;"), + ("receivers", "[Landroid/content/pm/ActivityInfo;"), + ("services", "[Landroid/content/pm/ServiceInfo;"), + ("providers", "[Landroid/content/pm/ProviderInfo;"), + ] { + let components = env + .get_field(info, field, signature) + .map_err(err)? + .l() + .map_err(err)?; + if components.is_null() { + continue; + } + let count = env.get_array_length(components.into_inner()).map_err(err)?; + if !(0..=4096).contains(&count) { + return Err(invalid( + "Android component inventory exceeds migration bound", + )); + } + for index in 0..count { + let component = env + .get_object_array_element(components.into_inner(), index) + .map_err(err)?; + let process = take_string( + env, + env.get_field(component, "processName", "Ljava/lang/String;") + .map_err(err)? + .l() + .map_err(err)?, + )?; + env.delete_local_ref(component).map_err(err)?; + if process != package { + return Err(invalid( + "multi-process Android apps cannot authorize relay migration", + )); + } + } + env.delete_local_ref(components).map_err(err)?; + } + let root = fs::canonicalize(take_string( + env, + env.get_field(application, "dataDir", "Ljava/lang/String;") + .map_err(err)? + .l() + .map_err(err)?, + )?)?; + let metadata = fs::metadata(&root)?; + if !metadata.is_dir() || metadata.uid() != uid as u32 || metadata.mode() & 0o022 != 0 { + return Err(invalid( + "Android data directory lacks exclusive application ownership", + )); + } + Ok(root) +} diff --git a/crates/lxmf-core/src/propagation_store_v2/migration.rs b/crates/lxmf-core/src/propagation_store_v2/migration.rs new file mode 100644 index 0000000..ed91735 --- /dev/null +++ b/crates/lxmf-core/src/propagation_store_v2/migration.rs @@ -0,0 +1,466 @@ +use super::*; +use rns_identity::persistence::{ + DurableFileReceipt, durable_create_dir_all, durable_reconcile_hash, durable_rename_directory, +}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; + +const MAX_INVENTORY: usize = 65_536; +const MAX_JOURNAL: usize = 32 * 1024 * 1024; +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct InventoryEntry { + pub path: PathBuf, + pub bytes: u64, + pub hash: Option<[u8; 32]>, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +struct MigrationJournal { + version: u8, + legacy: PathBuf, + archive: PathBuf, + v2: PathBuf, + inventory: Vec, + had_legacy: bool, + phase: u8, + renewal: Option, + renewal_sequence: u64, +} +#[derive(Debug, Clone)] +pub struct MigrationReport { + pub store: PathBuf, + pub quarantine: QuarantineSummary, +} +#[derive(Debug, Clone)] +pub struct QuarantineSummary { + pub files: usize, + pub bytes: u64, + pub reason: &'static str, +} +fn summary(j: &MigrationJournal) -> QuarantineSummary { + QuarantineSummary { + files: j.inventory.iter().filter(|e| e.hash.is_some()).count(), + bytes: j + .inventory + .iter() + .fold(0u64, |n, e| n.saturating_add(e.bytes)), + reason: "Preserved legacy files have no trusted per-entry opaque-ingress provenance", + } +} +fn encode(j: &MigrationJournal) -> io::Result> { + let encoded = rmp_serde::to_vec_named(j).map_err(err)?; + if encoded.len() > MAX_JOURNAL { + return Err(invalid("migration inventory exceeds journal bound")); + } + Ok(encoded) +} +fn paths(legacy: &Path) -> io::Result<(PathBuf, PathBuf, PathBuf)> { + Ok(( + sibling(legacy, ".migration")?, + sibling(legacy, ".legacy-quarantine")?, + sibling(legacy, ".v2")?, + )) +} +fn save(j: &MigrationJournal) -> io::Result { + durable_write(&paths(&j.legacy)?.0, &encode(j)?).map_err(err) +} +fn read_journal(legacy: &Path) -> io::Result { + let (path, archive, v2) = paths(legacy)?; + let j: MigrationJournal = + rmp_serde::from_slice(&read_bounded(&path, MAX_JOURNAL)?).map_err(err)?; + if j.version != 2 + || j.phase > 4 + || j.legacy != legacy + || j.archive != archive + || j.v2 != v2 + || j.inventory.len() > MAX_INVENTORY + { + return Err(invalid("migration journal path/version/phase mismatch")); + } + let mut unique = BTreeSet::new(); + for entry in &j.inventory { + if !safe_relative(&entry.path) || !unique.insert(entry.path.clone()) { + return Err(invalid("invalid inventory path")); + } + } + if let Some(path) = &j.renewal + && *path != sibling(&archive, &format!(".renewal-{}", j.renewal_sequence))? + { + return Err(invalid("directory renewal path mismatch")); + } + Ok(j) +} +pub fn quarantine_summary(legacy: &Path) -> io::Result { + Ok(summary(&read_journal(&canonical_legacy(legacy)?)?)) +} +fn safe_relative(path: &Path) -> bool { + !path.as_os_str().is_empty() + && path.as_os_str().len() <= 4096 + && path.components().count() <= 32 + && path + .components() + .all(|p| matches!(p, std::path::Component::Normal(_))) +} +fn hash_file(path: &Path) -> io::Result<(u64, [u8; 32])> { + let before = fs::symlink_metadata(path)?; + if !before.is_file() || before.file_type().is_symlink() { + return Err(invalid("legacy inventory contains a nonregular file")); + } + let mut file = File::open(path)?; + let mut hash = Sha256::new(); + let mut count = 0u64; + let mut buffer = [0; 8192]; + loop { + let n = file.read(&mut buffer)?; + if n == 0 { + break; + } + count = count + .checked_add(n as u64) + .ok_or_else(|| invalid("legacy size overflow"))?; + hash.update(&buffer[..n]); + } + let after = file.metadata()?; + if count != before.len() || after.len() != count || before.modified()? != after.modified()? { + return Err(invalid("legacy file changed during inventory")); + } + Ok((count, hash.finalize().into())) +} +fn inventory(root: &Path) -> io::Result> { + let metadata = fs::symlink_metadata(root)?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(invalid("legacy root is not a real directory")); + } + let mut todo = vec![PathBuf::new()]; + let mut result = Vec::new(); + while let Some(relative) = todo.pop() { + for entry in fs::read_dir(root.join(&relative))? { + let entry = entry?; + let relative = relative.join(entry.file_name()); + if !safe_relative(&relative) || result.len() >= MAX_INVENTORY { + return Err(invalid("legacy inventory exceeds safe path/count bound")); + } + let m = fs::symlink_metadata(entry.path())?; + if m.file_type().is_symlink() { + return Err(invalid( + "legacy symbolic links require explicit operator recovery", + )); + } + if m.is_dir() { + result.push(InventoryEntry { + path: relative.clone(), + bytes: 0, + hash: None, + }); + todo.push(relative); + } else if m.is_file() { + let (bytes, hash) = hash_file(&entry.path())?; + result.push(InventoryEntry { + path: relative, + bytes, + hash: Some(hash), + }); + } else { + return Err(invalid( + "legacy special files require explicit operator recovery", + )); + } + } + } + result.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(result) +} +fn verify_inventory(root: &Path, j: &MigrationJournal) -> io::Result<()> { + if inventory(root)? != j.inventory { + return Err(invalid( + "legacy inventory changed; preserve original and investigate before recovery", + )); + } + Ok(()) +} +/// Startup only initializes a truly absent store. An incomplete journal or +/// historical directory requires the explicit offline recovery path. +pub fn open_store(legacy: &Path) -> io::Result { + Ok(open_locked_store(legacy)?.0) +} +pub(crate) fn open_locked_store(legacy: &Path) -> io::Result<(PathBuf, File)> { + let legacy = canonical_legacy(legacy)?; + let lock = offline::lock_store(&legacy)?; + let (journal, archive, v2) = paths(&legacy)?; + if journal.exists() { + let j = read_journal(&legacy)?; + if j.phase != 4 || j.renewal.is_some() { + return Err(io::Error::other(MigrationRequired)); + } + verify_published(&j)?; + reconcile_deletions(&v2)?; + return Ok((v2, lock)); + } + if fs::symlink_metadata(&legacy).is_ok() + || fs::symlink_metadata(&archive).is_ok() + || fs::symlink_metadata(&v2).is_ok() + { + return Err(io::Error::other(MigrationRequired)); + } + let j = MigrationJournal { + version: 2, + legacy: legacy.clone(), + archive, + v2, + inventory: Vec::new(), + had_legacy: false, + phase: 0, + renewal: None, + renewal_sequence: 0, + }; + save(&j)?; + let report = run(j, None)?; + Ok((report.store, lock)) +} +fn verify_published(j: &MigrationJournal) -> io::Result<()> { + if read_bounded(&j.legacy, 256)? != TOMBSTONE + || read_bounded(&j.v2.join("FORMAT"), 256)? != FORMAT + { + return Err(invalid("v2 format or old-path guard mismatch")); + } + let objects = fs::symlink_metadata(j.v2.join("objects"))?; + if !objects.is_dir() || objects.file_type().is_symlink() { + return Err(invalid("v2 objects directory invalid")); + } + durable_reconcile(&j.legacy, TOMBSTONE).map_err(err)?; + durable_reconcile(&j.v2.join("FORMAT"), FORMAT).map_err(err)?; + Ok(()) +} +/// The guard binds both path and verified writer exclusion. Neither a retry nor +/// operator approval promotes any legacy object without independent provenance. +pub fn migrate_store_offline(guard: &OfflineMigrationGuard) -> io::Result { + migrate(&guard.legacy, None) +} +fn migrate(legacy: &Path, fault: Option) -> io::Result { + let canonical = canonical_legacy(legacy)?; + let legacy = canonical.as_path(); + let (journal, archive, v2) = paths(legacy)?; + let j = if journal.exists() { + read_journal(legacy)? + } else { + if archive.exists() || v2.exists() { + return Err(invalid( + "unowned archive/v2 path already exists; refusing overwrite", + )); + } + let had_legacy = fs::symlink_metadata(legacy).is_ok(); + let inventory = if had_legacy { + inventory(legacy)? + } else { + Vec::new() + }; + let j = MigrationJournal { + version: 2, + legacy: legacy.to_owned(), + archive, + v2, + inventory, + had_legacy, + phase: 0, + renewal: None, + renewal_sequence: 0, + }; + save(&j)?; + fail(fault, 0)?; + j + }; + run(j, fault) +} +fn fail(fault: Option, stage: u8) -> io::Result<()> { + if fault == Some(stage) { + Err(io::Error::other(format!( + "injected migration boundary {stage}" + ))) + } else { + Ok(()) + } +} +/// Re-publish a renamed archive through two fresh sibling transitions. This is +/// valid on Windows WRITE_THROUGH and avoids pretending existing directories +/// can be acknowledged by a generic file flush. Every recovery target is journaled. +fn renew_archive(j: &mut MigrationJournal, fault: Option) -> io::Result<()> { + if let Some(temporary) = j.renewal.clone() { + match (j.archive.exists(), temporary.exists()) { + (false, true) => { + verify_inventory(&temporary, j)?; + let witness = save(j)?; + durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?; + fail(fault, 6)?; + j.renewal = None; + save(j)?; + return Ok(()); + } + (true, false) => { + j.renewal = None; + } + _ => { + return Err(invalid( + "ambiguous archive renewal state; originals preserved", + )); + } + } + } + verify_inventory(&j.archive, j)?; + j.renewal_sequence = j + .renewal_sequence + .checked_add(1) + .ok_or_else(|| invalid("renewal generation exhausted"))?; + let temporary = sibling(&j.archive, &format!(".renewal-{}", j.renewal_sequence))?; + if fs::symlink_metadata(&temporary).is_ok() { + return Err(invalid("recovery target already exists")); + } + j.renewal = Some(temporary.clone()); + let witness = save(j)?; + durable_rename_directory(&j.archive, &temporary, &witness).map_err(err)?; + fail(fault, 5)?; + // Rewrite the journal after the first acknowledged move; if this write is + // uncertain the existing intent still describes both permitted locations. + let witness = save(j)?; + durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?; + fail(fault, 6)?; + j.renewal = None; + save(j)?; + Ok(()) +} +fn run(mut j: MigrationJournal, fault: Option) -> io::Result { + if j.had_legacy { + if j.legacy.is_dir() { + if j.phase != 0 || j.archive.exists() || j.renewal.is_some() { + return Err(invalid("ambiguous legacy archive state")); + } + verify_inventory(&j.legacy, &j)?; + // Renew barriers for every retained file before its directory move. + for entry in j.inventory.iter().filter(|e| e.hash.is_some()) { + let maximum = usize::try_from(entry.bytes).map_err(err)?; + durable_reconcile_hash(&j.legacy.join(&entry.path), entry.hash.unwrap(), maximum) + .map_err(err)?; + } + let witness = save(&j)?; + durable_rename_directory(&j.legacy, &j.archive, &witness).map_err(err)?; + fail(fault, 1)?; + } else { + renew_archive(&mut j, fault)?; + } + verify_inventory(&j.archive, &j)?; + } else if j.archive.exists() || j.renewal.is_some() { + return Err(invalid("unexpected archive for a fresh store")); + } + if j.phase < 1 { + j.phase = 1; + save(&j)?; + } + match fs::symlink_metadata(&j.legacy) { + Ok(_) if read_bounded(&j.legacy, 256)? != TOMBSTONE => { + return Err(invalid("unknown old-path guard")); + } + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => {} + } + durable_write(&j.legacy, TOMBSTONE).map_err(err)?; + fail(fault, 2)?; + if j.phase < 2 { + j.phase = 2; + save(&j)?; + } + let witness = save(&j)?; + durable_create_dir_all(&j.v2, &witness).map_err(err)?; + durable_create_dir_all(&j.v2.join("objects"), &witness).map_err(err)?; + durable_write(&j.v2.join("FORMAT"), FORMAT).map_err(err)?; + fail(fault, 3)?; + if j.phase < 3 { + j.phase = 3; + save(&j)?; + } + verify_published(&j)?; + j.phase = 4; + save(&j)?; + fail(fault, 4)?; + Ok(MigrationReport { + store: j.v2.clone(), + quarantine: summary(&j), + }) +} +pub(super) fn verified_archive( + guard: &OfflineMigrationGuard, +) -> io::Result<(PathBuf, PathBuf, Vec)> { + let j = read_journal(&guard.legacy)?; + if j.phase != 4 || j.renewal.is_some() { + return Err(io::Error::other(MigrationRequired)); + } + verify_published(&j)?; + verify_inventory(&j.archive, &j)?; + Ok((j.archive, j.v2, j.inventory)) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn migration_preserves_inventory_and_never_promotes_legacy_bytes() { + let temp = tempfile::tempdir().unwrap(); + let legacy = temp.path().join("store"); + fs::create_dir(&legacy).unwrap(); + fs::write(legacy.join("opaque"), [3; 200]).unwrap(); + fs::write(legacy.join("plaintext"), b"private message").unwrap(); + assert!(is_migration_required(&open_store(&legacy).unwrap_err())); + let report = migrate(&legacy, None).unwrap(); + assert_eq!(report.quarantine.files, 2); + assert_eq!( + fs::read( + sibling(&legacy, ".legacy-quarantine") + .unwrap() + .join("plaintext") + ) + .unwrap(), + b"private message" + ); + assert_eq!( + fs::read_dir(report.store.join("objects")).unwrap().count(), + 0 + ); + assert!(open_store(&legacy).is_ok()); + } + #[test] + fn every_migration_and_renewal_boundary_resumes_without_losing_originals() { + for stage in 0..=6 { + let temp = tempfile::tempdir().unwrap(); + let legacy = temp.path().join("store"); + fs::create_dir(&legacy).unwrap(); + fs::write(legacy.join("message"), b"untouched").unwrap(); + if stage >= 5 { + assert!(migrate(&legacy, Some(1)).is_err()); + } + assert!(migrate(&legacy, Some(stage)).is_err()); + let report = migrate(&legacy, None).unwrap(); + assert_eq!(report.quarantine.files, 1); + assert_eq!( + fs::read( + sibling(&legacy, ".legacy-quarantine") + .unwrap() + .join("message") + ) + .unwrap(), + b"untouched" + ); + assert!(open_store(&legacy).is_ok()); + } + } + #[test] + fn changed_inventory_and_unowned_targets_fail_without_overwrite() { + let temp = tempfile::tempdir().unwrap(); + let legacy = temp.path().join("store"); + fs::create_dir(&legacy).unwrap(); + fs::write(legacy.join("message"), b"original").unwrap(); + assert!(migrate(&legacy, Some(0)).is_err()); + fs::write(legacy.join("message"), b"changed").unwrap(); + assert!(migrate(&legacy, None).is_err()); + assert!(legacy.is_dir()); + let other = temp.path().join("other"); + fs::create_dir(sibling(&other, ".v2").unwrap()).unwrap(); + assert!(open_store(&other).is_err()); + assert!(!other.exists()); + } +} diff --git a/crates/lxmf-core/src/propagation_store_v2/mobile.rs b/crates/lxmf-core/src/propagation_store_v2/mobile.rs new file mode 100644 index 0000000..ef0e08f --- /dev/null +++ b/crates/lxmf-core/src/propagation_store_v2/mobile.rs @@ -0,0 +1,167 @@ +//! Restricted app-container migration authority. This is not an arbitrary-path +//! alternative to the desktop process probe. All current host workers must be +//! joined by the application before acquisition; the same v2 OS lock additionally +//! rejects live current hosts. iOS's main-app/container lifecycle excludes an +//! older installed bundle from concurrently owning this private data container. +use super::*; + +fn contained_store(legacy: &Path, root: &Path) -> io::Result { + let root = fs::canonicalize(root)?; + let legacy = canonical_legacy(legacy)?; + let parent = legacy + .parent() + .ok_or_else(|| invalid("store has no parent"))?; + if parent == root || !parent.starts_with(&root) { + return Err(invalid( + "relay migration requires a nested private app-container path", + )); + } + Ok(legacy) +} + +/// Acquire migration authority only inside the current native iOS main app's +/// private data container. App groups, extensions, external directories, and +/// command-line processes are refused. No caller-supplied root or skip flag is +/// accepted. Hold the application's identity/session lifecycle guard, stop all +/// hosted and sync writers, and join their actual workers before calling this. +#[cfg(target_os = "ios")] +pub fn begin_ios_container_migration(legacy: &Path) -> io::Result { + let root = native_ios_container()?; + let legacy = contained_store(legacy, &root)?; + let lock = offline::lock_store(&legacy)?; + Ok(offline::OfflineMigrationGuard { + legacy, + _lock: lock, + }) +} + +/// Acquire migration authority for the platform Context's single-package, +/// single-process private Android data directory. Shared UIDs, declared remote +/// processes, mismatched contexts and external/group-writable roots are refused. +/// The caller must hold its lifecycle guard and join all hosted/sync writers; +/// the returned guard also retains the same OS lock used by current v2 hosts. +#[cfg(target_os = "android")] +pub fn begin_android_container_migration<'a>( + legacy: &Path, + env: &jni::JNIEnv<'a>, + context: jni::objects::JObject<'a>, +) -> io::Result { + let root = android_container::private_root(env, context)?; + let legacy = contained_store(legacy, &root)?; + let lock = offline::lock_store(&legacy)?; + Ok(offline::OfflineMigrationGuard { + legacy, + _lock: lock, + }) +} + +#[cfg(target_os = "ios")] +fn native_ios_container() -> io::Result { + use objc2::{ + msg_send, + rc::autoreleasepool, + runtime::{AnyClass, AnyObject}, + }; + use std::ffi::CStr; + #[link(name = "Foundation", kind = "framework")] + unsafe extern "C" { + fn NSHomeDirectory() -> *mut AnyObject; + } + // SAFETY: both values are Foundation NSStrings, alive for the surrounding + // autorelease pool; UTF8String is copied before leaving that pool. + unsafe fn string(value: *mut AnyObject) -> io::Result { + if value.is_null() { + return Err(invalid("native app-container metadata unavailable")); + } + let bytes: *const std::ffi::c_char = unsafe { msg_send![value, UTF8String] }; + if bytes.is_null() { + return Err(invalid("native app-container path unavailable")); + } + unsafe { CStr::from_ptr(bytes) } + .to_str() + .map(str::to_owned) + .map_err(err) + } + autoreleasepool(|_| { + let class = AnyClass::get(c"NSBundle").ok_or_else(|| invalid("NSBundle unavailable"))?; + // SAFETY: documented synchronous Foundation getters, no ownership transfer. + let bundle: *mut AnyObject = unsafe { msg_send![class, mainBundle] }; + if bundle.is_null() { + return Err(invalid("native main app bundle unavailable")); + } + let path: *mut AnyObject = unsafe { msg_send![bundle, bundlePath] }; + let identifier: *mut AnyObject = unsafe { msg_send![bundle, bundleIdentifier] }; + let bundle_path = PathBuf::from(unsafe { string(path)? }); + if bundle_path.extension().and_then(|s| s.to_str()) != Some("app") + || unsafe { string(identifier)? }.is_empty() + { + return Err(invalid("relay migration requires an iOS main application")); + } + let root = fs::canonicalize(unsafe { string(NSHomeDirectory())? })?; + if !ios_data_container_path(&root) { + return Err(invalid( + "native home is not a private iOS app data container", + )); + } + Ok(root) + }) +} + +// The native home API, not this shape alone, supplies authority. Reject future +// unknown layouts instead of silently certifying a shared or group container. +#[cfg(any(target_os = "ios", test))] +fn ios_data_container_path(root: &Path) -> bool { + let Some(id) = root.file_name().and_then(|s| s.to_str()) else { + return false; + }; + let valid_id = id.len() == 36 + && id.bytes().enumerate().all(|(index, byte)| { + if [8, 13, 18, 23].contains(&index) { + byte == b'-' + } else { + byte.is_ascii_hexdigit() + } + }); + valid_id + && root + .parent() + .is_some_and(|p| p.ends_with("Containers/Data/Application")) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn private_container_policy_rejects_groups_siblings_and_root_store() { + assert!(ios_data_container_path(Path::new( + "/private/var/mobile/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef" + ))); + assert!(ios_data_container_path(Path::new( + "/sim/device/data/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef" + ))); + assert!(!ios_data_container_path(Path::new( + "/private/var/mobile/Containers/Shared/AppGroup/01234567-89AB-CDEF-0123-456789abcdef" + ))); + assert!(!ios_data_container_path(Path::new( + "/private/var/mobile/Containers/Bundle/Application/01234567-89AB-CDEF-0123-456789abcdef" + ))); + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("private"); + let nested = root.join("Library/state"); + fs::create_dir_all(&nested).unwrap(); + assert!(contained_store(&nested.join("relay"), &root).is_ok()); + assert!(contained_store(&root.join("relay"), &root).is_err()); + assert!(contained_store(&temp.path().join("relay"), &root).is_err()); + } + #[cfg(unix)] + #[test] + fn private_container_policy_rejects_symlink_escape() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("private"); + let outside = temp.path().join("external"); + fs::create_dir_all(&root).unwrap(); + fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap(); + assert!(contained_store(&root.join("escape/relay"), &root).is_err()); + } +} diff --git a/crates/lxmf-core/src/propagation_store_v2/offline.rs b/crates/lxmf-core/src/propagation_store_v2/offline.rs new file mode 100644 index 0000000..daf7f70 --- /dev/null +++ b/crates/lxmf-core/src/propagation_store_v2/offline.rs @@ -0,0 +1,165 @@ +use super::*; +use std::process::{Command, Stdio}; + +/// Holds the same OS lock as every v2 host. Legacy binaries ignore this lock; +/// the mandatory supervisor assertion and known-process probe address that gap. +pub struct OfflineMigrationGuard { + pub(super) legacy: PathBuf, + pub(super) _lock: File, +} + +pub(super) fn lock_store(legacy: &Path) -> io::Result { + let mut options = fs::OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let path = sibling(legacy, ".store-lock")?; + if fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file() || m.file_type().is_symlink()) { + return Err(invalid("invalid relay store lock")); + } + let lock = options.open(path)?; + rns_identity::persistence::try_lock_exclusive(&lock)?; + Ok(lock) +} + +/// The adapter must first stop its own hosting workers and service auto-restart. +/// This probes known app/daemon names and refuses if process enumeration fails. +/// Manually launching an old binary during migration remains unsupported. +pub fn begin_offline_migration( + legacy: &Path, + supervisor_writers_stopped: bool, +) -> io::Result { + if !supervisor_writers_stopped { + return Err(invalid( + "stop relay writers and their service supervisors before migration", + )); + } + let legacy = canonical_legacy(legacy)?; + let lock = lock_store(&legacy)?; + refuse_known_relay_processes()?; + Ok(OfflineMigrationGuard { + legacy, + _lock: lock, + }) +} +fn known_name(value: &str) -> bool { + let value = value + .trim_matches('"') + .rsplit(['/', '\\']) + .next() + .unwrap_or(value) + .to_ascii_lowercase(); + matches!( + value.as_str(), + "ratspeak" | "ratspeak.exe" | "lxmd" | "lxmd.py" | "lxmd-rs" | "lxmd-rs.exe" + ) +} +fn refuse_known_relay_processes() -> io::Result<()> { + #[cfg(unix)] + let mut command = { + let mut c = Command::new("ps"); + c.args(["-axo", "pid=,comm=,args="]); + c + }; + #[cfg(windows)] + let mut command = { + let mut c = Command::new("tasklist"); + c.args(["/FO", "CSV", "/NH"]); + c + }; + #[cfg(not(any(unix, windows)))] + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "process exclusion cannot be verified on this platform", + )); + #[cfg(any(unix, windows))] + { + command.stdout(Stdio::piped()).stderr(Stdio::null()); + let mut child = command.spawn()?; + let mut output = Vec::new(); + let read = child + .stdout + .take() + .ok_or_else(|| invalid("process probe has no output"))? + .take(4 * 1024 * 1024 + 1) + .read_to_end(&mut output); + if read.is_err() || output.len() > 4 * 1024 * 1024 { + let _ = child.kill(); + let _ = child.wait(); + return Err(invalid("process inventory exceeds safe bound")); + } + if !child.wait()?.success() { + return Err(invalid( + "process enumeration unavailable; relay writer exclusion unverified", + )); + } + let listing = std::str::from_utf8(&output).map_err(err)?; + check_listing(listing, std::process::id(), cfg!(windows)) + } +} +fn check_listing(listing: &str, own_pid: u32, windows: bool) -> io::Result<()> { + for line in listing.lines().filter(|l| !l.trim().is_empty()) { + if windows { + let fields: Vec<_> = line.trim_matches('"').split("\",\"").collect(); + if fields.len() < 2 { + return Err(invalid("unrecognized process inventory")); + } + let pid: u32 = fields[1].parse().map_err(err)?; + if pid != own_pid && known_name(fields[0]) { + return Err(invalid("a known relay app/daemon is still running")); + } + } else { + let mut fields = line.split_whitespace(); + let pid: u32 = fields + .next() + .ok_or_else(|| invalid("missing process ID"))? + .parse() + .map_err(err)?; + let Some(comm) = fields.next() else { + return Err(invalid("missing process name")); + }; + if pid == own_pid { + continue; + } + // For interpreted daemons, inspect only the executable/script prefix, + // not arbitrary argument text belonging to shells or other programs. + let python = comm + .rsplit('/') + .next() + .is_some_and(|c| c.starts_with("python")); + if known_name(comm) || (python && fields.take(3).any(known_name)) { + return Err(invalid("a known relay app/daemon is still running")); + } + } + } + Ok(()) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn known_process_probe_is_fail_closed_and_excludes_only_own_pid() { + assert!( + check_listing( + "7 /Applications/Ratspeak /Applications/Ratspeak\n", + 8, + false + ) + .is_err() + ); + assert!( + check_listing( + "7 /Applications/Ratspeak /Applications/Ratspeak\n", + 7, + false + ) + .is_ok() + ); + assert!(check_listing("9 python3 python3 /usr/bin/lxmd --service\n", 7, false).is_err()); + assert!(check_listing("oops", 7, false).is_err()); + assert!(check_listing("\"lxmd-rs.exe\",\"9\",\"Console\"", 7, true).is_err()); + } +} diff --git a/crates/lxmf-core/src/propagation_store_v2/recovery.rs b/crates/lxmf-core/src/propagation_store_v2/recovery.rs new file mode 100644 index 0000000..68f478f --- /dev/null +++ b/crates/lxmf-core/src/propagation_store_v2/recovery.rs @@ -0,0 +1,330 @@ +use super::*; +use std::collections::{HashMap, HashSet}; + +/// A local owner's independently verified ingress record. The approved manifest +/// digest is supplied separately by the recovery UI/CLI; a location or blanket +/// 'recover all' action is never an origin assertion. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TrustedRecoveryManifest { + pub version: u8, + pub provenance: String, + pub entries: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RecoveryEntry { + pub archive_relative_path: PathBuf, + pub content_hash: [u8; 32], + pub transient_id: [u8; 32], + pub stamped: bool, + pub stored_at: f64, +} +#[derive(Debug, Clone, Copy)] +pub struct RecoveryPolicy { + pub maximum_store_bytes: usize, + pub maximum_message_bytes: usize, + pub minimum_stamp_cost: u8, +} +#[derive(Debug, Clone, Copy)] +pub struct RecoveryReport { + pub imported: usize, + pub already_present: usize, +} + +fn validate( + record: &RecoveryEntry, + bytes: &[u8], + minimum_stamp_cost: u8, +) -> io::Result { + let tail = if record.stamped { 32 } else { 0 }; + if bytes.len() < 112 + tail + || !record.stored_at.is_finite() + || record.stored_at < 0.0 + || rns_crypto::sha::full_hash(bytes) != record.content_hash + { + return Err(invalid("recovery content hash/length/time mismatch")); + } + let opaque = &bytes[..bytes.len() - tail]; + if !(opaque.len() - 16 - 32 - rns_crypto::TOKEN_OVERHEAD).is_multiple_of(16) + || rns_crypto::sha::full_hash(opaque) != record.transient_id + { + return Err(invalid("recovery envelope/TID mismatch")); + } + if crate::message::LxMessage::unpack(opaque).is_ok() + || crate::message::LxMessage::unpack(bytes).is_ok() + { + return Err(invalid( + "raw plaintext LXMF is never eligible for relay recovery", + )); + } + let stamp_value = if record.stamped { + let stamp: &[u8; 32] = bytes[bytes.len() - 32..].try_into().map_err(err)?; + let workblock = crate::stamper::stamp_workblock( + &record.transient_id, + crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, + ); + let value = crate::stamper::stamp_value(&workblock, stamp).min(255) as u8; + if value < minimum_stamp_cost { + return Err(invalid("recovered stamp does not meet node policy")); + } + value + } else { + if minimum_stamp_cost > 0 { + return Err(invalid("unstamped recovery does not meet node policy")); + } + 0 + }; + let mut destination = [0; 16]; + destination.copy_from_slice(&bytes[..16]); + let mut entry = crate::propagation::PropagationEntry::new( + record.transient_id, + record.transient_id, + destination, + bytes.len(), + stamp_value, + ); + entry.stored_at = record.stored_at; + entry.stamped = record.stamped; + let mut manifest = EntryManifest::from_entry(&entry, bytes); + manifest.origin = OpaqueIngress::TrustedRecovery; + manifest.protocol = AdmissionProtocol::ExplicitTrustedRecovery; + Ok(manifest) +} + +/// Import exact positively attested archive entries under the same offline +/// guard. Every entry is checked before the first write, then rechecked at its +/// publication boundary. Partial IO completion is restart-safe and idempotent. +pub fn import_trusted_recovery_manifest( + guard: &OfflineMigrationGuard, + path: &Path, + approved_manifest_sha256: [u8; 32], + policy: RecoveryPolicy, +) -> io::Result { + let encoded = read_bounded(path, 32 * 1024 * 1024)?; + if rns_crypto::sha::full_hash(&encoded) != approved_manifest_sha256 { + return Err(invalid("recovery manifest changed after approval")); + } + let recovery: TrustedRecoveryManifest = rmp_serde::from_slice(&encoded).map_err(err)?; + if recovery.version != 2 + || recovery.provenance.trim().is_empty() + || recovery.provenance.len() > 4096 + || recovery.entries.len() > 65_536 + { + return Err(invalid("invalid trusted recovery manifest")); + } + let (archive, root, inventory) = migration::verified_archive(guard)?; + let known: HashMap<_, _> = inventory + .into_iter() + .filter_map(|e| e.hash.map(|h| (e.path, (e.bytes, h)))) + .collect(); + let mut existing = HashMap::new(); + let mut total = 0usize; + reconcile_deletions(&root)?; + for file in fs::read_dir(root.join("objects"))? { + let path = file?.path(); + if path.extension().and_then(|s| s.to_str()) != Some("active") { + continue; + } + let object = indexed_object(&path)?; + let (meta, _) = read_manifest(&object)?; + let bytes = read_validated_file(&object)?; + total = total + .checked_add(bytes.len()) + .ok_or_else(|| invalid("relay size overflow"))?; + if existing + .insert(meta.transient_id, meta.content_hash) + .is_some() + { + return Err(invalid("duplicate active relay TID")); + } + } + let maximum = policy + .maximum_message_bytes + .min(rns_protocol::resource::MAX_RESOURCE_SIZE); + let mut selected = HashSet::new(); + let mut plans = Vec::new(); + let mut already_present = 0; + for record in &recovery.entries { + if !selected.insert(record.transient_id) { + return Err(invalid("duplicate recovery TID")); + } + let Some((length, hash)) = known.get(&record.archive_relative_path) else { + return Err(invalid( + "recovery entry is outside the committed legacy inventory", + )); + }; + if *hash != record.content_hash || *length > maximum as u64 { + return Err(invalid("recovery inventory hash/size mismatch")); + } + let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?; + let meta = validate(record, &bytes, policy.minimum_stamp_cost)?; + if let Some(hash) = existing.get(&record.transient_id) { + if *hash != record.content_hash { + return Err(invalid( + "recovery would replace the first accepted relay image", + )); + } + already_present += 1; + continue; + } + total = total + .checked_add(bytes.len()) + .ok_or_else(|| invalid("relay size overflow"))?; + if total > policy.maximum_store_bytes { + return Err(invalid( + "trusted recovery exceeds active relay storage quota", + )); + } + plans.push((record, meta)); + } + let mut imported = 0; + for (record, meta) in plans { + let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?; + validate(record, &bytes, policy.minimum_stamp_cost)?; + let object = root.join("objects").join(meta.filename()); + if object.exists() && read_bounded(&object, maximum)? != bytes { + return Err(invalid("recovery object target contains different bytes")); + } + publish_object(&object, &meta, &bytes)?; + imported += 1; + } + Ok(RecoveryReport { + imported, + already_present, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn guard(legacy: &Path) -> OfflineMigrationGuard { + let legacy = canonical_legacy(legacy).unwrap(); + let lock = offline::lock_store(&legacy).unwrap(); + OfflineMigrationGuard { + legacy, + _lock: lock, + } + } + fn write_manifest(path: &Path, manifest: &TrustedRecoveryManifest) -> [u8; 32] { + let bytes = rmp_serde::to_vec_named(manifest).unwrap(); + fs::write(path, &bytes).unwrap(); + rns_crypto::sha::full_hash(&bytes) + } + fn policy() -> RecoveryPolicy { + RecoveryPolicy { + maximum_store_bytes: 8192, + maximum_message_bytes: 4096, + minimum_stamp_cost: 0, + } + } + fn record(bytes: &[u8], name: &str) -> RecoveryEntry { + RecoveryEntry { + archive_relative_path: name.into(), + content_hash: rns_crypto::sha::full_hash(bytes), + transient_id: rns_crypto::sha::full_hash(bytes), + stamped: false, + stored_at: 1.0, + } + } + #[test] + fn only_exact_approved_inventory_entries_are_imported_and_retry_is_idempotent() { + let temp = tempfile::tempdir().unwrap(); + let legacy = temp.path().join("store"); + fs::create_dir(&legacy).unwrap(); + let recipient = rns_identity::identity::Identity::new(); + let mut bytes = [2; 16].to_vec(); + bytes.extend_from_slice( + &recipient + .encrypt(b"private recovery payload", None) + .unwrap(), + ); + fs::write(legacy.join("opaque"), &bytes).unwrap(); + fs::write(legacy.join("unknown"), b"never infer eligibility").unwrap(); + let offline = guard(&legacy); + let report = migrate_store_offline(&offline).unwrap(); + assert_eq!(report.quarantine.files, 2); + assert_eq!( + fs::read_dir(report.store.join("objects")).unwrap().count(), + 0 + ); + let manifest = TrustedRecoveryManifest { + version: 2, + provenance: "operator verified original opaque ingress record #42".into(), + entries: vec![record(&bytes, "opaque")], + }; + let path = temp.path().join("recovery.msgpack"); + let hash = write_manifest(&path, &manifest); + assert!(import_trusted_recovery_manifest(&offline, &path, [0; 32], policy()).is_err()); + let first = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap(); + assert_eq!((first.imported, first.already_present), (1, 0)); + let retry = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap(); + assert_eq!((retry.imported, retry.already_present), (0, 1)); + assert_eq!( + fs::read_dir(report.store.join("objects")).unwrap().count(), + 3 + ); + assert_eq!( + fs::read( + sibling(&legacy, ".legacy-quarantine") + .unwrap() + .join("unknown") + ) + .unwrap(), + b"never infer eligibility" + ); + drop(offline); + let reopened = crate::propagation_node::PropagationNode::with_storage( + crate::propagation_node::PropagationNodeConfig::default(), + [1; 16], + legacy, + ) + .unwrap(); + assert_eq!(reopened.message_count(), 1); + assert_eq!( + fs::read(&reopened.plan_message_reads(&[rns_crypto::sha::full_hash(&bytes)])[0].path) + .unwrap(), + bytes + ); + } + #[test] + fn plaintext_or_outside_inventory_recovery_cannot_publish_any_entry() { + let temp = tempfile::tempdir().unwrap(); + let legacy = temp.path().join("store"); + fs::create_dir(&legacy).unwrap(); + let message = crate::message::test_message( + [2; 16], + [3; 16], + "Private", + "Do not relay cleartext", + crate::constants::DeliveryMethod::Direct, + ); + let bytes = message.wire_bytes(); + fs::write(legacy.join("plaintext"), bytes).unwrap(); + let offline = guard(&legacy); + let report = migrate_store_offline(&offline).unwrap(); + let path = temp.path().join("recovery.msgpack"); + let mut manifest = TrustedRecoveryManifest { + version: 2, + provenance: "inaccurate assertion does not override positive plaintext decode".into(), + entries: vec![record(bytes, "plaintext")], + }; + let hash = write_manifest(&path, &manifest); + assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err()); + manifest.entries[0].archive_relative_path = "../plaintext".into(); + let hash = write_manifest(&path, &manifest); + assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err()); + assert_eq!( + fs::read_dir(report.store.join("objects")).unwrap().count(), + 0 + ); + assert_eq!( + fs::read( + sibling(&legacy, ".legacy-quarantine") + .unwrap() + .join("plaintext") + ) + .unwrap(), + bytes + ); + } +} diff --git a/crates/lxmf-core/src/propagation_sync.rs b/crates/lxmf-core/src/propagation_sync.rs index fbf348e..167a254 100644 --- a/crates/lxmf-core/src/propagation_sync.rs +++ b/crates/lxmf-core/src/propagation_sync.rs @@ -136,6 +136,9 @@ pub struct PropagationSyncTask { pub propagation_node: Arc>, link: Option, link_id: Option<[u8; 16]>, + link_request_result: Option< + oneshot::Receiver>, + >, attached_interface: Option, pending_endpoint_bind: Option, pending_endpoint_sends: Vec, @@ -189,6 +192,7 @@ impl PropagationSyncTask { ))), link: None, link_id: None, + link_request_result: None, attached_interface: None, pending_endpoint_bind: None, pending_endpoint_sends: Vec::new(), @@ -248,6 +252,7 @@ impl PropagationSyncTask { )?)), link: None, link_id: None, + link_request_result: None, attached_interface: None, pending_endpoint_bind: None, pending_endpoint_sends: Vec::new(), @@ -303,6 +308,7 @@ impl PropagationSyncTask { propagation_node, link: None, link_id: None, + link_request_result: None, attached_interface: None, pending_endpoint_bind: None, pending_endpoint_sends: Vec::new(), @@ -648,17 +654,28 @@ impl PropagationSyncTask { self.link_establishment_rate = None; } - pub fn accept_message(&mut self, msg: &crate::message::LxMessage) -> bool { - self.propagation_node - .lock() - .map(|mut node| node.accept_message(msg)) - .unwrap_or(false) - } - /// Drain inbound events from transport. /// /// `known_identities` maps dest_hash_hex -> 64-byte public key, used for link proof validation. + fn poll_link_request(&mut self) { + let Some(mut receiver) = self.link_request_result.take() else { + return; + }; + match receiver.try_recv() { + Ok(Ok(())) => {} + Ok(Err(error)) => { + tracing::warn!(%error,"Link request rejected by transport"); + self.state = SyncTaskState::Failed; + } + Err(oneshot::error::TryRecvError::Closed) => { + self.state = SyncTaskState::Failed; + } + Err(oneshot::error::TryRecvError::Empty) => self.link_request_result = Some(receiver), + } + } + pub fn drain_events(&mut self, known_identities: &HashMap) { + self.poll_link_request(); self.poll_endpoint_control(); let mut events = Vec::new(); while let Ok(event) = self.event_rx.try_recv() { @@ -671,7 +688,10 @@ impl PropagationSyncTask { self.handle_link_closed(link_id, None); } DestinationEvent::InboundPacket { - raw, interface_id, .. + raw, + interface_id, + interface_owner, + .. } => { let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) { Ok(h) => h, @@ -724,11 +744,12 @@ impl PropagationSyncTask { let ed25519_bytes: [u8; 32] = pub_key[32..64].try_into().unwrap(); if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes) { - self.handle_link_proof( + self.handle_link_proof_with_owner( data, &verify_key, &ed25519_bytes, interface_id, + interface_owner, ); } } @@ -918,12 +939,23 @@ impl PropagationSyncTask { verified } + #[cfg(test)] fn handle_link_proof( &mut self, proof_data: &[u8], verify_key: &Ed25519PublicKey, ed25519_pub: &[u8; 32], interface_id: InterfaceId, + ) { + self.handle_link_proof_with_owner(proof_data, verify_key, ed25519_pub, interface_id, None) + } + fn handle_link_proof_with_owner( + &mut self, + proof_data: &[u8], + verify_key: &Ed25519PublicKey, + ed25519_pub: &[u8; 32], + interface_id: InterfaceId, + interface_owner: Option, ) { let proof_result = match self.link.as_mut() { Some(link) => link.validate_proof(proof_data, verify_key, ed25519_pub), @@ -956,6 +988,7 @@ impl PropagationSyncTask { let (result_tx, result_rx) = oneshot::channel(); if !self.queue_transport(TransportMessage::BindLinkEndpoint { binding: LinkEndpointBinding { + interface_owner, link_id, interface_id, role: LinkEndpointRole::Initiator, @@ -1084,6 +1117,7 @@ impl PropagationSyncTask { } pub fn tick(&mut self) { + self.poll_link_request(); if !self.flush_pending_transport() && self.state != SyncTaskState::Idle { self.state = SyncTaskState::Failed; } @@ -1428,15 +1462,21 @@ impl PropagationSyncTask { let mut raw = header.pack(); raw.extend_from_slice(&request_data); - if !self.queue_transport(TransportMessage::Outbound(OutboundRequest { - raw: Bytes::from(raw), - destination_hash: node_hash, - })) { + let (request_tx, request_rx) = oneshot::channel(); + if !self.queue_transport(TransportMessage::SendLinkRequest { + request: OutboundRequest { + raw: Bytes::from(raw), + destination_hash: node_hash, + }, + result_tx: request_tx, + }) { tracing::warn!("propagation sync transport closed before Link request"); self.state = SyncTaskState::Failed; return false; } + self.link_request_result = Some(request_rx); + let mut peer = LxmPeer::new(node_hash); peer.begin_sync(); @@ -1720,6 +1760,9 @@ impl PropagationSyncTask { /// Python LXMPeer.py:540-542. fn cleanup_sync(&mut self) { + self.link_request_result = None; + self.pending_transport + .retain(|message| !matches!(message, TransportMessage::SendLinkRequest { .. })); // No transfer packet should survive the attempt it belongs to. The // teardown and deregistration below form a new ordered tail. Preserve // a teardown already emitted by Link::tick() when it closed the link. @@ -1801,11 +1844,38 @@ impl PropagationSyncTask { #[cfg(test)] mod tests { use super::*; + fn test_task(tx: mpsc::Sender, dest: [u8; 16]) -> PropagationSyncTask { + PropagationSyncTask::with_shared_node( + tx, + Arc::new(Mutex::new( + crate::propagation_node::tests::durable_test_node( + PropagationNodeConfig::default(), + dest, + ), + )), + ) + } + impl PropagationSyncTask { + fn accept_fixture( + &mut self, + message: &crate::propagation_node::tests::OpaqueFixture, + ) -> bool { + self.propagation_node + .lock() + .unwrap() + .accept_fixture(message) + } + } fn next_link_request(rx: &mut mpsc::Receiver) -> OutboundRequest { while let Ok(message) = rx.try_recv() { match message { TransportMessage::Outbound(request) => return request, + TransportMessage::SendLinkRequest { request, result_tx } => { + let _ = result_tx.send(Ok(())); + return request; + } + TransportMessage::SendLinkEndpoint { request, result_tx, .. } => { @@ -1918,7 +1988,7 @@ mod tests { let (tx, mut rx) = mpsc::channel(4); let (initiator, responder) = active_link_pair([0x42; 16]); let link_id = initiator.link_id; - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link_id = Some(link_id); task.link = Some(initiator); task.attached_interface = Some(0); @@ -1960,6 +2030,7 @@ mod tests { let encrypted = responder.encrypt(plaintext).unwrap(); task.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet(link_id, context, &encrypted), interface_id: 0, metrics: Default::default(), @@ -1990,7 +2061,7 @@ mod tests { request.extend_from_slice(&resource_hash); request.extend_from_slice(&requested_hash); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link_id = Some(link_id); task.link = Some(initiator); task.attached_interface = Some(0); @@ -2051,7 +2122,7 @@ mod tests { request.extend_from_slice(&transfer.resource.map_hashes[hashmap_len - 1]); request.extend_from_slice(&resource_hash); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link_id = Some(link_id); task.link = Some(initiator); task.attached_interface = Some(0); @@ -2097,7 +2168,7 @@ mod tests { request.extend_from_slice(&transfer.resource.map_hashes[0]); request.extend_from_slice(&resource_hash); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link_id = Some(link_id); task.link = Some(initiator); task.attached_interface = Some(0); @@ -2146,7 +2217,7 @@ mod tests { .unwrap(); let transfer = transfers.pop_front().unwrap(); let resource_hash = transfer.resource.resource_hash; - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link_id = Some(link_id); task.link = Some(initiator); task.attached_interface = Some(0); @@ -2213,7 +2284,7 @@ mod tests { assert_eq!(reassembled, payload); let (tx, _rx) = mpsc::channel(4); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.state = SyncTaskState::Transferring; task.node_dest_hash = Some([0x43; 16]); task.active_transfer = transfers.pop_front(); @@ -2263,7 +2334,7 @@ mod tests { #[test] fn test_sync_task_creation() { let (tx, _rx) = mpsc::channel(16); - let task = PropagationSyncTask::new(tx, [0xAA; 16]); + let task = test_task(tx, [0xAA; 16]); assert_eq!(task.state, SyncTaskState::Idle); assert_eq!(task.message_count(), 0); } @@ -2271,7 +2342,7 @@ mod tests { #[test] fn test_set_node() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); assert!(task.node_dest_hash.is_none()); task.set_node([0xBB; 16]); @@ -2281,45 +2352,46 @@ mod tests { #[test] fn test_accept_message() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "sync test content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - assert!(task.accept_message(&msg)); + assert!(task.accept_fixture(&msg)); assert_eq!(task.message_count(), 1); } #[test] fn test_shared_node_store_is_live() { let (tx, mut rx) = mpsc::channel(64); - let shared_node = Arc::new(Mutex::new(PropagationNode::new( - PropagationNodeConfig::default(), - [0xAA; 16], - ))); + let shared_node = Arc::new(Mutex::new( + crate::propagation_node::tests::durable_test_node( + PropagationNodeConfig::default(), + [0xAA; 16], + ), + )); let mut task = PropagationSyncTask::with_shared_node(tx, shared_node.clone()); task.set_node([0xBB; 16]); make_sync_due(&mut task); assert_eq!(task.message_count(), 0); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "shared node content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - assert!(shared_node.lock().unwrap().accept_message(&msg)); + + assert!(shared_node.lock().unwrap().accept_fixture(&msg)); assert_eq!(task.message_count(), 1); task.tick(); @@ -2333,7 +2405,7 @@ mod tests { #[test] fn test_idle_no_node_configured() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.tick(); assert_eq!(task.state, SyncTaskState::Idle); } @@ -2341,7 +2413,7 @@ mod tests { #[test] fn test_idle_no_messages() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); task.tick(); @@ -2351,20 +2423,20 @@ mod tests { #[test] fn test_starts_sync_when_ready() { let (tx, mut rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - task.accept_message(&msg); + + task.accept_fixture(&msg); task.tick(); assert_eq!(task.state, SyncTaskState::Establishing); @@ -2376,26 +2448,29 @@ mod tests { TransportMessage::RegisterDestination { .. } )); let outbound = rx.try_recv(); - assert!(matches!(outbound.unwrap(), TransportMessage::Outbound(_))); + assert!(matches!( + outbound.unwrap(), + TransportMessage::SendLinkRequest { .. } + )); } #[test] fn test_sync_timeout() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - task.accept_message(&msg); + + task.accept_fixture(&msg); task.tick(); assert_eq!(task.state, SyncTaskState::Establishing); @@ -2423,7 +2498,7 @@ mod tests { link_keys, ) .unwrap(); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link = Some(initiator); task.link_id = Some(link_id); task.attached_interface = Some(0); @@ -2456,7 +2531,7 @@ mod tests { link_keys, ) .unwrap(); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link = Some(initiator); task.link_id = Some(link_id); task.attached_interface = Some(0); @@ -2484,7 +2559,7 @@ mod tests { let (tx, mut rx) = mpsc::channel(1); tx.try_send(TransportMessage::DeregisterDestination { hash: [0x01; 16] }) .unwrap(); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); assert!(task.request_sync_now([0xBB; 16])); assert_eq!(task.pending_transport.len(), 2); @@ -2500,7 +2575,7 @@ mod tests { task.tick(); assert!(matches!( rx.try_recv().unwrap(), - TransportMessage::Outbound(_) + TransportMessage::SendLinkRequest { .. } )); assert!(task.pending_transport.is_empty()); } @@ -2510,7 +2585,7 @@ mod tests { let (tx, _rx) = mpsc::channel(1); tx.try_send(TransportMessage::DeregisterDestination { hash: [0; 16] }) .unwrap(); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.state = SyncTaskState::Offering; for index in 0..PropagationSyncTask::PENDING_TRANSPORT_LIMIT { assert!( @@ -2541,7 +2616,7 @@ mod tests { let responder_public = responder_key.public_key(); let (_responder, proof) = Link::new_responder(&request_data, &responder_key, node_hash, 1).unwrap(); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.node_dest_hash = Some(node_hash); task.link_id = Some(link.link_id); task.link = Some(link); @@ -2580,7 +2655,7 @@ mod tests { .unwrap(); let transfer = transfers.pop_front().unwrap(); let resource_hash = transfer.resource.resource_hash; - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.link_id = Some(link_id); task.link = Some(initiator); task.attached_interface = Some(4); @@ -2590,6 +2665,7 @@ mod tests { let encrypted = responder.encrypt(&resource_hash).unwrap(); task.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::ResourceRcl, @@ -2608,23 +2684,27 @@ mod tests { #[test] fn test_cleanup_deregisters() { let (tx, mut rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - task.accept_message(&msg); + + task.accept_fixture(&msg); task.tick(); - while rx.try_recv().is_ok() {} + while let Ok(message) = rx.try_recv() { + if let TransportMessage::SendLinkRequest { result_tx, .. } = message { + let _ = result_tx.send(Ok(())); + } + } task.state = SyncTaskState::Complete; task.tick(); @@ -2636,7 +2716,7 @@ mod tests { #[test] fn rejected_endpoint_send_fails_the_sync_owner() { let (tx, mut rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); let link_id = [0xD8; 16]; task.link_id = Some(link_id); task.state = SyncTaskState::Offering; @@ -2662,7 +2742,7 @@ mod tests { #[test] fn test_authenticated_remote_link_close_fails_and_cleans_up() { let (tx, mut rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); let node_hash = [0xE3; 16]; let (link, mut responder_link) = active_link_pair(node_hash); let link_id = link.link_id; @@ -2681,6 +2761,7 @@ mod tests { .expect("remote active link emits authenticated teardown"); task.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet( link_id, rns_wire::context::PacketContext::LinkClose, @@ -2704,7 +2785,7 @@ mod tests { #[test] fn test_unauthenticated_link_close_is_ignored() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); let node_hash = [0xE4; 16]; let (link, _responder_link) = active_link_pair(node_hash); let link_id = link.link_id; @@ -2716,6 +2797,7 @@ mod tests { task.event_tx .try_send(DestinationEvent::InboundPacket { + interface_owner: None, raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]), interface_id: 0, metrics: Default::default(), @@ -2730,7 +2812,7 @@ mod tests { #[test] fn test_handle_offer_response_have_all() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); task.state = SyncTaskState::AwaitingResponse; @@ -2741,21 +2823,23 @@ mod tests { #[test] fn empty_policy_selection_completes_without_sending_offer_request() { let (tx, mut rx) = mpsc::channel(16); - let shared_node = Arc::new(Mutex::new(PropagationNode::new( - PropagationNodeConfig::default(), - [0xAA; 16], - ))); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut message = crate::message::LxMessage::new( + let shared_node = Arc::new(Mutex::new( + crate::propagation_node::tests::durable_test_node( + PropagationNodeConfig::default(), + [0xAA; 16], + ), + )); + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let message = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "already handled", crate::constants::DeliveryMethod::Propagated, ); - message.sign(&key).unwrap(); + let transient_id = message.transient_id.unwrap(); - assert!(shared_node.lock().unwrap().accept_message(&message)); + assert!(shared_node.lock().unwrap().accept_fixture(&message)); let node_hash = [0xDD; 16]; let (link, _responder) = active_link_pair(node_hash); @@ -2780,21 +2864,23 @@ mod tests { #[tokio::test(flavor = "current_thread")] async fn production_policy_preparation_runs_through_bounded_worker() { let (tx, mut rx) = mpsc::channel(16); - let shared_node = Arc::new(Mutex::new(PropagationNode::new( - PropagationNodeConfig::default(), - [0xAA; 16], - ))); - let key = Ed25519PrivateKey::generate(); - let mut message = crate::message::LxMessage::new( + let shared_node = Arc::new(Mutex::new( + crate::propagation_node::tests::durable_test_node( + PropagationNodeConfig::default(), + [0xAA; 16], + ), + )); + let _key = Ed25519PrivateKey::generate(); + let message = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "already handled async", crate::constants::DeliveryMethod::Propagated, ); - message.sign(&key).unwrap(); + let transient_id = message.transient_id.unwrap(); - assert!(shared_node.lock().unwrap().accept_message(&message)); + assert!(shared_node.lock().unwrap().accept_fixture(&message)); let node_hash = [0xDD; 16]; let mut task = PropagationSyncTask::with_shared_node(tx, shared_node); @@ -2823,21 +2909,23 @@ mod tests { fn terminal_offer_filters_are_exposed_and_complete_without_wire_offer() { let (tx, mut rx) = mpsc::channel(16); let node_hash = [0xDD; 16]; - let shared_node = Arc::new(Mutex::new(PropagationNode::new( - PropagationNodeConfig::default(), - [0xAA; 16], - ))); + let shared_node = Arc::new(Mutex::new( + crate::propagation_node::tests::durable_test_node( + PropagationNodeConfig::default(), + [0xAA; 16], + ), + )); let low = vec![0x11; 64]; let oversized = vec![0x22; 700]; - assert!(shared_node.lock().unwrap().accept_propagated_blob(&low, 9)); + assert!(shared_node.lock().unwrap().accept_blob_fixture(&low, 0)); assert!( shared_node .lock() .unwrap() - .accept_propagated_blob(&oversized, 20) + .accept_blob_fixture(&oversized, 2) ); let mut policy = OutboundOfferPolicy::unrestricted(node_hash); - policy.minimum_stamp_cost = 10; + policy.minimum_stamp_cost = 1; policy.propagation_transfer_limit = Some(0.5); let mut task = PropagationSyncTask::with_shared_node(tx, shared_node); task.set_node(node_hash); @@ -2861,7 +2949,8 @@ mod tests { #[test] fn have_all_exposes_every_offered_id_for_authoritative_persistence() { - let dir = std::env::temp_dir().join("lxmf_sync_have_all_persist"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let node_hash = [0xBB; 16]; let node = PropagationNode::with_storage( @@ -2871,17 +2960,17 @@ mod tests { ) .unwrap(); let shared_node = Arc::new(Mutex::new(node)); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); for content in ["first", "second"] { - let mut message = crate::message::LxMessage::new( + let message = crate::propagation_node::tests::opaque_message( [0xCC; 16], [0xDD; 16], "Test", content, crate::constants::DeliveryMethod::Propagated, ); - message.sign(&key).unwrap(); - assert!(shared_node.lock().unwrap().accept_message(&message)); + + assert!(shared_node.lock().unwrap().accept_fixture(&message)); } let policy = OutboundOfferPolicy::unrestricted(node_hash); let offered = { @@ -2907,7 +2996,8 @@ mod tests { #[test] fn want_some_is_intersected_with_offer_and_marks_complement_handled() { - let dir = std::env::temp_dir().join("lxmf_sync_want_some_bound"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let node_hash = [0xBB; 16]; let node = PropagationNode::with_storage( @@ -2917,17 +3007,17 @@ mod tests { ) .unwrap(); let shared_node = Arc::new(Mutex::new(node)); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); for content in ["first", "second"] { - let mut message = crate::message::LxMessage::new( + let message = crate::propagation_node::tests::opaque_message( [0xCC; 16], [0xDD; 16], "Test", content, crate::constants::DeliveryMethod::Propagated, ); - message.sign(&key).unwrap(); - assert!(shared_node.lock().unwrap().accept_message(&message)); + + assert!(shared_node.lock().unwrap().accept_fixture(&message)); } let policy = OutboundOfferPolicy::unrestricted(node_hash); let offered = { @@ -2959,7 +3049,7 @@ mod tests { #[test] fn test_handle_offer_response_error() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); task.state = SyncTaskState::AwaitingResponse; @@ -2970,21 +3060,21 @@ mod tests { #[test] fn test_handle_offer_response_want_all_no_storage() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); task.state = SyncTaskState::AwaitingResponse; // In-memory store -- message_get_request returns empty, so WantAll -> Complete. - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - task.accept_message(&msg); + + task.accept_fixture(&msg); task.handle_offer_response(OfferResponse::WantAll); assert_eq!(task.state, SyncTaskState::Complete); @@ -2993,7 +3083,7 @@ mod tests { #[test] fn test_handle_offer_response_want_some() { let (tx, _rx) = mpsc::channel(16); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); task.state = SyncTaskState::AwaitingResponse; @@ -3004,7 +3094,8 @@ mod tests { #[test] fn test_handle_offer_response_want_some_with_storage() { - let dir = std::env::temp_dir().join("lxmf_test_sync_want_some"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let (tx, _rx) = mpsc::channel(16); @@ -3012,17 +3103,17 @@ mod tests { task.set_node([0xBB; 16]); task.state = SyncTaskState::AwaitingResponse; - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "want some content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); + let tid = msg.transient_id.unwrap(); - task.accept_message(&msg); + task.accept_fixture(&msg); let policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); task.propagation_node @@ -3048,23 +3139,24 @@ mod tests { #[test] fn want_all_builds_one_timestamped_resource_batch_and_waits_for_proof() { - let dir = std::env::temp_dir().join("lxmf_test_sync_one_batch"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let node_hash = [0xBB; 16]; let (tx, _rx) = mpsc::channel(16); let mut task = PropagationSyncTask::with_storage(tx, [0xAA; 16], dir.clone()).unwrap(); task.set_node(node_hash); - let key = Ed25519PrivateKey::generate(); + let _key = Ed25519PrivateKey::generate(); for content in ["one", "two"] { - let mut message = crate::message::LxMessage::new( + let message = crate::propagation_node::tests::opaque_message( [0xCC; 16], [0xDD; 16], "Test", content, crate::constants::DeliveryMethod::Propagated, ); - message.sign(&key).unwrap(); - assert!(task.accept_message(&message)); + + assert!(task.accept_fixture(&message)); } let policy = OutboundOfferPolicy::unrestricted(node_hash); task.propagation_node @@ -3092,22 +3184,23 @@ mod tests { #[test] fn vanished_requested_file_fails_retryably_for_peer_backoff() { - let dir = std::env::temp_dir().join("lxmf_test_sync_vanished_batch"); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().join("store"); let _ = std::fs::remove_dir_all(&dir); let node_hash = [0xBB; 16]; let (tx, _rx) = mpsc::channel(16); let mut task = PropagationSyncTask::with_storage(tx, [0xAA; 16], dir.clone()).unwrap(); task.set_node(node_hash); - let key = Ed25519PrivateKey::generate(); - let mut message = crate::message::LxMessage::new( + let _key = Ed25519PrivateKey::generate(); + let message = crate::propagation_node::tests::opaque_message( [0xCC; 16], [0xDD; 16], "Test", "vanish", crate::constants::DeliveryMethod::Propagated, ); - message.sign(&key).unwrap(); - assert!(task.accept_message(&message)); + + assert!(task.accept_fixture(&message)); let policy = OutboundOfferPolicy::unrestricted(node_hash); let (generation, reads) = { let mut node = task.propagation_node.lock().unwrap(); @@ -3153,22 +3246,22 @@ mod tests { #[test] fn test_peer_created_on_sync_start() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); assert!(task.peer().is_none()); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - task.accept_message(&msg); + + task.accept_fixture(&msg); task.tick(); assert_eq!(task.state, SyncTaskState::Establishing); @@ -3181,7 +3274,7 @@ mod tests { #[test] fn request_sync_now_starts_without_waiting_for_interval() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.request_sync_now([0xBB; 16]); @@ -3194,7 +3287,7 @@ mod tests { #[test] fn active_sync_rejects_different_request_without_mutating_target_or_policy() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); let policy_a = OutboundOfferPolicy::unrestricted([0xA1; 16]); let policy_b = OutboundOfferPolicy::unrestricted([0xB2; 16]); @@ -3207,7 +3300,7 @@ mod tests { #[test] fn cancel_peer_sync_clears_active_pending_and_session_state() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); let peer_hash = [0xA1; 16]; assert!(task.request_sync_now_with_policy(OutboundOfferPolicy::unrestricted(peer_hash))); task.handled_updates.push([0x44; 32]); @@ -3233,7 +3326,7 @@ mod tests { #[test] fn terminal_results_advance_generation_only_on_success_and_must_be_drained() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.node_dest_hash = Some([0xA1; 16]); task.active_offer_generation = Some(7); task.generation_exhausted = false; @@ -3277,7 +3370,7 @@ mod tests { #[test] fn terminal_result_carries_python_peer_accounting_deltas() { let (tx, _rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.node_dest_hash = Some([0xC3; 16]); task.offered_count = 11; task.outgoing_count = 7; @@ -3307,7 +3400,7 @@ mod tests { let (_responder, proof_data) = Link::new_responder(&request_data, &responder_key, node_hash, 1).unwrap(); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); let local_key = Ed25519PrivateKey::generate(); let mut local_pub = [0x33; 64]; local_pub[32..].copy_from_slice(&local_key.public_key().to_bytes()); @@ -3318,16 +3411,16 @@ mod tests { task.peer = Some(LxmPeer::new(node_hash)); task.state = SyncTaskState::Establishing; - let message_key = Ed25519PrivateKey::generate(); - let mut message = crate::message::LxMessage::new( + let _message_key = Ed25519PrivateKey::generate(); + let message = crate::propagation_node::tests::opaque_message( [0xCC; 16], [0xDD; 16], "Test", "identify ordering", crate::constants::DeliveryMethod::Propagated, ); - message.sign(&message_key).unwrap(); - assert!(task.accept_message(&message)); + + assert!(task.accept_fixture(&message)); task.offer_policy = Some(OutboundOfferPolicy::unrestricted(node_hash)); task.handle_link_proof(&proof_data, &responder_pub, &responder_pub.to_bytes(), 0); @@ -3359,20 +3452,20 @@ mod tests { #[test] fn test_peer_cleared_on_cleanup() { let (tx, mut rx) = mpsc::channel(64); - let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = crate::message::LxMessage::new( + let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let msg = crate::propagation_node::tests::opaque_message( [0xBB; 16], [0xCC; 16], "Test", "content", crate::constants::DeliveryMethod::Propagated, ); - msg.sign(&key).unwrap(); - task.accept_message(&msg); + + task.accept_fixture(&msg); task.tick(); while rx.try_recv().is_ok() {} diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index 40539c7..3a30d39 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -15,14 +15,51 @@ use crate::inbound_resource::{ InboundResourceCancelRequest, InboundResourceEvent, InboundResourceHandle, InboundResourceKey, InboundResourceTracker, }; -use crate::message::{LxMessage, MessageError}; +use crate::message::{ + LxMessage, LxMessageDraft, MessageError, RecipientStamp, SignedLxMessage, VerifiedLxMessage, +}; use crate::peer::{LxmPeer, OutboundOfferPolicy}; use crate::propagation::PropagationStore; use crate::propagation_client::PropagationTransferStatus; use crate::stamper; -use crate::ticket::{Ticket, TicketStore, TicketStoreSnapshot}; +use crate::ticket::{Ticket, TicketStore}; use crate::types::PropagationTransientId; +/// Outstanding actor-owned admission. Only this router can match its nonce. +#[derive(Debug)] +pub struct InboundReservation { + message_id: [u8; 32], + nonce: u64, +} + +/// Durable barrier for router-minted reply tickets. Signing the marked draft +/// fails until this exact intent has committed its immutable ticket snapshot. +pub struct OutboundTicketIntent { + barrier: Option>, + snapshot: Option, + required_ticket: Option, +} +impl OutboundTicketIntent { + pub fn requires_persistence(&self) -> bool { + self.snapshot.is_some() + } + pub fn persist( + self, + state_dir: &std::path::Path, + draft: &mut LxMessageDraft, + ) -> std::io::Result<()> { + if let Some(snapshot) = self.snapshot { + snapshot.save(state_dir, self.required_ticket.as_ref())?; + if !draft.release_ticket_barrier(self.barrier.as_ref().expect("snapshot barrier")) { + return Err(std::io::Error::other( + "reply ticket intent belongs to a different draft", + )); + } + } + Ok(()) + } +} + /// Router configuration. /// /// Core fields are stable for downstream compatibility; additional Python @@ -141,6 +178,8 @@ impl std::error::Error for SendError {} pub enum TicketPreparationError { #[error("reply ticket must be added before the LXMF message is signed")] AlreadySigned, + #[error("another reply-ticket draft is awaiting durable persistence")] + PendingPersistence, #[error("failed to encode LXMF reply ticket: {0}")] Encode(String), } @@ -279,7 +318,7 @@ pub struct LxmRouter { pub config: RouterConfig, pub pending_outbound: Vec, /// Messages awaiting deferred stamp generation, keyed by message hash. - pub pending_deferred_stamps: HashMap<[u8; 32], LxMessage>, + pub pending_deferred_stamps: HashMap<[u8; 32], SignedLxMessage>, /// Captured at construction so deferred-stamp PoW can spawn onto the /// blocking pool even when the caller is itself on a `spawn_blocking` /// thread, where `Handle::try_current()` fails. Without it the tick grinds @@ -298,6 +337,7 @@ pub struct LxmRouter { /// Cached stamp costs keyed by destination hash. pub outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>, pub ticket_store: TicketStore, + ticket_intent_in_flight: std::sync::Weak<()>, /// Identity hash → priority level. pub prioritized: HashMap<[u8; 16], u8>, pub delivery_callback: Option, @@ -319,6 +359,8 @@ pub struct LxmRouter { /// Active ordinary delivery Resources. The embedding Reticulum runtime /// remains the transfer owner and feeds this registry lifecycle events. inbound_resource_tracker: InboundResourceTracker, + inbound_reservations: HashMap<[u8; 32], u64>, + next_inbound_reservation: u64, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -360,7 +402,7 @@ pub struct StampCostEntry { #[derive(Debug, Clone)] pub struct RouterStateSnapshot { outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>, - tickets: TicketStoreSnapshot, + tickets: crate::persist::TicketPersistenceSnapshot, local_deliveries: HashMap, locally_processed: HashMap, node_stats: crate::persist::PersistedNodeStats, @@ -375,7 +417,7 @@ impl RouterStateSnapshot { use crate::persist; persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?; - persist::save_tickets(state_dir, &self.tickets)?; + self.tickets.save(state_dir, None)?; persist::save_local_deliveries(state_dir, &self.local_deliveries)?; persist::save_locally_processed(state_dir, &self.locally_processed)?; persist::save_node_stats(state_dir, &self.node_stats)?; @@ -400,6 +442,7 @@ impl LxmRouter { propagation_store: PropagationStore::new(), outbound_stamp_costs: HashMap::new(), ticket_store: TicketStore::new(), + ticket_intent_in_flight: std::sync::Weak::new(), prioritized: HashMap::new(), delivery_callback: None, transport_tx: None, @@ -414,6 +457,8 @@ impl LxmRouter { unpeered_propagation_incoming: 0, unpeered_propagation_rx_bytes: 0, inbound_resource_tracker: InboundResourceTracker::default(), + inbound_reservations: HashMap::new(), + next_inbound_reservation: 0, } } @@ -497,9 +542,9 @@ impl LxmRouter { name = "router.send", skip_all, fields( - destination_hash = %hex::encode(&message.destination_hash[..8]), + destination_hash = %hex::encode(&message.destination_hash()[..8]), method = ?message.method, - content_len = message.content.len(), + content_len = message.content_bytes().len(), ), )] #[deprecated(note = "use try_send() and handle the immediate routing result")] @@ -525,42 +570,6 @@ impl LxmRouter { return Err(SendError::MissingOutboundPropagationNode(Box::new(message))); } - if let Err(source) = self.prepare_outbound(&mut message) { - message.mark_failed(); - return Err(SendError::TicketPreparation { - message: Box::new(message), - source, - }); - } - - if message.stamp.is_none() && message.stamp_cost.is_none() { - message.stamp_cost = self - .get_stamp_cost(&message.destination_hash) - .filter(|cost| *cost > 0); - } - - if message.stamp.is_none() - && message.outbound_ticket.is_some() - && (message.message_id.is_some() || message.compute_hash().is_ok()) - { - message.get_stamp(); - } - - if message.stamp.is_none() - && message.stamp_cost.unwrap_or(0) > 0 - && (message.message_id.is_some() || message.compute_hash().is_ok()) - { - if self.config.ext.defer_stamp_generation { - if let Some(message_hash) = message.message_id.or(message.hash) { - message.state = MessageState::Outbound; - self.pending_deferred_stamps.insert(message_hash, message); - return Ok(()); - } - } else { - message.get_stamp(); - } - } - if message.method == DeliveryMethod::Opportunistic && let Ok(packed) = message.pack_payload() { @@ -588,80 +597,100 @@ impl LxmRouter { /// `sign_with` without exposing private key material to the router. pub fn prepare_outbound( &mut self, - message: &mut LxMessage, - ) -> Result<(), TicketPreparationError> { + message: &mut LxMessageDraft, + ) -> Result { let now = now_f64(); - if message.outbound_ticket.is_none() - && let Some(ticket) = self + let destination = message.destination_hash(); + if message.outbound_ticket.is_none() { + message.outbound_ticket = self .ticket_store - .find_outbound(&message.destination_hash, now) + .find_outbound(&destination, now) + .map(|t| t.token); + } + if message.stamp_cost.is_none() { + message.stamp_cost = self.get_stamp_cost(&destination).filter(|v| *v > 0); + } + if message.include_ticket + && message.get_field(FIELD_TICKET).is_none() + && self.ticket_intent_in_flight.upgrade().is_some() { - message.outbound_ticket = Some(ticket.token); + return Err(TicketPreparationError::PendingPersistence); } - - if message.include_ticket && !message.fields.contains_key(&FIELD_TICKET) { - if message.signature.is_some() { - if self - .ticket_store - .should_issue_for(&message.destination_hash, now) - { - return Err(TicketPreparationError::AlreadySigned); - } - return Ok(()); - } - if let Some(ticket) = - self.ticket_store - .issue_for(message.destination_hash, TICKET_EXPIRY, now) - { - let encoded = ticket - .encode_field() - .map_err(|error| TicketPreparationError::Encode(error.to_string()))?; - message - .set_msgpack_field(FIELD_TICKET, encoded) - .map_err(|error| TicketPreparationError::Encode(error.to_string()))?; - } - } - - Ok(()) - } - - /// Queue `message` for off-thread stamp generation; it re-enters - /// `pending_outbound` with the stamp attached once the worker finishes. - /// Returns the message back when it carries no id to key the job on. - pub fn defer_stamp(&mut self, mut message: LxMessage) -> Option { - let id = message.message_id.or(message.hash).or_else(|| { - message.compute_hash().ok(); - message.hash - }); - let Some(message_hash) = id else { - return Some(message); + let mut intent = OutboundTicketIntent { + barrier: None, + snapshot: None, + required_ticket: None, }; + if message.include_ticket + && message.get_field(FIELD_TICKET).is_none() + && let Some(ticket) = self.ticket_store.issue_for(destination, TICKET_EXPIRY, now) + { + let encoded = ticket + .encode_field() + .map_err(|e| TicketPreparationError::Encode(e.to_string()))?; + message + .set_msgpack_field(FIELD_TICKET, encoded) + .map_err(|e| TicketPreparationError::Encode(e.to_string()))?; + let barrier = std::sync::Arc::new(()); + message.mark_ticket_pending(barrier.clone()); + self.ticket_intent_in_flight = std::sync::Arc::downgrade(&barrier); + intent.barrier = Some(barrier); + intent.required_ticket = Some(ticket); + intent.snapshot = Some(crate::persist::TicketPersistenceSnapshot::capture( + self.ticket_store.snapshot(), + )); + } + Ok(intent) + } + + /// Signatures freeze the body before recipient work; only finalized messages + /// enter outbound queues. Deferred completion can never mutate another body. + pub fn submit_signed(&mut self, message: SignedLxMessage) -> Result<(), MessageError> { + if message.method == DeliveryMethod::Propagated && self.outbound_propagation_node.is_none() + { + return Err(MessageError::PackFailed( + "outbound propagation node is not configured".into(), + )); + } + if self.config.ext.defer_stamp_generation + && message.outbound_ticket().is_none() + && message.stamp_cost().unwrap_or(0) > 0 + { + self.defer_stamp(message); + return Ok(()); + } + let stamp = message.generate_recipient_stamp()?; + self.try_send(message.finalize(stamp)?) + .map_err(|e| MessageError::PackFailed(e.to_string())) + } + + pub fn defer_stamp(&mut self, mut message: SignedLxMessage) { message.state = MessageState::Outbound; - self.pending_deferred_stamps.insert(message_hash, message); - None + self.pending_deferred_stamps + .insert(message.message_id(), message); } - /// Process deferred outbound message stamp generation. - /// - /// Python reference: `LXMRouter.process_deferred_stamps` — LXMRouter.py:2407-2498. pub fn process_deferred_stamps(&mut self) { self.poll_active_deferred_stamp(); if self.active_deferred_stamp.is_some() { return; } - let Some((&message_hash, message)) = self.pending_deferred_stamps.iter().next() else { return; }; - let cost = message.stamp_cost.unwrap_or(0); - if cost == 0 { - if let Some(mut message) = self.pending_deferred_stamps.remove(&message_hash) { - message.get_stamp(); - self.pending_outbound.push(message); + let cost = message.stamp_cost().unwrap_or(0); + if cost == 0 || message.outbound_ticket().is_some() { + if let Some(message) = self.pending_deferred_stamps.remove(&message_hash) { + let stamp = message.generate_recipient_stamp(); + match stamp.and_then(|stamp| message.finalize(stamp)) { + Ok(message) => { + let _ = self.try_send(message); + } + Err(error) => tracing::warn!(%error,"recipient stamp finalization failed"), + } } return; } - let runtime = tokio::runtime::Handle::try_current() .ok() .or_else(|| self.runtime_handle.clone()); @@ -677,20 +706,13 @@ impl LxmRouter { handle, rx, }); - } else if let Some(mut message) = self.pending_deferred_stamps.remove(&message_hash) { - tracing::warn!( - cost, - "no tokio runtime available; generating stamp inline (sync embedder only)" - ); - match stamper::generate_stamp(&message_hash, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS) { - Some((stamp, value)) => { - message.stamp = Some(stamp.to_vec()); - message.stamp_value = Some(value as u16); - self.pending_outbound.push(message); - } - None => { - message.mark_failed(); + } else if let Some(message) = self.pending_deferred_stamps.remove(&message_hash) { + let stamp = message.generate_recipient_stamp(); + match stamp.and_then(|stamp| message.finalize(stamp)) { + Ok(message) => { + let _ = self.try_send(message); } + Err(error) => tracing::warn!(%error,"recipient stamp generation failed"), } } } @@ -699,27 +721,20 @@ impl LxmRouter { let Some(mut job) = self.active_deferred_stamp.take() else { return; }; - match job.rx.try_recv() { - Ok(stamper::DeferredStampResult::Success { stamp, value }) => { - if let Some(mut message) = self.pending_deferred_stamps.remove(&job.message_hash) { - message.stamp = Some(stamp.to_vec()); - message.stamp_value = Some(value as u16); - self.pending_outbound.push(message); + Ok(stamper::DeferredStampResult::Success { stamp, .. }) => { + if let Some(message) = self.pending_deferred_stamps.remove(&job.message_hash) { + match message.finalize(Some(RecipientStamp::ProofOfWork(stamp))) { + Ok(message) => { + let _ = self.try_send(message); + } + Err(error) => tracing::warn!(%error,"recipient stamp finalization failed"), + } } } - Ok(stamper::DeferredStampResult::Cancelled) => { - if let Some(mut message) = self.pending_deferred_stamps.remove(&job.message_hash) { - message.cancel(); - } - } - Err(oneshot::error::TryRecvError::Empty) => { - self.active_deferred_stamp = Some(job); - } - Err(oneshot::error::TryRecvError::Closed) => { - if let Some(mut message) = self.pending_deferred_stamps.remove(&job.message_hash) { - message.mark_failed(); - } + Err(oneshot::error::TryRecvError::Empty) => self.active_deferred_stamp = Some(job), + _ => { + self.pending_deferred_stamps.remove(&job.message_hash); } } } @@ -900,7 +915,7 @@ impl LxmRouter { if let Some(pos) = self .pending_outbound .iter() - .position(|m| m.hash.as_ref() == Some(message_hash)) + .position(|m| &m.message_id() == message_hash) { let msg = &mut self.pending_outbound[pos]; msg.cancel(); @@ -908,8 +923,10 @@ impl LxmRouter { return true; } - if let Some(mut msg) = self.pending_deferred_stamps.remove(message_hash) { - msg.cancel(); + if let Some(msg) = self.pending_deferred_stamps.remove(message_hash) { + if let Ok(mut message) = msg.finalize(None) { + message.cancel(); + } let active_matches = self .active_deferred_stamp .as_ref() @@ -929,7 +946,7 @@ impl LxmRouter { let Some(pos) = self .pending_outbound .iter() - .position(|m| m.hash.as_ref() == Some(message_hash)) + .position(|m| &m.message_id() == message_hash) else { return false; }; @@ -947,9 +964,9 @@ impl LxmRouter { /// the message between those events and return it here only after proof so /// ticket-delivery accounting and callbacks reflect the observable result. pub fn complete_outbound_message(&mut self, mut msg: LxMessage) { - if msg.include_ticket && msg.fields.contains_key(&FIELD_TICKET) { + if msg.fields().contains(FIELD_TICKET) { self.ticket_store - .mark_ticket_delivered(msg.destination_hash, now_f64()); + .mark_ticket_delivered(msg.destination_hash(), now_f64()); } msg.mark_delivered(); } @@ -960,7 +977,7 @@ impl LxmRouter { let Some(pos) = self .pending_outbound .iter() - .position(|m| m.hash.as_ref() == Some(message_hash)) + .position(|m| &m.message_id() == message_hash) else { return false; }; @@ -976,7 +993,7 @@ impl LxmRouter { let Some(pos) = self .pending_outbound .iter() - .position(|m| m.hash.as_ref() == Some(message_hash)) + .position(|m| &m.message_id() == message_hash) else { return false; }; @@ -992,7 +1009,7 @@ impl LxmRouter { let Some(msg) = self .pending_outbound .iter_mut() - .find(|m| m.hash.as_ref() == Some(message_hash)) + .find(|m| &m.message_id() == message_hash) else { return false; }; @@ -1010,9 +1027,13 @@ impl LxmRouter { pub fn get_outbound_progress(&self, message_hash: &[u8; 32]) -> Option { self.pending_outbound .iter() - .chain(self.pending_deferred_stamps.values()) - .find(|m| m.hash.as_ref() == Some(message_hash)) + .find(|m| &m.message_id() == message_hash) .map(|m| m.progress) + .or_else(|| { + self.pending_deferred_stamps + .get(message_hash) + .map(|m| m.progress) + }) } /// Get the cached required stamp cost for a destination (delivery). @@ -1032,11 +1053,9 @@ impl LxmRouter { /// /// Python reference: `LXMRouter.get_outbound_lxm_propagation_stamp_cost` — LXMRouter.py:1149-1156. pub fn get_outbound_lxm_propagation_stamp_cost(&self, message_hash: &[u8; 32]) -> Option { - self.pending_outbound - .iter() - .chain(self.pending_deferred_stamps.values()) - .find(|m| m.hash.as_ref() == Some(message_hash)) - .and_then(|m| m.stamp_cost) + self.pending_deferred_stamps + .get(message_hash) + .and_then(|m| m.stamp_cost()) } /// Return whether a message or propagation transient ID has already been @@ -1056,54 +1075,94 @@ impl LxmRouter { /// distinct from its signed message hash; both identifiers are retained /// so a later delivery through another representation is still deduped. pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool { - self.learn_ticket_from_inbound(message); - - let Some(message_id) = message.message_id.or(message.hash) else { - return false; - }; - let transient_id = message.transient_id.unwrap_or(message_id); - let propagated = transient_id != message_id; - - if !allow_duplicate - && (self.propagation_store.is_locally_delivered(&message_id) - || self.propagation_store.is_locally_delivered(&transient_id) - || (propagated && self.propagation_store.is_locally_processed(&transient_id))) - { + let message_id = message.message_id(); + if !allow_duplicate && self.propagation_store.is_locally_delivered(&message_id) { return false; } - self.propagation_store.mark_locally_delivered(message_id); - if propagated { - self.propagation_store.mark_locally_processed(transient_id); - self.propagation_store.mark_locally_delivered(transient_id); - } - if let Some(ref callback) = self.delivery_callback { callback(message); } true } - /// Learn a reply ticket only from a cryptographically validated inbound - /// message. Returns whether valid outbound ticket state changed. - pub fn learn_ticket_from_inbound(&mut self, message: &LxMessage) -> bool { - if !message.signature_validated { + /// Reserve before local disk/DB work; no ticket learning, dedupe publication + /// or callback occurs until commit. An aborted write leaves retries possible. + pub fn reserve_inbound(&mut self, message: &LxMessage) -> Option { + let message_id = message.message_id(); + if self.inbound_reservations.contains_key(&message_id) { + return None; + } + self.next_inbound_reservation = self.next_inbound_reservation.wrapping_add(1); + let nonce = self.next_inbound_reservation; + self.inbound_reservations.insert(message_id, nonce); + Some(InboundReservation { message_id, nonce }) + } + + pub fn abort_inbound(&mut self, reservation: InboundReservation) { + if self.inbound_reservations.get(&reservation.message_id) == Some(&reservation.nonce) { + self.inbound_reservations.remove(&reservation.message_id); + } + } + + pub fn commit_inbound( + &mut self, + reservation: InboundReservation, + message: &LxMessage, + receipt: &crate::admission::DurableAdmissionReceipt, + verified: Option<&VerifiedLxMessage<'_>>, + ) -> bool { + if reservation.message_id != message.message_id() + || receipt.record().message_id != message.message_id() + || self.inbound_reservations.get(&reservation.message_id) != Some(&reservation.nonce) + { return false; } - let Some(encoded) = message.fields.get(&FIELD_TICKET) else { + self.inbound_reservations.remove(&reservation.message_id); + if matches!( + receipt.record().disposition, + crate::admission::DurableDisposition::Committed + | crate::admission::DurableDisposition::Duplicate + ) && let Some(verified) = verified + && verified.message().wire_bytes() == message.wire_bytes() + { + self.learn_ticket_from_inbound(verified); + } + self.propagation_store + .mark_locally_delivered(receipt.record().scope.transient_id); + self.propagation_store + .mark_locally_processed(receipt.record().scope.transient_id); + let new_message = !self + .propagation_store + .is_locally_delivered(&message.message_id()); + self.propagation_store + .mark_locally_delivered(message.message_id()); + if new_message + && receipt.record().disposition == crate::admission::DurableDisposition::Committed + { + if let Some(ref callback) = self.delivery_callback { + callback(message); + } + true + } else { + false + } + } + + pub fn learn_ticket_from_inbound(&mut self, verified: &VerifiedLxMessage<'_>) -> bool { + let message = verified.message(); + let Some(encoded) = message.fields().get(FIELD_TICKET) else { return false; }; - let Some(ticket) = Ticket::decode_field(message.source_hash, encoded, now_f64()) else { + let Some(ticket) = + Ticket::decode_field(message.source_hash(), encoded.encoded(), now_f64()) + else { return false; }; self.ticket_store.remember_outbound(ticket); true } - /// Ingest an encrypted paper (`lxm://...`) URI and invoke the delivery callback as if the - /// message had arrived via the network. - /// - /// Python reference: `LXMRouter.ingest_lxm_uri` — LXMRouter.py:2370-2385. pub fn ingest_lxm_uri( &mut self, uri: &str, @@ -1164,7 +1223,9 @@ impl LxmRouter { pub fn state_snapshot(&self) -> RouterStateSnapshot { RouterStateSnapshot { outbound_stamp_costs: self.outbound_stamp_costs.clone(), - tickets: self.ticket_store.snapshot(), + tickets: crate::persist::TicketPersistenceSnapshot::capture( + self.ticket_store.snapshot(), + ), local_deliveries: self.propagation_store.locally_delivered_ids().clone(), locally_processed: self.propagation_store.locally_processed_ids().clone(), node_stats: crate::persist::PersistedNodeStats { @@ -1382,7 +1443,7 @@ impl LxmRouter { let due_now = now - DELIVERY_RETRY_WAIT as f64; let mut triggered = 0; for message in &mut self.pending_outbound { - if message.destination_hash == destination_hash { + if message.destination_hash() == destination_hash { message.last_delivery_attempt = due_now; message.next_delivery_attempt = now; triggered += 1; @@ -1718,7 +1779,7 @@ impl LxmRouter { continue; } - let age = now - msg.timestamp; + let age = now - msg.timestamp(); if age > MESSAGE_EXPIRY as f64 { let mut msg = self.pending_outbound.remove(i); msg.mark_failed(); @@ -1737,7 +1798,7 @@ impl LxmRouter { DirectOutboundHandling::EmitLegacyAction => { let mut msg = self.pending_outbound.remove(i); msg.mark_sending(); - let dest_hash = msg.destination_hash; + let dest_hash = msg.destination_hash(); actions.push(OutboundAction::DeliverDirect { message: msg, dest_hash, @@ -1767,7 +1828,7 @@ impl LxmRouter { let mut msg = self.pending_outbound.remove(i); msg.mark_sent(); msg.progress = 0.50; - let dest_hash = msg.destination_hash; + let dest_hash = msg.destination_hash(); actions.push(OutboundAction::DeliverOpportunistic { message: msg, dest_hash, @@ -1821,7 +1882,7 @@ impl LxmRouter { continue; } - let age = now - self.pending_outbound[i].timestamp; + let age = now - self.pending_outbound[i].timestamp(); if age > MESSAGE_EXPIRY as f64 { let mut msg = self.pending_outbound.remove(i); msg.mark_failed(); @@ -1866,7 +1927,7 @@ impl LxmRouter { } _ => { let msg = self.pending_outbound[i].clone(); - let dest_hash = msg.destination_hash; + let dest_hash = msg.destination_hash(); actions.push(OutboundAction::PlanDirect { message: msg, dest_hash, @@ -1920,7 +1981,7 @@ impl LxmRouter { let mut msg = self.pending_outbound.remove(i); msg.mark_sent(); msg.progress = 0.50; - let dest_hash = msg.destination_hash; + let dest_hash = msg.destination_hash(); actions.push(OutboundAction::DeliverOpportunistic { message: msg, dest_hash, @@ -2216,7 +2277,7 @@ mod tests { use super::*; fn direct_policy_message() -> LxMessage { - let mut message = LxMessage::new( + let message = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Direct", @@ -2289,7 +2350,7 @@ mod tests { #[test] fn test_direct_delivery_plan_starts_link_with_current_path() { let mut msg = direct_policy_message(); - let dest = msg.destination_hash; + let dest = msg.destination_hash(); let now = 1000.0; let plan = plan_direct_delivery( &mut msg, @@ -2356,7 +2417,7 @@ mod tests { #[test] fn test_direct_delivery_plan_waits_for_pending_link() { let mut msg = direct_policy_message(); - let dest = msg.destination_hash; + let dest = msg.destination_hash(); let plan = plan_direct_delivery( &mut msg, DirectDeliveryPlanInput { @@ -2375,7 +2436,7 @@ mod tests { #[test] fn test_direct_delivery_plan_defers_terminal_failure_at_attempt_boundary() { let mut msg = direct_policy_message(); - let dest = msg.destination_hash; + let dest = msg.destination_hash(); msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS - 1; let now = 1000.0; let plan = plan_direct_delivery( @@ -2396,7 +2457,7 @@ mod tests { #[test] fn test_direct_delivery_plan_requests_rediscovery_for_closed_link() { let mut msg = direct_policy_message(); - let dest = msg.destination_hash; + let dest = msg.destination_hash(); let now = 1000.0; let plan = plan_direct_delivery( &mut msg, @@ -2422,7 +2483,7 @@ mod tests { #[test] fn test_direct_delivery_plan_fails_above_max_attempts() { let mut msg = direct_policy_message(); - let dest = msg.destination_hash; + let dest = msg.destination_hash(); msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS + 1; let plan = plan_direct_delivery( &mut msg, @@ -2442,20 +2503,20 @@ mod tests { fn test_process_outbound_with_direct_keeps_message_pending() { let mut router = LxmRouter::new(RouterConfig::default()); let msg = direct_policy_message(); - let msg_hash = msg.hash; - let dest = msg.destination_hash; + let msg_hash = Some(msg.message_id()); + let dest = msg.destination_hash(); router.try_send(msg).unwrap(); let actions = router.process_outbound_with_direct(|message, _now| DirectDeliveryPlanInput { identity_known: true, - route: Some(DirectRouteSnapshot::new(message.destination_hash, 4)), + route: Some(DirectRouteSnapshot::new(message.destination_hash(), 4)), reusable_link: DirectReusableLinkState::None, }); assert_eq!(router.pending_outbound.len(), 1); let pending = &router.pending_outbound[0]; - assert_eq!(pending.hash, msg_hash); + assert_eq!(Some(pending.message_id()), msg_hash); assert_eq!(pending.state, MessageState::Sending); assert_eq!(pending.delivery_attempts, 1); assert_eq!(pending.progress, 0.03); @@ -2468,7 +2529,7 @@ mod tests { }, ] => { assert_eq!(*dest_hash, dest); - assert_eq!(message.hash, msg_hash); + assert_eq!(Some(message.message_id()), msg_hash); assert_eq!(*plan, DirectDeliveryPlan::StartNewLink { hops: 4 }); } other => panic!("expected PlanDirect StartNewLink, got {other:?}"), @@ -2480,7 +2541,7 @@ mod tests { let mut router = LxmRouter::new(RouterConfig::default()); let mut msg = direct_policy_message(); msg.next_delivery_attempt = now_f64() + 3600.0; - let msg_hash = msg.hash; + let msg_hash = Some(msg.message_id()); router.try_send(msg).unwrap(); let actions = @@ -2491,7 +2552,7 @@ mod tests { }); assert_eq!(router.pending_outbound.len(), 1); - assert_eq!(router.pending_outbound[0].hash, msg_hash); + assert_eq!(Some(router.pending_outbound[0].message_id()), msg_hash); assert_eq!(router.pending_outbound[0].delivery_attempts, 0); match actions.as_slice() { [OutboundAction::PlanDirect { plan, .. }] => { @@ -2505,7 +2566,7 @@ mod tests { fn test_outbound_terminal_helpers_update_pending_queue() { let mut router = LxmRouter::new(RouterConfig::default()); let first = direct_policy_message(); - let first_hash = first.hash.expect("first hash"); + let first_hash = first.message_id(); router.try_send(first).unwrap(); assert!(router.defer_outbound_for_path_request(&first_hash, 1000.0)); @@ -2519,7 +2580,7 @@ mod tests { assert!(router.pending_outbound.is_empty()); let second = direct_policy_message(); - let second_hash = second.hash.expect("second hash"); + let second_hash = second.message_id(); router.try_send(second).unwrap(); assert!(router.mark_outbound_failed(&second_hash)); assert!(router.pending_outbound.is_empty()); @@ -2607,122 +2668,156 @@ mod tests { router.remember_ticket(dest, [0x42; 16], now_f64() + 60.0); router.set_stamp_cost(dest, 16); - let mut msg = LxMessage::new(dest, [0xBB; 16], "ticket", "stamp", DeliveryMethod::Direct); - msg.sign(&key).unwrap(); - router.try_send(msg).unwrap(); + let mut msg = crate::message::LxMessageDraft::new( + dest, + [0xBB; 16], + "ticket", + "stamp", + DeliveryMethod::Direct, + ) + .unwrap(); + router.prepare_outbound(&mut msg).unwrap(); + let msg = msg.sign(&key).unwrap(); + router.submit_signed(msg).unwrap(); assert!(router.pending_deferred_stamps.is_empty()); assert_eq!(router.pending_outbound.len(), 1); let queued = &router.pending_outbound[0]; - assert_eq!(queued.stamp.as_ref().map(Vec::len), Some(TICKET_LENGTH)); - assert_eq!(queued.stamp_value, Some(COST_TICKET)); + assert_eq!( + queued.recipient_stamp().map(|s| s.as_bytes().len()), + Some(TICKET_LENGTH) + ); + assert!(matches!( + queued.recipient_stamp(), + Some(RecipientStamp::Ticket(_)) + )); } #[test] fn prepare_outbound_issues_native_reply_ticket_before_signing() { let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); let mut router = LxmRouter::new(RouterConfig::default()); + let dir = tempfile::tempdir().unwrap(); let dest = [0xAA; 16]; - let mut msg = LxMessage::new(dest, [0xBB; 16], "ticket", "reply", DeliveryMethod::Direct); + let mut msg = + LxMessageDraft::new(dest, [0xBB; 16], "ticket", "reply", DeliveryMethod::Direct) + .unwrap(); msg.include_ticket = true; - - router.prepare_outbound(&mut msg).unwrap(); - assert!(msg.msgpack_field_ids.contains(&FIELD_TICKET)); - let field = msg.fields.get(&FIELD_TICKET).unwrap(); - let value = rmpv::decode::read_value(&mut field.as_slice()).unwrap(); + let intent = router.prepare_outbound(&mut msg).unwrap(); + assert!(intent.requires_persistence()); + let crate::message::FieldValue::MessagePack(field) = msg.get_field(FIELD_TICKET).unwrap() + else { + panic!("native ticket field required") + }; + let value = rmpv::decode::read_value(&mut field.encoded()).unwrap(); assert_eq!(value.as_array().unwrap().len(), 2); - msg.sign(&key).unwrap(); - router.try_send(msg).unwrap(); - - let hash = router.pending_outbound[0].hash.unwrap(); + assert!(msg.clone().sign(&key).is_err()); + intent.persist(dir.path(), &mut msg).unwrap(); + router.submit_signed(msg.sign(&key).unwrap()).unwrap(); + let hash = router.pending_outbound[0].message_id(); assert!(router.mark_outbound_delivered(&hash)); - - let mut next = LxMessage::new(dest, [0xBB; 16], "ticket", "later", DeliveryMethod::Direct); + let mut next = + LxMessageDraft::new(dest, [0xBB; 16], "ticket", "later", DeliveryMethod::Direct) + .unwrap(); next.include_ticket = true; - router.prepare_outbound(&mut next).unwrap(); - assert!(!next.fields.contains_key(&FIELD_TICKET)); + let intent = router.prepare_outbound(&mut next).unwrap(); + assert!(!next.fields().contains_key(&FIELD_TICKET.into())); + assert!(!intent.requires_persistence()); } #[test] fn externally_retained_message_updates_ticket_only_when_completed() { let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); let mut router = LxmRouter::new(RouterConfig::default()); + let dir = tempfile::tempdir().unwrap(); let dest = [0xAC; 16]; - let mut in_flight = LxMessage::new( + let mut in_flight = LxMessageDraft::new( dest, [0xBD; 16], "ticket", "proof", DeliveryMethod::Opportunistic, - ); + ) + .unwrap(); in_flight.include_ticket = true; - router.prepare_outbound(&mut in_flight).unwrap(); - in_flight.sign(&key).unwrap(); - + router + .prepare_outbound(&mut in_flight) + .unwrap() + .persist(dir.path(), &mut in_flight) + .unwrap(); + let in_flight = in_flight.sign(&key).unwrap().finalize(None).unwrap(); let mut before_proof = - LxMessage::new(dest, [0xBD; 16], "ticket", "before", DeliveryMethod::Direct); + LxMessageDraft::new(dest, [0xBD; 16], "ticket", "before", DeliveryMethod::Direct) + .unwrap(); before_proof.include_ticket = true; - router.prepare_outbound(&mut before_proof).unwrap(); - assert!(before_proof.fields.contains_key(&FIELD_TICKET)); - + router + .prepare_outbound(&mut before_proof) + .unwrap() + .persist(dir.path(), &mut before_proof) + .unwrap(); + assert!(before_proof.get_field(FIELD_TICKET).is_some()); router.complete_outbound_message(in_flight); - let mut after_proof = - LxMessage::new(dest, [0xBD; 16], "ticket", "after", DeliveryMethod::Direct); + LxMessageDraft::new(dest, [0xBD; 16], "ticket", "after", DeliveryMethod::Direct) + .unwrap(); after_proof.include_ticket = true; - router.prepare_outbound(&mut after_proof).unwrap(); - assert!(!after_proof.fields.contains_key(&FIELD_TICKET)); + let intent = router.prepare_outbound(&mut after_proof).unwrap(); + assert!(after_proof.get_field(FIELD_TICKET).is_none()); + assert!(!intent.requires_persistence()); } #[test] fn signed_message_requesting_ticket_fails_instead_of_invalidating_signature() { let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new( + let mut draft = LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "ticket", - "late", + "pending", DeliveryMethod::Direct, - ); - msg.include_ticket = true; - msg.sign(&key).unwrap(); - + ) + .unwrap(); + draft.include_ticket = true; + let intent = router.prepare_outbound(&mut draft).unwrap(); + assert!(intent.requires_persistence()); assert!(matches!( - router.try_send(msg), - Err(SendError::TicketPreparation { - source: TicketPreparationError::AlreadySigned, - .. - }) + draft.sign(&key), + Err(MessageError::TicketNotCommitted) )); assert!(router.pending_outbound.is_empty()); } #[test] fn deliver_inbound_learns_ticket_only_after_signature_validation() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let public = key.public_key(); - let source = [0xBB; 16]; + let identity = rns_identity::identity::Identity::new(); + let key = identity.get_signing_key().unwrap(); + let source = rns_identity::destination::Destination::hash_from_name_and_identity( + "lxmf.delivery", + Some(&identity.hash), + ); let mut sender = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new( + let dir = tempfile::tempdir().unwrap(); + let mut draft = LxMessageDraft::new( [0xAA; 16], source, "ticket", "learn", DeliveryMethod::Direct, - ); - msg.include_ticket = true; - sender.prepare_outbound(&mut msg).unwrap(); - msg.sign(&key).unwrap(); - - let mut unsigned_receiver = LxmRouter::new(RouterConfig::default()); - assert!(unsigned_receiver.deliver_inbound(&msg, false)); - assert!(unsigned_receiver.get_outbound_ticket(&source).is_none()); - - let mut verified = msg.clone(); - assert!(verified.verify(&public)); + ) + .unwrap(); + draft.include_ticket = true; + sender + .prepare_outbound(&mut draft) + .unwrap() + .persist(dir.path(), &mut draft) + .unwrap(); + let message = draft.sign(&key).unwrap().finalize(None).unwrap(); let mut receiver = LxmRouter::new(RouterConfig::default()); - assert!(receiver.deliver_inbound(&verified, false)); + assert!(receiver.deliver_inbound(&message, false)); + assert!(receiver.get_outbound_ticket(&source).is_none()); + let verified = message.verify(&identity.get_public_key()).unwrap(); + assert!(receiver.learn_ticket_from_inbound(&verified)); assert!(receiver.get_outbound_ticket(&source).is_some()); } @@ -2733,10 +2828,18 @@ mod tests { let dest = [0xAA; 16]; router.set_stamp_cost(dest, 1); - let mut msg = LxMessage::new(dest, [0xBB; 16], "defer", "stamp", DeliveryMethod::Direct); - msg.sign(&key).unwrap(); - let message_id = msg.message_id.unwrap(); - router.try_send(msg).unwrap(); + let mut msg = crate::message::LxMessageDraft::new( + dest, + [0xBB; 16], + "defer", + "stamp", + DeliveryMethod::Direct, + ) + .unwrap(); + router.prepare_outbound(&mut msg).unwrap(); + let msg = msg.sign(&key).unwrap(); + let message_id = msg.message_id(); + router.submit_signed(msg).unwrap(); assert!(router.pending_outbound.is_empty()); assert!(router.pending_deferred_stamps.contains_key(&message_id)); @@ -2752,8 +2855,19 @@ mod tests { assert!(router.pending_deferred_stamps.is_empty()); assert_eq!(router.pending_outbound.len(), 1); let queued = &router.pending_outbound[0]; - assert_eq!(queued.stamp.as_ref().map(Vec::len), Some(32)); - assert!(queued.stamp_value.unwrap_or(0) >= 1); + assert_eq!( + queued.recipient_stamp().map(|s| s.as_bytes().len()), + Some(32) + ); + let Some(RecipientStamp::ProofOfWork(stamp)) = queued.recipient_stamp() else { + panic!("PoW stamp required") + }; + assert!(stamper::validate_stamp( + &queued.message_id(), + stamp, + 1, + STAMP_WORKBLOCK_EXPAND_ROUNDS + )); } /// Production shape: the manager tick runs on `spawn_blocking`, where @@ -2771,16 +2885,18 @@ mod tests { let dest = [0xAA; 16]; router.set_stamp_cost(dest, 1); - let mut msg = LxMessage::new( + let mut msg = crate::message::LxMessageDraft::new( dest, [0xBB; 16], "defer", "blocking", DeliveryMethod::Direct, - ); - msg.sign(&key).unwrap(); - let message_id = msg.message_id.unwrap(); - router.try_send(msg).unwrap(); + ) + .unwrap(); + router.prepare_outbound(&mut msg).unwrap(); + let msg = msg.sign(&key).unwrap(); + let message_id = msg.message_id(); + router.submit_signed(msg).unwrap(); assert!(router.pending_deferred_stamps.contains_key(&message_id)); // Drive entirely from a blocking thread (no implicit runtime). @@ -2804,7 +2920,9 @@ mod tests { } assert_eq!(router.pending_outbound.len(), 1); assert_eq!( - router.pending_outbound[0].stamp.as_ref().map(Vec::len), + router.pending_outbound[0] + .recipient_stamp() + .map(|s| s.as_bytes().len()), Some(32) ); } @@ -2816,12 +2934,20 @@ mod tests { async fn defer_stamp_queues_message_with_id() { let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "d", "s", DeliveryMethod::Direct); - msg.sign(&key).unwrap(); + let mut msg = crate::message::LxMessageDraft::new( + [0xAA; 16], + [0xBB; 16], + "d", + "s", + DeliveryMethod::Direct, + ) + .unwrap(); msg.stamp_cost = Some(1); - let id = msg.message_id.unwrap(); + router.prepare_outbound(&mut msg).unwrap(); + let msg = msg.sign(&key).unwrap(); + let id = msg.message_id(); - assert!(router.defer_stamp(msg).is_none()); + router.defer_stamp(msg); assert!(router.pending_deferred_stamps.contains_key(&id)); } @@ -2832,10 +2958,18 @@ mod tests { let dest = [0xAA; 16]; router.set_stamp_cost(dest, 8); - let mut msg = LxMessage::new(dest, [0xBB; 16], "cancel", "stamp", DeliveryMethod::Direct); - msg.sign(&key).unwrap(); - let message_id = msg.message_id.unwrap(); - router.try_send(msg).unwrap(); + let mut msg = crate::message::LxMessageDraft::new( + dest, + [0xBB; 16], + "cancel", + "stamp", + DeliveryMethod::Direct, + ) + .unwrap(); + router.prepare_outbound(&mut msg).unwrap(); + let msg = msg.sign(&key).unwrap(); + let message_id = msg.message_id(); + router.submit_signed(msg).unwrap(); router.process_deferred_stamps(); assert!(router.active_deferred_stamp.is_some()); @@ -2917,10 +3051,10 @@ mod tests { #[test] fn test_cancel_outbound() { let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); + let mut msg = + crate::message::test_message([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); msg.state = MessageState::Outbound; - let hash = [0x11u8; 32]; - msg.hash = Some(hash); + let hash = msg.message_id(); router.pending_outbound.push(msg); assert!(router.cancel_outbound(&hash)); @@ -2931,10 +3065,10 @@ mod tests { #[test] fn test_get_outbound_progress() { let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); + let mut msg = + crate::message::test_message([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); msg.progress = 0.42; - let hash = [0x22u8; 32]; - msg.hash = Some(hash); + let hash = msg.message_id(); router.pending_outbound.push(msg); assert_eq!(router.get_outbound_progress(&hash), Some(0.42)); @@ -2953,10 +3087,8 @@ mod tests { fired_clone.store(true, Ordering::Relaxed); }); - let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); - msg.hash = Some([0x11; 32]); - msg.message_id = msg.hash; - msg.transient_id = msg.hash; + let msg = + crate::message::test_message([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); assert!(router.deliver_inbound(&msg, false)); assert!(fired.load(Ordering::Relaxed)); } @@ -2973,47 +3105,64 @@ mod tests { observed.fetch_add(1, Ordering::Relaxed); }); - let mut packet = LxMessage::new( + let packet = crate::message::test_message( [0xAA; 16], [0xBB; 16], "same", "message", DeliveryMethod::Opportunistic, ); - packet.hash = Some([0x22; 32]); - packet.message_id = packet.hash; - packet.transient_id = packet.hash; let mut resource = packet.clone(); resource.method = DeliveryMethod::Direct; assert!(router.deliver_inbound(&packet, false)); assert!(!router.deliver_inbound(&resource, false)); assert_eq!(deliveries.load(Ordering::Relaxed), 1); - assert!(router.has_message(&[0x22; 32])); + assert!(router.has_message(&packet.message_id())); } #[test] fn propagated_delivery_records_ciphertext_and_signed_message_ids() { + use crate::admission::{ + AdmissionRecord, AdmissionScope, DurableAdmissionReceipt, DurableDisposition, + }; let mut router = LxmRouter::new(RouterConfig::default()); - let mut propagated = LxMessage::new( + let message = crate::message::test_message( [0xAA; 16], [0xBB; 16], "propagated", "message", DeliveryMethod::Propagated, ); - propagated.hash = Some([0x33; 32]); - propagated.message_id = propagated.hash; - propagated.transient_id = Some([0x44; 32]); - - assert!(router.deliver_inbound(&propagated, false)); - assert!(router.has_message(&[0x33; 32])); - assert!(router.has_message(&[0x44; 32])); - assert!(router.propagation_store.is_locally_processed(&[0x44; 32])); - - let mut direct = propagated.clone(); + let temp = tempfile::tempdir().unwrap(); + let store = crate::admission_store::FileAdmissionStore::open( + temp.path(), + &temp.path().join("messages"), + ) + .unwrap(); + let tid = [0x44; 32]; + let record = AdmissionRecord { + scope: AdmissionScope { + identity: [1; 16], + node: [2; 16], + transient_id: tid, + }, + message_id: message.message_id(), + received_wire_hash: rns_crypto::sha::full_hash(message.wire_bytes()), + stored_message_wire_hash: None, + disposition: DurableDisposition::Committed, + committed_at: 100, + }; + let reservation = router.reserve_inbound(&message).unwrap(); + let receipt = + DurableAdmissionReceipt::commit(store.prepare(record, message.wire_owned(), false)) + .unwrap(); + assert!(router.commit_inbound(reservation, &message, &receipt, None)); + assert!(router.has_message(&message.message_id())); + assert!(router.has_message(&tid)); + assert!(router.propagation_store.is_locally_processed(&tid)); + let mut direct = message.clone(); direct.method = DeliveryMethod::Direct; - direct.transient_id = direct.hash; assert!(!router.deliver_inbound(&direct, false)); } @@ -3023,14 +3172,15 @@ mod tests { let mut router = LxmRouter::new(RouterConfig::default()); let key = Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "paper", "hello", DeliveryMethod::Paper, - ); - msg.sign(&key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&key).unwrap().finalize(None).unwrap(); let uri = msg .to_paper_uri(|plaintext| Ok(plaintext.to_vec())) .unwrap(); @@ -3046,7 +3196,7 @@ mod tests { let decoded = router .ingest_lxm_uri(&uri, |ciphertext| Ok(ciphertext.to_vec())) .unwrap(); - assert_eq!(decoded.title, "paper"); + assert_eq!(decoded.title_text(), "paper"); assert!(fired.load(Ordering::Relaxed)); } @@ -3116,8 +3266,11 @@ mod tests { router.unpeered_propagation_rx_bytes = 23; assert_eq!(snapshot.outbound_stamp_costs[&dest].cost, 8); - assert_eq!(snapshot.tickets.outbound.len(), 1); - assert_eq!(snapshot.tickets.outbound[0].token, [0xC3; 16]); + let dir = tempfile::tempdir().unwrap(); + snapshot.tickets.save(dir.path(), None).unwrap(); + let (tickets, _) = crate::persist::load_tickets(dir.path()).unwrap(); + assert_eq!(tickets.outbound.len(), 1); + assert_eq!(tickets.outbound[0].token, [0xC3; 16]); assert!(snapshot.local_deliveries.contains_key(&transient)); assert!(snapshot.locally_processed.contains_key(&transient)); assert_eq!(snapshot.node_stats.client_propagation_messages_received, 10); @@ -3322,7 +3475,7 @@ mod tests { #[test] fn test_send_message() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Test", @@ -3337,7 +3490,7 @@ mod tests { #[test] fn test_try_send_propagated_without_node_fails_immediately() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Propagated", @@ -3356,7 +3509,7 @@ mod tests { #[test] fn test_process_outbound_fails_only_above_max_attempts() { let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new( + let mut msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Test", @@ -3376,7 +3529,7 @@ mod tests { #[test] fn test_process_outbound_at_max_attempts_not_failed() { let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new( + let mut msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Test", @@ -3431,7 +3584,7 @@ mod tests { #[test] fn test_process_outbound_direct_delivery() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Direct", @@ -3455,7 +3608,7 @@ mod tests { router.add_peer(peer); router.set_outbound_propagation_node(Some(peer_hash)); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Propagated", @@ -3474,7 +3627,7 @@ mod tests { #[test] fn test_process_outbound_opportunistic_delivery() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Opportunistic", @@ -3493,7 +3646,7 @@ mod tests { #[test] fn test_process_outbound_propagated_no_node() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Propagated", @@ -3515,7 +3668,7 @@ mod tests { fn test_delivery_announce_trigger_clears_direct_retry_backoff() { let mut router = LxmRouter::new(RouterConfig::default()); let dest = [0xAA; 16]; - let mut msg = LxMessage::new( + let mut msg = crate::message::test_message( dest, [0xBB; 16], "Direct", @@ -3541,7 +3694,7 @@ mod tests { let dest = [0xAA; 16]; let node = [0xCC; 16]; router.set_outbound_propagation_node(Some(node)); - let mut msg = LxMessage::new( + let mut msg = crate::message::test_message( dest, [0xBB; 16], "Propagated", @@ -3566,7 +3719,7 @@ mod tests { let mut router = LxmRouter::new(RouterConfig::default()); let node = [0xCC; 16]; router.set_outbound_propagation_node(Some(node)); - let mut msg = LxMessage::new( + let mut msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Propagated", @@ -3599,7 +3752,7 @@ mod tests { let node = [0xCC; 16]; router.set_outbound_propagation_node(Some(node)); router - .try_send(LxMessage::new( + .try_send(crate::message::test_message( [0xAA; 16], [0xBB; 16], "Propagated", @@ -3625,15 +3778,22 @@ mod tests { #[test] fn test_process_outbound_expired_message_marked_failed() { let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new( + let mut msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Stale", "Content", DeliveryMethod::Direct, - ); + ) + .unwrap(); // Anchor the timestamp comfortably past the expiry window. - msg.timestamp = now_f64() - (MESSAGE_EXPIRY as f64) - 60.0; + msg.set_timestamp(now_f64() - (MESSAGE_EXPIRY as f64) - 60.0) + .unwrap(); + let msg = msg + .sign(&rns_crypto::ed25519::Ed25519PrivateKey::generate()) + .unwrap() + .finalize(None) + .unwrap(); router.try_send(msg).unwrap(); let actions = router.process_outbound(); @@ -3656,7 +3816,7 @@ mod tests { #[test] fn test_process_outbound_retry_backoff_defers_within_window() { let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new( + let mut msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Backoff", @@ -3687,7 +3847,7 @@ mod tests { #[test] fn test_process_outbound_retry_backoff_uses_last_attempt_timestamp() { let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = LxMessage::new( + let mut msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Backoff", @@ -3715,7 +3875,7 @@ mod tests { #[test] fn test_process_outbound_direct_transitions_to_sending() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Direct", @@ -3745,14 +3905,15 @@ mod tests { router.set_transport(tx); let signing_key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Tick Test", "Content", DeliveryMethod::Opportunistic, - ); - msg.sign(&signing_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&signing_key).unwrap().finalize(None).unwrap(); router.try_send(msg).unwrap(); router.tick_with_encryptor(|_dest, plaintext| Ok(plaintext.to_vec())); @@ -3770,7 +3931,13 @@ mod tests { let mut router = LxmRouter::new(RouterConfig::default()); // No transport set — execute_actions must be a no-op. let actions = vec![OutboundAction::DeliverDirect { - message: LxMessage::new([0; 16], [0; 16], "t", "c", DeliveryMethod::Direct), + message: crate::message::test_message( + [0; 16], + [0; 16], + "t", + "c", + DeliveryMethod::Direct, + ), dest_hash: [0; 16], }]; router.execute_actions(actions); @@ -3786,17 +3953,25 @@ mod tests { let mut router = LxmRouter::new(RouterConfig::default()); router.set_transport(tx); - let mut direct = LxMessage::new(dest_hash, src_hash, "Direct", "d", DeliveryMethod::Direct); - direct.sign(&key).unwrap(); + let direct = crate::message::LxMessageDraft::new( + dest_hash, + src_hash, + "Direct", + "d", + DeliveryMethod::Direct, + ) + .unwrap(); + let direct = direct.sign(&key).unwrap().finalize(None).unwrap(); - let mut opportunistic = LxMessage::new( + let opportunistic = crate::message::LxMessageDraft::new( dest_hash, src_hash, "Opp", "o", DeliveryMethod::Opportunistic, - ); - opportunistic.sign(&key).unwrap(); + ) + .unwrap(); + let opportunistic = opportunistic.sign(&key).unwrap().finalize(None).unwrap(); let opportunistic_packed = opportunistic.pack().unwrap(); router.execute_actions_with_encryptor( @@ -3845,15 +4020,16 @@ mod tests { .unwrap(); let mut router = LxmRouter::new(RouterConfig::default()); router.set_transport(tx); - let mut message = LxMessage::new( + let message = crate::message::LxMessageDraft::new( dest_hash, [0xB1; 16], "defer", "payload", DeliveryMethod::Opportunistic, - ); - message.sign(&key).unwrap(); - let message_hash = message.hash; + ) + .unwrap(); + let message = message.sign(&key).unwrap().finalize(None).unwrap(); + let message_hash = Some(message.message_id()); router.execute_actions_with_encryptor( vec![OutboundAction::DeliverOpportunistic { message, dest_hash }], @@ -3865,7 +4041,10 @@ mod tests { rns_transport::messages::TransportMessage::DeregisterDestination { .. } )); assert_eq!(router.pending_outbound.len(), 1); - assert_eq!(router.pending_outbound.first().unwrap().hash, message_hash); + assert_eq!( + Some(router.pending_outbound.first().unwrap().message_id()), + message_hash + ); } #[test] @@ -3878,17 +4057,25 @@ mod tests { let mut router = LxmRouter::new(RouterConfig::default()); router.set_transport(tx); - let mut direct = LxMessage::new(dest_hash, src_hash, "Direct", "d", DeliveryMethod::Direct); - direct.sign(&key).unwrap(); + let direct = crate::message::LxMessageDraft::new( + dest_hash, + src_hash, + "Direct", + "d", + DeliveryMethod::Direct, + ) + .unwrap(); + let direct = direct.sign(&key).unwrap().finalize(None).unwrap(); - let mut opportunistic = LxMessage::new( + let opportunistic = crate::message::LxMessageDraft::new( dest_hash, src_hash, "Opp", "o", DeliveryMethod::Opportunistic, - ); - opportunistic.sign(&key).unwrap(); + ) + .unwrap(); + let opportunistic = opportunistic.sign(&key).unwrap().finalize(None).unwrap(); router.execute_actions(vec![ OutboundAction::DeliverDirect { @@ -4220,7 +4407,7 @@ mod tests { let mut router = LxmRouter::new(config); router - .try_send(LxMessage::new( + .try_send(crate::message::test_message( [0x01; 16], [0; 16], "a", @@ -4229,7 +4416,7 @@ mod tests { )) .unwrap(); router - .try_send(LxMessage::new( + .try_send(crate::message::test_message( [0x02; 16], [0; 16], "c", @@ -4257,7 +4444,7 @@ mod tests { fn test_opportunistic_fallback_to_direct() { let mut router = LxmRouter::new(RouterConfig::default()); let large_content = "x".repeat(500); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Large", @@ -4272,7 +4459,7 @@ mod tests { #[test] fn test_direct_message_state_sending() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Direct", @@ -4299,7 +4486,7 @@ mod tests { router.add_peer(peer); router.set_outbound_propagation_node(Some(peer_hash)); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Propagated", @@ -4321,7 +4508,7 @@ mod tests { #[test] fn test_opportunistic_message_state_sent() { let mut router = LxmRouter::new(RouterConfig::default()); - let msg = LxMessage::new( + let msg = crate::message::test_message( [0xAA; 16], [0xBB; 16], "Opportunistic", @@ -4348,14 +4535,15 @@ mod tests { router.set_transport(tx); let signing_key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut msg = LxMessage::new( + let msg = crate::message::LxMessageDraft::new( [0xAA; 16], [0xBB; 16], "Direct Sent", "Content", DeliveryMethod::Direct, - ); - msg.sign(&signing_key).unwrap(); + ) + .unwrap(); + let msg = msg.sign(&signing_key).unwrap().finalize(None).unwrap(); router.try_send(msg).unwrap(); router.tick(); diff --git a/crates/lxmf-core/src/stamper.rs b/crates/lxmf-core/src/stamper.rs index 2d161e6..384bc13 100644 --- a/crates/lxmf-core/src/stamper.rs +++ b/crates/lxmf-core/src/stamper.rs @@ -96,6 +96,20 @@ pub fn stamp_iteration_cap(cost: u8) -> Option { /// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the /// cost is unsatisfiable. pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> { + generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false)) +} + +/// Synchronous bounded worker entry. Cancellation revokes work without claiming +/// that an async task abort stopped this closure or released its byte owners. +pub fn generate_stamp_cancellable( + material: &[u8], + cost: u8, + expand_rounds: usize, + cancel: &AtomicBool, +) -> Option<([u8; 32], u32)> { + if cancel.load(Ordering::Acquire) { + return None; + } if cost == 0 { return Some(([0u8; 32], 0)); } @@ -107,7 +121,10 @@ pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option base_hasher.update(&workblock); let mut rng = rand::thread_rng(); - for _ in 0..max_iterations { + for iteration in 0..max_iterations { + if iteration % 1000 == 0 && cancel.load(Ordering::Acquire) { + return None; + } let stamp = rand_bytes_from(&mut rng); let value = stamp_value_from_base(&base_hasher, &stamp); if value >= cost as u32 { diff --git a/crates/lxmf-core/tests/durable_delivery.rs b/crates/lxmf-core/tests/durable_delivery.rs new file mode 100644 index 0000000..87ed2eb --- /dev/null +++ b/crates/lxmf-core/tests/durable_delivery.rs @@ -0,0 +1,560 @@ +//! Focused public-boundary regressions for durable propagation delivery. +use lxmf_core::admission::*; +use lxmf_core::admission_store::FileAdmissionStore; +use lxmf_core::constants::DeliveryMethod; +use lxmf_core::message::{LxMessage, LxMessageDraft, RecipientStamp}; +use lxmf_core::propagation_send::*; +use rns_crypto::{ed25519::Ed25519PrivateKey, sha::full_hash}; + +// These tests deliberately exhaust the shared production admission budget. +// Exclude only other budget-exhaustion fixtures, without changing its limits. +static PROCESSING_BUDGET_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn message(stamp: Option) -> LxMessage { + let mut draft = LxMessageDraft::new( + [1; 16], + [2; 16], + "title", + "body", + DeliveryMethod::Propagated, + ) + .unwrap(); + draft.set_timestamp(100.).unwrap(); + draft + .sign(&Ed25519PrivateKey::from_bytes(&[3; 32])) + .unwrap() + .finalize(stamp) + .unwrap() +} +fn scope(n: u8) -> AdmissionScope { + AdmissionScope { + identity: [4; 16], + node: [5; 16], + transient_id: [n; 32], + } +} +fn record(msg: &LxMessage, n: u8, time: u64, disposition: DurableDisposition) -> AdmissionRecord { + AdmissionRecord { + scope: scope(n), + message_id: msg.message_id(), + received_wire_hash: full_hash(msg.wire_bytes()), + stored_message_wire_hash: None, + disposition, + committed_at: time, + } +} +fn commit( + store: &FileAdmissionStore, + msg: &LxMessage, + n: u8, + time: u64, + disposition: DurableDisposition, +) -> DurableAdmissionReceipt { + DurableAdmissionReceipt::commit(store.prepare( + record(msg, n, time, disposition), + msg.wire_owned(), + true, + )) + .unwrap() +} +#[test] +fn duplicate_stamp_images_keep_first_archive_and_one_hook_across_restart() { + let temp = tempfile::tempdir().unwrap(); + let bodies = temp.path().join("messages"); + let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + let first = message(None); + let second = message(Some(RecipientStamp::ProofOfWork([7; 32]))); + assert_eq!(first.message_id(), second.message_id()); + assert_ne!(first.wire_bytes(), second.wire_bytes()); + commit(&store, &first, 1, 100, DurableDisposition::Committed); + let duplicate = commit(&store, &second, 2, 101, DurableDisposition::Committed); + assert_eq!( + duplicate.record().disposition, + DurableDisposition::Duplicate + ); + assert_eq!( + duplicate.record().received_wire_hash, + full_hash(second.wire_bytes()) + ); + assert_eq!( + duplicate.record().stored_message_wire_hash, + Some(full_hash(first.wire_bytes())) + ); + assert_eq!( + std::fs::read(bodies.join(format!("{}.lxm", hex::encode(first.message_id())))).unwrap(), + first.wire_bytes() + ); + assert_eq!(store.pending_hooks().len(), 1); + drop(store); + let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + assert_eq!( + reopened.haves(scope(1).identity, scope(1).node, 102).len(), + 2 + ); + assert_eq!(reopened.pending_hooks().len(), 1); + let event = reopened.pending_hooks()[0].0; + reopened.complete_hook(event).unwrap(); + drop(reopened); + assert!( + FileAdmissionStore::open(temp.path(), &bodies) + .unwrap() + .pending_hooks() + .is_empty() + ); +} +#[test] +fn published_body_intent_recovers_original_tid_after_missing_commit() { + let temp = tempfile::tempdir().unwrap(); + let bodies = temp.path().join("messages"); + let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + let msg = message(None); + commit(&store, &msg, 9, 100, DurableDisposition::Committed); + drop(store); + let dir = temp.path().join("download-admission-v1"); + for file in std::fs::read_dir(&dir).unwrap() { + let path = file.unwrap().path(); + if path.extension().is_some_and(|s| s == "commit") { + std::fs::remove_file(path).unwrap(); + } + } + let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + assert_eq!( + recovered.haves(scope(9).identity, scope(9).node, 101), + vec![scope(9).transient_id.to_vec()] + ); + assert_eq!(recovered.pending_hooks().len(), 1); +} +#[test] +fn damaged_archive_never_becomes_purge_authority_on_restart() { + let temp = tempfile::tempdir().unwrap(); + let bodies = temp.path().join("messages"); + let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + let msg = message(None); + commit(&store, &msg, 1, 100, DurableDisposition::Committed); + drop(store); + let archive = bodies.join(format!("{}.lxm", hex::encode(msg.message_id()))); + std::fs::write(&archive, b"preserved corrupt evidence").unwrap(); + let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + assert!( + reopened + .haves(scope(1).identity, scope(1).node, 101) + .is_empty() + ); + assert!(reopened.pending_hooks().is_empty()); + assert_eq!( + std::fs::read(archive).unwrap(), + b"preserved corrupt evidence" + ); +} +#[test] +fn expired_policy_receipt_is_revalidated_and_user_deletion_outlives_tid_receipts() { + let temp = tempfile::tempdir().unwrap(); + let bodies = temp.path().join("messages"); + let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + let msg = message(None); + commit(&store, &msg, 1, 100, DurableDisposition::PolicyDiscard); + assert!( + !bodies + .join(format!("{}.lxm", hex::encode(msg.message_id()))) + .exists() + ); + let now = 101 + POLICY_RECEIPT_LIFETIME; + assert!( + store + .haves(scope(1).identity, scope(1).node, now) + .is_empty() + ); + assert_eq!( + commit(&store, &msg, 1, now, DurableDisposition::Committed) + .record() + .disposition, + DurableDisposition::Committed + ); + store + .mark_user_deleted(scope(1).identity, msg.message_id(), now + 1) + .unwrap(); + assert!(store.pending_hooks().is_empty()); + assert_eq!( + store.maintain(now + 2 + POLICY_RECEIPT_LIFETIME).unwrap(), + 1 + ); + drop(store); + let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + assert_eq!( + commit( + &reopened, + &msg, + 2, + now + 3 + POLICY_RECEIPT_LIFETIME, + DurableDisposition::Committed + ) + .record() + .disposition, + DurableDisposition::UserDeleted + ); + assert!( + !bodies + .join(format!("{}.lxm", hex::encode(msg.message_id()))) + .exists() + ); +} +#[test] +fn suppression_retries_transient_failures_and_revalidates_epoch_changes() { + let mut ledger = SuppressionLedger::default(); + let epoch = AdmissionEpochs::default(); + ledger + .record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100) + .unwrap(); + assert!(ledger.get(&scope(1)).unwrap().active(101, epoch)); + let mut new = epoch; + new.keys[0] = 1; + assert!(!ledger.get(&scope(1)).unwrap().active(101, new)); + for _ in 0..20 { + ledger + .record_failure(scope(2), SuppressionReason::StorageBusy, epoch, 100) + .unwrap(); + } + let retry = ledger.get(&scope(2)).unwrap(); + assert!((3340..=4060).contains(&retry.next_retry)); + assert!(!retry.active(retry.next_retry, epoch)); + let wire = rmp_serde::to_vec(&ledger).unwrap(); + let restored: SuppressionLedger = rmp_serde::from_slice(&wire).unwrap(); + assert_eq!(restored.records().count(), 2); +} +#[test] +fn processing_admission_fails_promptly_without_partial_credit_deadlock() { + let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap(); + assert!(matches!( + ProcessingLease::try_acquire(usize::MAX), + Err(SuppressionReason::TooLarge) + )); + let workers = (0..MAX_PROCESSORS) + .map(|_| ProcessingLease::try_acquire(100).unwrap()) + .collect::>(); + assert!(matches!( + ProcessingLease::try_acquire(100), + Err(SuppressionReason::WorkerUnavailable) + )); + drop(workers); + assert!(ProcessingLease::try_acquire(100).is_ok()); +} +#[test] +fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() { + let msg = message(None); + let mut envelope = PropagationEnvelope::new(msg, [6; 32], 0, |p| Ok(p.to_vec())).unwrap(); + let initial = envelope.ciphertext().clone(); + let tid = envelope.transient_id(); + let policy = AdvertisedNodePolicy { + stamp_cost: 0, + transfer_limit_kb: 256., + recorded_at: 100., + }; + let mut ready = propagation_readiness([8; 16], true, true, Some(policy), true, 101.).unwrap(); + envelope.pack_for(ready, 101.).unwrap(); + ready.policy.stamp_cost = 4; + envelope.pack_for(ready, 102.).unwrap(); + assert_eq!(envelope.ciphertext(), &initial); + assert_eq!(envelope.transient_id(), tid); + assert!(envelope.stamp_value() >= 4); + assert_eq!( + propagation_readiness([8; 16], true, true, None, true, 101.).unwrap_err(), + MissingPropagationInput::NodePolicy + ); + assert!(propagation_readiness([8; 16], true, true, Some(policy), true, 101.).is_ok()); +} +#[test] +fn reply_ticket_cannot_sign_before_its_exact_durable_intent() { + let temp = tempfile::tempdir().unwrap(); + let mut router = lxmf_core::router::LxmRouter::new(Default::default()); + let mut draft = + LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap(); + draft.include_ticket = true; + let intent = router.prepare_outbound(&mut draft).unwrap(); + assert!(intent.requires_persistence()); + assert!( + draft + .clone() + .sign(&Ed25519PrivateKey::from_bytes(&[3; 32])) + .is_err() + ); + let mut other = + LxMessageDraft::new([3; 16], [2; 16], "", "other", DeliveryMethod::Direct).unwrap(); + other.include_ticket = true; + assert!(matches!( + router.prepare_outbound(&mut other), + Err(lxmf_core::router::TicketPreparationError::PendingPersistence) + )); + intent.persist(temp.path(), &mut draft).unwrap(); + let msg = draft + .sign(&Ed25519PrivateKey::from_bytes(&[3; 32])) + .unwrap() + .finalize(None) + .unwrap(); + assert!( + msg.fields() + .get(lxmf_core::constants::FIELD_TICKET) + .is_some() + ); + let loaded = lxmf_core::persist::load_tickets(temp.path()).unwrap(); + assert!(!loaded.0.inbound.is_empty()); + assert!(router.prepare_outbound(&mut other).is_ok()); +} + +#[test] +fn suppression_hydration_rejects_duplicate_scopes_and_node_quota() { + let mut ledger = SuppressionLedger::default(); + let row = ledger + .record_failure( + scope(1), + SuppressionReason::InvalidSignature, + AdmissionEpochs::default(), + 100, + ) + .unwrap() + .clone(); + assert!(SuppressionLedger::from_records([row.clone(), row.clone()]).is_err()); + let mut keys = row.epochs; + keys.keys[0] = 1; + assert!(!row.active(101, keys)); + let mut policy = row.epochs; + policy.policy[0] = 1; + assert!(!row.active(101, policy)); + let rows = (0..=SuppressionLedger::PER_NODE).map(|index| { + let mut value = row.clone(); + value.scope.transient_id[..8].copy_from_slice(&(index as u64).to_be_bytes()); + value + }); + assert!(matches!( + SuppressionLedger::from_records(rows), + Err(AdmissionError::DispositionLedgerFull) + )); + assert_eq!( + SuppressionLedger::from_records([row]) + .unwrap() + .records() + .count(), + 1 + ); +} + +#[test] +fn adapter_processing_memory_shares_peak_budget_without_second_worker() { + let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap(); + let worker = ProcessingLease::try_acquire(1).unwrap(); + assert!(matches!( + ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES), + Err(SuppressionReason::WorkerUnavailable) + )); + let extra = ProcessingMemoryLease::try_acquire(8 * 1024 * 1024).unwrap(); + drop(extra); + drop(worker); + let all = ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES).unwrap(); + assert!(matches!( + ProcessingLease::try_acquire(1), + Err(SuppressionReason::WorkerUnavailable) + )); + drop(all); + assert!(ProcessingLease::try_acquire(1).is_ok()); +} + +fn reject_link_request( + receiver: &mut tokio::sync::mpsc::Receiver, +) { + use rns_transport::messages::TransportMessage; + while let Ok(message) = receiver.try_recv() { + if let TransportMessage::SendLinkRequest { result_tx, .. } = message { + result_tx + .send(Err( + rns_transport::link_messages::LinkRequestDispatchError::Capacity( + rns_transport::InterfaceCapacityError::LinkCapacityUnavailable { + interface_id: 7, + clear_mtu: 499, + required: 500, + }, + ), + )) + .unwrap(); + return; + } + } + panic!("exact Link request dispatch channel was not staged"); +} +#[test] +fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeout() { + use lxmf_core::link_delivery::{DeliveryResult, LinkDeliveryManager}; + use lxmf_core::propagation_client::{PropagationClient, PropagationClientState}; + use lxmf_core::propagation_sync::{PeerSyncTerminalState, PropagationSyncTask}; + let (tx, mut rx) = tokio::sync::mpsc::channel(32); + let mut delivery = LinkDeliveryManager::new(tx.clone(), None, None); + delivery.start_delivery(message(None), [3; 16], 1).unwrap(); + reject_link_request(&mut rx); + assert!(delivery.tick().iter().any( + |result| matches!(result,DeliveryResult::Failed {reason,..} if reason.contains("499")) + )); + let (tx, mut rx) = tokio::sync::mpsc::channel(32); + let mut client = PropagationClient::new(tx, None, None); + client.set_propagation_node([3; 16]); + assert!(client.start_download()); + reject_link_request(&mut rx); + client.tick(); + assert_eq!( + client.transfer_status().state, + PropagationClientState::Failed + ); + let (tx, mut rx) = tokio::sync::mpsc::channel(32); + let mut sync = PropagationSyncTask::new(tx, [8; 16]); + assert!(sync.request_sync_now([3; 16])); + reject_link_request(&mut rx); + sync.tick(); + assert_eq!( + sync.take_terminal_peer_result().unwrap().state, + PeerSyncTerminalState::Failed + ); +} +#[test] +fn canceled_download_closes_exact_request_admission_reply() { + let (tx, mut rx) = tokio::sync::mpsc::channel(32); + let mut client = lxmf_core::propagation_client::PropagationClient::new(tx, None, None); + client.set_propagation_node([3; 16]); + assert!(client.start_download()); + client.cancel_download(); + let mut found = false; + while let Ok(message) = rx.try_recv() { + if let rns_transport::messages::TransportMessage::SendLinkRequest { result_tx, .. } = + message + { + assert!(result_tx.is_closed()); + found = true; + } + } + assert!(found); +} + +#[test] +fn stale_checkpoint_cannot_erase_ticket_after_signing_intent_commit() { + let temp = tempfile::tempdir().unwrap(); + let mut router = lxmf_core::router::LxmRouter::new(Default::default()); + let stale = router.state_snapshot(); + let mut draft = + LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap(); + draft.include_ticket = true; + let intent = router.prepare_outbound(&mut draft).unwrap(); + intent.persist(temp.path(), &mut draft).unwrap(); + let committed = lxmf_core::persist::load_tickets(temp.path()).unwrap().0; + assert_eq!(committed.inbound.len(), 1); + stale.save_state(temp.path()).unwrap(); + assert_eq!( + lxmf_core::persist::load_tickets(temp.path()).unwrap().0, + committed + ); + // A newer checkpoint can commit while a draft is waiting for its exact + // intent. The old intent verifies that its ticket is still present. + drop(draft); + let mut next = + LxMessageDraft::new([4; 16], [2; 16], "", "next", DeliveryMethod::Direct).unwrap(); + next.include_ticket = true; + let intent = router.prepare_outbound(&mut next).unwrap(); + router.state_snapshot().save_state(temp.path()).unwrap(); + intent.persist(temp.path(), &mut next).unwrap(); + assert!(next.sign(&Ed25519PrivateKey::from_bytes(&[3; 32])).is_ok()); + assert_eq!( + lxmf_core::persist::load_tickets(temp.path()) + .unwrap() + .0 + .inbound + .len(), + 2 + ); +} + +#[test] +fn suppression_checkpoint_rejects_duplicate_scope_and_truncated_allocation_claim() { + let temp = tempfile::tempdir().unwrap(); + let mut ledger = SuppressionLedger::default(); + ledger + .record_failure( + scope(1), + SuppressionReason::Malformed, + AdmissionEpochs::default(), + 100, + ) + .unwrap(); + lxmf_core::persist::save_suppression(temp.path(), &ledger).unwrap(); + assert_eq!( + lxmf_core::persist::load_suppression(temp.path()) + .unwrap() + .records() + .count(), + 1 + ); + let path = temp.path().join("propagation_suppression_v1"); + let bytes = std::fs::read(&path).unwrap(); + let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap(); + let rmpv::Value::Array(fields) = &mut value else { + panic!("ledger wrapper") + }; + let rmpv::Value::Map(rows) = &mut fields[0] else { + panic!("ledger records") + }; + rows.push(rows[0].clone()); + let mut duplicate = Vec::new(); + rmpv::encode::write_value(&mut duplicate, &value).unwrap(); + std::fs::write(&path, duplicate).unwrap(); + assert!(lxmf_core::persist::load_suppression(temp.path()).is_err()); + std::fs::write(&path, [0x91, 0xdf, 0xff, 0xff, 0xff, 0xff]).unwrap(); + assert!(lxmf_core::persist::load_suppression(temp.path()).is_err()); +} + +#[test] +fn strict_ratchet_checkpoints_round_trip_and_surface_failed_publication() { + use rns_identity::{ + announce_state::RatchetControlState, + identity::Identity, + ratchet::{RatchetRing, ReceivedRatchet}, + }; + let temp = tempfile::tempdir().unwrap(); + let identity = Identity::new(); + let mut ring = RatchetRing::new(); + let public = ring.rotate_at(100.); + let ring_path = temp.path().join("ring"); + ring.save_verified_durable(&ring_path, &identity).unwrap(); + assert_eq!( + RatchetRing::load_verified(&ring_path, &identity) + .unwrap() + .ring() + .current_public_key(), + Some(public) + ); + let control = RatchetControlState::new(identity.hash, [2; 16]) + .prepare_announce(100) + .unwrap() + .unwrap(); + let control_path = temp.path().join("control"); + control + .save_verified_durable(&control_path, &identity) + .unwrap(); + assert_eq!( + RatchetControlState::load_verified(&control_path, &identity, [2; 16]).unwrap(), + control + ); + let received = ReceivedRatchet::new_at(public, 100.); + let received_path = temp.path().join("received"); + received.save_durable(&received_path).unwrap(); + assert_eq!( + ReceivedRatchet::load(&received_path).unwrap().ratchet_pub, + public + ); + let blocker = temp.path().join("not-a-directory"); + std::fs::write(&blocker, b"preserve").unwrap(); + assert!( + ring.save_verified_durable(&blocker.join("ring"), &identity) + .is_err() + ); + assert!( + control + .save_verified_durable(&blocker.join("control"), &identity) + .is_err() + ); + assert!(received.save_durable(&blocker.join("received")).is_err()); + assert_eq!(std::fs::read(blocker).unwrap(), b"preserve"); +} diff --git a/crates/lxmf-core/tests/relay_store_v2.rs b/crates/lxmf-core/tests/relay_store_v2.rs new file mode 100644 index 0000000..8cda71e --- /dev/null +++ b/crates/lxmf-core/tests/relay_store_v2.rs @@ -0,0 +1,243 @@ +use bytes::Bytes; +use lxmf_core::propagation_node::{ + PropagationAdmission, PropagationAdmissionOutcome, PropagationNode, PropagationNodeConfig, + ValidatedOpaquePropagationBlob, +}; +use rmpv::Value; +fn payload(destination: [u8; 16]) -> Bytes { + let recipient = rns_identity::identity::Identity::new(); + let mut bytes = destination.to_vec(); + bytes.extend_from_slice(&recipient.encrypt(b"private test payload", None).unwrap()); + bytes.extend_from_slice(&[0; 32]); + bytes.into() +} +fn validated(bytes: Bytes) -> ValidatedOpaquePropagationBlob { + ValidatedOpaquePropagationBlob::validate(bytes, 0).unwrap() +} +fn request(wants: Option>, haves: Option>) -> Vec { + let ids = |value: Option>| { + value + .map(|v| Value::Array(v.into_iter().map(|id| Value::Binary(id.to_vec())).collect())) + .unwrap_or(Value::Nil) + }; + encode(&Value::Array(vec![ids(wants), ids(haves)])) +} +fn reserve( + node: &mut PropagationNode, + bytes: Bytes, +) -> lxmf_core::propagation_node::PropagationStoreWritePlan { + match node.plan_opaque_admission(validated(bytes)) { + PropagationAdmission::Reserved(plan) => *plan, + other => panic!("expected new admission: {other:?}"), + } +} +#[tokio::test] +async fn duplicate_waits_for_exact_commit_and_rechecks_retained_files() { + let dir = tempfile::tempdir().unwrap(); + let old = dir.path().join("store"); + let mut node = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone()) + .unwrap(); + let bytes = payload([2; 16]); + let tid = validated(bytes.clone()).transient_id(); + let plan = reserve(&mut node, bytes.clone()); + let PropagationAdmission::Pending(waiter) = + node.plan_opaque_admission(validated(bytes.clone())) + else { + panic!("duplicate must coalesce") + }; + let task = tokio::spawn(waiter.wait()); + tokio::task::yield_now().await; + assert!(!task.is_finished()); + assert!(node.commit_store_write(plan.persist().unwrap())); + assert_eq!(task.await.unwrap(), PropagationAdmissionOutcome::Committed); + let PropagationAdmission::CommittedDuplicate(check) = + node.plan_opaque_admission(validated(bytes.clone())) + else { + panic!("committed duplicate") + }; + check.verify().unwrap(); + let path = node.plan_message_reads(&[tid]).pop().unwrap().path; + std::fs::write(&path, b"corruption").unwrap(); + let PropagationAdmission::CommittedDuplicate(check) = + node.plan_opaque_admission(validated(bytes)) + else { + panic!("duplicate requires file check") + }; + assert!(check.verify().is_err()); + drop(node); + assert!(PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).is_err()); +} +#[tokio::test] +async fn cancelled_reservation_releases_waiters_without_authority_and_can_retry() { + let dir = tempfile::tempdir().unwrap(); + let mut node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [1; 16], + dir.path().join("store"), + ) + .unwrap(); + let bytes = payload([2; 16]); + let plan = reserve(&mut node, bytes.clone()); + let PropagationAdmission::Pending(waiter) = + node.plan_opaque_admission(validated(bytes.clone())) + else { + panic!("duplicate must coalesce") + }; + drop(plan); + assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed); + let retry = reserve(&mut node, bytes); + assert!(node.commit_store_write(retry.persist().unwrap())); +} +#[tokio::test] +async fn lost_persisted_callback_reuses_first_image_and_restart_has_one_admission() { + let dir = tempfile::tempdir().unwrap(); + let legacy = dir.path().join("store"); + let mut node = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone()) + .unwrap(); + let bytes = payload([2; 16]); + let tid = validated(bytes.clone()).transient_id(); + let plan = reserve(&mut node, bytes.clone()); + let PropagationAdmission::Pending(waiter) = + node.plan_opaque_admission(validated(bytes.clone())) + else { + panic!("duplicate must coalesce") + }; + drop(plan.persist().unwrap()); + assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed); + let objects = legacy.with_extension("v2").join("objects"); + let first_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(first_files.len(), 3); + let plan = reserve(&mut node, bytes.clone()); + assert!(node.commit_store_write(plan.persist().unwrap())); + let retry_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(retry_files, first_files); + drop(node); + let reopened = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap(); + assert_eq!(reopened.message_count(), 1); + assert_eq!( + std::fs::read(&reopened.plan_message_reads(&[tid])[0].path).unwrap(), + bytes + ); +} +#[test] +fn purge_cannot_report_success_when_its_durable_intent_cannot_be_published() { + let dir = tempfile::tempdir().unwrap(); + let legacy = dir.path().join("store"); + let mut node = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone()) + .unwrap(); + let destination = [2; 16]; + let bytes = payload(destination); + let tid = validated(bytes.clone()).transient_id(); + let plan = reserve(&mut node, bytes.clone()); + assert!(node.commit_store_write(plan.persist().unwrap())); + let objects = legacy.with_extension("v2").join("objects"); + let unavailable = legacy.with_extension("v2").join("temporarily-unavailable"); + std::fs::rename(&objects, &unavailable).unwrap(); + assert_eq!( + node.handle_get_request(&request(None, Some(vec![tid])), &destination) + .into_response(), + encode(&Value::Nil) + ); + assert!(node.contains(&tid)); + std::fs::rename(&unavailable, &objects).unwrap(); + assert_eq!( + node.handle_get_request(&request(None, Some(vec![tid])), &destination) + .into_response(), + encode(&Value::Array(vec![])) + ); + drop(node); + let reopened = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap(); + assert!(!reopened.contains(&tid)); +} +#[test] +fn purge_is_durable_before_success_and_old_plan_cannot_delete_readmission() { + let dir = tempfile::tempdir().unwrap(); + let old = dir.path().join("store"); + let destination = [2; 16]; + let mut node = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone()) + .unwrap(); + let bytes = payload(destination); + let tid = validated(bytes.clone()).transient_id(); + let plan = reserve(&mut node, bytes.clone()); + assert!(node.commit_store_write(plan.persist().unwrap())); + let old_path = node.plan_message_reads(&[tid]).pop().unwrap().path; + let stale = node.handle_get_request(&request(None, Some(vec![tid])), &destination); + let purge = node.handle_get_request(&request(None, Some(vec![tid])), &destination); + assert_eq!(purge.into_response(), encode(&Value::Array(vec![]))); + assert!(!node.contains(&tid)); + assert!(!old_path.exists()); + let replacement = reserve(&mut node, bytes.clone()); + assert!(node.commit_store_write(replacement.persist().unwrap())); + let new_path = node.plan_message_reads(&[tid]).pop().unwrap().path; + assert_ne!(old_path, new_path); + // The old plan fails or sees an already completed retirement; it cannot + // gain authority over the distinct new admission path. + let _ = stale.into_response(); + assert!(node.contains(&tid)); + assert_eq!(std::fs::read(&new_path).unwrap(), bytes); + drop(node); + let reopened = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).unwrap(); + assert!(reopened.contains(&tid)); +} +#[test] +fn foreign_purge_has_no_effect_and_maintenance_publishes_retirement_off_lock() { + let dir = tempfile::tempdir().unwrap(); + let config = PropagationNodeConfig { + max_storage: 0, + ..Default::default() + }; + let mut node = + PropagationNode::with_storage(config, [1; 16], dir.path().join("store")).unwrap(); + let bytes = payload([2; 16]); + let tid = validated(bytes.clone()).transient_id(); + let plan = reserve(&mut node, bytes); + assert!(node.commit_store_write(plan.persist().unwrap())); + node.handle_get_request(&request(None, Some(vec![tid])), &[3; 16]) + .into_response(); + assert!(node.contains(&tid)); + let maintenance = node.plan_maintenance(); + assert!(!maintenance.is_empty()); + assert!(node.contains(&tid)); + maintenance.persist().unwrap(); + assert!(!node.contains(&tid)); + assert!(node.create_offer([4; 16], None).is_empty()); +} +#[test] +fn legacy_trees_and_second_live_host_cannot_be_opened_implicitly() { + let dir = tempfile::tempdir().unwrap(); + let old = dir.path().join("legacy"); + std::fs::create_dir(&old).unwrap(); + std::fs::write(old.join("private"), b"plaintext").unwrap(); + assert!( + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone()) + .is_err() + ); + assert_eq!(std::fs::read(old.join("private")).unwrap(), b"plaintext"); + let fresh = dir.path().join("fresh"); + let node = + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh.clone()) + .unwrap(); + assert!( + PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh).is_err() + ); + drop(node); +} + +fn encode(value: &Value) -> Vec { + let mut out = Vec::new(); + rmpv::encode::write_value(&mut out, value).unwrap(); + out +} diff --git a/crates/lxmf-tools/Cargo.toml b/crates/lxmf-tools/Cargo.toml index e8fe184..3740e43 100644 --- a/crates/lxmf-tools/Cargo.toml +++ b/crates/lxmf-tools/Cargo.toml @@ -24,6 +24,7 @@ hex = { workspace = true } base64 = { workspace = true } serde_json = { workspace = true } rmpv = { workspace = true } +zeroize = "1" [dev-dependencies] tempfile = { workspace = true } diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index ed1c31a..5548f69 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -11,10 +11,16 @@ use std::time::{Duration, Instant}; use bytes::Bytes; use clap::Parser; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, oneshot}; use std::sync::{Arc, Mutex}; +use lxmf_core::admission::{ + AdmissionEpochs, AdmissionRecord, DownloadAdmissionOutcome, DownloadAdmissionToken, + DownloadedPropagationMessage, DurableAdmissionReceipt, DurableDisposition, ProcessingLease, + SuppressionReason, +}; +use lxmf_core::admission_store::FileAdmissionStore; use lxmf_core::constants::{ DELIVERY_RETRY_WAIT, DeliveryMethod, MAX_DELIVERY_ATTEMPTS, PATH_REQUEST_WAIT, }; @@ -27,11 +33,14 @@ use lxmf_core::link_delivery::{ BackchannelSendCommand, BackchannelSendError, BackchannelSendReceipt, DeliveryResult, is_retryable_link_delivery_failure, }; -use lxmf_core::message::LxMessage; +use lxmf_core::message::{LxMessage, LxMessageDraft, MessageError}; use lxmf_core::peer::{LxmPeer, OutboundOfferPolicy}; use lxmf_core::propagation_node::{ PropagationNode, PropagationNodeConfig, PropagationStoreWritePlan, }; +use lxmf_core::propagation_send::{ + AdvertisedNodePolicy, MissingPropagationInput, PropagationEnvelope, propagation_readiness, +}; use lxmf_core::router::{ AutopeerCandidate, DirectDeliveryPlan, DirectDeliveryPlanInput, DirectReusableLinkState, DirectRouteSnapshot, LxmRouter, OutboundAction, plan_direct_delivery, @@ -215,17 +224,100 @@ struct PnValidationWorkerResult { #[derive(Debug)] struct PnPacketValidationWorkerResult { + receipt: Option, + payload_owner: Bytes, + malformed: bool, + stored: bool, + committed: Vec<([u8; 32], u64)>, link_id: [u8; 16], + #[cfg(test)] entries: Vec, + #[cfg(test)] + timing: Option, rejected: usize, } #[derive(Debug)] struct PnPacketValidationJob { link_id: [u8; 16], - data: Vec, + data: Bytes, + receipt: Option, + node: Arc>, max_transfer_bytes: usize, min_cost: u8, + #[cfg(test)] + store_delay: Duration, + #[cfg(test)] + enqueued_at: Instant, +} + +/// The request callback only admits a bounded blocking job. Closing this owner +/// excludes new jobs under the same lock used to register actual worker handles. +#[derive(Clone, Default)] +struct PnGetWorkers { + state: Arc>, + active: Arc>, + #[cfg(test)] + pause: Arc>>, +} +#[derive(Default)] +struct PnGetWorkerState { + closed: bool, + tasks: Vec>, +} +impl PnGetWorkers { + fn spawn(&self, job: impl FnOnce() + Send + 'static) -> bool { + let Ok(mut state) = self.state.lock() else { + return false; + }; + state.tasks.retain(|task| !task.is_finished()); + if state.closed || state.tasks.len() >= 4 { + return false; + } + let Ok(active) = self.active.clone().try_read_owned() else { + return false; + }; + #[cfg(test)] + let pause = self.pause.lock().unwrap().clone(); + state.tasks.push(tokio::task::spawn_blocking(move || { + let _active = active; + #[cfg(test)] + if let Some(root) = pause { + std::fs::write(root.join("get.entered"), b"worker owns request\n").unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + while !root.join("get.release").exists() { + assert!(Instant::now() < deadline, "private get pause timed out"); + std::thread::sleep(Duration::from_millis(5)); + } + } + job(); + })); + true + } + async fn close_and_join(&self) { + self.state.lock().unwrap_or_else(|e| e.into_inner()).closed = true; + // A cancelled shutdown waiter does not lose ownership of live workers. + let _quiescent = self.active.clone().write_owned().await; + let tasks = { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::take(&mut state.tasks) + }; + for task in tasks { + if let Err(error) = task.await { + tracing::warn!(%error, "PN get worker failed during shutdown"); + } + } + } +} + +#[cfg(test)] +#[derive(Debug)] +struct PnTestTiming { + received_at: Instant, + packet_hash: String, + queue_ms: f64, + validation_ms: f64, + store_ms: f64, } #[derive(Debug)] @@ -238,7 +330,6 @@ struct PendingOpportunisticDelivery { enum PropagationStoreWriteOrigin { Peer([u8; 16]), Client, - LocalDelivery, } #[derive(Debug)] @@ -346,7 +437,6 @@ fn apply_propagation_store_commit( .client_propagation_messages_received .saturating_add(committed_count); } - PropagationStoreWriteOrigin::LocalDelivery => {} } } @@ -497,7 +587,7 @@ fn validate_pn_resource_job( let data = job.into_data(); let (_, entries) = - match LxMessage::unpack_propagation_wrapper_bounded(&data, max_transfer_bytes) { + match LxMessage::unpack_propagation_wrapper_owned(data.into(), max_transfer_bytes) { Ok(parsed) => parsed, Err(error) => { tracing::warn!( @@ -552,74 +642,219 @@ fn validate_pn_resource_job( } } +#[cfg(test)] fn validate_pn_packet_job( link_id: [u8; 16], - data: Vec, + data: Bytes, max_transfer_bytes: usize, min_cost: u8, ) -> PnPacketValidationWorkerResult { - let (_, entries) = - match LxMessage::unpack_propagation_wrapper_bounded(&data, max_transfer_bytes) { - Ok(parsed) => parsed, - Err(error) => { - tracing::warn!( - link_id = %hex::encode(link_id), - "failed to unpack propagation packet: {error}" - ); - return PnPacketValidationWorkerResult { - link_id, - entries: Vec::new(), - rejected: 1, - }; - } - }; - - let mut validated = Vec::with_capacity(entries.len()); - let mut rejected = 0usize; + let mut result = PnPacketValidationWorkerResult { + link_id, + receipt: None, + payload_owner: data.clone(), + malformed: false, + stored: false, + committed: Vec::new(), + entries: Vec::new(), + timing: None, + rejected: 0, + }; + let (_, entries) = match LxMessage::unpack_propagation_wrapper_owned(data, max_transfer_bytes) { + Ok(parsed) => parsed, + Err(_) => { + result.malformed = true; + return result; + } + }; for entry in entries { match lxmf_core::stamper::validate_pn_stamp(&entry, min_cost) { - Some((_transient_id, lxmf_data, stamp_value, stamp_data)) => { - validated.push(ValidatedPnEntry { + Some((_, lxmf_data, stamp_value, stamp_data)) => { + result.entries.push(ValidatedPnEntry { lxmf_data, stamp_value, stamp_data, - }); + }) } - None => rejected += 1, + None => result.rejected += 1, } } - - PnPacketValidationWorkerResult { - link_id, - entries: validated, - rejected, - } + result } -async fn run_pn_packet_validation_worker( - jobs: Arc>>, +/// Worker output may observe another packet's in-progress exact-image write. +/// Those observations retain packet ownership, but wait outside the four +/// validation/storage workers so duplicates cannot deadlock their original. +struct PnPacketExecution { + result: PnPacketValidationWorkerResult, + pending: Vec, +} + +fn execute_pn_packet_job(job: PnPacketValidationJob) -> PnPacketExecution { + use lxmf_core::propagation_node::{PropagationAdmission, ValidatedOpaquePropagationBlob}; + #[cfg(test)] + let validation_started = Instant::now(); + #[cfg(test)] + let timing = (!job.store_delay.is_zero()).then(|| PnTestTiming { + received_at: job.enqueued_at, + packet_hash: hex::encode(rns_crypto::sha::full_hash(&job.data)), + queue_ms: job.enqueued_at.elapsed().as_secs_f64() * 1000., + validation_ms: 0., + store_ms: 0., + }); + let mut result = PnPacketValidationWorkerResult { + link_id: job.link_id, + receipt: job.receipt, + payload_owner: job.data.clone(), + malformed: false, + stored: false, + committed: Vec::new(), + #[cfg(test)] + entries: Vec::new(), + #[cfg(test)] + timing, + rejected: 0, + }; + let mut pending = Vec::new(); + let (_, entries) = + match LxMessage::unpack_propagation_wrapper_owned(job.data, job.max_transfer_bytes) { + Ok(parsed) => parsed, + Err(_) => { + result.malformed = true; + return PnPacketExecution { result, pending }; + } + }; + // Validate the complete packet before admitting even its first entry. + let mut validated = Vec::with_capacity(entries.len()); + for entry in entries { + match ValidatedOpaquePropagationBlob::validate(entry, job.min_cost) { + Some(blob) => validated.push(blob), + None => result.rejected += 1, + } + } + if result.rejected != 0 { + return PnPacketExecution { result, pending }; + } + #[cfg(test)] + if let Some(timing) = result.timing.as_mut() { + timing.validation_ms = validation_started.elapsed().as_secs_f64() * 1000.; + } + #[cfg(test)] + let store_started = Instant::now(); + result.stored = true; + for blob in validated { + let tid = blob.transient_id(); + let admission = job + .node + .lock() + .map(|mut node| node.plan_opaque_admission(blob)); + match admission { + Ok(PropagationAdmission::Reserved(plan)) => { + let size = plan.size(); + #[cfg(test)] + std::thread::sleep(job.store_delay); + match plan.persist() { + Ok(persisted) => { + if job + .node + .lock() + .map(|mut node| node.commit_store_write(persisted)) + .unwrap_or(false) + { + result.committed.push((tid, size.saturating_sub(32) as u64)); + } else { + result.stored = false; + break; + } + } + Err(error) => { + if let Ok(mut node) = job.node.lock() { + node.abort_store_write(&tid, size); + } + tracing::warn!(%error, "PN packet store admission failed; withholding ordinary proof"); + result.stored = false; + break; + } + } + } + Ok(PropagationAdmission::CommittedDuplicate(check)) => { + #[cfg(test)] + std::thread::sleep(job.store_delay); + if let Err(error) = check.verify() { + tracing::warn!(%error, "PN duplicate failed durable revalidation"); + result.stored = false; + break; + } + } + Ok(PropagationAdmission::Pending(waiter)) => pending.push(waiter), + _ => { + result.stored = false; + break; + } + } + } + #[cfg(test)] + if let Some(timing) = result.timing.as_mut() { + timing.store_ms = store_started.elapsed().as_secs_f64() * 1000.; + } + PnPacketExecution { result, pending } +} + +/// FIFO within each Link; one ready Link per round. Admission capacity and byte +/// leases belong to RNS and survive queue, worker, observation and dispatch. +async fn run_pn_packet_validation_pool( + mut jobs: mpsc::Receiver, results: mpsc::Sender, ) { + let mut queues: HashMap<[u8; 16], VecDeque> = HashMap::new(); + let mut ready = VecDeque::new(); + let mut running = tokio::task::JoinSet::new(); + let mut observers = tokio::task::JoinSet::new(); + let mut closed = false; loop { - let job = { - let mut jobs = jobs.lock().await; - jobs.recv().await - }; - let Some(job) = job else { - return; - }; - let link_id = job.link_id; - let result = tokio::task::spawn_blocking(move || { - validate_pn_packet_job(job.link_id, job.data, job.max_transfer_bytes, job.min_cost) - }) - .await - .unwrap_or(PnPacketValidationWorkerResult { - link_id, - entries: Vec::new(), - rejected: 1, - }); - if results.send(result).await.is_err() { - return; + while running.len() < PN_PACKET_VALIDATION_WORKERS { + let Some(link) = ready.pop_front() else { + break; + }; + let queue = queues.get_mut(&link).expect("ready Link queue"); + let job = queue.pop_front().expect("nonempty ready Link queue"); + if !queue.is_empty() { + ready.push_back(link); + } else { + queues.remove(&link); + } + running.spawn_blocking(move || execute_pn_packet_job(job)); + } + if closed && running.is_empty() && observers.is_empty() && ready.is_empty() { + break; + } + tokio::select! { + job = jobs.recv(), if !closed => match job { + Some(job) => { + let link = job.link_id; + let queue = queues.entry(link).or_default(); + if queue.is_empty() { ready.push_back(link); } + queue.push_back(job); + } + None => closed = true, + }, + finished = running.join_next(), if !running.is_empty() => if let Some(Ok(execution)) = finished { + if execution.pending.is_empty() || !execution.result.stored { + if results.send(execution.result).await.is_err() { return; } + } else { + observers.spawn(async move { + let mut result = execution.result; + for waiter in execution.pending { + if waiter.wait().await != lxmf_core::propagation_node::PropagationAdmissionOutcome::Committed { + result.stored = false; + } + } + result + }); + } + }, + finished = observers.join_next(), if !observers.is_empty() => if let Some(Ok(result)) = finished + && results.send(result).await.is_err() { return; }, } } } @@ -810,7 +1045,7 @@ fn requeue_after_path_request( message.next_delivery_attempt = now + PATH_REQUEST_WAIT as f64; queue_path_request(transport_tx, request_hash, false, reason); tracing::warn!( - dest = %hex::encode(message.destination_hash), + dest = %hex::encode(message.destination_hash()), request_dest = %hex::encode(request_hash), attempts = message.delivery_attempts, reason, @@ -1187,6 +1422,159 @@ fn queue_required_transport( .map_err(|error| std::io::Error::other(format!("{operation} could not be queued: {error}"))) } +#[derive(Debug)] +enum PropagationPreparationError { + Missing(MissingPropagationInput), + Pending, + Invalid(String), +} +struct PendingPropagationEnvelope { + binding: [u8; 32], + cost: u8, + result: oneshot::Receiver>, + cancel: Arc, +} +impl Drop for PendingPropagationEnvelope { + fn drop(&mut self) { + self.cancel + .store(true, std::sync::atomic::Ordering::Release); + } +} +fn propagation_preparation_slots() -> Arc { + static SLOTS: std::sync::OnceLock> = std::sync::OnceLock::new(); + SLOTS + .get_or_init(|| Arc::new(tokio::sync::Semaphore::new(2))) + .clone() +} + +/// Pure decode stage used by the bounded download worker. Decryption failure is +/// final for this attempt; plaintext input never enters the admission path. +fn decode_download_payload( + data: &[u8], + identity: &Identity, + destination: [u8; 16], + ratchets: &[[u8; 32]], + limits: lxmf_core::message::MessageDecodeLimits, +) -> Result { + if data.len() < 17 || data[..16] != destination { + return Err(SuppressionReason::WrongDestination); + } + let refs = ratchets.iter().collect::>(); + let plaintext = identity + .decrypt( + &data[16..], + (!refs.is_empty()).then_some(refs.as_slice()), + false, + ) + .map_err(|_| SuppressionReason::DecryptionFailed)?; + let mut full = Vec::with_capacity(16 + plaintext.len()); + full.extend_from_slice(&destination); + full.extend_from_slice(&plaintext); + drop(plaintext); + let mut message = LxMessage::unpack_owned(Bytes::from(full), limits) + .map_err(|_| SuppressionReason::Malformed)?; + message.method = DeliveryMethod::Propagated; + Ok(message) +} + +/// Apply recipient policy before any durable receipt or hook can be created. +fn validate_download_policy( + msg: &LxMessage, + public_key: Option<[u8; 64]>, + tickets: &[[u8; 16]], + cost: u8, +) -> Result<(), SuppressionReason> { + if public_key.is_some_and(|key| msg.verify(&key).is_err()) { + return Err(SuppressionReason::InvalidSignature); + } + if cost > 0 { + let Some(stamp) = msg.recipient_stamp().map(|s| s.as_bytes()) else { + return Err(SuppressionReason::InvalidStamp); + }; + let ticket_valid = tickets.iter().any(|ticket| { + let mut material = [0u8; 48]; + material[..16].copy_from_slice(ticket); + material[16..].copy_from_slice(&msg.message_id()); + stamp == rns_crypto::sha::truncated_hash(&material) + }); + let pow_valid = <&[u8; 32]>::try_from(stamp).is_ok_and(|stamp| { + lxmf_core::stamper::validate_stamp( + &msg.message_id(), + stamp, + cost, + lxmf_core::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS, + ) + }); + if !ticket_valid && !pow_valid { + return Err(SuppressionReason::InvalidStamp); + } + } + Ok(()) +} + +struct DownloadDecoded { + message: Result, + token: DownloadAdmissionToken, + processing: ProcessingLease, + ciphertext: Bytes, +} +struct SuppressionPersistResult { + revision: u64, + result: std::io::Result<()>, +} +struct SuppressionPersistTask { + result: oneshot::Receiver, + task: tokio::task::JoinHandle<()>, +} +enum DownloadWorkerError { + Rejected(SuppressionReason), + Storage(lxmf_core::admission::AdmissionError), +} +struct DownloadCommitResult { + message: LxMessage, + reservation: lxmf_core::router::InboundReservation, + receipt: Result, + token: DownloadAdmissionToken, + _processing: ProcessingLease, + _ciphertext: Bytes, +} + +struct DaemonCheckpoint { + ratchets: PathBuf, + received: HashMap, + keys: HashMap, + state_dir: PathBuf, + router: lxmf_core::router::RouterStateSnapshot, + policies: HashMap<[u8; 16], AdvertisedNodePolicy>, +} +impl DaemonCheckpoint { + fn persist(self) -> std::io::Result<()> { + let received = self.ratchets.join("received"); + for (hash, ratchet) in self.received { + if !hex::decode(&hash).is_ok_and(|bytes| bytes.len() == 16) { + return Err(std::io::Error::other("invalid ratchet destination")); + } + ratchet.save_durable(&received.join(format!("{hash}.ratchet")))?; + } + let mut keys = Vec::with_capacity(self.keys.len() * 80); + for (hash, key) in self.keys { + let hash = hex::decode(hash).map_err(std::io::Error::other)?; + if hash.len() != 16 { + return Err(std::io::Error::other("invalid identity destination")); + } + keys.extend_from_slice(&hash); + keys.extend_from_slice(&key); + } + lxmf_core::persist::write_file_atomic(&self.ratchets.join("known_identities"), &keys)?; + self.router.save_state(&self.state_dir)?; + lxmf_core::persist::save_node_policies(&self.state_dir, &self.policies) + } +} +struct DaemonCheckpointTask { + result: oneshot::Receiver>, + task: tokio::task::JoinHandle<()>, +} + /// Owns identity, router, and crypto state; drives the daemon main loop. // Several fields are long-lived state handles that are intentionally retained // even when the runner only touches them through setup or shutdown paths. @@ -1201,6 +1589,25 @@ struct LxmdRunner { config: DaemonConfig, data_dir: PathBuf, messages_dir: PathBuf, + admission_store: Option, + download_decode_tx: mpsc::UnboundedSender, + download_decode_rx: mpsc::UnboundedReceiver, + download_commit_tx: mpsc::UnboundedSender, + download_commit_rx: mpsc::UnboundedReceiver, + download_tasks: Vec>, + pending_downloads: VecDeque<(Bytes, lxmf_core::admission::DownloadAdmissionToken)>, + hook_task: Option>, + hook_result_tx: mpsc::UnboundedSender, + hook_result_rx: mpsc::UnboundedReceiver, + maintenance_task: Option>, + next_admission_maintenance: Instant, + next_hook_attempt: Instant, + suppression_task: Option, + next_suppression_retry: Instant, + node_policies: HashMap<[u8; 16], AdvertisedNodePolicy>, + propagation_envelopes: HashMap<[u8; 32], PropagationEnvelope>, + pending_propagation_envelopes: HashMap<[u8; 32], PendingPropagationEnvelope>, + propagation_preparation_tasks: Vec>, ratchets_dir: PathBuf, delivery_ratchets: DeliveryRatchetState, received_ratchets: HashMap, @@ -1244,7 +1651,7 @@ struct LxmdRunner { /// consumed from `delivery_accounting_rx` instead. delivery_resource_event_rx: mpsc::Receiver, /// Plaintext propagation-wrapper packets decoded by the propagation LinkManager. - prop_link_packet_rx: mpsc::UnboundedReceiver<(Vec, [u8; 16])>, + prop_link_packet_rx: mpsc::Receiver, /// Ordered, lossless lifecycle and completion stream from the propagation LinkManager. prop_accounting_rx: mpsc::UnboundedReceiver, @@ -1256,6 +1663,11 @@ struct LxmdRunner { prop_packet_validation_rx: mpsc::Receiver, /// Bounded admission queue for the fixed packet-validation worker pool. prop_packet_validation_job_tx: mpsc::Sender, + prop_packet_validation_pool: Option>, + prop_get_workers: PnGetWorkers, + #[cfg(test)] + pn_packet_store_delay: Duration, + prop_maintenance_task: Option, /// Durable propagation-store commits. Accounting and handled IDs advance /// only after these events, never merely after validation/reservation. prop_store_commit_rx: mpsc::UnboundedReceiver, @@ -1275,6 +1687,7 @@ struct LxmdRunner { last_node_announce: f64, last_propagation_check: f64, last_crypto_save: f64, + checkpoint_task: Option, last_cull: f64, last_ratchet_clean: f64, last_route_refresh: f64, @@ -1442,7 +1855,7 @@ impl LxmdRunner { mpsc::channel::(64); router.set_inbound_resource_cancel_sender(inbound_resource_cancel_tx); let (prop_link_packet_tx, prop_link_packet_rx) = - mpsc::unbounded_channel::<(Vec, [u8; 16])>(); + mpsc::channel::(256); let (prop_accounting_tx, prop_accounting_rx) = mpsc::unbounded_channel::(); let (prop_validation_tx, prop_validation_rx) = @@ -1453,14 +1866,10 @@ impl LxmdRunner { mpsc::channel::(PN_PACKET_VALIDATION_QUEUE_DEPTH); let (prop_store_commit_tx, prop_store_commit_rx) = mpsc::unbounded_channel::(); - let prop_packet_validation_job_rx = - Arc::new(tokio::sync::Mutex::new(prop_packet_validation_job_rx)); - for _ in 0..PN_PACKET_VALIDATION_WORKERS { - tokio::spawn(run_pn_packet_validation_worker( - Arc::clone(&prop_packet_validation_job_rx), - prop_packet_validation_result_tx.clone(), - )); - } + let prop_packet_validation_pool = Some(tokio::spawn(run_pn_packet_validation_pool( + prop_packet_validation_job_rx, + prop_packet_validation_result_tx, + ))); let (client_propagation_served_tx, client_propagation_served_rx) = mpsc::unbounded_channel::(); let (peering_key_result_tx, peering_key_result_rx) = @@ -1487,7 +1896,7 @@ impl LxmdRunner { if let Some(handle) = &endpoint_dispatch { link_mgr.set_link_endpoint_dispatch_handle(handle.clone()); } - link_mgr.set_link_packet_channel(link_packet_tx); + link_mgr.set_link_packet_channel(link_packet_tx)?; link_mgr.set_accounting_event_channel(delivery_accounting_tx); link_mgr.set_resource_event_channel(delivery_resource_event_tx); link_mgr.set_inbound_raw_channel(inbound_raw_tx); @@ -1539,6 +1948,7 @@ impl LxmdRunner { let required_announces = AnnounceMailbox::default(); let mut propagation_admission = None; + let prop_get_workers = PnGetWorkers::default(); let mut prop_link_command_tx = None; let propagation_node: Option>> = if config.propagation_enabled { let (prop_delivery_tx, prop_delivery_rx) = mpsc::channel(256); @@ -1570,33 +1980,11 @@ impl LxmdRunner { ..Default::default() }; let prop_storage_path = paths.propagation_store_dir.clone(); - let pn = match PropagationNode::with_storage( + let pn = Arc::new(Mutex::new(PropagationNode::with_storage( pn_config, propagation_dest_hash, prop_storage_path, - ) { - Ok(node) => Arc::new(Mutex::new(node)), - Err(e) => { - tracing::warn!("Propagation disk storage failed, using in-memory: {e}"); - Arc::new(Mutex::new(PropagationNode::new( - PropagationNodeConfig { - max_storage: config.message_storage_limit.unwrap_or( - configured_kilobytes_to_bytes(config.propagation_limit_kb), - ), - max_message_size: configured_kilobytes_to_bytes( - config.propagation_limit_kb, - ), - max_offer_size: configured_kilobytes_to_bytes(config.sync_limit_kb), - max_message_age: lxmf_core::constants::MESSAGE_EXPIRY, - min_stamp_cost: config - .propagation_stamp_cost - .saturating_sub(config.propagation_stamp_flex), - ..Default::default() - }, - propagation_dest_hash, - ))) - } - }; + )?)); if let Ok(node) = pn.lock() { for mut peer in node.load_peers() { peer.is_static = static_peer_hashes.contains(&peer.destination_hash); @@ -1628,7 +2016,10 @@ impl LxmdRunner { if let Some(handle) = &endpoint_dispatch { prop_link_mgr.set_link_endpoint_dispatch_handle(handle.clone()); } - prop_link_mgr.set_link_packet_channel(prop_link_packet_tx); + prop_link_mgr.set_inbound_link_packet_channel(prop_link_packet_tx)?; + prop_link_mgr.set_ordinary_packet_proof_strategy( + rns_identity::destination::ProofStrategy::ProveApp, + )?; prop_link_mgr.set_accounting_event_channel(prop_accounting_tx); prop_link_mgr.set_resource_strategy(rns_runtime::prelude::ResourceStrategy::AcceptApp); @@ -1636,8 +2027,6 @@ impl LxmdRunner { let offer_path_hash = rns_crypto::sha::truncated_hash( lxmf_core::constants::OFFER_REQUEST_PATH.as_bytes(), ); - let get_path_hash = - rns_crypto::sha::truncated_hash(lxmf_core::constants::MESSAGE_GET_PATH.as_bytes()); let link_identities = prop_link_mgr.link_identities_handle(); let accept_link_identities = link_identities.clone(); let admission_for_resources = pn_admission.clone(); @@ -1667,14 +2056,102 @@ impl LxmdRunner { let local_identity_hash = identity.hash; let admission_for_handler = pn_admission.clone(); - let client_served_tx_for_handler = client_propagation_served_tx.clone(); - let access_state_for_handler = control_state.clone(); + let get_node = pn_for_handler.clone(); + let get_admission = pn_admission.clone(); + let get_access = control_state.clone(); + let get_workers = prop_get_workers.clone(); + let get_served = client_propagation_served_tx.clone(); + let response_limit = configured_kilobytes_to_bytes(config.propagation_limit_kb) + .clamp(1, 64 * 1024 * 1024); + if !prop_link_mgr.register_deferred_request_handler( + lxmf_core::constants::MESSAGE_GET_PATH, + rns_identity::destination::AllowPolicy::AllowAll, + None, + false, + response_limit, + move |request, responder| { + let node = get_node.clone(); + let admission = get_admission.clone(); + let access = get_access.clone(); + let served_tx = get_served.clone(); + // The responder's byte/job reservation precedes request + // parsing and any durable haves retirement. + let accepted = get_workers.spawn(move || { + use rns_runtime::link_manager::{DeferredResponseOutcome, RequestOutcome}; + if responder.is_cancelled() { + return; + } + let limit = responder.response_byte_limit(); + let remote = request + .remote_identity + .as_ref() + .map(|identity| identity.hash); + let reply = if admission + .lock() + .map(|state| state.is_link_quarantined(&request.link_id)) + .unwrap_or(true) + { + (None, 0) + } else { + let allowed = access + .lock() + .map(|state| propagation_client_allowed(&state, remote.as_ref())) + .unwrap_or(false); + if !allowed { + ( + Some(encode_peer_error( + lxmf_core::constants::PeerError::NoAccess, + )), + 0, + ) + } else if let Some(remote) = remote { + let client = Destination::hash_from_name_and_identity( + DELIVERY_APP_NAME, + Some(&remote), + ); + let action = node.lock().ok().map(|mut node| { + node.handle_get_request_bounded(&request.data, &client, limit) + }); + if responder.is_cancelled() { + return; + } + action.map_or((None, 0), |action| { + let (bytes, count) = + action.into_response_with_served_count_bounded(limit); + (Some(bytes), count) + }) + } else { + ( + Some(encode_peer_error( + lxmf_core::constants::PeerError::NoIdentity, + )), + 0, + ) + } + }; + let (bytes, served) = reply; + let outcome = bytes.map_or(RequestOutcome::Drop, RequestOutcome::Reply); + // Retain the actual worker and request capability until + // exact-owner dispatch accepts or refuses the response. + if let Ok(dispatch) = responder.respond(outcome) + && matches!(dispatch.blocking_recv(), Ok(DeferredResponseOutcome::Sent)) + && served > 0 + { + let _ = served_tx.send(served); + } + }); + if !accepted { + tracing::debug!("PN get not admitted by bounded worker owner"); + } + }, + ) { + return Err("failed to register bounded propagation get handler".into()); + } prop_link_mgr.set_request_handler(move |link_id, path_hash, data| { let remote_identity_hash = link_identities .lock() .ok() .and_then(|ids| ids.get(&link_id).copied()); - let remote_identity_ref = remote_identity_hash.as_ref(); if path_hash == offer_path_hash { tracing::info!("propagation: handling offer request"); handle_pn_offer_request( @@ -1685,48 +2162,6 @@ impl LxmdRunner { remote_identity_hash, &data, ) - } else if path_hash == get_path_hash { - if admission_for_handler - .lock() - .map(|admission| admission.is_link_quarantined(&link_id)) - .unwrap_or(true) - { - return None; - } - let access_snapshot = access_state_for_handler - .lock() - .map(|state| state.clone()) - .unwrap_or_default(); - if !propagation_client_allowed(&access_snapshot, remote_identity_hash.as_ref()) - { - return Some(encode_peer_error(lxmf_core::constants::PeerError::NoAccess)); - } - tracing::info!("propagation: handling get request"); - let client_dest_hash = remote_identity_hash - .map(|identity_hash| { - Destination::hash_from_name_and_identity( - DELIVERY_APP_NAME, - Some(&identity_hash), - ) - }) - .unwrap_or([0; 16]); - let handler = - lxmf_core::handlers::PropagationRequestHandler::new(local_identity_hash); - let action = { - let mut node = pn_for_handler.lock().ok()?; - handler.handle_message_get_request( - remote_identity_ref, - &client_dest_hash, - &data, - &mut node, - ) - }; - // Phase-2 file reads happen here, after the node lock drops. - let (response, served) = action.into_response_with_served_count(); - if served > 0 { - let _ = client_served_tx_for_handler.send(served); - } - Some(response) } else { tracing::debug!( path = hex::encode(path_hash), @@ -1887,6 +2322,17 @@ impl LxmdRunner { let messages_dir = paths.messages_dir.clone(); std::fs::create_dir_all(&messages_dir)?; + let admission_store = match FileAdmissionStore::open(&paths.router_state_dir, &messages_dir) + { + Ok(store) => Some(store), + Err(error) => { + tracing::error!(%error,"durable download storage unavailable; propagation downloads disabled"); + None + } + }; + let (hook_result_tx, hook_result_rx) = mpsc::unbounded_channel(); + let (download_decode_tx, download_decode_rx) = mpsc::unbounded_channel(); + let (download_commit_tx, download_commit_rx) = mpsc::unbounded_channel(); let now = now_f64(); let mut runner = Self { @@ -1897,8 +2343,28 @@ impl LxmdRunner { control_dest_hash, router, config, - data_dir: paths.router_state_dir, + data_dir: paths.router_state_dir.clone(), messages_dir, + admission_store, + download_decode_tx, + download_decode_rx, + download_commit_tx, + download_commit_rx, + download_tasks: Vec::new(), + pending_downloads: VecDeque::new(), + hook_task: None, + hook_result_tx, + hook_result_rx, + maintenance_task: None, + next_admission_maintenance: Instant::now(), + next_hook_attempt: Instant::now(), + suppression_task: None, + next_suppression_retry: Instant::now(), + node_policies: lxmf_core::persist::load_node_policies(&paths.router_state_dir) + .unwrap_or_default(), + propagation_envelopes: HashMap::new(), + pending_propagation_envelopes: HashMap::new(), + propagation_preparation_tasks: Vec::new(), ratchets_dir: paths.ratchets_dir, delivery_ratchets, received_ratchets, @@ -1938,6 +2404,11 @@ impl LxmdRunner { prop_validation_tx, prop_packet_validation_rx, prop_packet_validation_job_tx, + prop_packet_validation_pool, + prop_get_workers, + #[cfg(test)] + pn_packet_store_delay: Duration::ZERO, + prop_maintenance_task: None, prop_store_commit_rx, prop_store_commit_tx, prop_store_write_tasks: Vec::new(), @@ -1953,6 +2424,7 @@ impl LxmdRunner { last_node_announce: 0.0, last_propagation_check: 0.0, last_crypto_save: now, + checkpoint_task: None, last_cull: now, last_ratchet_clean: now, last_route_refresh: 0.0, @@ -2017,6 +2489,13 @@ impl LxmdRunner { } } } + match lxmf_core::persist::load_suppression(&runner.data_dir) { + Ok(ledger) => client.set_suppression_ledger(ledger, runner.download_epochs()), + Err(error) => { + tracing::error!(%error,"suppression state unavailable; automatic downloads paused"); + client.suppression_persistence_failed(); + } + } runner.propagation_client = Some(client); tracing::info!("propagation client initialized"); @@ -2561,6 +3040,8 @@ impl LxmdRunner { match result { DeliveryResult::Complete { msg_hash, .. } => { if let Some(hash) = msg_hash { + self.propagation_envelopes.remove(&hash); + self.pending_propagation_envelopes.remove(&hash); let _ = self.router.mark_outbound_delivered(&hash); tracing::info!(hash = %hex::encode(hash), "link delivery complete"); } @@ -2577,6 +3058,8 @@ impl LxmdRunner { "link delivery rejected" ); if let Some(hash) = msg_hash { + self.propagation_envelopes.remove(&hash); + self.pending_propagation_envelopes.remove(&hash); let _ = self.router.mark_outbound_rejected(&hash); } self.last_delivery_failure = Some(reason); @@ -2598,7 +3081,7 @@ impl LxmdRunner { self.router .pending_outbound .iter() - .any(|pending| pending.hash == Some(hash)) + .any(|pending| pending.message_id() == hash) }); if link_failure_retryable(&reason) && message.delivery_attempts <= MAX_DELIVERY_ATTEMPTS @@ -2628,6 +3111,8 @@ impl LxmdRunner { } } else { if let Some(hash) = msg_hash { + self.propagation_envelopes.remove(&hash); + self.pending_propagation_envelopes.remove(&hash); if router_owned { let _ = self.router.mark_outbound_failed(&hash); } @@ -2716,6 +3201,7 @@ impl LxmdRunner { /// Advance callback-driven propagation peer synchronization independently /// from the four-second router maintenance job loop. fn drive_propagation_sync(&mut self) { + self.poll_download_commits(); let mut peer_handled_updates = None; let mut peer_terminal_result = None; if let Some(ref mut sync) = self.propagation_sync { @@ -2927,7 +3413,7 @@ impl LxmdRunner { .pending_outbound .iter() .filter(|message| message.method == DeliveryMethod::Direct) - .map(|message| message.destination_hash) + .map(|message| message.destination_hash()) .collect::>() .into_iter() .map(|dest| { @@ -2946,7 +3432,7 @@ impl LxmdRunner { .collect::>(); let actions = self.router.process_outbound_with_direct(|message, _now| { direct_inputs - .get(&message.destination_hash) + .get(&message.destination_hash()) .cloned() .unwrap_or(DirectDeliveryPlanInput { identity_known: false, @@ -2983,27 +3469,29 @@ impl LxmdRunner { .outbound_propagation_node .map(|node| self.known_identities.contains_key(&hex::encode(node))) .unwrap_or(false); + self.poll_download_commits(); + self.drive_hook_outbox(); let locally_delivered_ids = self - .router - .propagation_store - .locally_delivered_ids() - .keys() - .map(|id| id.to_vec()) - .collect::>(); + .admission_store + .as_ref() + .zip(self.router.outbound_propagation_node) + .map(|(store, node)| store.durable_haves(self.identity.hash, node, now as u64)) + .unwrap_or_default(); let retain_synced_on_node = self.router.retain_node_lxms(); if let Some(ref mut client) = self.propagation_client { - client.replace_local_message_ids(locally_delivered_ids); + client.replace_durable_haves(locally_delivered_ids); client.set_retain_synced_on_node(retain_synced_on_node); client.drain_events(&self.known_identities); client.tick(); - downloaded_messages = client.take_received_messages(); + downloaded_messages = client.take_downloaded_messages(); + let _ = client.take_suppression_updates(); // Auto-download every 90s if now - self.last_propagation_check > 90.0 && client.state() == lxmf_core::propagation_client::PropagationClientState::Idle { - if propagation_node_ready { + if propagation_node_ready && self.admission_store.is_some() { client.start_download(); self.last_propagation_check = now; tracing::debug!("auto-triggered propagation download"); @@ -3025,6 +3513,7 @@ impl LxmdRunner { acknowledge_propagation = matches!( status.state, lxmf_core::propagation_client::PropagationClientState::Complete + | lxmf_core::propagation_client::PropagationClientState::Partial | lxmf_core::propagation_client::PropagationClientState::Failed ); propagation_status = Some(status); @@ -3032,9 +3521,10 @@ impl LxmdRunner { if let Some(status) = propagation_status { self.router.update_propagation_transfer_status(status); } + self.drive_suppression_persistence(); // Borrow is released; process downloaded messages. for msg_data in downloaded_messages { - self.handle_propagation_downloaded_data(&msg_data); + self.handle_propagation_downloaded_message(msg_data); } if acknowledge_propagation && let Some(client) = self.propagation_client.as_mut() { client.acknowledge_transfer(); @@ -3089,25 +3579,70 @@ impl LxmdRunner { } } - if now - self.last_cull > 300.0 { + if let Some(task) = self.prop_maintenance_task.as_mut() { + match task.result.try_recv() { + Ok(Ok(())) => self.prop_maintenance_task = None, + Ok(Err(error)) => { + tracing::warn!(%error, "relay maintenance remains pending"); + self.prop_maintenance_task = None; + self.last_cull = now - 240.0; + } + Err(oneshot::error::TryRecvError::Closed) => { + self.prop_maintenance_task = None; + self.last_cull = now - 240.0; + } + Err(oneshot::error::TryRecvError::Empty) => {} + } + } + if self.prop_maintenance_task.is_none() && now - self.last_cull > 300.0 { self.router.cull_stamp_costs(); - // Store cull + peer rotation now run via `run_jobs_tick` at Python - // jobloop cadences. The propagation node's own store (separate - // from the router's) ages out expired messages and enforces the - // weight cap here — previously this never ran. + // Reserve only metadata under the lock. Native durable deletion + // barriers run on one joined worker, away from receipt dispatch. if let Some(ref pn) = self.propagation_node && let Ok(mut node) = pn.lock() { - node.tick(); + let plan = node.plan_maintenance(); + if !plan.is_empty() { + let (tx, result) = oneshot::channel(); + let task = tokio::task::spawn_blocking(move || { + let _ = tx.send(plan.persist()); + }); + self.prop_maintenance_task = Some(DaemonCheckpointTask { result, task }); + } } self.last_cull = now; } - if now - self.last_crypto_save > 300.0 { - self.save_crypto_state(); - if let Err(e) = self.router.save_state(&self.data_dir) { - tracing::warn!("Failed to save router state: {e}"); + if let Some(task) = self.checkpoint_task.as_mut() { + match task.result.try_recv() { + Ok(result) => { + self.checkpoint_task = None; + if let Err(error) = result { + tracing::warn!(%error,"daemon checkpoint did not commit"); + self.last_crypto_save = now - 240.0; + } + } + Err(oneshot::error::TryRecvError::Closed) => { + self.checkpoint_task = None; + self.last_crypto_save = now - 240.0; + } + Err(oneshot::error::TryRecvError::Empty) => {} } + } + if self.checkpoint_task.is_none() && now - self.last_crypto_save > 300.0 { + let checkpoint = DaemonCheckpoint { + ratchets: self.ratchets_dir.clone(), + received: self.received_ratchets.clone(), + keys: self.known_identities.clone(), + state_dir: self.data_dir.clone(), + router: self.router.state_snapshot(), + policies: self.node_policies.clone(), + }; + let (tx, result) = oneshot::channel(); + let task = tokio::task::spawn_blocking(move || { + let _ = tx.send(checkpoint.persist()); + }); + self.checkpoint_task = Some(DaemonCheckpointTask { result, task }); self.last_crypto_save = now; } @@ -3189,6 +3724,14 @@ impl LxmdRunner { { self.router .set_stamp_cost(event.destination_hash, pn.stamp_cost); + self.node_policies.insert( + event.destination_hash, + AdvertisedNodePolicy { + stamp_cost: pn.stamp_cost, + transfer_limit_kb: pn.transfer_limit as f64, + recorded_at: now_f64(), + }, + ); let is_static = self.router.static_peers.contains(&event.destination_hash); let previous_offer_constraints = self .router @@ -3360,13 +3903,8 @@ impl LxmdRunner { self.handle_link_delivered_data(&plaintext); } - while let Ok((data, link_id)) = self.prop_link_packet_rx.try_recv() { - tracing::info!( - link_id = %hex::encode(link_id), - len = data.len(), - "received propagation packet via link" - ); - self.handle_propagation_transfer_data(link_id, &data); + while let Ok(packet) = self.prop_link_packet_rx.try_recv() { + self.handle_propagation_packet(packet); } while let Ok(event) = self.prop_accounting_rx.try_recv() { @@ -3542,16 +4080,16 @@ impl LxmdRunner { match LxMessage::unpack(&unpack_data) { Ok(mut msg) => { tracing::info!( - from = %hex::encode(msg.source_hash), - title = %msg.title, - len = msg.content.len(), + from = %hex::encode(msg.source_hash()), + title = %msg.title_text(), + len = msg.content_bytes().len(), "inbound LXMF message via link" ); - msg.source_blackholed = self.source_blackholed(&msg.source_hash); + msg.source_blackholed = self.source_blackholed(&msg.source_hash()); if msg.source_blackholed { // LXMRouter.py:1739-1741. tracing::debug!( - from = %hex::encode(msg.source_hash), + from = %hex::encode(msg.source_hash()), "Dropping LXM from blackholed identity" ); return; @@ -3697,169 +4235,440 @@ impl LxmdRunner { } } - fn handle_propagation_transfer_data(&mut self, link_id: [u8; 16], data: &[u8]) { - if self - .propagation_admission - .as_ref() - .is_some_and(|admission| { - admission - .lock() - .map(|admission| admission.is_link_quarantined(&link_id)) - .unwrap_or(true) - }) - { + fn handle_propagation_packet(&mut self, packet: rns_runtime::link_manager::InboundLinkPacket) { + let link_id = packet.link_id(); + let Some(node) = self.propagation_node.clone() else { return; - } - - if self.propagation_node.is_none() { - tracing::debug!("received propagation data but node storage is disabled"); - return; - } - - let max_transfer_bytes = configured_kilobytes_to_bytes(self.config.propagation_limit_kb); - let min_cost = self - .config - .propagation_stamp_cost - .saturating_sub(self.config.propagation_stamp_flex); + }; + let (data, receipt) = packet.into_parts(); let job = PnPacketValidationJob { link_id, - data: data.to_vec(), - max_transfer_bytes, - min_cost, + data, + receipt, + node, + max_transfer_bytes: configured_kilobytes_to_bytes(self.config.propagation_limit_kb), + min_cost: self + .config + .propagation_stamp_cost + .saturating_sub(self.config.propagation_stamp_flex), + #[cfg(test)] + store_delay: self.pn_packet_store_delay, + #[cfg(test)] + enqueued_at: Instant::now(), }; - match enqueue_pn_packet_validation(&self.prop_packet_validation_job_tx, job) { - Ok(()) => {} - Err(PnPacketValidationEnqueueError::Overloaded) => { - tracing::warn!( - link_id = %hex::encode(link_id), - queue_depth = PN_PACKET_VALIDATION_QUEUE_DEPTH, - "closing propagation Link because packet validation is overloaded" - ); - if let Some(command_tx) = self.prop_link_command_tx.clone() { - tokio::spawn(async move { - let _ = command_tx - .send(rns_runtime::link_manager::LinkManagerCommand::CloseLink { - link_id, - reason: rns_runtime::prelude::CloseReason::DestinationClosed, - send_teardown: true, - }) - .await; - }); - } - } - Err(PnPacketValidationEnqueueError::Closed) => { - tracing::debug!("propagation packet validation worker pool closed"); - } + if let Err(reason) = enqueue_pn_packet_validation(&self.prop_packet_validation_job_tx, job) + { + // Drop only this unadmitted packet. Closing would revoke accepted + // receipts on the same Link and turn bounded overload into loss. + tracing::debug!(?reason, "PN packet not admitted by bounded worker queue"); } } fn handle_propagation_packet_validation_result( &mut self, - result: PnPacketValidationWorkerResult, + mut result: PnPacketValidationWorkerResult, ) { - let mut write_plans = Vec::new(); - if let Some(ref node) = self.propagation_node - && let Ok(mut node) = node.lock() - { - for entry in &result.entries { - if let Some(plan) = node.plan_accept_stamped_propagated_blob( - &entry.lxmf_data, - &entry.stamp_data, - u8::try_from(entry.stamp_value).unwrap_or(u8::MAX), - ) { - write_plans.push((plan, entry.lxmf_data.len() as u64)); - } - } - } - let reserved = write_plans.len(); - if let Some(node) = self.propagation_node.clone() - && let Some(task) = spawn_propagation_store_writes( - node, - write_plans, - PropagationStoreWriteOrigin::Client, - self.prop_store_commit_tx.clone(), - "client packet ingress", - ) - { - self.prop_store_write_tasks.push(task); - } - - tracing::info!( - link_id = %hex::encode(result.link_id), - reserved, - rejected = result.rejected, - "processed inbound propagation packet" + tracing::debug!(link_id=%hex::encode(result.link_id),stored=result.stored,rejected=result.rejected,malformed=result.malformed,"propagation packet admission completed"); + apply_propagation_store_commit( + &mut self.router, + self.propagation_node.as_ref(), + PropagationStoreCommitResult { + origin: PropagationStoreWriteOrigin::Client, + committed: std::mem::take(&mut result.committed), + }, ); - - if result.rejected > 0 - && let Some(command_tx) = self.prop_link_command_tx.clone() - { + let Some(receipt) = result.receipt.take() else { + return; + }; + if result.malformed { + receipt.drop_without_proof(); + } else if result.rejected > 0 { + let dispatch = receipt.reject_and_close( + rns_runtime::link_manager::LinkPacketRejection::InvalidPropagationStamp, + ); tokio::spawn(async move { - let _ = command_tx - .send(rns_runtime::link_manager::LinkManagerCommand::CloseLink { - link_id: result.link_id, - reason: rns_runtime::prelude::CloseReason::DestinationClosed, - send_teardown: true, - }) - .await; + let _owner = result.payload_owner; + let _ = dispatch.await; + }); + } else if result.stored { + #[cfg(test)] + let dispatched_at = Instant::now(); + let dispatch = receipt.accept(); + tokio::spawn(async move { + let _owner = result.payload_owner; + let _outcome = dispatch.await; + #[cfg(test)] + if let Some(timing) = result.timing { + eprintln!( + "PN_RECEIPT_TIMING {}", + serde_json::json!({ + "packet_hash": timing.packet_hash, + "queue_ms": timing.queue_ms, + "validation_ms": timing.validation_ms, + "store_ms": timing.store_ms, + "dispatch_ms": dispatched_at.elapsed().as_secs_f64() * 1000., + "receive_to_dispatch_ms": timing.received_at.elapsed().as_secs_f64() * 1000., + "outcome": format!("{_outcome:?}"), + }) + ); + } + }); + } else { + // A valid packet that could not be durably admitted has no proof or + // invalid-stamp authority. Close so the sender can retry promptly. + let dispatch = receipt.close_without_proof(); + tokio::spawn(async move { + let _owner = result.payload_owner; + let _ = dispatch.await; }); } } - fn handle_propagation_downloaded_data(&mut self, data: &[u8]) { - if data.len() < 16 { + fn handle_propagation_downloaded_message(&mut self, item: DownloadedPropagationMessage) { + let (data, token) = item.into_parts(); + if self.pending_downloads.len() >= lxmf_core::admission::MAX_DOWNLOAD_ITEMS { + let _ = token.resolve(DownloadAdmissionOutcome::Rejected(SuppressionReason::Quota)); return; } - - // The propagation transient ID is over the representation received - // from the node, before destination decryption. Retain it alongside - // the signed message hash so redelivery through a different LXMF path - // is still suppressed by the router-owned gate. - let propagation_transient_id = LxMessage::compute_propagation_transient_id(data); - - let unpack_data = if data[..16] == self.lxmf_dest_hash { - match self.decrypt_inbound(&data[16..]) { - Some(plaintext) => { - let mut full = self.lxmf_dest_hash.to_vec(); - full.extend_from_slice(&plaintext); - full - } - None => data.to_vec(), + // The core raw-response lease follows these slices. Queued items hold + // no partial processing reservation and never consume a worker slot. + self.pending_downloads.push_back((data, token)); + self.drive_download_queue(); + } + fn drive_download_queue(&mut self) { + while let Some((data, token)) = self.pending_downloads.front() { + if !token.is_current() { + self.pending_downloads.pop_front(); + continue; } - } else { - data.to_vec() + if self.admission_store.is_none() { + let (_, token) = self.pending_downloads.pop_front().unwrap(); + let _ = token.resolve(DownloadAdmissionOutcome::Rejected( + SuppressionReason::StorageUnavailable, + )); + continue; + } + let processing = match ProcessingLease::try_acquire(data.len()) { + Ok(lease) => lease, + Err(SuppressionReason::WorkerUnavailable) => break, + Err(reason) => { + let (_, token) = self.pending_downloads.pop_front().unwrap(); + let _ = token.resolve(DownloadAdmissionOutcome::Rejected(reason)); + continue; + } + }; + let (data, token) = self.pending_downloads.pop_front().unwrap(); + self.start_download_decode(data, token, processing); + } + } + fn start_download_decode( + &mut self, + data: Bytes, + token: lxmf_core::admission::DownloadAdmissionToken, + processing: ProcessingLease, + ) { + let identity = self.identity.clone(); + let destination = self.lxmf_dest_hash; + let ratchets = + zeroize::Zeroizing::new(self.delivery_ratchets.ring().private_keys().to_vec()); + let limits = lxmf_core::message::MessageDecodeLimits { + max_wire_bytes: (self.config.delivery_transfer_max_accepted_size * 1000.) as usize, + ..Default::default() }; - - match LxMessage::unpack(&unpack_data) { - Ok(mut msg) => { - msg.method = lxmf_core::constants::DeliveryMethod::Propagated; - msg.transient_id = Some(propagation_transient_id); - tracing::info!( - from = %hex::encode(msg.source_hash), - title = %msg.title, - len = msg.content.len(), - "propagation: downloaded message" - ); - msg.source_blackholed = self.source_blackholed(&msg.source_hash); - if msg.source_blackholed { - // LXMRouter.py:1739-1741. - tracing::debug!( - from = %hex::encode(msg.source_hash), - "Dropping LXM from blackholed identity" - ); - return; + let results = self.download_decode_tx.clone(); + self.download_tasks + .push(tokio::task::spawn_blocking(move || { + let message = (|| { + if !token.is_current() { + return Err(SuppressionReason::Cancelled); + } + decode_download_payload(&data, &identity, destination, &ratchets, limits) + })(); + let _ = results.send(DownloadDecoded { + message, + token, + processing, + ciphertext: data, + }); + })); + } + fn poll_download_decodes(&mut self) { + while let Ok(decoded) = self.download_decode_rx.try_recv() { + let DownloadDecoded { + message, + token, + processing, + ciphertext, + } = decoded; + let msg = match message { + Ok(msg) => msg, + Err(reason) => { + let _ = token.resolve(DownloadAdmissionOutcome::Rejected(reason)); + continue; } - // LXMRouter.py:1773-1775: enforcement covers propagated deliveries too. - if self.should_reject_for_signature(&mut msg) || self.should_reject_for_stamp(&msg) - { - return; - } - self.handle_inbound_message(msg); + }; + if !token.is_current() { + continue; } - Err(e) => { - tracing::warn!("failed to unpack downloaded propagation message: {e}"); + let Some(store) = self.admission_store.clone() else { + let _ = token.resolve(DownloadAdmissionOutcome::Rejected( + SuppressionReason::StorageUnavailable, + )); + continue; + }; + let Some(reservation) = self.router.reserve_inbound(&msg) else { + let _ = token.resolve(DownloadAdmissionOutcome::Rejected( + SuppressionReason::WorkerUnavailable, + )); + continue; + }; + let public_key = self + .known_identities + .get(&hex::encode(msg.source_hash())) + .copied(); + let tickets = self + .router + .ticket_store + .inbound_tokens(&msg.source_hash(), now_f64()); + let cost = if self.config.enforce_stamps { + self.config.stamp_cost.unwrap_or(0) + } else { + 0 + }; + let disposition = if self.source_blackholed(&msg.source_hash()) { + DurableDisposition::PolicyDiscard + } else { + DurableDisposition::Committed + }; + let record = AdmissionRecord { + scope: token.scope(), + message_id: msg.message_id(), + received_wire_hash: rns_crypto::sha::full_hash(msg.wire_bytes()), + stored_message_wire_hash: None, + disposition, + committed_at: now_f64() as u64, + }; + let hook = self.config.on_inbound_command.is_some(); + let results = self.download_commit_tx.clone(); + self.download_tasks + .push(tokio::task::spawn_blocking(move || { + let receipt = (|| { + if !token.is_current() { + return Err(DownloadWorkerError::Rejected( + SuppressionReason::Cancelled, + )); + } + validate_download_policy(&msg, public_key, &tickets, cost) + .map_err(DownloadWorkerError::Rejected)?; + DurableAdmissionReceipt::commit(store.prepare( + record, + msg.wire_owned(), + hook, + )) + .map_err(DownloadWorkerError::Storage) + })(); + let _ = results.send(DownloadCommitResult { + message: msg, + reservation, + receipt, + token, + _processing: processing, + _ciphertext: ciphertext, + }); + })); + } + } + + fn poll_download_commits(&mut self) { + self.poll_download_decodes(); + self.download_tasks.retain(|task| !task.is_finished()); + while let Ok(result) = self.download_commit_rx.try_recv() { + match result.receipt { + Ok(receipt) => { + if !result.token.is_current() { + self.router.abort_inbound(result.reservation); + continue; + } + let verified = self + .known_identities + .get(&hex::encode(result.message.source_hash())) + .and_then(|key| result.message.verify(key).ok()); + self.router.commit_inbound( + result.reservation, + &result.message, + &receipt, + verified.as_ref(), + ); + let _ = result + .token + .resolve(DownloadAdmissionOutcome::Accepted(receipt)); + } + Err(error) => { + self.router.abort_inbound(result.reservation); + let reason = match error { + DownloadWorkerError::Rejected(reason) => reason, + DownloadWorkerError::Storage(error) => { + tracing::warn!(%error,"download admission failed; ciphertext retained remotely"); + SuppressionReason::StorageUnavailable + } + }; + let _ = result + .token + .resolve(DownloadAdmissionOutcome::Rejected(reason)); + } } } + self.drive_download_queue(); + } + + fn download_epochs(&self) -> AdmissionEpochs { + let mut policy = b"lxmd admission policy v1".to_vec(); + policy.push(u8::from(self.config.enforce_stamps)); + policy.push(self.config.stamp_cost.unwrap_or(0)); + let mut blocked = self + .blackholed_identities + .iter() + .copied() + .collect::>(); + blocked.sort_unstable(); + for hash in blocked { + policy.extend_from_slice(&hash); + } + let mut identities = self.known_identities.iter().collect::>(); + identities.sort_unstable_by(|a, b| a.0.cmp(b.0)); + let mut keys = b"lxmd admission keys v1".to_vec(); + for (dest, key) in identities { + keys.extend_from_slice(dest.as_bytes()); + keys.extend_from_slice(key); + } + let mut ratchets = self + .delivery_ratchets + .ring() + .private_keys() + .iter() + .map(rns_identity::ratchet::ratchet_public_bytes) + .collect::>(); + ratchets.sort_unstable(); + for key in ratchets { + keys.extend_from_slice(&key); + } + let budget = format!( + "lxmd file admission v1:{}:{}:{}", + self.config.delivery_transfer_max_accepted_size, + lxmf_core::admission::MAX_PROCESSING_BYTES, + lxmf_core::admission::MAX_RETAINED_DOWNLOAD_BYTES + ); + AdmissionEpochs { + policy: rns_crypto::sha::full_hash(&policy), + keys: rns_crypto::sha::full_hash(&keys), + budget: rns_crypto::sha::full_hash(budget.as_bytes()), + storage_health: rns_crypto::sha::full_hash(b"lxmd file admission storage schema v1"), + } + } + fn drive_suppression_persistence(&mut self) { + let epochs = self.download_epochs(); + let Some(client) = self.propagation_client.as_mut() else { + return; + }; + client.update_admission_epochs(epochs); + if let Some(task) = self.suppression_task.as_mut() { + match task.result.try_recv() { + Ok(done) => { + self.suppression_task.take(); + match done.result { + Ok(()) => { + let _ = client.acknowledge_suppression_persistence(done.revision); + } + Err(error) => { + tracing::warn!(%error,"suppression persistence failed; pausing wants until retry"); + client.suppression_persistence_failed(); + self.next_suppression_retry = Instant::now() + Duration::from_secs(60); + } + } + } + Err(oneshot::error::TryRecvError::Empty) => return, + Err(oneshot::error::TryRecvError::Closed) => { + self.suppression_task.take(); + client.suppression_persistence_failed(); + self.next_suppression_retry = Instant::now() + Duration::from_secs(60); + } + } + } + if !client.suppression_persistence_pending() || Instant::now() < self.next_suppression_retry + { + return; + } + let ledger = client.suppression_ledger().clone(); + let path = self.data_dir.clone(); + let revision = client.suppression_revision(); + let (tx, result) = oneshot::channel(); + let task = tokio::task::spawn_blocking(move || { + let result = lxmf_core::persist::save_suppression(&path, &ledger); + let _ = tx.send(SuppressionPersistResult { revision, result }); + }); + self.suppression_task = Some(SuppressionPersistTask { result, task }); + } + + fn drive_hook_outbox(&mut self) { + if Instant::now() >= self.next_admission_maintenance + && self + .maintenance_task + .as_ref() + .is_none_or(|task| task.is_finished()) + { + self.next_admission_maintenance = Instant::now() + Duration::from_secs(3600); + if let Some(store) = self.admission_store.clone() { + self.maintenance_task = Some(tokio::task::spawn_blocking(move || { + if let Err(error) = store.maintain(now_f64() as u64) { + tracing::warn!(%error,"admission metadata cleanup pending"); + } + })); + } + } + while let Ok(success) = self.hook_result_rx.try_recv() { + self.next_hook_attempt = + Instant::now() + Duration::from_secs(if success { 0 } else { 60 }); + } + if self + .hook_task + .as_ref() + .is_some_and(|task| !task.is_finished()) + || Instant::now() < self.next_hook_attempt + { + return; + } + let Some(store) = self.admission_store.clone() else { + return; + }; + let Some(command) = self.config.on_inbound_command.clone() else { + return; + }; + let Some((event, path)) = store.pending_hooks().into_iter().next() else { + return; + }; + let result_tx = self.hook_result_tx.clone(); + self.hook_task = Some(tokio::task::spawn_blocking(move || { + match lxmf_tools::daemon::execute_on_inbound_with_event( + &command, + &path.to_string_lossy(), + &hex::encode(event), + ) { + Ok(()) => { + let success = match store.complete_hook(event) { + Ok(()) => true, + Err(error) => { + tracing::warn!(%error,"hook completion persistence failed; event may replay"); + false + } + }; + let _ = result_tx.send(success); + } + Err(error) => { + tracing::warn!(%error,event=%hex::encode(event),"inbound hook failed; retained for retry"); + let _ = result_tx.send(false); + } + } + })); } fn handle_inbound_packet(&mut self, raw: &[u8]) { @@ -3898,17 +4707,17 @@ impl LxmdRunner { match LxMessage::unpack(&unpack_data) { Ok(mut msg) => { tracing::info!( - from = %hex::encode(msg.source_hash), - title = %msg.title, - len = msg.content.len(), + from = %hex::encode(msg.source_hash()), + title = %msg.title_text(), + len = msg.content_bytes().len(), "inbound LXMF message received" ); - msg.source_blackholed = self.source_blackholed(&msg.source_hash); + msg.source_blackholed = self.source_blackholed(&msg.source_hash()); if msg.source_blackholed { // LXMRouter.py:1739-1741. tracing::debug!( - from = %hex::encode(msg.source_hash), + from = %hex::encode(msg.source_hash()), "Dropping LXM from blackholed identity" ); return; @@ -3948,20 +4757,14 @@ impl LxmdRunner { /// Validate a recalled sender signature. Unknown senders remain deliverable /// like Python, but can never teach the router a ticket. fn should_reject_for_signature(&self, msg: &mut LxMessage) -> bool { - let Some(public_key) = self.known_identities.get(&hex::encode(msg.source_hash)) else { + let Some(public_key) = self.known_identities.get(&hex::encode(msg.source_hash())) else { return false; }; - let mut signing_key = [0u8; 32]; - signing_key.copy_from_slice(&public_key[32..64]); - let Ok(signing_key) = rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&signing_key) - else { - return true; - }; - if msg.verify(&signing_key) { + if msg.verify(public_key).is_ok() { false } else { tracing::warn!( - from = %hex::encode(msg.source_hash), + from = %hex::encode(msg.source_hash()), "inbound message rejected: invalid LXMF signature" ); true @@ -3977,22 +4780,22 @@ impl LxmdRunner { Some(c) if c > 0 => c, _ => return false, }; - let stamp = match msg.stamp.as_deref() { + let stamp = match msg.recipient_stamp().map(|stamp| stamp.as_bytes()) { Some(s) => s, None => { tracing::warn!( - from = %hex::encode(msg.source_hash), + from = %hex::encode(msg.source_hash()), required_cost, "inbound message rejected: no stamp (enforce_stamps=true)" ); return true; } }; - let message_id = match msg.message_id.or(msg.hash) { + let message_id = match Some(msg.message_id()) { Some(id) => id, None => { tracing::warn!( - from = %hex::encode(msg.source_hash), + from = %hex::encode(msg.source_hash()), "inbound message rejected: no message_id for stamp validation" ); return true; @@ -4002,10 +4805,10 @@ impl LxmdRunner { &message_id, stamp, required_cost, - &msg.source_hash, + &msg.source_hash(), ) { tracing::warn!( - from = %hex::encode(msg.source_hash), + from = %hex::encode(msg.source_hash()), required_cost, "inbound message rejected: stamp PoW invalid or below required cost" ); @@ -4018,40 +4821,16 @@ impl LxmdRunner { fn handle_inbound_message(&mut self, msg: LxMessage) { if !self.router.deliver_inbound(&msg, false) { tracing::debug!( - message = ?msg.message_id.or(msg.hash).map(hex::encode), + message = %hex::encode(msg.message_id()), "ignoring already delivered inbound LXMF message" ); return; } - // Also deposit into the propagation store (if enabled) so peers can - // download it via offer/get sync. - if let Some(pn) = self.propagation_node.clone() { - let plan = pn - .lock() - .ok() - .and_then(|mut node| node.plan_accept_message(&msg)); - if let Some(plan) = plan { - let accounted_bytes = plan.size() as u64; - if let Some(task) = spawn_propagation_store_writes( - pn, - vec![(plan, accounted_bytes)], - PropagationStoreWriteOrigin::LocalDelivery, - self.prop_store_commit_tx.clone(), - "local inbound delivery", - ) { - self.prop_store_write_tasks.push(task); - } - } - } - let messages_dir = self.messages_dir.clone(); std::fs::create_dir_all(&messages_dir).ok(); - let msg_hash = msg - .hash - .map(hex::encode) - .unwrap_or_else(|| format!("{:.0}", now_f64())); + let msg_hash = hex::encode(msg.message_id()); let msg_path = messages_dir.join(format!("{msg_hash}.lxm")); // Pack synchronously (CPU-bound, no IO) and offload the disk write @@ -4085,7 +4864,7 @@ impl LxmdRunner { // (The source_hash to public_key mapping comes from announce processing, // not directly from the message. Log for diagnostics.) tracing::debug!( - from = %hex::encode(msg.source_hash), + from = %hex::encode(msg.source_hash()), "inbound message processed" ); } @@ -4107,29 +4886,13 @@ impl LxmdRunner { OutboundAction::DeliverPropagated { message, prop_hash } => { let mut message = message; let prop_hex = hex::encode(prop_hash); - if !self.known_identities.contains_key(&prop_hex) { - tracing::warn!( - prop = %prop_hex, - attempts = message.delivery_attempts, - "propagation node identity unknown, requesting path before link delivery" - ); - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - message, - prop_hash, - "propagation node identity unknown", - true, - ); - continue; - } tracing::info!( - dest = %hex::encode(message.destination_hash), + dest = %hex::encode(message.destination_hash()), prop = %hex::encode(prop_hash), "routing message via propagation node" ); - match self.pack_message_for_propagation(&mut message, prop_hash) { - Some(packed) => { + match self.pack_message_for_propagation(&message, prop_hash) { + Ok(packed) => { let attempts = mark_delivery_attempt(&mut message); if attempts >= MAX_DELIVERY_ATTEMPTS { tracing::warn!( @@ -4163,19 +4926,38 @@ impl LxmdRunner { ); } } - None => { - tracing::warn!( - dest = %hex::encode(message.destination_hash), - "failed to prepare propagated LXMF message; re-queueing" + Err(PropagationPreparationError::Pending) => { + message.next_delivery_attempt = now_f64() + 0.5; + self.queue_router_message(message, "propagation envelope preparation"); + } + Err(PropagationPreparationError::Missing(missing)) => { + let path = if missing == MissingPropagationInput::RecipientIdentity { + message.destination_hash() + } else { + prop_hash + }; + requeue_after_path_request( + &mut self.router, + &self.transport_tx, + message, + path, + "propagation readiness incomplete", + true, ); - self.queue_router_message(message, "propagated preparation retry"); + } + Err(PropagationPreparationError::Invalid(error)) => { + self.last_delivery_failure = Some(error); + message.mark_failed(); + self.propagation_envelopes.remove(&message.message_id()); } } continue; } OutboundAction::Failed(message) => { - let reason = message - .hash + self.propagation_envelopes.remove(&message.message_id()); + self.pending_propagation_envelopes + .remove(&message.message_id()); + let reason = Some(message.message_id()) .map(|hash| { format!("delivery attempts exhausted for {}", hex::encode(hash)) }) @@ -4184,8 +4966,10 @@ impl LxmdRunner { continue; } OutboundAction::Expired(message) => { - let reason = message - .hash + self.propagation_envelopes.remove(&message.message_id()); + self.pending_propagation_envelopes + .remove(&message.message_id()); + let reason = Some(message.message_id()) .map(|hash| { format!("message {} expired before delivery", hex::encode(hash)) }) @@ -4195,19 +4979,6 @@ impl LxmdRunner { } }; - if message.stamp.is_none() - && let Some(cost) = self.router.get_stamp_cost(&message.destination_hash) - && cost > 0 - { - tracing::info!( - dest = %hex::encode(message.destination_hash), - cost = cost, - "generating stamp" - ); - message.stamp_cost = Some(cost); - message.get_stamp(); - } - let dest_hex = hex::encode(dest_hash); if !is_opportunistic { let router_owned = direct_plan.is_some(); @@ -4300,7 +5071,8 @@ impl LxmdRunner { false, &reason, ); - if let Some(hash) = returned_message.hash { + if let Some(hash) = Some(returned_message.message_id()) + { let _ = self.router.defer_outbound_for_path_request( &hash, @@ -4339,7 +5111,7 @@ impl LxmdRunner { false, &reason, ); - if let Some(hash) = returned_message.hash { + if let Some(hash) = Some(returned_message.message_id()) { let _ = self .router .defer_outbound_for_path_request(&hash, now_f64()); @@ -4420,7 +5192,7 @@ impl LxmdRunner { ); continue; }; - let msg_hash = message.message_id.or(message.hash); + let msg_hash = Some(message.message_id()); let flags = rns_wire::flags::PacketFlags { header_type: rns_wire::flags::HeaderType::Header1, @@ -4556,34 +5328,114 @@ impl LxmdRunner { } fn pack_message_for_propagation( - &self, - message: &mut LxMessage, + &mut self, + message: &LxMessage, prop_hash: [u8; 16], - ) -> Option> { - let dest_hex = hex::encode(message.destination_hash); - let target_cost = self.router.get_stamp_cost(&prop_hash).unwrap_or(0); - let (packed, _tid, stamp_value) = message - .pack_propagated_encrypted_with_stamp( - |plaintext| { - self.encrypt_for_destination(&dest_hex, plaintext) - .ok_or_else(|| { - lxmf_core::message::MessageError::PackFailed(format!( - "no identity key for destination {dest_hex}" - )) - }) - }, - target_cost, - ) - .ok()?; - tracing::debug!( - dest = %dest_hex, - prop = %hex::encode(prop_hash), - target_cost, - stamp_value, - packed_len = packed.len(), - "prepared propagation wrapper" + ) -> Result, PropagationPreparationError> { + let dest_hex = hex::encode(message.destination_hash()); + let prepared = propagation_readiness( + prop_hash, + self.known_identities.contains_key(&hex::encode(prop_hash)), + self.route_hops.contains_key(&prop_hash), + self.node_policies.get(&prop_hash).copied(), + self.known_identities.contains_key(&dest_hex), + now_f64(), + ) + .map_err(PropagationPreparationError::Missing)?; + let key = self.known_identities[&dest_hex]; + let ratchet = self + .received_ratchets + .get(&dest_hex) + .filter(|r| !r.is_expired()) + .map(|r| r.ratchet_pub); + let mut binding = key.to_vec(); + if let Some(r) = ratchet { + binding.extend_from_slice(&r); + } + let binding = rns_crypto::sha::full_hash(&binding); + let id = message.message_id(); + self.propagation_preparation_tasks + .retain(|task| !task.is_finished()); + if let Some(job) = self.pending_propagation_envelopes.get_mut(&id) { + if job.binding != binding || job.cost != prepared.policy.stamp_cost { + self.pending_propagation_envelopes.remove(&id); + } else { + match job.result.try_recv() { + Ok(Ok(envelope)) => { + self.pending_propagation_envelopes.remove(&id); + self.propagation_envelopes.insert(id, envelope); + } + Ok(Err(error)) => { + self.pending_propagation_envelopes.remove(&id); + return Err(PropagationPreparationError::Invalid(error.to_string())); + } + Err(oneshot::error::TryRecvError::Empty) => { + return Err(PropagationPreparationError::Pending); + } + Err(oneshot::error::TryRecvError::Closed) => { + self.pending_propagation_envelopes.remove(&id); + return Err(PropagationPreparationError::Invalid( + "propagation worker unavailable".into(), + )); + } + } + } + } + if let Some(envelope) = self.propagation_envelopes.get_mut(&id) + && envelope.matches(message, &binding) + && envelope.stamp_value() >= u32::from(prepared.policy.stamp_cost) + { + return envelope + .pack_for(prepared, now_f64()) + .map_err(|e| PropagationPreparationError::Invalid(e.to_string())); + } + let Ok(permit) = propagation_preparation_slots().try_acquire_owned() else { + return Err(PropagationPreparationError::Pending); + }; + let previous = self + .propagation_envelopes + .remove(&id) + .filter(|envelope| envelope.matches(message, &binding)); + let message = message.clone(); + let cost = prepared.policy.stamp_cost; + let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let worker_cancel = cancel.clone(); + let (tx, result) = oneshot::channel(); + self.propagation_preparation_tasks + .push(tokio::task::spawn_blocking(move || { + let _permit = permit; + let outcome = (|| { + let mut envelope = match previous { + Some(envelope) => envelope, + None => PropagationEnvelope::new_cancellable( + message, + binding, + cost, + |plaintext| { + let remote = Identity::from_public_key(&key) + .map_err(|e| MessageError::PackFailed(e.to_string()))?; + remote + .encrypt(plaintext, ratchet.as_ref()) + .map_err(|e| MessageError::PackFailed(e.to_string())) + }, + &worker_cancel, + )?, + }; + envelope.pack_for_cancellable(prepared, now_f64(), &worker_cancel)?; + Ok(envelope) + })(); + let _ = tx.send(outcome); + })); + self.pending_propagation_envelopes.insert( + id, + PendingPropagationEnvelope { + binding, + cost, + result, + cancel, + }, ); - Some(packed) + Err(PropagationPreparationError::Pending) } fn decrypt_inbound(&self, ciphertext: &[u8]) -> Option> { @@ -4624,19 +5476,23 @@ impl LxmdRunner { Some(proof_raw) } - fn save_crypto_state(&self) { + fn save_crypto_state(&self) -> std::io::Result<()> { let ratchet_dir = self.ratchets_dir.clone(); - std::fs::create_dir_all(&ratchet_dir).ok(); + std::fs::create_dir_all(&ratchet_dir)?; - self.delivery_ratchets.save(&self.identity); + self.delivery_ratchets.save_durable(&self.identity)?; let received_dir = ratchet_dir.join("received"); - std::fs::create_dir_all(&received_dir).ok(); + std::fs::create_dir_all(&received_dir)?; for (hash_hex, rr) in &self.received_ratchets { let path = received_dir.join(format!("{hash_hex}.ratchet")); - if let Err(e) = rr.save(&path) { - tracing::warn!("Failed to save received ratchet {hash_hex}: {e}"); + if !hex::decode(hash_hex).is_ok_and(|hash| hash.len() == 16) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "invalid received ratchet destination", + )); } + rr.save_durable(&path)?; } // Flat binary: [dest_hash:16][pub:64] per entry. @@ -4650,9 +5506,7 @@ impl LxmdRunner { data.extend_from_slice(pk); } } - if let Err(e) = rns_identity::persistence::atomic_write(&ki_path, &data) { - tracing::warn!("Failed to save known identities: {e}"); - } + lxmf_core::persist::write_file_atomic(&ki_path, &data) } } @@ -4670,6 +5524,62 @@ pub(crate) async fn main() { let (config_dir, rns_config_dir) = resolve_config_dirs(args.config.as_deref(), args.rnsconfig.as_deref()); + if args.migrate_propagation_store { + let result = (|| -> std::io::Result<()> { + use lxmf_core::propagation_store_v2::{ + RecoveryPolicy, begin_offline_migration, import_trusted_recovery_manifest, + migrate_store_offline, + }; + let paths = LxmdPaths::new(config_dir.clone()); + let guard = + begin_offline_migration(&paths.propagation_store_dir, args.relay_writers_stopped)?; + let report = migrate_store_offline(&guard)?; + println!( + "Relay store v2 ready at {}. Preserved {} legacy files ({} bytes) in quarantine.", + report.store.display(), + report.quarantine.files, + report.quarantine.bytes + ); + if let Some(manifest) = args.recover_propagation_manifest.as_ref() { + let digest = hex::decode(args.recovery_manifest_sha256.as_deref().unwrap_or("")) + .map_err(std::io::Error::other)?; + let digest: [u8; 32] = digest.try_into().map_err(|_| { + std::io::Error::other( + "recovery manifest SHA-256 must be 64 hexadecimal characters", + ) + })?; + let source = rns_runtime::config::Config::from_file(&config_dir.join("config")) + .map_err(std::io::Error::other)?; + let config = DaemonConfig::from_config(&source); + let policy = RecoveryPolicy { + maximum_store_bytes: config + .message_storage_limit + .unwrap_or(configured_kilobytes_to_bytes(config.propagation_limit_kb)), + maximum_message_bytes: configured_kilobytes_to_bytes( + config.propagation_limit_kb, + ), + minimum_stamp_cost: config + .propagation_stamp_cost + .saturating_sub(config.propagation_stamp_flex), + }; + let recovered = import_trusted_recovery_manifest(&guard, manifest, digest, policy)?; + println!( + "Recovered {} verified opaque entries; {} were already present.", + recovered.imported, recovered.already_present + ); + } + println!( + "Keep legacy propagation hosting and sync disabled. Retry alone never promotes quarantined files." + ); + Ok(()) + })(); + if let Err(error) = result { + eprintln!("Relay migration unavailable: {error}"); + std::process::exit(1); + } + return; + } + let is_control_command = args.status || args.peers || args.sync.is_some() || args.unpeer.is_some(); let control_preflight = if is_control_command { @@ -5033,151 +5943,155 @@ pub(crate) async fn main() { tracing::info!("On-inbound command: {}", cmd); } + let mut one_shot_status = None; if let Some(send_args) = args.send.as_ref().filter(|_| !shutdown.is_triggered()) { - let dest_hex = normalize_hash_hex(&send_args[0]); - let content = match args.send_file.as_ref() { - Some(path) => match std::fs::read_to_string(path) { - Ok(content) => content, + one_shot_status = Some(1); + 'one_shot: { + let dest_hex = normalize_hash_hex(&send_args[0]); + let content = match args.send_file.as_ref() { + Some(path) => match std::fs::read_to_string(path) { + Ok(content) => content, + Err(e) => { + tracing::error!(path = %path.display(), error = %e, "failed to read --send-file"); + break 'one_shot; + } + }, + None => match send_args.get(1) { + Some(content) => content.clone(), + None => { + tracing::error!("--send requires CONTENT unless --send-file is provided"); + break 'one_shot; + } + }, + }; + + let dest_hash = match parse_destination_hash(&dest_hex) { + Ok(hash) => hash, Err(e) => { - tracing::error!(path = %path.display(), error = %e, "failed to read --send-file"); - std::process::exit(1); + tracing::error!("{e}"); + break 'one_shot; } - }, - None => match send_args.get(1) { - Some(content) => content.clone(), - None => { - tracing::error!("--send requires CONTENT unless --send-file is provided"); - std::process::exit(1); - } - }, - }; + }; - let dest_hash = match parse_destination_hash(&dest_hex) { - Ok(hash) => hash, - Err(e) => { - tracing::error!("{e}"); - std::process::exit(1); - } - }; + tracing::info!(dest = %dest_hex, "sending message..."); + runner.last_delivery_failure = None; - tracing::info!(dest = %dest_hex, "sending message..."); - runner.last_delivery_failure = None; - - // Wait up to 15s for a fresh announce so we learn the destination's key and - // install a current path before queueing. A persisted key alone is not enough - // behind transport hubs: link delivery can start before the path exists. - let mut have_key = runner.known_identities.contains_key(&dest_hex); - let mut saw_dest_announce = false; - for _ in 0..30 { - for announced in runner.drain_announce_events() { - if announced == dest_hash { - saw_dest_announce = true; - } + // Wait up to 15s for a fresh announce so we learn the destination's key and + // install a current path before queueing. A persisted key alone is not enough + // behind transport hubs: link delivery can start before the path exists. + if !runner.known_identities.contains_key(&dest_hex) { + queue_path_request( + &runner.transport_tx, + dest_hash, + false, + "one-shot recipient key discovery", + ); } - runner.refresh_route_hops_from_transport().await; - runner.drain_link_packets(); - have_key = runner.known_identities.contains_key(&dest_hex); - if have_key && saw_dest_announce { - break; - } - if sleep_or_shutdown(&shutdown, Duration::from_millis(500)).await { - tracing::info!("message send interrupted by shutdown"); - return; - } - } - if !have_key { - tracing::warn!( - dest = %dest_hex, - "no announce received for destination in 15s; sending anyway" - ); - } else if !saw_dest_announce { - tracing::warn!( - dest = %dest_hex, - "no fresh path announce received for destination in 15s; sending anyway" - ); - } - - let mut msg = LxMessage::new( - dest_hash, - runner.lxmf_dest_hash, - "", - &content, - args.send_method.delivery_method(), - ); - if let Some(raw) = args.send_fields_json.as_deref() { - match parse_send_fields_json(raw) { - Ok(fields) => { - tracing::info!(count = fields.len(), "attaching custom fields to --send"); - msg.fields = fields; - } - Err(e) => { - tracing::error!("--send-fields-json: {e}"); - std::process::exit(1); - } - } - } - msg.include_ticket = true; - if let Err(error) = runner.router.prepare_outbound(&mut msg) { - tracing::error!(%error, "failed to prepare reply ticket"); - eprintln!("Error: {error}"); - std::process::exit(1); - } - let Some(signing_key) = runner.identity.get_signing_key() else { - tracing::error!("identity has no signing key"); - std::process::exit(1); - }; - if let Err(e) = msg.sign(&signing_key) { - tracing::error!(error = ?e, "failed to sign message"); - std::process::exit(1); - } - if let Err(e) = runner.router.try_send(msg) { - tracing::error!(error = %e, "failed to queue message"); - eprintln!("Error: {e}"); - std::process::exit(1); - } - - // Completion phase: do not confuse queue acceptance with delivery. - // Opportunistic messages leave the router queue while a validated - // Reticulum delivery proof is outstanding, so both ownership sets - // must converge before the command can report success. - let mut drained = false; - for _ in 0..args.send_timeout_secs { - runner.drain_announce_events(); - runner.refresh_route_hops_from_transport().await; - runner.drain_link_packets(); - runner.tick(); - if sleep_or_shutdown(&shutdown, Duration::from_secs(1)).await { - tracing::info!("message send interrupted by shutdown"); - return; - } - - let stats = runner.router.stats(); - if stats.pending_outbound == 0 - && stats.pending_deferred_stamps == 0 - && runner.opportunistic_in_flight.is_empty() + if args.send_method.delivery_method() == DeliveryMethod::Propagated + && let Some(node) = runner.router.outbound_propagation_node { - drained = true; - break; + queue_path_request( + &runner.transport_tx, + node, + false, + "one-shot propagation node readiness", + ); + } + let mut have_key = runner.known_identities.contains_key(&dest_hex); + let mut saw_dest_announce = false; + for _ in 0..30 { + for announced in runner.drain_announce_events() { + if announced == dest_hash { + saw_dest_announce = true; + } + } + runner.refresh_route_hops_from_transport().await; + runner.drain_link_packets(); + have_key = runner.known_identities.contains_key(&dest_hex); + if have_key + && (saw_dest_announce + || args.send_method.delivery_method() == DeliveryMethod::Propagated) + { + break; + } + if sleep_or_shutdown(&shutdown, Duration::from_millis(500)).await { + tracing::info!("message send interrupted by shutdown"); + break 'one_shot; + } + } + if !have_key { + tracing::warn!( + dest = %dest_hex, + "no announce received for destination in 15s; sending anyway" + ); + } else if !saw_dest_announce { + tracing::warn!( + dest = %dest_hex, + "no fresh path announce received for destination in 15s; sending anyway" + ); } - } - if !drained { - tracing::warn!("message send timed out before delivery completed"); - eprintln!("Error: send timed out (delivery was not confirmed)"); - std::process::exit(1); - } + let mut msg = match LxMessageDraft::new( + dest_hash, + runner.lxmf_dest_hash, + "", + &content, + args.send_method.delivery_method(), + ) { + Ok(value) => value, + Err(error) => { + tracing::error!(%error,"invalid message size"); + break 'one_shot; + } + }; + if let Some(raw) = args.send_fields_json.as_deref() { + match parse_send_fields_json(raw) { + Ok(fields) => { + tracing::info!(count = fields.len(), "attaching custom fields to --send"); + for (id, value) in fields { + if let Err(error) = msg.set_field(id, value) { + tracing::error!(%error,"invalid --send field"); + break 'one_shot; + } + } + } + Err(e) => { + tracing::error!("--send-fields-json: {e}"); + break 'one_shot; + } + } + } + msg.include_ticket = true; + let prepared = runner.router.prepare_outbound(&mut msg).and_then(|intent| { + intent + .persist(&runner.data_dir, &mut msg) + .map_err(|e| lxmf_core::router::TicketPreparationError::Encode(e.to_string())) + }); + if let Err(error) = prepared { + tracing::error!(%error,"reply ticket persistence failed"); + break 'one_shot; + } + let Some(signing_key) = runner.identity.get_signing_key() else { + tracing::error!("identity has no signing key"); + break 'one_shot; + }; + let signed = match msg.sign(&signing_key) { + Ok(value) => value, + Err(error) => { + tracing::error!(%error,"failed to sign message"); + break 'one_shot; + } + }; + if let Err(error) = runner.router.submit_signed(signed) { + tracing::error!(%error,"failed to queue message"); + break 'one_shot; + } - // Link-delivery completion phase: when escalated to link delivery - // (Opportunistic>MTU auto-downgrade, Direct, or Propagated), the - // router queue empties immediately but the transfer continues on the - // link. Wait up to 90s so the proof can come back. - if runner - .link_delivery - .as_ref() - .is_some_and(|ld| ld.pending_count() > 0) - { - tracing::info!("waiting for link delivery to complete..."); - let mut link_done = false; + // Completion phase: do not confuse queue acceptance with delivery. + // Opportunistic messages leave the router queue while a validated + // Reticulum delivery proof is outstanding, so both ownership sets + // must converge before the command can report success. + let mut drained = false; for _ in 0..args.send_timeout_secs { runner.drain_announce_events(); runner.refresh_route_hops_from_transport().await; @@ -5185,36 +6099,75 @@ pub(crate) async fn main() { runner.tick(); if sleep_or_shutdown(&shutdown, Duration::from_secs(1)).await { tracing::info!("message send interrupted by shutdown"); - return; + break 'one_shot; } - if runner - .link_delivery - .as_ref() - .is_none_or(|ld| ld.pending_count() == 0) + let stats = runner.router.stats(); + if stats.pending_outbound == 0 + && stats.pending_deferred_stamps == 0 + && runner.opportunistic_in_flight.is_empty() { - link_done = true; + drained = true; break; } } - if !link_done { - tracing::warn!( - timeout_secs = args.send_timeout_secs, - "link delivery did not complete before timeout" - ); - eprintln!("Error: link delivery did not complete in time"); - std::process::exit(1); - } - } - if let Some(reason) = runner.last_delivery_failure.as_ref() { - tracing::warn!(reason = %reason, "message send failed during link delivery"); - eprintln!("Error: link delivery failed: {reason}"); - std::process::exit(1); - } - tracing::info!("message sent successfully"); - println!("Message sent to {}", dest_hex); - std::process::exit(0); + if !drained { + tracing::warn!("message send timed out before delivery completed"); + eprintln!("Error: send timed out (delivery was not confirmed)"); + break 'one_shot; + } + + // Link-delivery completion phase: when escalated to link delivery + // (Opportunistic>MTU auto-downgrade, Direct, or Propagated), the + // router queue empties immediately but the transfer continues on the + // link. Wait up to 90s so the proof can come back. + if runner + .link_delivery + .as_ref() + .is_some_and(|ld| ld.pending_count() > 0) + { + tracing::info!("waiting for link delivery to complete..."); + let mut link_done = false; + for _ in 0..args.send_timeout_secs { + runner.drain_announce_events(); + runner.refresh_route_hops_from_transport().await; + runner.drain_link_packets(); + runner.tick(); + if sleep_or_shutdown(&shutdown, Duration::from_secs(1)).await { + tracing::info!("message send interrupted by shutdown"); + break 'one_shot; + } + + if runner + .link_delivery + .as_ref() + .is_none_or(|ld| ld.pending_count() == 0) + { + link_done = true; + break; + } + } + if !link_done { + tracing::warn!( + timeout_secs = args.send_timeout_secs, + "link delivery did not complete before timeout" + ); + eprintln!("Error: link delivery did not complete in time"); + break 'one_shot; + } + } + if let Some(reason) = runner.last_delivery_failure.as_ref() { + tracing::warn!(reason = %reason, "message send failed during link delivery"); + eprintln!("Error: link delivery failed: {reason}"); + break 'one_shot; + } + + tracing::info!("message sent successfully"); + println!("Message sent to {}", dest_hex); + one_shot_status = Some(0); + } + shutdown.trigger(); } if !shutdown.is_triggered() { @@ -5263,8 +6216,8 @@ pub(crate) async fn main() { } runner.drain_link_packets(); } - Some((data, link_id)) = runner.prop_link_packet_rx.recv() => { - runner.handle_propagation_transfer_data(link_id, &data); + Some(packet) = runner.prop_link_packet_rx.recv() => { + runner.handle_propagation_packet(packet); runner.drain_link_packets(); } Some(event) = runner.prop_accounting_rx.recv() => { @@ -5295,6 +6248,49 @@ pub(crate) async fn main() { tracing::info!("LXMF Daemon shutting down"); runner.close_announce_subscriptions().await; + runner.prop_get_workers.close_and_join().await; + // Revoke new packet admission, then retain and join every already admitted + // owner through its actual validation/store completion before final state. + runner.prop_link_packet_rx.close(); + while runner.prop_link_packet_rx.try_recv().is_ok() {} + let (closed_sender, closed_receiver) = mpsc::channel(1); + drop(closed_receiver); + let old_sender = std::mem::replace(&mut runner.prop_packet_validation_job_tx, closed_sender); + drop(old_sender); + if let Some(task) = runner.prop_packet_validation_pool.take() { + let _ = task.await; + } + while let Ok(result) = runner.prop_packet_validation_rx.try_recv() { + runner.handle_propagation_packet_validation_result(result); + } + if let Some(task) = runner.prop_maintenance_task.take() { + let _ = task.task.await; + if !matches!(task.result.await, Ok(Ok(()))) && one_shot_status.is_some() { + one_shot_status = Some(1); + } + } + + runner.pending_propagation_envelopes.clear(); + for task in std::mem::take(&mut runner.propagation_preparation_tasks) { + let _ = task.await; + } + if let Some(client) = runner.propagation_client.as_mut() { + client.cancel_download(); + } + for task in std::mem::take(&mut runner.download_tasks) { + let _ = task.await; + } + runner.pending_downloads.clear(); + runner.poll_download_commits(); + if let Some(task) = runner.suppression_task.take() { + let _ = task.task.await; + } + if let Some(task) = runner.hook_task.take() { + let _ = task.await; + } + if let Some(task) = runner.maintenance_task.take() { + let _ = task.await; + } for task in std::mem::take(&mut runner.prop_store_write_tasks) { if let Err(error) = task.await { tracing::warn!(%error, "propagation store write task failed during shutdown"); @@ -5307,21 +6303,175 @@ pub(crate) async fn main() { result, ); } - runner.save_crypto_state(); + if let Some(task) = runner.checkpoint_task.take() { + let _ = task.task.await; + if !matches!(task.result.await, Ok(Ok(()))) { + tracing::warn!("pending daemon checkpoint did not commit at shutdown"); + if one_shot_status.is_some() { + one_shot_status = Some(1); + } + } + } + if let Err(error) = runner.save_crypto_state() { + tracing::warn!(%error,"crypto checkpoint did not commit on shutdown"); + if one_shot_status.is_some() { + one_shot_status = Some(1); + } + } + if let Err(error) = + lxmf_core::persist::save_node_policies(&runner.data_dir, &runner.node_policies) + { + tracing::warn!(%error,"failed to persist propagation node policies"); + if one_shot_status.is_some() { + one_shot_status = Some(1); + } + } if let Err(e) = runner.router.save_state(&runner.data_dir) { tracing::warn!("Failed to save router state on shutdown: {e}"); + if one_shot_status.is_some() { + one_shot_status = Some(1); + } } - tracing::info!("Crypto state saved"); + tracing::info!("LXMF Daemon stopped"); + if let Some(status) = one_shot_status { + std::process::exit(status); + } } #[cfg(test)] mod tests { use super::*; + fn signed_fixture( + destination: [u8; 16], + source: [u8; 16], + title: &str, + content: &str, + method: DeliveryMethod, + ) -> LxMessage { + lxmf_core::message::LxMessageDraft::new(destination, source, title, content, method) + .unwrap() + .sign(&rns_crypto::ed25519::Ed25519PrivateKey::generate()) + .unwrap() + .finalize(None) + .unwrap() + } + + #[tokio::test] + async fn get_workers_are_bounded_and_cancelled_shutdown_keeps_actual_jobs_owned() { + let workers = PnGetWorkers::default(); + let (entered_tx, mut entered_rx) = mpsc::channel(4); + let completed = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut releases = Vec::new(); + for _ in 0..4 { + let (release, wait) = tokio::sync::oneshot::channel(); + releases.push(release); + let entered = entered_tx.clone(); + let completed = completed.clone(); + assert!(workers.spawn(move || { + entered.blocking_send(()).unwrap(); + wait.blocking_recv().unwrap(); + completed.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + })); + } + for _ in 0..4 { + entered_rx.recv().await.unwrap(); + } + assert!(!workers.spawn(|| panic!("fifth worker must not execute"))); + // The current-thread async loop remains runnable while all four actual + // blocking workers are parked, unlike the old inline request handler. + tokio::time::timeout(Duration::from_secs(1), tokio::task::yield_now()) + .await + .unwrap(); + let closing = workers.clone(); + let waiter = tokio::spawn(async move { closing.close_and_join().await }); + tokio::task::yield_now().await; + assert!(!waiter.is_finished()); + waiter.abort(); + let _ = waiter.await; + assert!(!workers.spawn(|| panic!("shutdown must remain closed"))); + assert_eq!(completed.load(std::sync::atomic::Ordering::Acquire), 0); + for release in releases { + release.send(()).unwrap(); + } + tokio::time::timeout(Duration::from_secs(2), workers.close_and_join()) + .await + .unwrap(); + assert_eq!(completed.load(std::sync::atomic::Ordering::Acquire), 4); + assert!(workers.state.lock().unwrap().tasks.is_empty()); + } + + #[tokio::test] + #[ignore = "private live Python receipt harness supplies a temporary config"] + async fn live_pn_packet_delay_endpoint() { + let config_dir = PathBuf::from( + std::env::var_os("RATSPEAK_PN_TEST_CONFIG").expect("private fixture config"), + ); + let config = rns_runtime::config::Config::from_file(&config_dir.join("config")).unwrap(); + let config = DaemonConfig::from_config(&config); + assert!(config.propagation_enabled); + let shutdown = ShutdownSignal::new(); + let rns_config = config_dir.join("rns"); + eprintln!("PN_RECEIPT_START initializing Reticulum"); + let handle = rns_runtime::reticulum::init( + Some(rns_config.to_str().unwrap()), + None, + shutdown.clone(), + Arc::new(std::sync::atomic::AtomicBool::new(true)), + ) + .await + .unwrap(); + eprintln!("PN_RECEIPT_START opening daemon storage"); + let mut runner = LxmdRunner::new( + config, + &config_dir, + handle.transport_tx.clone(), + Some(handle.link_endpoint_dispatch_handle()), + ) + .unwrap(); + eprintln!("PN_RECEIPT_START installing daemon subscriptions"); + runner.pn_packet_store_delay = Duration::from_millis(100); + *runner.prop_get_workers.pause.lock().unwrap() = Some(config_dir.clone()); + runner + .install_announce_subscriptions(&handle) + .await + .unwrap(); + runner.apply_config(); + assert!(wait_for_online_interface(&handle, Duration::from_secs(30)).await); + eprintln!("PN_RECEIPT_START interface online; announcing"); + runner.send_propagation_announce().await.unwrap(); + eprintln!("PN_RECEIPT_START announced"); + let deadline = Instant::now() + Duration::from_secs(300); + let mut tick = tokio::time::interval(Duration::from_millis(25)); + loop { + assert!( + Instant::now() < deadline, + "private receipt endpoint timed out" + ); + tokio::select! { + _ = tick.tick() => { + runner.drain_link_packets(); + runner.drive_propagation_sync(); + } + Some(packet) = runner.prop_link_packet_rx.recv() => { + runner.handle_propagation_packet(packet); + runner.drain_link_packets(); + } + Some(result) = runner.prop_packet_validation_rx.recv() => { + runner.handle_propagation_packet_validation_result(result); + runner.drain_link_packets(); + } + Some(event) = runner.prop_accounting_rx.recv() => { + runner.handle_propagation_accounting_event(event); + runner.drain_link_packets(); + } + } + } + } + #[tokio::test] async fn backchannel_accounting_retains_exact_windows_and_resource_cancellation() { - use rns_crypto::ed25519::Ed25519PrivateKey; use std::time::{Duration, Instant}; let unique = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -5343,15 +6493,14 @@ mod tests { let link_id = [0x61; 16]; let dest = [0x62; 16]; let resource_hash = [0x63; 32]; - let mut message = LxMessage::new( + let message = signed_fixture( dest, [0x64; 16], "accounting", "bounded", DeliveryMethod::Direct, ); - message.sign(&Ed25519PrivateKey::generate()).unwrap(); - let hash = message.hash.unwrap(); + let hash = message.message_id(); let ld = runner.link_delivery.as_mut().unwrap(); ld.register_backchannel(dest, link_id); ld.start_backchannel_delivery(message, dest).unwrap(); @@ -5846,7 +6995,7 @@ mod tests { let (tx, mut rx) = mpsc::channel::(4); let dest = [0x22; 16]; let source = [0x11; 16]; - let message = LxMessage::new(dest, source, "retry", "hello", DeliveryMethod::Direct); + let message = signed_fixture(dest, source, "retry", "hello", DeliveryMethod::Direct); let before = now_f64(); requeue_after_path_request(&mut router, &tx, message, dest, "test path wait", true); @@ -5933,7 +7082,7 @@ mod tests { let (tx, _rx) = mpsc::channel::(4); let dest = [0x44; 16]; let source = [0x33; 16]; - let mut message = LxMessage::new(dest, source, "retry", "hello", DeliveryMethod::Direct); + let mut message = signed_fixture(dest, source, "retry", "hello", DeliveryMethod::Direct); message.delivery_attempts = 3; requeue_after_path_request(&mut router, &tx, message, dest, "transport full", false); @@ -5947,7 +7096,7 @@ mod tests { fn delivery_attempt_uses_delivery_retry_deadline() { let dest = [0x66; 16]; let source = [0x55; 16]; - let mut message = LxMessage::new(dest, source, "direct", "hello", DeliveryMethod::Direct); + let mut message = signed_fixture(dest, source, "direct", "hello", DeliveryMethod::Direct); let before = now_f64(); let attempts = mark_delivery_attempt(&mut message); @@ -6000,58 +7149,141 @@ mod tests { assert_eq!(snapshot.hops, 5); } - /// Pins LXMRouter.py:1773-1775: stamp enforcement covers PROPAGATED - /// deliveries, not just link-delivered messages. - #[tokio::test] - async fn propagation_downloaded_data_respects_stamp_enforcement() { - let unique = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) + /// Real encrypted downloads pass the same decode/policy stages as workers; + /// only validated bytes can create an archive, purge receipt, or hook. + #[test] + fn propagation_downloaded_data_respects_stamp_enforcement() { + use lxmf_core::admission::AdmissionScope; + use lxmf_core::message::{LxMessageDraft, MessageDecodeLimits, RecipientStamp}; + let temp = tempfile::tempdir().unwrap(); + let bodies = temp.path().join("messages"); + let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + let recipient = Identity::new(); + let sender = Identity::new(); + let destination = + Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&recipient.hash)); + let source = + Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&sender.hash)); + let mut draft = LxMessageDraft::new( + destination, + source, + "title", + "encrypted body", + DeliveryMethod::Propagated, + ) + .unwrap(); + draft.set_timestamp(100.).unwrap(); + let missing = draft + .clone() + .sign(&sender.get_signing_key().unwrap()) .unwrap() - .as_nanos(); - let temp = std::env::temp_dir().join(format!( - "lxmd-prop-stamp-gate-{}-{unique}", - std::process::id() - )); - let (tx, _rx) = mpsc::channel::(64); - let config = DaemonConfig { - enforce_stamps: true, - stamp_cost: Some(8), - ..Default::default() + .finalize(None) + .unwrap(); + let signed = draft.sign(&sender.get_signing_key().unwrap()).unwrap(); + let encrypt = |message: &LxMessage| { + let mut wire = destination.to_vec(); + wire.extend_from_slice( + &recipient + .encrypt(&message.wire_bytes()[16..], None) + .unwrap(), + ); + wire }; - let mut runner = LxmdRunner::new(config, &temp, tx, None).expect("runner"); - - let dest = [0xAB; 16]; - assert_ne!(dest, runner.lxmf_dest_hash); - let mut msg = LxMessage::new(dest, [0xCD; 16], "t", "hello", DeliveryMethod::Propagated); - msg.signature = Some([0u8; 64]); - let data = msg.pack().expect("pack"); - let hash = LxMessage::unpack(&data) - .expect("unpack") - .hash - .expect("hash"); - let msg_path = runner - .messages_dir - .join(format!("{}.lxm", hex::encode(hash))); - - runner.handle_propagation_downloaded_data(&data); - // Grace period: an (incorrectly) accepted message would be written on the blocking pool. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - assert!( - !msg_path.exists(), - "unstamped propagated message must be rejected" + let cipher = encrypt(&missing); + let decoded = decode_download_payload( + &cipher, + &recipient, + destination, + &[], + MessageDecodeLimits::default(), + ) + .unwrap(); + assert_eq!(decoded.wire_bytes(), missing.wire_bytes()); + assert_eq!( + validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 8), + Err(SuppressionReason::InvalidStamp) ); - - runner.config.enforce_stamps = false; - runner.handle_propagation_downloaded_data(&data); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while !msg_path.exists() && std::time::Instant::now() < deadline { - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - } + assert!(store.haves(recipient.hash, [9; 16], 101).is_empty()); + assert!(store.pending_hooks().is_empty()); assert!( - msg_path.exists(), - "message must be stored once enforcement is off" + !bodies + .join(format!("{}.lxm", hex::encode(missing.message_id()))) + .exists() ); - let _ = std::fs::remove_dir_all(&temp); + assert_eq!( + validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 0), + Ok(()) + ); + assert!(matches!( + decode_download_payload( + missing.wire_bytes(), + &recipient, + destination, + &[], + MessageDecodeLimits::default() + ), + Err(SuppressionReason::DecryptionFailed) + )); + let mut corrupt = missing.wire_bytes().to_vec(); + corrupt[32] ^= 1; + let corrupt = LxMessage::unpack(&corrupt).unwrap(); + assert_eq!( + validate_download_policy(&corrupt, Some(sender.get_public_key()), &[], 0), + Err(SuppressionReason::InvalidSignature) + ); + let ticket = [7u8; 16]; + let mut material = [0u8; 48]; + material[..16].copy_from_slice(&ticket); + material[16..].copy_from_slice(&missing.message_id()); + let accepted = signed + .finalize(Some(RecipientStamp::Ticket( + rns_crypto::sha::truncated_hash(&material), + ))) + .unwrap(); + let cipher = encrypt(&accepted); + let accepted = decode_download_payload( + &cipher, + &recipient, + destination, + &[], + MessageDecodeLimits::default(), + ) + .unwrap(); + validate_download_policy(&accepted, Some(sender.get_public_key()), &[ticket], 8).unwrap(); + let scope = AdmissionScope { + identity: recipient.hash, + node: [9; 16], + transient_id: rns_crypto::sha::full_hash(&cipher), + }; + let record = AdmissionRecord { + scope, + message_id: accepted.message_id(), + received_wire_hash: rns_crypto::sha::full_hash(accepted.wire_bytes()), + stored_message_wire_hash: None, + disposition: DurableDisposition::Committed, + committed_at: 100, + }; + let receipt = + DurableAdmissionReceipt::commit(store.prepare(record, accepted.wire_owned(), true)) + .unwrap(); + assert_eq!(receipt.record().scope, scope); + assert_eq!( + std::fs::read(bodies.join(format!("{}.lxm", hex::encode(accepted.message_id())))) + .unwrap(), + accepted.wire_bytes() + ); + assert_eq!( + store.haves(recipient.hash, [9; 16], 101), + vec![scope.transient_id.to_vec()] + ); + assert_eq!(store.pending_hooks().len(), 1); + drop(store); + let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap(); + assert_eq!( + reopened.haves(recipient.hash, [9; 16], 101), + vec![scope.transient_id.to_vec()] + ); + assert_eq!(reopened.pending_hooks().len(), 1); } #[tokio::test] @@ -6076,19 +7308,15 @@ mod tests { observed.fetch_add(1, Ordering::Relaxed); }); - let mut message = LxMessage::new( + let message = signed_fixture( runner.lxmf_dest_hash, [0xCD; 16], "one", "delivery", DeliveryMethod::Direct, ); - message.signature = Some([0u8; 64]); let packed = message.pack().expect("pack"); - let message_id = LxMessage::unpack(&packed) - .expect("unpack") - .message_id - .expect("message id"); + let message_id = LxMessage::unpack(&packed).expect("unpack").message_id(); let ciphertext = runner .identity @@ -6180,13 +7408,18 @@ mod tests { [], 1_000, ))); - let node = Arc::new(Mutex::new(PropagationNode::new( - PropagationNodeConfig { - peering_cost: 0, - ..PropagationNodeConfig::default() - }, - local_identity, - ))); + let temporary = tempfile::tempdir().unwrap(); + let node = Arc::new(Mutex::new( + PropagationNode::with_storage( + PropagationNodeConfig { + peering_cost: 0, + ..PropagationNodeConfig::default() + }, + local_identity, + temporary.path().join("store"), + ) + .unwrap(), + )); let offer = pn_test_offer(vec![[0x44; 32]]); let response = handle_pn_offer_request( @@ -6262,7 +7495,7 @@ mod tests { fn packet_validation_worker_handles_hundred_plus_entries_off_loop() { let wrapper = pn_test_wrapper((0..128).map(pn_test_entry).collect()); - let result = validate_pn_packet_job([0x91; 16], wrapper.clone(), wrapper.len(), 0); + let result = validate_pn_packet_job([0x91; 16], wrapper.clone().into(), wrapper.len(), 0); assert_eq!(result.entries.len(), 128); assert_eq!(result.rejected, 0); @@ -6272,9 +7505,16 @@ mod tests { fn packet_validation_queue_rejects_overload_and_closed_workers() { let job = |link_byte| PnPacketValidationJob { link_id: [link_byte; 16], - data: vec![0xc1], + data: Bytes::from_static(&[0xc1]), + receipt: None, + node: Arc::new(Mutex::new(PropagationNode::new( + Default::default(), + [0; 16], + ))), max_transfer_bytes: 1, min_cost: 0, + store_delay: Duration::ZERO, + enqueued_at: Instant::now(), }; let (jobs, jobs_rx) = mpsc::channel(1); assert_eq!(enqueue_pn_packet_validation(&jobs, job(1)), Ok(())); @@ -6292,10 +7532,11 @@ mod tests { #[test] fn malformed_packet_validation_requests_link_teardown() { - let result = validate_pn_packet_job([0x92; 16], vec![0xc1], 1, 0); + let result = validate_pn_packet_job([0x92; 16], Bytes::from_static(&[0xc1]), 1, 0); assert!(result.entries.is_empty()); - assert_eq!(result.rejected, 1); + assert!(result.malformed); + assert_eq!(result.rejected, 0); } #[test] diff --git a/crates/lxmf-tools/src/daemon.rs b/crates/lxmf-tools/src/daemon.rs index 8ad6b9f..6faad1d 100644 --- a/crates/lxmf-tools/src/daemon.rs +++ b/crates/lxmf-tools/src/daemon.rs @@ -404,6 +404,16 @@ pub fn create_router_with_transport( /// argument rather than interpolating into a shell string, so untrusted path /// contents cannot inject shell metacharacters. pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<()> { + execute_on_inbound_with_event(command, message_path, "") +} + +/// Durable propagation outbox events may replay after a crash. Hooks can use +/// this stable identifier for their own idempotency boundary. +pub fn execute_on_inbound_with_event( + command: &str, + message_path: &str, + event_id: &str, +) -> std::io::Result<()> { use std::process::Command; let parts = split_command_line(command)?; @@ -416,10 +426,15 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result< cmd.arg(arg); } cmd.arg(message_path); + if !event_id.is_empty() { + cmd.env("LXMF_EVENT_ID", event_id); + } let status = cmd.status()?; if !status.success() { - tracing::warn!("on_inbound command exited with status: {}", status); + return Err(std::io::Error::other(format!( + "on_inbound command exited with status: {status}" + ))); } Ok(()) } diff --git a/crates/lxmf-tools/src/lxmd_cli.rs b/crates/lxmf-tools/src/lxmd_cli.rs index 56c3fcd..3f25ffa 100644 --- a/crates/lxmf-tools/src/lxmd_cli.rs +++ b/crates/lxmf-tools/src/lxmd_cli.rs @@ -46,6 +46,23 @@ pub struct Args { #[arg(short = 'p', long = "propagation-node")] pub propagation_node: bool, + /// Quarantine the legacy relay store and initialize the separate v2 store. + /// Run only after stopping all old relay writers and their auto-restart jobs. + #[arg(long, requires = "relay_writers_stopped")] + pub migrate_propagation_store: bool, + + /// Confirm all legacy app/daemon relay writers are stopped for migration. + #[arg(long, requires = "migrate_propagation_store")] + pub relay_writers_stopped: bool, + + /// Import an independently verified legacy opaque-ingress recovery manifest. + #[arg(long, requires_all = ["migrate_propagation_store", "recovery_manifest_sha256"])] + pub recover_propagation_manifest: Option, + + /// Separately approved SHA-256 of the exact recovery manifest file. + #[arg(long, requires = "recover_propagation_manifest")] + pub recovery_manifest_sha256: Option, + /// Executable to run when a message is received, overriding config. #[arg(short = 'i', long = "on-inbound", value_name = "PATH")] pub on_inbound: Option, diff --git a/tools/check-api-baseline.py b/tools/check-api-baseline.py index aee7c08..98e039c 100644 --- a/tools/check-api-baseline.py +++ b/tools/check-api-baseline.py @@ -97,7 +97,7 @@ def validate_metadata( ) -> list[dict[str, object]]: require_keys( config, {"schemaVersion", "tool", "baseline", "compatibilityFloor", "packages"}, - "metadata", + "metadata", {"approvedBreakingChanges"}, ) if config["schemaVersion"] != 2: fail("unsupported api-stability schema") @@ -111,6 +111,10 @@ def validate_metadata( "compatibility floor", ) + if "approvedBreakingChanges" in config: + require_keys(config["approvedBreakingChanges"], + {"releaseLine", "migrationGuide", "removed"}, "approved break") + tool = config.get("tool") if not isinstance(tool, dict): fail("tool contract is missing") diff --git a/tools/check-api-compatibility.py b/tools/check-api-compatibility.py index fc4aebc..f342215 100644 --- a/tools/check-api-compatibility.py +++ b/tools/check-api-compatibility.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 -"""Reject removals from the reviewed public-API compatibility floor.""" +"""Reject unapproved removals from the retained public-API compatibility floor.""" from __future__ import annotations import json +import re import subprocess import sys from pathlib import Path @@ -45,6 +46,48 @@ def load_floor_ledger(commit: str) -> dict[str, object]: fail(f"cannot read API ledger at compatibility floor {commit}") +def approved_removals(ledger: dict[str, object], version: str) -> dict[str, set[str]]: + """A breaking release allows exact reviewed lines, never a blanket waiver.""" + record = ledger.get("approvedBreakingChanges") + if record is None: + return {} + if not isinstance(record, dict) or set(record) != {"releaseLine", "migrationGuide", "removed"}: + fail("approved break needs releaseLine, migrationGuide and exact removed lines") + release_line = record["releaseLine"] + if not isinstance(release_line, str) or not re.fullmatch(r"\d+\.\d+", release_line): + fail("approved break release line is invalid") + if version.split(".")[:2] != release_line.split("."): + fail("approved break does not match the current workspace release line") + guide = record["migrationGuide"] + if not isinstance(guide, str) or not guide.startswith("api/migrations/"): + fail("approved break must link a public API migration guide") + guide_path = (ROOT / guide).resolve() + if not guide_path.is_relative_to(ROOT / "api/migrations") or not guide_path.is_file(): + fail("approved break migration guide is missing or outside its directory") + removed = record["removed"] + packages = {package["name"] for package in ledger["packages"]} + if not isinstance(removed, dict) or not removed or not set(removed).issubset(packages): + fail("approved removals must name existing packages") + result = {} + for package, lines in removed.items(): + if (not isinstance(lines, list) or not lines + or not all(isinstance(line, str) and line.strip() for line in lines) + or len(set(lines)) != len(lines)): + fail("approved removals must be unique nonempty exact API lines") + result[package] = set(lines) + return result + + +def validate_removed(package: str, removed: set[str], approved: dict[str, set[str]]) -> None: + allowed = approved.get(package, set()) + if removed != allowed: + for line in sorted(removed - allowed): + print(f"unapproved removal: {line}", file=sys.stderr) + for line in sorted(allowed - removed): + print(f"unused removal approval: {line}", file=sys.stderr) + fail(f"{package} removals differ from the exact approved migration") + + def main() -> None: metadata = subprocess.run( [sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT @@ -52,6 +95,16 @@ def main() -> None: if metadata.returncode != 0: fail("snapshot metadata is invalid") ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8")) + metadata_result = subprocess.run( + ["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"], + cwd=ROOT, capture_output=True, text=True, + ) + if metadata_result.returncode: + fail("cannot resolve workspace release version") + versions = {package["version"] for package in json.loads(metadata_result.stdout)["packages"]} + if len(versions) != 1: + fail("workspace release versions disagree") + approved = approved_removals(ledger, versions.pop()) floor = ledger.get("compatibilityFloor", {}).get("evidenceCommit") if not isinstance(floor, str): fail("api/stability.json has no compatibility-floor commit") @@ -79,12 +132,9 @@ def main() -> None: if removed: for line in removed: print(f"- {line}", file=sys.stderr) - if total_removed: - fail( - f"{total_removed} public API lines were removed from the compatibility floor; " - "the current policy permits additions only" - ) - print(f"api compatibility: additive-only (+{total_added}, -0)") + validate_removed(package["name"], set(removed), approved) + print(f"api compatibility: checked (+{total_added}, -{total_removed}); " + "unapproved removals forbidden") if __name__ == "__main__":