From e527b84bc30589a35f1982fe361b3dd2c1f67864 Mon Sep 17 00:00:00 2001 From: Antigravity Date: Fri, 27 Nov 2026 15:37:19 +0000 Subject: [PATCH] feat: bootstrap moon-i2p core protocol foundation --- .githooks/README.md | 21 ++ .githooks/pre-commit | 3 + .github/workflows/stable_check.yml | 46 +++ .gitignore | 6 + AGENTS.md | 53 +++ LICENSE | 202 +++++++++++ README.md | 48 +++ cmd/main/main.mbt | 4 + cmd/main/moon.pkg | 5 + cmd/main/pkg.generated.mbti | 12 + common/common_test.mbt | 109 ++++++ common/identity.mbt | 256 ++++++++++++++ common/moon.pkg | 4 + common/pkg.generated.mbti | 219 ++++++++++++ common/router_info.mbt | 244 +++++++++++++ common/types.mbt | 488 ++++++++++++++++++++++++++ crypto/chacha20.mbt | 384 +++++++++++++++++++++ crypto/crypto_test.mbt | 119 +++++++ crypto/hmac.mbt | 80 +++++ crypto/moon.pkg | 3 + crypto/pkg.generated.mbti | 59 ++++ crypto/sha256.mbt | 166 +++++++++ crypto/siphash.mbt | 80 +++++ crypto/x25519.mbt | 214 ++++++++++++ encoding/base32.mbt | 66 ++++ encoding/base64.mbt | 110 ++++++ encoding/binary.mbt | 325 ++++++++++++++++++ encoding/encoding_test.mbt | 81 +++++ encoding/moon.pkg | 1 + encoding/pkg.generated.mbti | 67 ++++ i2np/i2np_test.mbt | 96 ++++++ i2np/message.mbt | 483 ++++++++++++++++++++++++++ i2np/moon.pkg | 5 + i2np/pkg.generated.mbti | 92 +++++ moon.mod | 15 + moon.pkg | 8 + moon_i2p.mbt | 56 +++ moon_i2p_test.mbt | 12 + noise/moon.pkg | 7 + noise/noise_test.mbt | 82 +++++ noise/noise_xk.mbt | 529 +++++++++++++++++++++++++++++ noise/pkg.generated.mbti | 91 +++++ pkg.generated.mbti | 21 ++ sam/moon.pkg | 1 + sam/pkg.generated.mbti | 45 +++ sam/sam.mbt | 282 +++++++++++++++ sam/sam_test.mbt | 50 +++ 47 files changed, 5350 insertions(+) create mode 100644 .githooks/README.md create mode 100755 .githooks/pre-commit create mode 100644 .github/workflows/stable_check.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cmd/main/main.mbt create mode 100644 cmd/main/moon.pkg create mode 100644 cmd/main/pkg.generated.mbti create mode 100644 common/common_test.mbt create mode 100644 common/identity.mbt create mode 100644 common/moon.pkg create mode 100644 common/pkg.generated.mbti create mode 100644 common/router_info.mbt create mode 100644 common/types.mbt create mode 100644 crypto/chacha20.mbt create mode 100644 crypto/crypto_test.mbt create mode 100644 crypto/hmac.mbt create mode 100644 crypto/moon.pkg create mode 100644 crypto/pkg.generated.mbti create mode 100644 crypto/sha256.mbt create mode 100644 crypto/siphash.mbt create mode 100644 crypto/x25519.mbt create mode 100644 encoding/base32.mbt create mode 100644 encoding/base64.mbt create mode 100644 encoding/binary.mbt create mode 100644 encoding/encoding_test.mbt create mode 100644 encoding/moon.pkg create mode 100644 encoding/pkg.generated.mbti create mode 100644 i2np/i2np_test.mbt create mode 100644 i2np/message.mbt create mode 100644 i2np/moon.pkg create mode 100644 i2np/pkg.generated.mbti create mode 100644 moon.mod create mode 100644 moon.pkg create mode 100644 moon_i2p.mbt create mode 100644 moon_i2p_test.mbt create mode 100644 noise/moon.pkg create mode 100644 noise/noise_test.mbt create mode 100644 noise/noise_xk.mbt create mode 100644 noise/pkg.generated.mbti create mode 100644 pkg.generated.mbti create mode 100644 sam/moon.pkg create mode 100644 sam/pkg.generated.mbti create mode 100644 sam/sam.mbt create mode 100644 sam/sam_test.mbt diff --git a/.githooks/README.md b/.githooks/README.md new file mode 100644 index 0000000..61c0ad6 --- /dev/null +++ b/.githooks/README.md @@ -0,0 +1,21 @@ +# Git Hooks + +## Pre-commit Hook + +This pre-commit hook performs automatic checks before finalizing your commit. + +### Usage Instructions + +To use this pre-commit hook: + +1. Make the hook executable if it isn't already: + ```bash + chmod +x .githooks/pre-commit + ``` + +2. Configure Git to use the hooks in the .githooks directory: + ```bash + git config core.hooksPath .githooks + ``` + +3. The hook will automatically run when you execute `git commit` diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..e2a32b0 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,3 @@ +#!/bin/sh + +moon check \ No newline at end of file diff --git a/.github/workflows/stable_check.yml b/.github/workflows/stable_check.yml new file mode 100644 index 0000000..1908185 --- /dev/null +++ b/.github/workflows/stable_check.yml @@ -0,0 +1,46 @@ +name: check + +on: + push: + branches: + - main + pull_request: + +jobs: + check: + name: check (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + continue-on-error: false + steps: + - uses: actions/checkout@v4 + + - name: Install MoonBit toolchain + uses: moonbit-community/setup-moonbit@04293a8a813bfd4b6c2fce22701b52ae1050d100 + + - name: moon version + run: | + moon version --all + + - name: moon update + run: | + moon update + + - name: moon check + run: moon check --deny-warn + + - name: format diff + run: | + moon fmt + git diff --exit-code + + - name: moon test + run: | + moon test --target all + + - name: moon test --release + run: | + moon test --target all --release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..efa2da1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +_build/ +target/ +target +.mooncakes/ +.moonagent/ \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c0e8474 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,53 @@ +# Project Agents.md Guide + +This is a [MoonBit](https://docs.moonbitlang.com) project. + +You can browse and install extra skills here: + + +## Project Structure + +- MoonBit packages are organized per directory; each directory contains a + `moon.pkg` file listing its dependencies. Each package has its files and + blackbox test files (ending in `_test.mbt`) and whitebox test files (ending in + `_wbtest.mbt`). + +- In the toplevel directory, there is a `moon.mod` file listing module + metadata. + +## Coding convention + +- MoonBit code is organized in block style, each block is separated by `///|`, + the order of each block is irrelevant. In some refactorings, you can process + block by block independently. + +- Try to keep deprecated blocks in file called `deprecated.mbt` in each + directory. + +## Tooling + +- `moon fmt` is used to format your code properly. + +- `moon ide` provides project navigation helpers like `peek-def`, `outline`, and + `find-references`. See $moonbit-agent-guide for details. + +- `moon info` is used to update the generated interface of the package, each + package has a generated interface file `.mbti`, it is a brief formal + description of the package. If nothing in `.mbti` changes, this means your + change does not bring the visible changes to the external package users, it is + typically a safe refactoring. + +- In the last step, run `moon info && moon fmt` to update the interface and + format the code. Check the diffs of `.mbti` file to see if the changes are + expected. + +- Run `moon test` to check tests pass. MoonBit supports snapshot testing; when + changes affect outputs, run `moon test --update` to refresh snapshots. + +- Prefer `assert_eq` or `assert_true(pattern is Pattern(...))` for results that + are stable or very unlikely to change. For snapshot tests that record + structured debugging output, derive `Debug` and use `debug_inspect`, rather + than deriving `Show` for debugging. For solid, well-defined results (e.g. + scientific computations), prefer assertion tests. You can use + `moon coverage analyze > uncovered.log` to see which parts of your code are + not covered by tests. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d050cf3 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# moon-i2p + +A clean, zero-dependency, pure-[MoonBit](https://www.moonbitlang.com/) port of the modern **I2P (Invisible Internet Project)** protocol suite targeting `wasm`, `wasm-gc`, `js`, and `native`. + +## Architecture & Implemented Modules + +``` +moon-i2p/ +├── encoding/ # I2P Base64 (-/~), Base32 (.b32.i2p), big-endian Reader/Writer, UTF-8, Hex +├── crypto/ # Pure-MoonBit SHA-256, HMAC-SHA256, HKDF-SHA256, ChaCha20-Poly1305, X25519, SipHash-2-4 +├── common/ # Hash, KeyTypes, Certificate/KeyCertificate, Mapping, Destination, RouterIdentity, RouterInfo, Lease2, LeaseSet2 +├── i2np/ # 16-byte standard & 9-byte NTCP2 short headers, SHA-256 checksums, core I2NP messages +├── noise/ # Noise_XK_25519_ChaChaPoly_SHA256 handshake/transport + NTCP2 SipHash-2-4 length masking +├── sam/ # SAMv3 text protocol parser, serializer, and command builders +└── cmd/main/ # Demo CLI entrypoint +``` + +### Verified Test Vectors +Every cryptographic primitive in `crypto/` is verified against official standards: +- **SHA-256**: FIPS 180-4 / NIST test vectors +- **HMAC-SHA256**: RFC 4231 test cases 1 & 2 +- **HKDF-SHA256**: RFC 5869 test case 1 +- **ChaCha20-Poly1305 AEAD**: RFC 8439 Section 2.8.2 +- **X25519**: RFC 7748 Sections 5.2 & 6.1 +- **SipHash-2-4**: Official SipHash reference test vector + +## Running Checks & Tests + +```bash +moon check +moon test +moon test --target native +moon run cmd/main +``` + +## Roadmap + +1. **Phase 1–2 (Completed):** Core encoding, pure-MoonBit modern crypto, I2P Common Structures, I2NP messages, `Noise_XK_25519_ChaChaPoly_SHA256` state machine, NTCP2 SipHash length masking, and SAMv3 protocol codec. +2. **Phase 3 (Signatures & Ratchet):** + - Pure-MoonBit **Ed25519** signing & verification (`RouterInfo` & `LeaseSet2` signatures). + - **ECIES-X25519-AEAD-Ratchet** (Proposal 144) for Garlic encryption & end-to-end sessions. +3. **Phase 4 (Transports & Networking):** + - **NTCP2** full TCP transport (AES-256-CBC ephemeral key obfuscation, options/padding blocks, session manager). + - **SAMv3** live TCP client for interacting with an existing I2P/i2pd router. +4. **Phase 5 (Router Core):** + - **NetDB** & Floodfill DHT (Kademlia XOR routing with daily routing key derivation). + - **Tunnel** builder (`ShortTunnelBuild` Proposal 157), layered tunnel encryption, and tunnel pool management. + - **Streaming** & **Repliable Datagrams** libraries. diff --git a/cmd/main/main.mbt b/cmd/main/main.mbt new file mode 100644 index 0000000..123129c --- /dev/null +++ b/cmd/main/main.mbt @@ -0,0 +1,4 @@ +///| +fn main { + println(@lib.demo_summary()) +} diff --git a/cmd/main/moon.pkg b/cmd/main/moon.pkg new file mode 100644 index 0000000..0e4b593 --- /dev/null +++ b/cmd/main/moon.pkg @@ -0,0 +1,5 @@ +import { + "experiments/moon_i2p" @lib, +} + +pkgtype(kind: "executable") diff --git a/cmd/main/pkg.generated.mbti b/cmd/main/pkg.generated.mbti new file mode 100644 index 0000000..7b115d9 --- /dev/null +++ b/cmd/main/pkg.generated.mbti @@ -0,0 +1,12 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/cmd/main" + +// Values + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/common/common_test.mbt b/common/common_test.mbt new file mode 100644 index 0000000..45c7083 --- /dev/null +++ b/common/common_test.mbt @@ -0,0 +1,109 @@ +///| +test "Mapping canonical sorted encoding and round-trip" { + let m = @common.Mapping::new() + m.set("v", "2") + m.set("host", "127.0.0.1") + m.set("port", "12345") + m.set("caps", "LR") + let w = @encoding.Writer::new() + m.encode(w) + let raw = w.to_bytes() + let decoded = @common.Mapping::decode(@encoding.Reader::new(raw)) + assert_eq(decoded.length(), 4) + assert_eq(decoded.get("caps"), Some("LR")) + assert_eq(decoded.get("host"), Some("127.0.0.1")) + assert_eq(decoded.get("port"), Some("12345")) + assert_eq(decoded.get("v"), Some("2")) + // Verify canonical sorted order: caps, host, port, v + assert_eq(decoded.entries[0].0, "caps") + assert_eq(decoded.entries[1].0, "host") + assert_eq(decoded.entries[2].0, "port") + assert_eq(decoded.entries[3].0, "v") +} + +///| +test "Destination X25519+Ed25519 key extraction, Base64, and .b32.i2p address" { + let crypto_pub = Bytes::make(32, b'\x11') + let sig_pub = Bytes::make(32, b'\x22') + let dest = @common.Destination::new_x25519_ed25519(crypto_pub, sig_pub) + let raw = dest.to_bytes() + // 384 bytes keys + 1 byte type + 2 bytes len + 4 bytes KeyCert = 391 bytes + assert_eq(raw.length(), 391) + assert_eq(dest.inner.crypto_public_key(), crypto_pub) + assert_eq(dest.inner.signing_public_key(), sig_pub) + assert_eq(dest.inner.crypto_type(), X25519) + assert_eq(dest.inner.signing_type(), EdDsaSha512Ed25519) + + // Base64 round-trip + let b64 = dest.to_base64() + let restored = @common.Destination::from_base64(b64) + assert_eq(restored, dest) + + // .b32.i2p address is 52 base32 chars + ".b32.i2p" (60 chars total) + let b32 = dest.b32_address() + assert_eq(b32.length(), 60) + assert_true(b32.has_suffix(".b32.i2p")) +} + +///| +test "RouterInfo encode and decode round-trip" { + let ri_id = @common.RouterIdentity::new_x25519_ed25519( + Bytes::make(32, b'\x33'), + Bytes::make(32, b'\x44'), + ) + let addr_opts = @common.Mapping::from_entries([ + ("host", "192.0.2.10"), + ("port", "9001"), + ("v", "2"), + ]) + let addr = @common.RouterAddress::new(b'\x03', "NTCP2", addr_opts) + let ri_opts = @common.Mapping::from_entries([ + ("caps", "OR"), + ("netId", "2"), + ("router.version", "0.9.64"), + ]) + let ri : @common.RouterInfo = { + identity: ri_id, + published: 1700000000000UL, + addresses: [addr], + options: ri_opts, + signature: Bytes::make(64, b'\x55'), + } + let w = @encoding.Writer::new() + ri.encode(w) + let decoded = @common.RouterInfo::decode(@encoding.Reader::new(w.to_bytes())) + assert_eq(decoded.identity, ri.identity) + assert_eq(decoded.published, ri.published) + assert_eq(decoded.addresses.length(), 1) + assert_eq(decoded.addresses[0].transport_style, "NTCP2") + assert_eq(decoded.options.get("netId"), Some("2")) + assert_eq(decoded.signature, ri.signature) +} + +///| +test "LeaseSet2 encode and decode round-trip" { + let dest = @common.Destination::new_x25519_ed25519( + Bytes::make(32, b'\xaa'), + Bytes::make(32, b'\xbb'), + ) + let gw = @common.Hash::from_bytes(Bytes::make(32, b'\xcc')) + let lease : @common.Lease2 = { + tunnel_gw: gw, + tunnel_id: 424242U, + end_date_sec: 1700000600U, + } + let ls2 : @common.LeaseSet2 = { + destination: dest, + published_sec: 1700000000U, + expires_offset: 600U, + flags: 0U, + options: @common.Mapping::new(), + encryption_keys: [{ key_type: X25519, key_data: Bytes::make(32, b'\xdd'), }], + leases: [lease], + signature: Bytes::make(64, b'\xee'), + } + let w = @encoding.Writer::new() + ls2.encode(w) + let decoded = @common.LeaseSet2::decode(@encoding.Reader::new(w.to_bytes())) + assert_eq(decoded, ls2) +} diff --git a/common/identity.mbt b/common/identity.mbt new file mode 100644 index 0000000..ddbc00d --- /dev/null +++ b/common/identity.mbt @@ -0,0 +1,256 @@ +///| +/// KeysAndCert is the 387+ byte base structure shared by `RouterIdentity` and `Destination`: +/// - 256 bytes: crypto public key (with trailing padding if key < 256 bytes) +/// - 128 bytes: signing public key (right-aligned with leading padding if key < 128 bytes) +/// - 3+ bytes: `Certificate` (typically `Certificate::Key` for modern X25519 + Ed25519). +#derive(Eq, Debug) +pub struct KeysAndCert { + key_data : Bytes // exactly 384 bytes (256 + 128) + certificate : Certificate +} + +///| +/// Constructs a modern X25519 + Ed25519 `KeysAndCert` (CryptoType=4, SigType=7). +/// Per I2P spec: X25519 public key (32 bytes) is placed at bytes 0..32, +/// `padding` (320 bytes, or zero-filled if omitted) occupies bytes 32..352, +/// and Ed25519 signing public key (32 bytes) is right-aligned at bytes 352..384. +pub fn KeysAndCert::new_x25519_ed25519( + crypto_pub : Bytes, + signing_pub : Bytes, + padding~ : Bytes = b"", +) -> KeysAndCert raise CommonError { + if crypto_pub.length() != 32 { + raise InvalidLength( + "X25519 public key must be 32 bytes, got \{crypto_pub.length()}", + ) + } + if signing_pub.length() != 32 { + raise InvalidLength( + "Ed25519 public key must be 32 bytes, got \{signing_pub.length()}", + ) + } + let buf = FixedArray::make(384, b'\x00') + for i = 0; i < 32; i = i + 1 { + buf[i] = crypto_pub[i] + } + let pad_len = if padding.length() < 320 { padding.length() } else { 320 } + for i = 0; i < pad_len; i = i + 1 { + buf[32 + i] = padding[i] + } + for i = 0; i < 32; i = i + 1 { + buf[352 + i] = signing_pub[i] + } + let cert = Certificate::Key(KeyCertificate::new(EdDsaSha512Ed25519, X25519)) + { key_data: Bytes::from_array(buf), certificate: cert, } +} + +///| +pub fn KeysAndCert::crypto_type(self : KeysAndCert) -> CryptoPublicKeyType { + match self.certificate { + Key(kc) => kc.crypto_type + _ => ElGamal + } +} + +///| +pub fn KeysAndCert::signing_type(self : KeysAndCert) -> SigningPublicKeyType { + match self.certificate { + Key(kc) => kc.sig_type + _ => DsaSha1 + } +} + +///| +/// Extracts the active cryptography public key from the 384-byte key block. +pub fn KeysAndCert::crypto_public_key(self : KeysAndCert) -> Bytes { + let klen = self.crypto_type().key_length() + let take = if klen <= 256 { klen } else { 256 } + let out = FixedArray::make(take, b'\x00') + for i = 0; i < take; i = i + 1 { + out[i] = self.key_data[i] + } + Bytes::from_array(out) +} + +///| +/// Extracts the active signing public key (right-aligned in bytes 256..384, plus any excess in KeyCert). +pub fn KeysAndCert::signing_public_key(self : KeysAndCert) -> Bytes { + let klen = self.signing_type().public_key_length() + if klen <= 128 { + let start = 384 - klen + let out = FixedArray::make(klen, b'\x00') + for i = 0; i < klen; i = i + 1 { + out[i] = self.key_data[start + i] + } + Bytes::from_array(out) + } else { + let excess = match self.certificate { + Key(kc) => kc.excess_signing_key + _ => b"" + } + let out = FixedArray::make(128 + excess.length(), b'\x00') + for i = 0; i < 128; i = i + 1 { + out[i] = self.key_data[256 + i] + } + for i = 0; i < excess.length(); i = i + 1 { + out[128 + i] = excess[i] + } + Bytes::from_array(out) + } +} + +///| +pub fn KeysAndCert::encode(self : KeysAndCert, w : @encoding.Writer) -> Unit { + w.write_bytes(self.key_data) + self.certificate.encode(w) +} + +///| +pub fn KeysAndCert::to_bytes(self : KeysAndCert) -> Bytes { + let w = @encoding.Writer::new(capacity=391) + self.encode(w) + w.to_bytes() +} + +///| +pub fn KeysAndCert::decode( + r : @encoding.Reader, +) -> KeysAndCert raise CommonError { + let key_data = r.read_bytes(384) catch { e => raise Encoding(e) } + let certificate = Certificate::decode(r) + { key_data, certificate, } +} + +///| +pub fn KeysAndCert::hash(self : KeysAndCert) -> Hash { + Hash::sha256(self.to_bytes()) +} + +///| +/// I2P Destination: identifies a client endpoint (service or client tunnel) on the I2P network. +#derive(Eq, Debug) +pub struct Destination { + inner : KeysAndCert +} + +///| +pub fn Destination::new(inner : KeysAndCert) -> Destination { + { inner, } +} + +///| +pub fn Destination::new_x25519_ed25519( + crypto_pub : Bytes, + signing_pub : Bytes, + padding~ : Bytes = b"", +) -> Destination raise CommonError { + { inner: KeysAndCert::new_x25519_ed25519(crypto_pub, signing_pub, padding~), } +} + +///| +pub fn Destination::encode(self : Destination, w : @encoding.Writer) -> Unit { + self.inner.encode(w) +} + +///| +pub fn Destination::decode( + r : @encoding.Reader, +) -> Destination raise CommonError { + { inner: KeysAndCert::decode(r), } +} + +///| +pub fn Destination::to_bytes(self : Destination) -> Bytes { + self.inner.to_bytes() +} + +///| +pub fn Destination::hash(self : Destination) -> Hash { + self.inner.hash() +} + +///| +/// Returns the canonical `<52-char-base32>.b32.i2p` address for this Destination. +pub fn Destination::b32_address(self : Destination) -> String { + self.hash().to_b32_address() +} + +///| +pub fn Destination::to_base64(self : Destination) -> String { + @encoding.base64_encode(self.to_bytes()) +} + +///| +pub fn Destination::from_base64(s : String) -> Destination raise CommonError { + let raw = @encoding.base64_decode(s) catch { e => raise Encoding(e) } + let r = @encoding.Reader::new(raw) + Destination::decode(r) +} + +///| +/// I2P RouterIdentity: uniquely identifies an I2P router in the NetDB and NTCP2/SSU2 handshakes. +#derive(Eq, Debug) +pub struct RouterIdentity { + inner : KeysAndCert +} + +///| +pub fn RouterIdentity::new(inner : KeysAndCert) -> RouterIdentity { + { inner, } +} + +///| +pub fn RouterIdentity::new_x25519_ed25519( + crypto_pub : Bytes, + signing_pub : Bytes, + padding~ : Bytes = b"", +) -> RouterIdentity raise CommonError { + { inner: KeysAndCert::new_x25519_ed25519(crypto_pub, signing_pub, padding~), } +} + +///| +pub fn RouterIdentity::encode( + self : RouterIdentity, + w : @encoding.Writer, +) -> Unit { + self.inner.encode(w) +} + +///| +pub fn RouterIdentity::decode( + r : @encoding.Reader, +) -> RouterIdentity raise CommonError { + { inner: KeysAndCert::decode(r), } +} + +///| +pub fn RouterIdentity::to_bytes(self : RouterIdentity) -> Bytes { + self.inner.to_bytes() +} + +///| +pub fn RouterIdentity::hash(self : RouterIdentity) -> Hash { + self.inner.hash() +} + +///| +pub fn RouterIdentity::b32_address(self : RouterIdentity) -> String { + self.hash().to_b32_address() +} + +///| +pub fn RouterIdentity::signing_type( + self : RouterIdentity, +) -> SigningPublicKeyType { + self.inner.signing_type() +} + +///| +pub fn RouterIdentity::crypto_public_key(self : RouterIdentity) -> Bytes { + self.inner.crypto_public_key() +} + +///| +pub fn RouterIdentity::signing_public_key(self : RouterIdentity) -> Bytes { + self.inner.signing_public_key() +} diff --git a/common/moon.pkg b/common/moon.pkg new file mode 100644 index 0000000..2713f62 --- /dev/null +++ b/common/moon.pkg @@ -0,0 +1,4 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", +} diff --git a/common/pkg.generated.mbti b/common/pkg.generated.mbti new file mode 100644 index 0000000..c488395 --- /dev/null +++ b/common/pkg.generated.mbti @@ -0,0 +1,219 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/common" + +import { + "experiments/moon_i2p/encoding", + "moonbitlang/core/debug", +} + +// Values + +// Errors +#derive(Eq, @debug.Debug) +pub suberror CommonError { + Encoding(@encoding.EncodingError) + InvalidLength(String) + InvalidFormat(String) +} + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum Certificate { + Null + HashCash(Bytes) + Hidden + Signed(Bytes) + Multiple(Bytes) + Key(KeyCertificate) + Unknown(Byte, Bytes) +} +pub fn Certificate::decode(@encoding.Reader) -> Self raise CommonError +pub fn Certificate::encode(Self, @encoding.Writer) -> Unit + +#derive(Eq, @debug.Debug) +pub(all) enum CryptoPublicKeyType { + ElGamal + P256 + P384 + P521 + X25519 + Unknown(UInt32) +} +pub fn CryptoPublicKeyType::from_u16(UInt32) -> Self +pub fn CryptoPublicKeyType::key_length(Self) -> Int32 +pub fn CryptoPublicKeyType::to_u16(Self) -> UInt32 + +#derive(Eq, @debug.Debug) +pub struct Destination { + inner : KeysAndCert +} +pub fn Destination::b32_address(Self) -> String +pub fn Destination::decode(@encoding.Reader) -> Self raise CommonError +pub fn Destination::encode(Self, @encoding.Writer) -> Unit +pub fn Destination::from_base64(String) -> Self raise CommonError +pub fn Destination::hash(Self) -> Hash +pub fn Destination::new(KeysAndCert) -> Self +pub fn Destination::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError +pub fn Destination::to_base64(Self) -> String +pub fn Destination::to_bytes(Self) -> Bytes + +#derive(Eq, @debug.Debug) +pub struct Hash { + bytes : Bytes +} +pub fn Hash::as_bytes(Self) -> Bytes +pub fn Hash::decode(@encoding.Reader) -> Self raise CommonError +pub fn Hash::encode(Self, @encoding.Writer) -> Unit +pub fn Hash::from_bytes(Bytes) -> Self raise CommonError +pub fn Hash::sha256(Bytes) -> Self +pub fn Hash::to_b32_address(Self) -> String +pub fn Hash::to_base32(Self) -> String +pub fn Hash::to_base64(Self) -> String +pub fn Hash::to_hex(Self) -> String + +#derive(Eq, @debug.Debug) +pub(all) struct KeyCertificate { + sig_type : SigningPublicKeyType + crypto_type : CryptoPublicKeyType + excess_signing_key : Bytes + excess_crypto_key : Bytes +} +pub fn KeyCertificate::new(SigningPublicKeyType, CryptoPublicKeyType, excess_signing_key? : Bytes, excess_crypto_key? : Bytes) -> Self + +#derive(Eq, @debug.Debug) +pub struct KeysAndCert { + key_data : Bytes + certificate : Certificate +} +pub fn KeysAndCert::crypto_public_key(Self) -> Bytes +pub fn KeysAndCert::crypto_type(Self) -> CryptoPublicKeyType +pub fn KeysAndCert::decode(@encoding.Reader) -> Self raise CommonError +pub fn KeysAndCert::encode(Self, @encoding.Writer) -> Unit +pub fn KeysAndCert::hash(Self) -> Hash +pub fn KeysAndCert::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError +pub fn KeysAndCert::signing_public_key(Self) -> Bytes +pub fn KeysAndCert::signing_type(Self) -> SigningPublicKeyType +pub fn KeysAndCert::to_bytes(Self) -> Bytes + +#derive(Eq, @debug.Debug) +pub(all) struct Lease { + tunnel_gw : Hash + tunnel_id : UInt32 + end_date_ms : UInt64 +} +pub fn Lease::decode(@encoding.Reader) -> Self raise CommonError +pub fn Lease::encode(Self, @encoding.Writer) -> Unit + +#derive(Eq, @debug.Debug) +pub(all) struct Lease2 { + tunnel_gw : Hash + tunnel_id : UInt32 + end_date_sec : UInt32 +} +pub fn Lease2::decode(@encoding.Reader) -> Self raise CommonError +pub fn Lease2::encode(Self, @encoding.Writer) -> Unit + +#derive(Eq, @debug.Debug) +pub(all) struct LeaseSet2 { + destination : Destination + published_sec : UInt32 + expires_offset : UInt32 + flags : UInt32 + options : Mapping + encryption_keys : Array[LeaseSet2EncryptionKey] + leases : Array[Lease2] + signature : Bytes +} +pub fn LeaseSet2::decode(@encoding.Reader) -> Self raise CommonError +pub fn LeaseSet2::encode(Self, @encoding.Writer) -> Unit raise CommonError + +#derive(Eq, @debug.Debug) +pub(all) struct LeaseSet2EncryptionKey { + key_type : CryptoPublicKeyType + key_data : Bytes +} + +#derive(Eq, @debug.Debug) +pub struct Mapping { + entries : Array[(String, String)] +} +pub fn Mapping::decode(@encoding.Reader) -> Self raise CommonError +pub fn Mapping::encode(Self, @encoding.Writer) -> Unit raise CommonError +pub fn Mapping::from_entries(Array[(String, String)]) -> Self +pub fn Mapping::get(Self, String) -> String? +pub fn Mapping::length(Self) -> Int32 +pub fn Mapping::new() -> Self +pub fn Mapping::set(Self, String, String) -> Unit + +#derive(Eq, @debug.Debug) +pub(all) struct RouterAddress { + cost : Byte + expiration : UInt64 + transport_style : String + options : Mapping +} +pub fn RouterAddress::decode(@encoding.Reader) -> Self raise CommonError +pub fn RouterAddress::encode(Self, @encoding.Writer) -> Unit raise CommonError +pub fn RouterAddress::new(Byte, String, Mapping, expiration? : UInt64) -> Self + +#derive(Eq, @debug.Debug) +pub struct RouterIdentity { + inner : KeysAndCert +} +pub fn RouterIdentity::b32_address(Self) -> String +pub fn RouterIdentity::crypto_public_key(Self) -> Bytes +pub fn RouterIdentity::decode(@encoding.Reader) -> Self raise CommonError +pub fn RouterIdentity::encode(Self, @encoding.Writer) -> Unit +pub fn RouterIdentity::hash(Self) -> Hash +pub fn RouterIdentity::new(KeysAndCert) -> Self +pub fn RouterIdentity::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError +pub fn RouterIdentity::signing_public_key(Self) -> Bytes +pub fn RouterIdentity::signing_type(Self) -> SigningPublicKeyType +pub fn RouterIdentity::to_bytes(Self) -> Bytes + +#derive(Eq, @debug.Debug) +pub(all) struct RouterInfo { + identity : RouterIdentity + published : UInt64 + addresses : Array[RouterAddress] + options : Mapping + signature : Bytes +} +pub fn RouterInfo::decode(@encoding.Reader) -> Self raise CommonError +pub fn RouterInfo::encode(Self, @encoding.Writer) -> Unit raise CommonError +pub fn RouterInfo::unsigned_bytes(Self) -> Bytes raise CommonError + +#derive(Eq, @debug.Debug) +pub struct SessionKey { + bytes : Bytes +} +pub fn SessionKey::from_bytes(Bytes) -> Self raise CommonError + +#derive(Eq, @debug.Debug) +pub struct SessionTag { + bytes : Bytes +} +pub fn SessionTag::from_bytes(Bytes) -> Self raise CommonError + +#derive(Eq, @debug.Debug) +pub(all) enum SigningPublicKeyType { + DsaSha1 + EcdsaSha256P256 + EcdsaSha384P384 + EcdsaSha512P521 + RsaSha256_2048 + RsaSha384_3072 + RsaSha512_4096 + EdDsaSha512Ed25519 + EdDsaSha512Ed25519ph + RedDsaSha512Ed25519 + Unknown(UInt32) +} +pub fn SigningPublicKeyType::from_u16(UInt32) -> Self +pub fn SigningPublicKeyType::public_key_length(Self) -> Int32 +pub fn SigningPublicKeyType::signature_length(Self) -> Int32 +pub fn SigningPublicKeyType::to_u16(Self) -> UInt32 + +// Type aliases + +// Traits diff --git a/common/router_info.mbt b/common/router_info.mbt new file mode 100644 index 0000000..f072998 --- /dev/null +++ b/common/router_info.mbt @@ -0,0 +1,244 @@ +///| +/// RouterAddress: transport endpoint advertised inside a RouterInfo (e.g., NTCP2, SSU2). +#derive(Eq, Debug) +pub(all) struct RouterAddress { + cost : Byte + expiration : UInt64 // milliseconds since Unix epoch (0 = never) + transport_style : String + options : Mapping +} + +///| +pub fn RouterAddress::new( + cost : Byte, + transport_style : String, + options : Mapping, + expiration~ : UInt64 = 0UL, +) -> RouterAddress { + { cost, expiration, transport_style, options, } +} + +///| +pub fn RouterAddress::encode( + self : RouterAddress, + w : @encoding.Writer, +) -> Unit raise CommonError { + w.write_u8(self.cost) + w.write_u64_be(self.expiration) + w.write_i2p_string(self.transport_style) catch { + e => raise Encoding(e) + } + self.options.encode(w) +} + +///| +pub fn RouterAddress::decode( + r : @encoding.Reader, +) -> RouterAddress raise CommonError { + let cost = r.read_u8() catch { e => raise Encoding(e) } + let expiration = r.read_u64_be() catch { e => raise Encoding(e) } + let transport_style = r.read_i2p_string() catch { e => raise Encoding(e) } + let options = Mapping::decode(r) + { cost, expiration, transport_style, options, } +} + +///| +/// RouterInfo: NetDB record advertising a router's identity, transport addresses, and capabilities. +#derive(Eq, Debug) +pub(all) struct RouterInfo { + identity : RouterIdentity + published : UInt64 // milliseconds since Unix epoch + addresses : Array[RouterAddress] + options : Mapping + signature : Bytes +} + +///| +/// Encodes the unsigned body of RouterInfo (the exact bytes signed by `signature`). +pub fn RouterInfo::unsigned_bytes(self : RouterInfo) -> Bytes raise CommonError { + let w = @encoding.Writer::new(capacity=512) + self.identity.encode(w) + w.write_u64_be(self.published) + w.write_u8(self.addresses.length().to_byte()) + for addr in self.addresses { + addr.encode(w) + } + // peer_size is always 0 in I2P spec + w.write_u8(b'\x00') + self.options.encode(w) + w.to_bytes() +} + +///| +pub fn RouterInfo::encode( + self : RouterInfo, + w : @encoding.Writer, +) -> Unit raise CommonError { + w.write_bytes(self.unsigned_bytes()) + w.write_bytes(self.signature) +} + +///| +pub fn RouterInfo::decode(r : @encoding.Reader) -> RouterInfo raise CommonError { + let identity = RouterIdentity::decode(r) + let published = r.read_u64_be() catch { e => raise Encoding(e) } + let addr_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let addresses : Array[RouterAddress] = Array(capacity=addr_count) + for _i = 0; _i < addr_count; _i = _i + 1 { + addresses.push(RouterAddress::decode(r)) + } + let peer_size = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + for _i = 0; _i < peer_size; _i = _i + 1 { + let _ = Hash::decode(r) + } + let options = Mapping::decode(r) + let sig_len = identity.signing_type().signature_length() + let signature = if sig_len > 0 { + r.read_bytes(sig_len) catch { + e => raise Encoding(e) + } + } else { + r.read_remaining() + } + { identity, published, addresses, options, signature, } +} + +///| +/// Legacy Lease (44 bytes): 32-byte tunnel gateway hash, 4-byte tunnel ID, 8-byte ms end date. +#derive(Eq, Debug) +pub(all) struct Lease { + tunnel_gw : Hash + tunnel_id : UInt32 + end_date_ms : UInt64 +} + +///| +pub fn Lease::encode(self : Lease, w : @encoding.Writer) -> Unit { + self.tunnel_gw.encode(w) + w.write_u32_be(self.tunnel_id) + w.write_u64_be(self.end_date_ms) +} + +///| +pub fn Lease::decode(r : @encoding.Reader) -> Lease raise CommonError { + let tunnel_gw = Hash::decode(r) + let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } + let end_date_ms = r.read_u64_be() catch { e => raise Encoding(e) } + { tunnel_gw, tunnel_id, end_date_ms, } +} + +///| +/// Modern Lease2 (40 bytes, used in LeaseSet2): 32-byte tunnel gateway hash, 4-byte tunnel ID, +/// 4-byte end date in seconds since Unix epoch. +#derive(Eq, Debug) +pub(all) struct Lease2 { + tunnel_gw : Hash + tunnel_id : UInt32 + end_date_sec : UInt32 +} + +///| +pub fn Lease2::encode(self : Lease2, w : @encoding.Writer) -> Unit { + self.tunnel_gw.encode(w) + w.write_u32_be(self.tunnel_id) + w.write_u32_be(self.end_date_sec) +} + +///| +pub fn Lease2::decode(r : @encoding.Reader) -> Lease2 raise CommonError { + let tunnel_gw = Hash::decode(r) + let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } + let end_date_sec = r.read_u32_be() catch { e => raise Encoding(e) } + { tunnel_gw, tunnel_id, end_date_sec, } +} + +///| +/// Encryption key entry inside a LeaseSet2. +#derive(Eq, Debug) +pub(all) struct LeaseSet2EncryptionKey { + key_type : CryptoPublicKeyType + key_data : Bytes +} + +///| +/// Modern LeaseSet2 (I2P Proposal 123, NetDB type 3). +#derive(Eq, Debug) +pub(all) struct LeaseSet2 { + destination : Destination + published_sec : UInt32 + expires_offset : UInt32 // uint16 offset in seconds from published_sec + flags : UInt32 // uint16 + options : Mapping + encryption_keys : Array[LeaseSet2EncryptionKey] + leases : Array[Lease2] + signature : Bytes +} + +///| +pub fn LeaseSet2::encode( + self : LeaseSet2, + w : @encoding.Writer, +) -> Unit raise CommonError { + self.destination.encode(w) + w.write_u32_be(self.published_sec) + w.write_u16_be(self.expires_offset) + w.write_u16_be(self.flags) + self.options.encode(w) + w.write_u8(self.encryption_keys.length().to_byte()) + for ek in self.encryption_keys { + w.write_u16_be(ek.key_type.to_u16()) + w.write_u16_be(ek.key_data.length().reinterpret_as_uint()) + w.write_bytes(ek.key_data) + } + w.write_u8(self.leases.length().to_byte()) + for lease in self.leases { + lease.encode(w) + } + w.write_bytes(self.signature) +} + +///| +pub fn LeaseSet2::decode(r : @encoding.Reader) -> LeaseSet2 raise CommonError { + let destination = Destination::decode(r) + let published_sec = r.read_u32_be() catch { e => raise Encoding(e) } + let expires_offset = r.read_u16_be() catch { e => raise Encoding(e) } + let flags = r.read_u16_be() catch { e => raise Encoding(e) } + let options = Mapping::decode(r) + let key_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let encryption_keys : Array[LeaseSet2EncryptionKey] = Array( + capacity=key_count, + ) + for _i = 0; _i < key_count; _i = _i + 1 { + let kt = CryptoPublicKeyType::from_u16( + r.read_u16_be() catch { + e => raise Encoding(e) + }, + ) + let klen = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let kd = r.read_bytes(klen) catch { e => raise Encoding(e) } + encryption_keys.push({ key_type: kt, key_data: kd, }) + } + let lease_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let leases : Array[Lease2] = Array(capacity=lease_count) + for _i = 0; _i < lease_count; _i = _i + 1 { + leases.push(Lease2::decode(r)) + } + let sig_len = destination.inner.signing_type().signature_length() + let signature = if sig_len > 0 { + r.read_bytes(sig_len) catch { + e => raise Encoding(e) + } + } else { + r.read_remaining() + } + { + destination, + published_sec, + expires_offset, + flags, + options, + encryption_keys, + leases, + signature, + } +} diff --git a/common/types.mbt b/common/types.mbt new file mode 100644 index 0000000..9bc0310 --- /dev/null +++ b/common/types.mbt @@ -0,0 +1,488 @@ +///| +/// Errors raised when encoding, decoding, or validating I2P Common Structures. +#derive(Eq, Debug) +pub suberror CommonError { + Encoding(@encoding.EncodingError) + InvalidLength(String) + InvalidFormat(String) +} + +///| +/// A 32-byte SHA-256 hash used throughout I2P for RouterIdentities, Destinations, and NetDB keys. +#derive(Eq, Debug) +pub struct Hash { + bytes : Bytes +} + +///| +pub fn Hash::from_bytes(bytes : Bytes) -> Hash raise CommonError { + if bytes.length() != 32 { + raise InvalidLength("I2P Hash must be 32 bytes, got \{bytes.length()}") + } + { bytes, } +} + +///| +pub fn Hash::sha256(data : Bytes) -> Hash { + { bytes: @crypto.sha256(data), } +} + +///| +pub fn Hash::as_bytes(self : Hash) -> Bytes { + self.bytes +} + +///| +pub fn Hash::to_base32(self : Hash) -> String { + @encoding.base32_encode(self.bytes) +} + +///| +pub fn Hash::to_b32_address(self : Hash) -> String { + self.to_base32() + ".b32.i2p" +} + +///| +pub fn Hash::to_base64(self : Hash) -> String { + @encoding.base64_encode(self.bytes) +} + +///| +pub fn Hash::to_hex(self : Hash) -> String { + @encoding.hex_encode(self.bytes) +} + +///| +pub fn Hash::encode(self : Hash, w : @encoding.Writer) -> Unit { + w.write_bytes(self.bytes) +} + +///| +pub fn Hash::decode(r : @encoding.Reader) -> Hash raise CommonError { + let bytes = r.read_bytes(32) catch { e => raise Encoding(e) } + { bytes, } +} + +///| +/// 32-byte symmetric session key. +#derive(Eq, Debug) +pub struct SessionKey { + bytes : Bytes +} + +///| +pub fn SessionKey::from_bytes(bytes : Bytes) -> SessionKey raise CommonError { + if bytes.length() != 32 { + raise InvalidLength("SessionKey must be 32 bytes, got \{bytes.length()}") + } + { bytes, } +} + +///| +/// Session tag (8 bytes for ECIES-X25519-AEAD-Ratchet, or 32 bytes for legacy ElGamal/AES). +#derive(Eq, Debug) +pub struct SessionTag { + bytes : Bytes +} + +///| +pub fn SessionTag::from_bytes(bytes : Bytes) -> SessionTag raise CommonError { + if bytes.length() != 8 && bytes.length() != 32 { + raise InvalidLength( + "SessionTag must be 8 or 32 bytes, got \{bytes.length()}", + ) + } + { bytes, } +} + +///| +/// I2P Cryptography Public Key types (per I2P Common Structures specification). +#derive(Eq, Debug) +pub(all) enum CryptoPublicKeyType { + ElGamal // 0 (256 bytes) + P256 // 1 (64 bytes) + P384 // 2 (96 bytes) + P521 // 3 (132 bytes) + X25519 // 4 (32 bytes) - modern default + Unknown(UInt32) +} + +///| +pub fn CryptoPublicKeyType::to_u16(self : CryptoPublicKeyType) -> UInt32 { + match self { + ElGamal => 0U + P256 => 1U + P384 => 2U + P521 => 3U + X25519 => 4U + Unknown(v) => v + } +} + +///| +pub fn CryptoPublicKeyType::from_u16(v : UInt32) -> CryptoPublicKeyType { + match v { + 0U => ElGamal + 1U => P256 + 2U => P384 + 3U => P521 + 4U => X25519 + _ => Unknown(v) + } +} + +///| +pub fn CryptoPublicKeyType::key_length(self : CryptoPublicKeyType) -> Int32 { + match self { + ElGamal => 256 + P256 => 64 + P384 => 96 + P521 => 132 + X25519 => 32 + Unknown(_) => 0 + } +} + +///| +/// I2P Signing Public Key types (per I2P Common Structures specification). +#derive(Eq, Debug) +pub(all) enum SigningPublicKeyType { + DsaSha1 // 0 (128B key, 40B sig) + EcdsaSha256P256 // 1 (64B key, 64B sig) + EcdsaSha384P384 // 2 (96B key, 96B sig) + EcdsaSha512P521 // 3 (132B key, 132B sig) + RsaSha256_2048 // 4 (256B key, 256B sig) + RsaSha384_3072 // 5 (384B key, 384B sig) + RsaSha512_4096 // 6 (512B key, 512B sig) + EdDsaSha512Ed25519 // 7 (32B key, 64B sig) - modern default + EdDsaSha512Ed25519ph // 8 (32B key, 64B sig) + RedDsaSha512Ed25519 // 11 (32B key, 64B sig) + Unknown(UInt32) +} + +///| +pub fn SigningPublicKeyType::to_u16(self : SigningPublicKeyType) -> UInt32 { + match self { + DsaSha1 => 0U + EcdsaSha256P256 => 1U + EcdsaSha384P384 => 2U + EcdsaSha512P521 => 3U + RsaSha256_2048 => 4U + RsaSha384_3072 => 5U + RsaSha512_4096 => 6U + EdDsaSha512Ed25519 => 7U + EdDsaSha512Ed25519ph => 8U + RedDsaSha512Ed25519 => 11U + Unknown(v) => v + } +} + +///| +pub fn SigningPublicKeyType::from_u16(v : UInt32) -> SigningPublicKeyType { + match v { + 0U => DsaSha1 + 1U => EcdsaSha256P256 + 2U => EcdsaSha384P384 + 3U => EcdsaSha512P521 + 4U => RsaSha256_2048 + 5U => RsaSha384_3072 + 6U => RsaSha512_4096 + 7U => EdDsaSha512Ed25519 + 8U => EdDsaSha512Ed25519ph + 11U => RedDsaSha512Ed25519 + _ => Unknown(v) + } +} + +///| +pub fn SigningPublicKeyType::public_key_length( + self : SigningPublicKeyType, +) -> Int32 { + match self { + DsaSha1 => 128 + EcdsaSha256P256 => 64 + EcdsaSha384P384 => 96 + EcdsaSha512P521 => 132 + RsaSha256_2048 => 256 + RsaSha384_3072 => 384 + RsaSha512_4096 => 512 + EdDsaSha512Ed25519 | EdDsaSha512Ed25519ph | RedDsaSha512Ed25519 => 32 + Unknown(_) => 0 + } +} + +///| +pub fn SigningPublicKeyType::signature_length( + self : SigningPublicKeyType, +) -> Int32 { + match self { + DsaSha1 => 40 + EcdsaSha256P256 => 64 + EcdsaSha384P384 => 96 + EcdsaSha512P521 => 132 + RsaSha256_2048 => 256 + RsaSha384_3072 => 384 + RsaSha512_4096 => 512 + EdDsaSha512Ed25519 | EdDsaSha512Ed25519ph | RedDsaSha512Ed25519 => 64 + Unknown(_) => 0 + } +} + +///| +/// Key Certificate payload (Certificate type 5). +#derive(Eq, Debug) +pub(all) struct KeyCertificate { + sig_type : SigningPublicKeyType + crypto_type : CryptoPublicKeyType + excess_signing_key : Bytes + excess_crypto_key : Bytes +} + +///| +pub fn KeyCertificate::new( + sig_type : SigningPublicKeyType, + crypto_type : CryptoPublicKeyType, + excess_signing_key~ : Bytes = b"", + excess_crypto_key~ : Bytes = b"", +) -> KeyCertificate { + { sig_type, crypto_type, excess_signing_key, excess_crypto_key, } +} + +///| +/// I2P Certificate structure (1-byte type, 2-byte big-endian length, payload). +#derive(Eq, Debug) +pub(all) enum Certificate { + Null // 0 + HashCash(Bytes) // 1 + Hidden // 2 + Signed(Bytes) // 3 + Multiple(Bytes) // 4 + Key(KeyCertificate) // 5 + Unknown(Byte, Bytes) +} + +///| +pub fn Certificate::encode(self : Certificate, w : @encoding.Writer) -> Unit { + match self { + Null => { + w.write_u8(b'\x00') + w.write_u16_be(0U) + } + HashCash(p) => { + w.write_u8(b'\x01') + w.write_u16_be(p.length().reinterpret_as_uint()) + w.write_bytes(p) + } + Hidden => { + w.write_u8(b'\x02') + w.write_u16_be(0U) + } + Signed(p) => { + w.write_u8(b'\x03') + w.write_u16_be(p.length().reinterpret_as_uint()) + w.write_bytes(p) + } + Multiple(p) => { + w.write_u8(b'\x04') + w.write_u16_be(p.length().reinterpret_as_uint()) + w.write_bytes(p) + } + Key(kc) => { + let payload_len = 4 + + kc.excess_signing_key.length() + + kc.excess_crypto_key.length() + w.write_u8(b'\x05') + w.write_u16_be(payload_len.reinterpret_as_uint()) + w.write_u16_be(kc.sig_type.to_u16()) + w.write_u16_be(kc.crypto_type.to_u16()) + w.write_bytes(kc.excess_signing_key) + w.write_bytes(kc.excess_crypto_key) + } + Unknown(t, p) => { + w.write_u8(t) + w.write_u16_be(p.length().reinterpret_as_uint()) + w.write_bytes(p) + } + } +} + +///| +pub fn Certificate::decode( + r : @encoding.Reader, +) -> Certificate raise CommonError { + let cert_type = r.read_u8() catch { e => raise Encoding(e) } + let payload_len = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let payload = r.read_bytes(payload_len) catch { e => raise Encoding(e) } + match cert_type.to_int() { + 0 => { + if payload_len != 0 { + raise InvalidLength("Null certificate must have 0-byte payload") + } + Null + } + 1 => HashCash(payload) + 2 => Hidden + 3 => Signed(payload) + 4 => Multiple(payload) + 5 => { + if payload_len < 4 { + raise InvalidLength("Key certificate payload must be at least 4 bytes") + } + let pr = @encoding.Reader::new(payload) + let sig_type = SigningPublicKeyType::from_u16( + pr.read_u16_be() catch { + e => raise Encoding(e) + }, + ) + let crypto_type = CryptoPublicKeyType::from_u16( + pr.read_u16_be() catch { + e => raise Encoding(e) + }, + ) + let sig_excess = if sig_type.public_key_length() > 128 { + sig_type.public_key_length() - 128 + } else { + 0 + } + let excess_sig = if sig_excess > 0 && pr.remaining() >= sig_excess { + pr.read_bytes(sig_excess) catch { + e => raise Encoding(e) + } + } else { + b"" + } + let excess_crypto = pr.read_remaining() + Key({ + sig_type, + crypto_type, + excess_signing_key: excess_sig, + excess_crypto_key: excess_crypto, + }) + } + _ => Unknown(cert_type, payload) + } +} + +///| +/// I2P Mapping: 2-byte big-endian total byte length followed by `key=value;` pairs +/// where keys and values are I2P Strings. Canonical encoding sorts entries by key. +#derive(Eq, Debug) +pub struct Mapping { + entries : Array[(String, String)] +} + +///| +pub fn Mapping::new() -> Mapping { + { entries: [], } +} + +///| +pub fn Mapping::from_entries(entries : Array[(String, String)]) -> Mapping { + let copy : Array[(String, String)] = Array(capacity=entries.length()) + for entry in entries { + copy.push(entry) + } + { entries: copy, } +} + +///| +pub fn Mapping::set(self : Mapping, key : String, value : String) -> Unit { + for i = 0; i < self.entries.length(); i = i + 1 { + if self.entries[i].0 == key { + self.entries[i] = (key, value) + return + } + } + self.entries.push((key, value)) +} + +///| +pub fn Mapping::get(self : Mapping, key : String) -> String? { + for entry in self.entries { + if entry.0 == key { + return Some(entry.1) + } + } + None +} + +///| +pub fn Mapping::length(self : Mapping) -> Int32 { + self.entries.length() +} + +///| +fn bytes_lex_gt(a : Bytes, b : Bytes) -> Bool { + let min_len = if a.length() < b.length() { a.length() } else { b.length() } + for i = 0; i < min_len; i = i + 1 { + let ai = a[i].to_int() + let bi = b[i].to_int() + if ai != bi { + return ai > bi + } + } + a.length() > b.length() +} + +///| +/// Encodes the Mapping in canonical I2P order (sorted ascending by UTF-8 key bytes). +pub fn Mapping::encode( + self : Mapping, + w : @encoding.Writer, +) -> Unit raise CommonError { + let sorted : Array[(String, String)] = Array(capacity=self.entries.length()) + for entry in self.entries { + sorted.push(entry) + } + // Insertion sort by UTF-8 key bytes (canonical I2P Mapping sort order) + for i = 1; i < sorted.length(); i = i + 1 { + let cur = sorted[i] + let cur_bytes = @encoding.string_to_utf8_bytes(cur.0) + let mut j = i - 1 + while j >= 0 && + bytes_lex_gt(@encoding.string_to_utf8_bytes(sorted[j].0), cur_bytes) { + sorted[j + 1] = sorted[j] + j -= 1 + } + sorted[j + 1] = cur + } + let body = @encoding.Writer::new() + for entry in sorted { + body.write_i2p_string(entry.0) catch { + e => raise Encoding(e) + } + body.write_u8(b'\x3d') // '=' + body.write_i2p_string(entry.1) catch { + e => raise Encoding(e) + } + body.write_u8(b'\x3b') // ';' + } + let raw = body.to_bytes() + if raw.length() > 65535 { + raise InvalidLength("Mapping exceeds 65535 bytes: \{raw.length()}") + } + w.write_u16_be(raw.length().reinterpret_as_uint()) + w.write_bytes(raw) +} + +///| +pub fn Mapping::decode(r : @encoding.Reader) -> Mapping raise CommonError { + let byte_len = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let raw = r.read_bytes(byte_len) catch { e => raise Encoding(e) } + let mr = @encoding.Reader::new(raw) + let entries : Array[(String, String)] = [] + while !mr.is_eof() { + let k = mr.read_i2p_string() catch { e => raise Encoding(e) } + let eq = mr.read_u8() catch { e => raise Encoding(e) } + if eq != b'\x3d' { + raise InvalidFormat("expected '=' in Mapping, got \{eq}") + } + let v = mr.read_i2p_string() catch { e => raise Encoding(e) } + let semi = mr.read_u8() catch { e => raise Encoding(e) } + if semi != b'\x3b' { + raise InvalidFormat("expected ';' in Mapping, got \{semi}") + } + entries.push((k, v)) + } + { entries, } +} diff --git a/crypto/chacha20.mbt b/crypto/chacha20.mbt new file mode 100644 index 0000000..eeb2f46 --- /dev/null +++ b/crypto/chacha20.mbt @@ -0,0 +1,384 @@ +///| +fn rotl32(x : UInt32, n : Int32) -> UInt32 { + (x << n) | (x >> (32 - n)) +} + +///| +fn read_u32_le(data : Bytes, offset : Int32) -> UInt32 { + data[offset].to_uint() | + (data[offset + 1].to_uint() << 8) | + (data[offset + 2].to_uint() << 16) | + (data[offset + 3].to_uint() << 24) +} + +///| +fn write_u32_le(buf : FixedArray[Byte], offset : Int32, v : UInt32) -> Unit { + buf[offset] = (v & 0xFFU).to_byte() + buf[offset + 1] = ((v >> 8) & 0xFFU).to_byte() + buf[offset + 2] = ((v >> 16) & 0xFFU).to_byte() + buf[offset + 3] = ((v >> 24) & 0xFFU).to_byte() +} + +///| +fn quarter_round( + s : FixedArray[UInt32], + a : Int32, + b : Int32, + c : Int32, + d : Int32, +) -> Unit { + s[a] = s[a] + s[b] + s[d] = rotl32(s[d] ^ s[a], 16) + s[c] = s[c] + s[d] + s[b] = rotl32(s[b] ^ s[c], 12) + s[a] = s[a] + s[b] + s[d] = rotl32(s[d] ^ s[a], 8) + s[c] = s[c] + s[d] + s[b] = rotl32(s[b] ^ s[c], 7) +} + +///| +/// Computes a single 64-byte ChaCha20 keystream block (RFC 8439 Section 2.3). +pub fn chacha20_block( + key : Bytes, + counter : UInt32, + nonce : Bytes, +) -> Bytes raise CryptoError { + if key.length() != 32 { + raise InvalidKeyLength( + "ChaCha20 requires a 32-byte key, got \{key.length()}", + ) + } + if nonce.length() != 12 { + raise InvalidNonceLength( + "ChaCha20 requires a 12-byte nonce, got \{nonce.length()}", + ) + } + let state : FixedArray[UInt32] = [ + 0x61707865U, + 0x3320646eU, + 0x79622d32U, + 0x6b206574U, + read_u32_le(key, 0), + read_u32_le(key, 4), + read_u32_le(key, 8), + read_u32_le(key, 12), + read_u32_le(key, 16), + read_u32_le(key, 20), + read_u32_le(key, 24), + read_u32_le(key, 28), + counter, + read_u32_le(nonce, 0), + read_u32_le(nonce, 4), + read_u32_le(nonce, 8), + ] + let working = FixedArray::make(16, 0U) + for i = 0; i < 16; i = i + 1 { + working[i] = state[i] + } + for _i = 0; _i < 10; _i = _i + 1 { + quarter_round(working, 0, 4, 8, 12) + quarter_round(working, 1, 5, 9, 13) + quarter_round(working, 2, 6, 10, 14) + quarter_round(working, 3, 7, 11, 15) + quarter_round(working, 0, 5, 10, 15) + quarter_round(working, 1, 6, 11, 12) + quarter_round(working, 2, 7, 8, 13) + quarter_round(working, 3, 4, 9, 14) + } + let out = FixedArray::make(64, b'\x00') + for i = 0; i < 16; i = i + 1 { + write_u32_le(out, i * 4, working[i] + state[i]) + } + Bytes::from_array(out) +} + +///| +/// Encrypts or decrypts `input` with ChaCha20 starting at `counter` (RFC 8439 Section 2.4). +pub fn chacha20_xor( + key : Bytes, + counter : UInt32, + nonce : Bytes, + input : Bytes, +) -> Bytes raise CryptoError { + if key.length() != 32 { + raise InvalidKeyLength( + "ChaCha20 requires a 32-byte key, got \{key.length()}", + ) + } + if nonce.length() != 12 { + raise InvalidNonceLength( + "ChaCha20 requires a 12-byte nonce, got \{nonce.length()}", + ) + } + let len = input.length() + let out = FixedArray::make(len, b'\x00') + let mut ctr = counter + let mut offset = 0 + while offset < len { + let block = chacha20_block(key, ctr, nonce) + let chunk = if len - offset < 64 { len - offset } else { 64 } + for i = 0; i < chunk; i = i + 1 { + out[offset + i] = (input[offset + i].to_int() ^ block[i].to_int()).to_byte() + } + offset += chunk + ctr = ctr + 1U + } + Bytes::from_array(out) +} + +///| +/// Computes the 16-byte Poly1305 MAC (RFC 8439 Section 2.5). +/// `key` must be a 32-byte one-time key. +pub fn poly1305_mac(key : Bytes, msg : Bytes) -> Bytes raise CryptoError { + if key.length() != 32 { + raise InvalidKeyLength( + "Poly1305 requires a 32-byte one-time key, got \{key.length()}", + ) + } + // Load and clamp r (first 16 bytes) into 5 x 26-bit limbs + let t0 = read_u32_le(key, 0).to_uint64() + let t1 = read_u32_le(key, 4).to_uint64() + let t2 = read_u32_le(key, 8).to_uint64() + let t3 = read_u32_le(key, 12).to_uint64() + + let r0 = t0 & 0x03ffffffUL + let r1 = ((t0 >> 26) | (t1 << 6)) & 0x03ffff03UL + let r2 = ((t1 >> 20) | (t2 << 12)) & 0x03ffc0ffUL + let r3 = ((t2 >> 14) | (t3 << 18)) & 0x03f03fffUL + let r4 = (t3 >> 8) & 0x000fffffUL + + let s1 = r1 * 5UL + let s2 = r2 * 5UL + let s3 = r3 * 5UL + let s4 = r4 * 5UL + + let mut h0 = 0UL + let mut h1 = 0UL + let mut h2 = 0UL + let mut h3 = 0UL + let mut h4 = 0UL + + let len = msg.length() + let mut offset = 0 + while offset < len { + let rem = len - offset + let block_len = if rem >= 16 { 16 } else { rem } + let blk = FixedArray::make(16, b'\x00') + for i = 0; i < block_len; i = i + 1 { + blk[i] = msg[offset + i] + } + let hibit = if block_len == 16 { + 1UL << 24 + } else { + blk[block_len] = b'\x01' + 0UL + } + let b_bytes = Bytes::from_array(blk) + let m0 = read_u32_le(b_bytes, 0).to_uint64() + let m1 = read_u32_le(b_bytes, 4).to_uint64() + let m2 = read_u32_le(b_bytes, 8).to_uint64() + let m3 = read_u32_le(b_bytes, 12).to_uint64() + + h0 = h0 + (m0 & 0x03ffffffUL) + h1 = h1 + (((m0 >> 26) | (m1 << 6)) & 0x03ffffffUL) + h2 = h2 + (((m1 >> 20) | (m2 << 12)) & 0x03ffffffUL) + h3 = h3 + (((m2 >> 14) | (m3 << 18)) & 0x03ffffffUL) + h4 = h4 + (m3 >> 8) + hibit + + let d0 = h0 * r0 + h1 * s4 + h2 * s3 + h3 * s2 + h4 * s1 + let mut d1 = h0 * r1 + h1 * r0 + h2 * s4 + h3 * s3 + h4 * s2 + let mut d2 = h0 * r2 + h1 * r1 + h2 * r0 + h3 * s4 + h4 * s3 + let mut d3 = h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * s4 + let mut d4 = h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0 + + let mut c = d0 >> 26 + h0 = d0 & 0x03ffffffUL + d1 = d1 + c + c = d1 >> 26 + h1 = d1 & 0x03ffffffUL + d2 = d2 + c + c = d2 >> 26 + h2 = d2 & 0x03ffffffUL + d3 = d3 + c + c = d3 >> 26 + h3 = d3 & 0x03ffffffUL + d4 = d4 + c + c = d4 >> 26 + h4 = d4 & 0x03ffffffUL + h0 = h0 + c * 5UL + c = h0 >> 26 + h0 = h0 & 0x03ffffffUL + h1 = h1 + c + + offset += block_len + } + + // Final carry propagation + let mut c = h1 >> 26 + h1 = h1 & 0x03ffffffUL + h2 = h2 + c + c = h2 >> 26 + h2 = h2 & 0x03ffffffUL + h3 = h3 + c + c = h3 >> 26 + h3 = h3 & 0x03ffffffUL + h4 = h4 + c + c = h4 >> 26 + h4 = h4 & 0x03ffffffUL + h0 = h0 + c * 5UL + c = h0 >> 26 + h0 = h0 & 0x03ffffffUL + h1 = h1 + c + + // Compute h + 5 - 2^130 + let mut g0 = h0 + 5UL + c = g0 >> 26 + g0 = g0 & 0x03ffffffUL + let mut g1 = h1 + c + c = g1 >> 26 + g1 = g1 & 0x03ffffffUL + let mut g2 = h2 + c + c = g2 >> 26 + g2 = g2 & 0x03ffffffUL + let mut g3 = h3 + c + c = g3 >> 26 + g3 = g3 & 0x03ffffffUL + let g4 = h4 + c - (1UL << 26) + + // Select h if h < p else g (constant-time) + let mask = (g4 >> 63) - 1UL // all 1s if g4 >= 0 (i.e. h >= p), 0 otherwise + g0 = g0 & mask + g1 = g1 & mask + g2 = g2 & mask + g3 = g3 & mask + let g4_masked = g4 & mask + let nmask = mask.lnot() + h0 = (h0 & nmask) | g0 + h1 = (h1 & nmask) | g1 + h2 = (h2 & nmask) | g2 + h3 = (h3 & nmask) | g3 + h4 = (h4 & nmask) | g4_masked + + // Pack 5 x 26-bit limbs into 4 x 32-bit words + let f0 = (h0 | (h1 << 26)) & 0xffffffffUL + let f1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffffUL + let f2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffffUL + let f3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffffUL + + // Add s (second 16 bytes of key) mod 2^128 + let mut acc = f0 + read_u32_le(key, 16).to_uint64() + let w0 = (acc & 0xffffffffUL).to_uint() + acc = f1 + read_u32_le(key, 20).to_uint64() + (acc >> 32) + let w1 = (acc & 0xffffffffUL).to_uint() + acc = f2 + read_u32_le(key, 24).to_uint64() + (acc >> 32) + let w2 = (acc & 0xffffffffUL).to_uint() + acc = f3 + read_u32_le(key, 28).to_uint64() + (acc >> 32) + let w3 = (acc & 0xffffffffUL).to_uint() + + let out = FixedArray::make(16, b'\x00') + write_u32_le(out, 0, w0) + write_u32_le(out, 4, w1) + write_u32_le(out, 8, w2) + write_u32_le(out, 12, w3) + Bytes::from_array(out) +} + +///| +fn build_aead_mac_data(aad : Bytes, ciphertext : Bytes) -> Bytes { + let pad16 = fn(n : Int32) -> Int32 { + let rem = n % 16 + if rem == 0 { + 0 + } else { + 16 - rem + } + } + let aad_pad = pad16(aad.length()) + let ct_pad = pad16(ciphertext.length()) + let total = aad.length() + aad_pad + ciphertext.length() + ct_pad + 16 + let buf = FixedArray::make(total, b'\x00') + let mut pos = 0 + for i = 0; i < aad.length(); i = i + 1 { + buf[pos] = aad[i] + pos += 1 + } + pos += aad_pad + for i = 0; i < ciphertext.length(); i = i + 1 { + buf[pos] = ciphertext[i] + pos += 1 + } + pos += ct_pad + let aad_len = aad.length().to_uint64() + let ct_len = ciphertext.length().to_uint64() + for i = 0; i < 8; i = i + 1 { + buf[pos + i] = ((aad_len >> (i * 8)) & 0xFFUL).to_byte() + buf[pos + 8 + i] = ((ct_len >> (i * 8)) & 0xFFUL).to_byte() + } + Bytes::from_array(buf) +} + +///| +/// AEAD_CHACHA20_POLY1305 encryption (RFC 8439 Section 2.8). +/// Returns `ciphertext || 16-byte tag`. +pub fn aead_chacha20_poly1305_encrypt( + key : Bytes, + nonce : Bytes, + aad : Bytes, + plaintext : Bytes, +) -> Bytes raise CryptoError { + let otk_block = chacha20_block(key, 0U, nonce) + let otk = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + otk[i] = otk_block[i] + } + let ciphertext = chacha20_xor(key, 1U, nonce, plaintext) + let mac_data = build_aead_mac_data(aad, ciphertext) + let tag = poly1305_mac(Bytes::from_array(otk), mac_data) + + let out = FixedArray::make(ciphertext.length() + 16, b'\x00') + for i = 0; i < ciphertext.length(); i = i + 1 { + out[i] = ciphertext[i] + } + for i = 0; i < 16; i = i + 1 { + out[ciphertext.length() + i] = tag[i] + } + Bytes::from_array(out) +} + +///| +/// AEAD_CHACHA20_POLY1305 decryption (RFC 8439 Section 2.8). +/// Expects `ciphertext_and_tag` to be `ciphertext || 16-byte tag`. +pub fn aead_chacha20_poly1305_decrypt( + key : Bytes, + nonce : Bytes, + aad : Bytes, + ciphertext_and_tag : Bytes, +) -> Bytes raise CryptoError { + if ciphertext_and_tag.length() < 16 { + raise AuthenticationFailed + } + let ct_len = ciphertext_and_tag.length() - 16 + let ct_arr = FixedArray::make(ct_len, b'\x00') + for i = 0; i < ct_len; i = i + 1 { + ct_arr[i] = ciphertext_and_tag[i] + } + let ciphertext = Bytes::from_array(ct_arr) + let tag_arr = FixedArray::make(16, b'\x00') + for i = 0; i < 16; i = i + 1 { + tag_arr[i] = ciphertext_and_tag[ct_len + i] + } + let expected_tag = Bytes::from_array(tag_arr) + + let otk_block = chacha20_block(key, 0U, nonce) + let otk = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + otk[i] = otk_block[i] + } + let mac_data = build_aead_mac_data(aad, ciphertext) + let computed_tag = poly1305_mac(Bytes::from_array(otk), mac_data) + if !ct_eq(computed_tag, expected_tag) { + raise AuthenticationFailed + } + chacha20_xor(key, 1U, nonce, ciphertext) +} diff --git a/crypto/crypto_test.mbt b/crypto/crypto_test.mbt new file mode 100644 index 0000000..4f45d89 --- /dev/null +++ b/crypto/crypto_test.mbt @@ -0,0 +1,119 @@ +///| +test "sha256 NIST standard test vectors" { + assert_eq( + @encoding.hex_encode(@crypto.sha256(b"")), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ) + assert_eq( + @encoding.hex_encode(@crypto.sha256(b"abc")), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ) + assert_eq( + @encoding.hex_encode( + @crypto.sha256( + b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + ), + ), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", + ) +} + +///| +test "hmac_sha256 RFC 4231 test cases 1 and 2" { + // Case 1 + let key1 = Bytes::make(20, b'\x0b') + let data1 = b"Hi There" + assert_eq( + @encoding.hex_encode(@crypto.hmac_sha256(key1, data1)), + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7", + ) + // Case 2 + let key2 = b"Jefe" + let data2 = b"what do ya want for nothing?" + assert_eq( + @encoding.hex_encode(@crypto.hmac_sha256(key2, data2)), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843", + ) +} + +///| +test "hkdf_sha256 RFC 5869 test case 1" { + let ikm = @encoding.hex_decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b") + let salt = @encoding.hex_decode("000102030405060708090a0b0c") + let info = @encoding.hex_decode("f0f1f2f3f4f5f6f7f8f9") + let prk = @crypto.hkdf_extract(salt, ikm) + assert_eq( + @encoding.hex_encode(prk), + "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", + ) + let okm = @crypto.hkdf_expand(prk, info, 42) + assert_eq( + @encoding.hex_encode(okm), + "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", + ) +} + +///| +test "chacha20_poly1305 AEAD RFC 8439 Section 2.8.2" { + let key = @encoding.hex_decode( + "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", + ) + let nonce = @encoding.hex_decode("070000004041424344454647") + let aad = @encoding.hex_decode("50515253c0c1c2c3c4c5c6c7") + let pt = b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it." + let expected_ct_and_tag = @encoding.hex_decode( + "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd0600691", + ) + let ct_and_tag = @crypto.aead_chacha20_poly1305_encrypt(key, nonce, aad, pt) + assert_eq(ct_and_tag, expected_ct_and_tag) + let opened = @crypto.aead_chacha20_poly1305_decrypt( + key, nonce, aad, ct_and_tag, + ) + assert_eq(opened, pt) +} + +///| +test "x25519 RFC 7748 Section 5.2 and 6.1 test vectors" { + // Section 5.2 scalar multiplication + let scalar = @encoding.hex_decode( + "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", + ) + let u_coord = @encoding.hex_decode( + "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", + ) + let expected = "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552" + assert_eq(@encoding.hex_encode(@crypto.x25519(scalar, u_coord)), expected) + + // Section 6.1 Diffie-Hellman key exchange + let alice_priv = @encoding.hex_decode( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + ) + let alice_pub = @crypto.x25519_public_key(alice_priv) + assert_eq( + @encoding.hex_encode(alice_pub), + "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a", + ) + let bob_priv = @encoding.hex_decode( + "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", + ) + let bob_pub = @crypto.x25519_public_key(bob_priv) + assert_eq( + @encoding.hex_encode(bob_pub), + "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", + ) + let shared_a = @crypto.x25519(alice_priv, bob_pub) + let shared_b = @crypto.x25519(bob_priv, alice_pub) + assert_eq(shared_a, shared_b) + assert_eq( + @encoding.hex_encode(shared_a), + "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742", + ) +} + +///| +test "siphash_2_4 official test vector" { + // Key = 00 01 ... 0f, msg = 00 01 ... 0e (15 bytes) -> 0xa129ca6149be45e5 + let key = @encoding.hex_decode("000102030405060708090a0b0c0d0e0f") + let msg = @encoding.hex_decode("000102030405060708090a0b0c0d0e") + assert_eq(@crypto.siphash_2_4(key, msg), 0xa129ca6149be45e5UL) +} diff --git a/crypto/hmac.mbt b/crypto/hmac.mbt new file mode 100644 index 0000000..2019042 --- /dev/null +++ b/crypto/hmac.mbt @@ -0,0 +1,80 @@ +///| +/// Computes HMAC-SHA256 (RFC 2104 / RFC 4231). +pub fn hmac_sha256(key : Bytes, data : Bytes) -> Bytes { + let block_key = FixedArray::make(64, b'\x00') + let effective_key = if key.length() > 64 { sha256(key) } else { key } + for i = 0; i < effective_key.length(); i = i + 1 { + block_key[i] = effective_key[i] + } + let ipad = FixedArray::make(64, b'\x00') + let opad = FixedArray::make(64, b'\x00') + for i = 0; i < 64; i = i + 1 { + ipad[i] = (block_key[i].to_int() ^ 0x36).to_byte() + opad[i] = (block_key[i].to_int() ^ 0x5c).to_byte() + } + let inner = Sha256::new() + inner.update(Bytes::from_array(ipad)) + inner.update(data) + let inner_digest = inner.finalize() + + let outer = Sha256::new() + outer.update(Bytes::from_array(opad)) + outer.update(inner_digest) + outer.finalize() +} + +///| +/// HKDF-Extract (RFC 5869) using SHA-256. +pub fn hkdf_extract(salt : Bytes, ikm : Bytes) -> Bytes { + let actual_salt = if salt.length() == 0 { + Bytes::make(32, b'\x00') + } else { + salt + } + hmac_sha256(actual_salt, ikm) +} + +///| +/// HKDF-Expand (RFC 5869) using SHA-256. +pub fn hkdf_expand( + prk : Bytes, + info : Bytes, + length : Int32, +) -> Bytes raise CryptoError { + if length < 0 || length > 255 * 32 { + raise InvalidLength("HKDF-Expand output length out of range: \{length}") + } + if length == 0 { + return b"" + } + let n = (length + 31) / 32 + let out : Array[Byte] = Array(capacity=length) + let mut prev : Bytes = b"" + for i = 1; i <= n; i = i + 1 { + let msg : Array[Byte] = Array(capacity=prev.length() + info.length() + 1) + for j = 0; j < prev.length(); j = j + 1 { + msg.push(prev[j]) + } + for j = 0; j < info.length(); j = j + 1 { + msg.push(info[j]) + } + msg.push(i.to_byte()) + prev = hmac_sha256(prk, Bytes::from_array(msg)) + for j = 0; j < prev.length() && out.length() < length; j = j + 1 { + out.push(prev[j]) + } + } + Bytes::from_array(out) +} + +///| +/// Full HKDF-SHA256 (Extract + Expand, RFC 5869). +pub fn hkdf( + salt : Bytes, + ikm : Bytes, + info : Bytes, + length : Int32, +) -> Bytes raise CryptoError { + let prk = hkdf_extract(salt, ikm) + hkdf_expand(prk, info, length) +} diff --git a/crypto/moon.pkg b/crypto/moon.pkg new file mode 100644 index 0000000..6727d16 --- /dev/null +++ b/crypto/moon.pkg @@ -0,0 +1,3 @@ +import { + "experiments/moon_i2p/encoding", +} for "test" diff --git a/crypto/pkg.generated.mbti b/crypto/pkg.generated.mbti new file mode 100644 index 0000000..d91164c --- /dev/null +++ b/crypto/pkg.generated.mbti @@ -0,0 +1,59 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/crypto" + +import { + "moonbitlang/core/debug", +} + +// Values +pub fn aead_chacha20_poly1305_decrypt(Bytes, Bytes, Bytes, Bytes) -> Bytes raise CryptoError + +pub fn aead_chacha20_poly1305_encrypt(Bytes, Bytes, Bytes, Bytes) -> Bytes raise CryptoError + +pub fn chacha20_block(Bytes, UInt32, Bytes) -> Bytes raise CryptoError + +pub fn chacha20_xor(Bytes, UInt32, Bytes, Bytes) -> Bytes raise CryptoError + +pub fn ct_eq(Bytes, Bytes) -> Bool + +pub fn hkdf(Bytes, Bytes, Bytes, Int32) -> Bytes raise CryptoError + +pub fn hkdf_expand(Bytes, Bytes, Int32) -> Bytes raise CryptoError + +pub fn hkdf_extract(Bytes, Bytes) -> Bytes + +pub fn hmac_sha256(Bytes, Bytes) -> Bytes + +pub fn poly1305_mac(Bytes, Bytes) -> Bytes raise CryptoError + +pub fn sha256(Bytes) -> Bytes + +pub fn siphash_2_4(Bytes, Bytes) -> UInt64 raise CryptoError + +pub fn x25519(Bytes, Bytes) -> Bytes raise CryptoError + +pub fn x25519_public_key(Bytes) -> Bytes raise CryptoError + +// Errors +#derive(Eq, @debug.Debug) +pub suberror CryptoError { + InvalidKeyLength(String) + InvalidNonceLength(String) + InvalidLength(String) + AuthenticationFailed +} + +// Types and methods +pub struct Sha256 { + state : FixedArray[UInt32] + block : FixedArray[Byte] + mut block_len : Int32 + mut total_len : UInt64 +} +pub fn Sha256::finalize(Self) -> Bytes +pub fn Sha256::new() -> Self +pub fn Sha256::update(Self, Bytes) -> Unit + +// Type aliases + +// Traits diff --git a/crypto/sha256.mbt b/crypto/sha256.mbt new file mode 100644 index 0000000..b226431 --- /dev/null +++ b/crypto/sha256.mbt @@ -0,0 +1,166 @@ +///| +/// Cryptographic errors raised by I2P crypto primitives. +#derive(Eq, Debug) +pub suberror CryptoError { + InvalidKeyLength(String) + InvalidNonceLength(String) + InvalidLength(String) + AuthenticationFailed +} + +///| +/// Constant-time equality comparison for two byte slices. +pub fn ct_eq(a : Bytes, b : Bytes) -> Bool { + if a.length() != b.length() { + return false + } + let mut diff = 0 + for i = 0; i < a.length(); i = i + 1 { + diff = diff | (a[i].to_int() ^ b[i].to_int()) + } + diff == 0 +} + +///| +let sha256_k : FixedArray[UInt32] = [ + 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U, 0x923f82a4U, + 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, 0x72be5d74U, 0x80deb1feU, + 0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, + 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, + 0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, + 0x53380d13U, 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU, + 0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U, 0x19a4c116U, + 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U, + 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, + 0xc67178f2U, +] + +///| +fn rotr32(x : UInt32, n : Int32) -> UInt32 { + (x >> n) | (x << (32 - n)) +} + +///| +/// Incremental SHA-256 hasher (FIPS 180-4). +pub struct Sha256 { + state : FixedArray[UInt32] + block : FixedArray[Byte] + mut block_len : Int32 + mut total_len : UInt64 +} + +///| +pub fn Sha256::new() -> Sha256 { + { + state: [ + 0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU, + 0x1f83d9abU, 0x5be0cd19U, + ], + block: FixedArray::make(64, b'\x00'), + block_len: 0, + total_len: 0UL, + } +} + +///| +fn Sha256::compress(self : Sha256) -> Unit { + let w = FixedArray::make(64, 0U) + for i = 0; i < 16; i = i + 1 { + let j = i * 4 + w[i] = (self.block[j].to_uint() << 24) | + (self.block[j + 1].to_uint() << 16) | + (self.block[j + 2].to_uint() << 8) | + self.block[j + 3].to_uint() + } + for i = 16; i < 64; i = i + 1 { + let s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >> 3) + let s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >> 10) + w[i] = w[i - 16] + s0 + w[i - 7] + s1 + } + let mut a = self.state[0] + let mut b = self.state[1] + let mut c = self.state[2] + let mut d = self.state[3] + let mut e = self.state[4] + let mut f = self.state[5] + let mut g = self.state[6] + let mut h = self.state[7] + for i = 0; i < 64; i = i + 1 { + let s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) + let ch = (e & f) ^ (e.lnot() & g) + let temp1 = h + s1 + ch + sha256_k[i] + w[i] + let s0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) + let maj = (a & b) ^ (a & c) ^ (b & c) + let temp2 = s0 + maj + h = g + g = f + f = e + e = d + temp1 + d = c + c = b + b = a + a = temp1 + temp2 + } + self.state[0] = self.state[0] + a + self.state[1] = self.state[1] + b + self.state[2] = self.state[2] + c + self.state[3] = self.state[3] + d + self.state[4] = self.state[4] + e + self.state[5] = self.state[5] + f + self.state[6] = self.state[6] + g + self.state[7] = self.state[7] + h +} + +///| +pub fn Sha256::update(self : Sha256, data : Bytes) -> Unit { + let len = data.length() + self.total_len = self.total_len + len.to_uint64() + for i = 0; i < len; i = i + 1 { + self.block[self.block_len] = data[i] + self.block_len += 1 + if self.block_len == 64 { + self.compress() + self.block_len = 0 + } + } +} + +///| +pub fn Sha256::finalize(self : Sha256) -> Bytes { + let bit_len = self.total_len * 8UL + self.block[self.block_len] = b'\x80' + self.block_len += 1 + if self.block_len > 56 { + while self.block_len < 64 { + self.block[self.block_len] = b'\x00' + self.block_len += 1 + } + self.compress() + self.block_len = 0 + } + while self.block_len < 56 { + self.block[self.block_len] = b'\x00' + self.block_len += 1 + } + for i = 0; i < 8; i = i + 1 { + self.block[56 + i] = ((bit_len >> (56 - i * 8)) & 0xFFUL).to_byte() + } + self.compress() + let out = FixedArray::make(32, b'\x00') + for i = 0; i < 8; i = i + 1 { + let v = self.state[i] + out[i * 4] = ((v >> 24) & 0xFFU).to_byte() + out[i * 4 + 1] = ((v >> 16) & 0xFFU).to_byte() + out[i * 4 + 2] = ((v >> 8) & 0xFFU).to_byte() + out[i * 4 + 3] = (v & 0xFFU).to_byte() + } + Bytes::from_array(out) +} + +///| +/// Computes the 32-byte SHA-256 digest of `data`. +pub fn sha256(data : Bytes) -> Bytes { + let h = Sha256::new() + h.update(data) + h.finalize() +} diff --git a/crypto/siphash.mbt b/crypto/siphash.mbt new file mode 100644 index 0000000..87a9104 --- /dev/null +++ b/crypto/siphash.mbt @@ -0,0 +1,80 @@ +///| +fn rotl64(x : UInt64, n : Int32) -> UInt64 { + (x << n) | (x >> (64 - n)) +} + +///| +fn read_u64_le(data : Bytes, offset : Int32) -> UInt64 { + data[offset].to_uint64() | + (data[offset + 1].to_uint64() << 8) | + (data[offset + 2].to_uint64() << 16) | + (data[offset + 3].to_uint64() << 24) | + (data[offset + 4].to_uint64() << 32) | + (data[offset + 5].to_uint64() << 40) | + (data[offset + 6].to_uint64() << 48) | + (data[offset + 7].to_uint64() << 56) +} + +///| +/// Computes SipHash-2-4 (used by NTCP2 for frame length obfuscation). +/// `key` must be 16 bytes. +pub fn siphash_2_4(key : Bytes, data : Bytes) -> UInt64 raise CryptoError { + if key.length() != 16 { + raise InvalidKeyLength( + "SipHash-2-4 requires a 16-byte key, got \{key.length()}", + ) + } + let k0 = read_u64_le(key, 0) + let k1 = read_u64_le(key, 8) + let mut v0 = 0x736f6d6570736575UL ^ k0 + let mut v1 = 0x646f72616e646f6dUL ^ k1 + let mut v2 = 0x6c7967656e657261UL ^ k0 + let mut v3 = 0x7465646279746573UL ^ k1 + + let sipround = fn() { + v0 = v0 + v1 + v1 = rotl64(v1, 13) + v1 = v1 ^ v0 + v0 = rotl64(v0, 32) + v2 = v2 + v3 + v3 = rotl64(v3, 16) + v3 = v3 ^ v2 + v0 = v0 + v3 + v3 = rotl64(v3, 21) + v3 = v3 ^ v0 + v2 = v2 + v1 + v1 = rotl64(v1, 17) + v1 = v1 ^ v2 + v2 = rotl64(v2, 32) + } + + let len = data.length() + let full_blocks = len / 8 + for i = 0; i < full_blocks; i = i + 1 { + let m = read_u64_le(data, i * 8) + v3 = v3 ^ m + sipround() + sipround() + v0 = v0 ^ m + } + + let mut b = (len.to_uint64() & 0xFFUL) << 56 + let rem = len % 8 + let base = full_blocks * 8 + for i = 0; i < rem; i = i + 1 { + b = b | (data[base + i].to_uint64() << (i * 8)) + } + + v3 = v3 ^ b + sipround() + sipround() + v0 = v0 ^ b + + v2 = v2 ^ 0xFFUL + sipround() + sipround() + sipround() + sipround() + + v0 ^ v1 ^ v2 ^ v3 +} diff --git a/crypto/x25519.mbt b/crypto/x25519.mbt new file mode 100644 index 0000000..4326616 --- /dev/null +++ b/crypto/x25519.mbt @@ -0,0 +1,214 @@ +///| +/// Pure-MoonBit RFC 7748 X25519 Elliptic Curve Diffie-Hellman on Curve25519. +/// Field elements mod 2^255 - 19 are represented as 16 signed 64-bit limbs (16 bits per limb). + +///| +fn gf_zero() -> FixedArray[Int64] { + FixedArray::make(16, 0L) +} + +///| +fn gf_one() -> FixedArray[Int64] { + let r = FixedArray::make(16, 0L) + r[0] = 1L + r +} + +///| +fn gf_copy(src : FixedArray[Int64]) -> FixedArray[Int64] { + let dst = FixedArray::make(16, 0L) + for i = 0; i < 16; i = i + 1 { + dst[i] = src[i] + } + dst +} + +///| +fn gf_carry(o : FixedArray[Int64]) -> Unit { + for i = 0; i < 16; i = i + 1 { + o[i] = o[i] + 65536L + let c = o[i] >> 16 + if i < 15 { + o[i + 1] = o[i + 1] + c - 1L + } else { + o[0] = o[0] + (c - 1L) * 38L + } + o[i] = o[i] - (c << 16) + } +} + +///| +fn gf_cswap(p : FixedArray[Int64], q : FixedArray[Int64], b : Int64) -> Unit { + let mask = -b + for i = 0; i < 16; i = i + 1 { + let t = mask & (p[i] ^ q[i]) + p[i] = p[i] ^ t + q[i] = q[i] ^ t + } +} + +///| +fn gf_unpack(n : Bytes) -> FixedArray[Int64] { + let o = FixedArray::make(16, 0L) + for i = 0; i < 16; i = i + 1 { + o[i] = n[2 * i].to_int64() + (n[2 * i + 1].to_int64() << 8) + } + o[15] = o[15] & 0x7fffL + o +} + +///| +fn gf_pack(n : FixedArray[Int64]) -> Bytes { + let t = gf_copy(n) + let m = FixedArray::make(16, 0L) + gf_carry(t) + gf_carry(t) + gf_carry(t) + for _j = 0; _j < 2; _j = _j + 1 { + m[0] = t[0] - 0xffedL + for i = 1; i < 15; i = i + 1 { + m[i] = t[i] - 0xffffL - ((m[i - 1] >> 16) & 1L) + m[i - 1] = m[i - 1] & 0xffffL + } + m[15] = t[15] - 0x7fffL - ((m[14] >> 16) & 1L) + let b = (m[15] >> 16) & 1L + m[14] = m[14] & 0xffffL + gf_cswap(t, m, 1L - b) + } + let out = FixedArray::make(32, b'\x00') + for i = 0; i < 16; i = i + 1 { + out[2 * i] = (t[i] & 0xffL).to_byte() + out[2 * i + 1] = ((t[i] >> 8) & 0xffL).to_byte() + } + Bytes::from_array(out) +} + +///| +fn gf_add(a : FixedArray[Int64], b : FixedArray[Int64]) -> FixedArray[Int64] { + let o = FixedArray::make(16, 0L) + for i = 0; i < 16; i = i + 1 { + o[i] = a[i] + b[i] + } + o +} + +///| +fn gf_sub(a : FixedArray[Int64], b : FixedArray[Int64]) -> FixedArray[Int64] { + let o = FixedArray::make(16, 0L) + for i = 0; i < 16; i = i + 1 { + o[i] = a[i] - b[i] + } + o +} + +///| +fn gf_mul(a : FixedArray[Int64], b : FixedArray[Int64]) -> FixedArray[Int64] { + let t = FixedArray::make(31, 0L) + for i = 0; i < 16; i = i + 1 { + for j = 0; j < 16; j = j + 1 { + t[i + j] = t[i + j] + a[i] * b[j] + } + } + for i = 0; i < 15; i = i + 1 { + t[i] = t[i] + 38L * t[i + 16] + } + let o = FixedArray::make(16, 0L) + for i = 0; i < 16; i = i + 1 { + o[i] = t[i] + } + gf_carry(o) + gf_carry(o) + o +} + +///| +fn gf_sq(a : FixedArray[Int64]) -> FixedArray[Int64] { + gf_mul(a, a) +} + +///| +fn gf_inv(a : FixedArray[Int64]) -> FixedArray[Int64] { + let mut c = gf_copy(a) + for i = 253; i >= 0; i = i - 1 { + c = gf_sq(c) + if i != 2 && i != 4 { + c = gf_mul(c, a) + } + } + c +} + +///| +/// Computes the X25519 scalar multiplication `scalar * u_coord` (RFC 7748 Section 5). +/// Both `scalar` and `u_coord` must be 32 bytes. +pub fn x25519(scalar : Bytes, u_coord : Bytes) -> Bytes raise CryptoError { + if scalar.length() != 32 { + raise InvalidKeyLength( + "X25519 scalar must be 32 bytes, got \{scalar.length()}", + ) + } + if u_coord.length() != 32 { + raise InvalidKeyLength( + "X25519 u-coordinate must be 32 bytes, got \{u_coord.length()}", + ) + } + let z = FixedArray::make(32, 0) + for i = 0; i < 32; i = i + 1 { + z[i] = scalar[i].to_int() + } + // Clamp scalar per RFC 7748 + z[0] = z[0] & 248 + z[31] = (z[31] & 127) | 64 + + let x = gf_unpack(u_coord) + let mut a = gf_one() + let mut b = gf_copy(x) + let mut c = gf_zero() + let mut d = gf_one() + + let a24 = gf_zero() + a24[0] = 0xdb41L + a24[1] = 1L + + for i = 254; i >= 0; i = i - 1 { + let r = ((z[i >> 3] >> (i & 7)) & 1).to_int64() + gf_cswap(a, b, r) + gf_cswap(c, d, r) + let e = gf_add(a, c) + let a1 = gf_sub(a, c) + let c1 = gf_add(b, d) + let b1 = gf_sub(b, d) + let d1 = gf_sq(e) + let f = gf_sq(a1) + let a2 = gf_mul(c1, a1) + let c2 = gf_mul(b1, e) + let e2 = gf_add(a2, c2) + let a3 = gf_sub(a2, c2) + let b2 = gf_sq(a3) + let c3 = gf_sub(d1, f) + let a4 = gf_mul(c3, a24) + let a5 = gf_add(a4, d1) + let c4 = gf_mul(c3, a5) + let a6 = gf_mul(d1, f) + let d2 = gf_mul(b2, x) + let b3 = gf_sq(e2) + a = a6 + b = b3 + c = c4 + d = d2 + gf_cswap(a, b, r) + gf_cswap(c, d, r) + } + + let inv_c = gf_inv(c) + let res = gf_mul(a, inv_c) + gf_pack(res) +} + +///| +/// Computes the 32-byte X25519 public key from a 32-byte private scalar. +pub fn x25519_public_key(private_key : Bytes) -> Bytes raise CryptoError { + let basepoint = FixedArray::make(32, b'\x00') + basepoint[0] = b'\x09' + x25519(private_key, Bytes::from_array(basepoint)) +} diff --git a/encoding/base32.mbt b/encoding/base32.mbt new file mode 100644 index 0000000..5277190 --- /dev/null +++ b/encoding/base32.mbt @@ -0,0 +1,66 @@ +///| +/// I2P Base32 alphabet (RFC 4648 lowercase `a-z2-7`, unpadded, used for `.b32.i2p` addresses). +let i2p_b32_alphabet : Bytes = b"abcdefghijklmnopqrstuvwxyz234567" + +///| +fn b32_decode_char(c : Int32) -> Int32 raise EncodingError { + if c >= 97 && c <= 122 { + c - 97 + } else if c >= 65 && c <= 90 { + // Accept uppercase too (case-insensitive) + c - 65 + } else if c >= 50 && c <= 55 { + // '2'..'7' -> 26..31 + c - 50 + 26 + } else { + raise InvalidCharacter("invalid Base32 character code: \{c}") + } +} + +///| +/// Encodes bytes as lowercase unpadded Base32 (standard for I2P `.b32.i2p` addresses). +pub fn base32_encode(data : Bytes) -> String { + let len = data.length() + if len == 0 { + return "" + } + let buf = StringBuilder(capacity=(len * 8 + 4) / 5) + let mut buffer = 0 + let mut bits_left = 0 + for i = 0; i < len; i = i + 1 { + buffer = (buffer << 8) | data[i].to_int() + bits_left += 8 + while bits_left >= 5 { + bits_left -= 5 + let idx = (buffer >> bits_left) & 0x1F + buf.write_char(i2p_b32_alphabet[idx].to_int().unsafe_to_char()) + } + } + if bits_left > 0 { + let idx = (buffer << (5 - bits_left)) & 0x1F + buf.write_char(i2p_b32_alphabet[idx].to_int().unsafe_to_char()) + } + buf.to_string() +} + +///| +/// Decodes an I2P Base32 string (case-insensitive, optional `=` padding) into `Bytes`. +pub fn base32_decode(input : String) -> Bytes raise EncodingError { + let out : Array[Byte] = [] + let mut buffer = 0 + let mut bits_left = 0 + for ch in input { + let c = ch.to_int() + if c == 61 || c == 32 || c == 9 || c == 10 || c == 13 { + continue + } + let val = b32_decode_char(c) + buffer = (buffer << 5) | val + bits_left += 5 + if bits_left >= 8 { + bits_left -= 8 + out.push(((buffer >> bits_left) & 0xFF).to_byte()) + } + } + Bytes::from_array(out) +} diff --git a/encoding/base64.mbt b/encoding/base64.mbt new file mode 100644 index 0000000..f6a3806 --- /dev/null +++ b/encoding/base64.mbt @@ -0,0 +1,110 @@ +///| +/// I2P custom Base64 alphabet: `A-Z`, `a-z`, `0-9`, `-`, `~` with `=` padding. +let i2p_b64_alphabet : Bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~" + +///| +fn b64_decode_char(c : Int32) -> Int32 raise EncodingError { + if c >= 65 && c <= 90 { + c - 65 + } else if c >= 97 && c <= 122 { + c - 97 + 26 + } else if c >= 48 && c <= 57 { + c - 48 + 52 + } else if c == 45 { + // '-' + 62 + } else if c == 126 { + // '~' + 63 + } else { + raise InvalidCharacter("invalid I2P Base64 character code: \{c}") + } +} + +///| +/// Encodes bytes using the I2P Base64 alphabet (`-` and `~`, padded with `=`). +pub fn base64_encode(data : Bytes) -> String { + let len = data.length() + if len == 0 { + return "" + } + let buf = StringBuilder(capacity=(len + 2) / 3 * 4) + let mut i = 0 + while i < len { + let b0 = data[i].to_int() + let has_b1 = i + 1 < len + let has_b2 = i + 2 < len + let b1 = if has_b1 { data[i + 1].to_int() } else { 0 } + let b2 = if has_b2 { data[i + 2].to_int() } else { 0 } + + let c0 = b0 >> 2 + let c1 = ((b0 & 0x03) << 4) | (b1 >> 4) + let c2 = ((b1 & 0x0F) << 2) | (b2 >> 6) + let c3 = b2 & 0x3F + + buf.write_char(i2p_b64_alphabet[c0].to_int().unsafe_to_char()) + buf.write_char(i2p_b64_alphabet[c1].to_int().unsafe_to_char()) + if has_b1 { + buf.write_char(i2p_b64_alphabet[c2].to_int().unsafe_to_char()) + } else { + buf.write_char('=') + } + if has_b2 { + buf.write_char(i2p_b64_alphabet[c3].to_int().unsafe_to_char()) + } else { + buf.write_char('=') + } + i += 3 + } + buf.to_string() +} + +///| +/// Decodes an I2P Base64 string (`-` and `~`, optional `=` padding) into `Bytes`. +pub fn base64_decode(input : String) -> Bytes raise EncodingError { + let chars : Array[Int32] = [] + for ch in input { + let c = ch.to_int() + if c == 32 || c == 9 || c == 10 || c == 13 { + continue + } + chars.push(c) + } + let len = chars.length() + if len == 0 { + return b"" + } + if len % 4 != 0 { + raise InvalidLength("I2P Base64 length must be a multiple of 4, got \{len}") + } + let out : Array[Byte] = Array(capacity=len / 4 * 3) + let mut i = 0 + while i < len { + let c0 = chars[i] + let c1 = chars[i + 1] + let c2 = chars[i + 2] + let c3 = chars[i + 3] + let v0 = b64_decode_char(c0) + let v1 = b64_decode_char(c1) + let pad2 = c2 == 61 // '=' + let pad3 = c3 == 61 // '=' + if pad2 && !pad3 { + raise InvalidCharacter("invalid Base64 padding") + } + if (pad2 || pad3) && i + 4 < len { + raise InvalidCharacter("Base64 padding before end of input") + } + let v2 = if pad2 { 0 } else { b64_decode_char(c2) } + let v3 = if pad3 { 0 } else { b64_decode_char(c3) } + + out.push(((v0 << 2) | (v1 >> 4)).to_byte()) + if !pad2 { + out.push((((v1 & 0x0F) << 4) | (v2 >> 2)).to_byte()) + } + if !pad3 { + out.push((((v2 & 0x03) << 6) | v3).to_byte()) + } + i += 4 + } + Bytes::from_array(out) +} diff --git a/encoding/binary.mbt b/encoding/binary.mbt new file mode 100644 index 0000000..11f5c65 --- /dev/null +++ b/encoding/binary.mbt @@ -0,0 +1,325 @@ +///| +/// Errors raised during I2P binary, Base64, Base32, or Hex encoding/decoding. +#derive(Eq, Debug) +pub suberror EncodingError { + UnexpectedEof(String) + InvalidCharacter(String) + InvalidLength(String) + ValueOutOfRange(String) +} + +///| +/// Big-endian binary reader over an immutable `Bytes` buffer. +pub struct Reader { + data : Bytes + mut pos : Int32 +} + +///| +pub fn Reader::new(data : Bytes) -> Reader { + { data, pos: 0, } +} + +///| +pub fn Reader::position(self : Reader) -> Int32 { + self.pos +} + +///| +pub fn Reader::remaining(self : Reader) -> Int32 { + self.data.length() - self.pos +} + +///| +pub fn Reader::is_eof(self : Reader) -> Bool { + self.pos >= self.data.length() +} + +///| +pub fn Reader::skip(self : Reader, n : Int32) -> Unit raise EncodingError { + if n < 0 || self.remaining() < n { + raise UnexpectedEof("skip: need \{n} bytes, have \{self.remaining()}") + } + self.pos += n +} + +///| +pub fn Reader::read_u8(self : Reader) -> Byte raise EncodingError { + if self.remaining() < 1 { + raise UnexpectedEof("read_u8: unexpected EOF at \{self.pos}") + } + let b = self.data[self.pos] + self.pos += 1 + b +} + +///| +pub fn Reader::read_u16_be(self : Reader) -> UInt32 raise EncodingError { + if self.remaining() < 2 { + raise UnexpectedEof("read_u16_be: unexpected EOF at \{self.pos}") + } + let b0 = self.data[self.pos].to_uint() + let b1 = self.data[self.pos + 1].to_uint() + self.pos += 2 + (b0 << 8) | b1 +} + +///| +pub fn Reader::read_u32_be(self : Reader) -> UInt32 raise EncodingError { + if self.remaining() < 4 { + raise UnexpectedEof("read_u32_be: unexpected EOF at \{self.pos}") + } + let b0 = self.data[self.pos].to_uint() + let b1 = self.data[self.pos + 1].to_uint() + let b2 = self.data[self.pos + 2].to_uint() + let b3 = self.data[self.pos + 3].to_uint() + self.pos += 4 + (b0 << 24) | (b1 << 16) | (b2 << 8) | b3 +} + +///| +pub fn Reader::read_u64_be(self : Reader) -> UInt64 raise EncodingError { + if self.remaining() < 8 { + raise UnexpectedEof("read_u64_be: unexpected EOF at \{self.pos}") + } + let mut acc : UInt64 = 0UL + for i = 0; i < 8; i = i + 1 { + acc = (acc << 8) | self.data[self.pos + i].to_uint64() + } + self.pos += 8 + acc +} + +///| +pub fn Reader::read_bytes( + self : Reader, + len : Int32, +) -> Bytes raise EncodingError { + if len < 0 || self.remaining() < len { + raise UnexpectedEof( + "read_bytes: need \{len} bytes, have \{self.remaining()}", + ) + } + let out = FixedArray::make(len, b'\x00') + for i = 0; i < len; i = i + 1 { + out[i] = self.data[self.pos + i] + } + self.pos += len + Bytes::from_array(out) +} + +///| +pub fn Reader::read_remaining(self : Reader) -> Bytes { + let len = self.remaining() + let out = FixedArray::make(len, b'\x00') + for i = 0; i < len; i = i + 1 { + out[i] = self.data[self.pos + i] + } + self.pos = self.data.length() + Bytes::from_array(out) +} + +///| +/// Reads an I2P String: 1-byte unsigned length prefix (0..255) followed by UTF-8 bytes. +pub fn Reader::read_i2p_string(self : Reader) -> String raise EncodingError { + let len = self.read_u8().to_int() + let raw = self.read_bytes(len) + utf8_bytes_to_string(raw) +} + +///| +/// Big-endian binary writer backed by a growable byte buffer. +pub struct Writer { + buf : Array[Byte] +} + +///| +pub fn Writer::new(capacity~ : Int32 = 64) -> Writer { + { buf: Array(capacity~), } +} + +///| +pub fn Writer::length(self : Writer) -> Int32 { + self.buf.length() +} + +///| +pub fn Writer::write_u8(self : Writer, v : Byte) -> Unit { + self.buf.push(v) +} + +///| +pub fn Writer::write_u16_be(self : Writer, v : UInt32) -> Unit { + self.buf.push(((v >> 8) & 0xFFU).to_byte()) + self.buf.push((v & 0xFFU).to_byte()) +} + +///| +pub fn Writer::write_u32_be(self : Writer, v : UInt32) -> Unit { + self.buf.push(((v >> 24) & 0xFFU).to_byte()) + self.buf.push(((v >> 16) & 0xFFU).to_byte()) + self.buf.push(((v >> 8) & 0xFFU).to_byte()) + self.buf.push((v & 0xFFU).to_byte()) +} + +///| +pub fn Writer::write_u64_be(self : Writer, v : UInt64) -> Unit { + self.buf.push(((v >> 56) & 0xFFUL).to_byte()) + self.buf.push(((v >> 48) & 0xFFUL).to_byte()) + self.buf.push(((v >> 40) & 0xFFUL).to_byte()) + self.buf.push(((v >> 32) & 0xFFUL).to_byte()) + self.buf.push(((v >> 24) & 0xFFUL).to_byte()) + self.buf.push(((v >> 16) & 0xFFUL).to_byte()) + self.buf.push(((v >> 8) & 0xFFUL).to_byte()) + self.buf.push((v & 0xFFUL).to_byte()) +} + +///| +pub fn Writer::write_bytes(self : Writer, data : Bytes) -> Unit { + for i = 0; i < data.length(); i = i + 1 { + self.buf.push(data[i]) + } +} + +///| +/// Writes an I2P String (1-byte length + UTF-8 bytes, max 255 bytes). +pub fn Writer::write_i2p_string( + self : Writer, + s : String, +) -> Unit raise EncodingError { + let raw = string_to_utf8_bytes(s) + if raw.length() > 255 { + raise ValueOutOfRange("I2P string exceeds 255 UTF-8 bytes: \{raw.length()}") + } + self.write_u8(raw.length().to_byte()) + self.write_bytes(raw) +} + +///| +pub fn Writer::to_bytes(self : Writer) -> Bytes { + Bytes::from_array(self.buf) +} + +///| +/// Encodes a MoonBit `String` to UTF-8 `Bytes`. +pub fn string_to_utf8_bytes(s : String) -> Bytes { + let out : Array[Byte] = [] + for ch in s { + let cp = ch.to_int() + if cp < 0x80 { + out.push(cp.to_byte()) + } else if cp < 0x800 { + out.push((0xC0 | (cp >> 6)).to_byte()) + out.push((0x80 | (cp & 0x3F)).to_byte()) + } else if cp < 0x10000 { + out.push((0xE0 | (cp >> 12)).to_byte()) + out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (cp & 0x3F)).to_byte()) + } else { + out.push((0xF0 | (cp >> 18)).to_byte()) + out.push((0x80 | ((cp >> 12) & 0x3F)).to_byte()) + out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (cp & 0x3F)).to_byte()) + } + } + Bytes::from_array(out) +} + +///| +/// Decodes UTF-8 `Bytes` to a MoonBit `String`. +pub fn utf8_bytes_to_string(data : Bytes) -> String raise EncodingError { + let buf = StringBuilder() + let len = data.length() + let mut i = 0 + while i < len { + let b0 = data[i].to_int() + if b0 < 0x80 { + buf.write_char(b0.unsafe_to_char()) + i += 1 + } else if (b0 & 0xE0) == 0xC0 { + if i + 1 >= len { + raise InvalidCharacter("truncated 2-byte UTF-8 sequence") + } + let b1 = data[i + 1].to_int() + let cp = ((b0 & 0x1F) << 6) | (b1 & 0x3F) + buf.write_char(cp.unsafe_to_char()) + i += 2 + } else if (b0 & 0xF0) == 0xE0 { + if i + 2 >= len { + raise InvalidCharacter("truncated 3-byte UTF-8 sequence") + } + let b1 = data[i + 1].to_int() + let b2 = data[i + 2].to_int() + let cp = ((b0 & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F) + buf.write_char(cp.unsafe_to_char()) + i += 3 + } else if (b0 & 0xF8) == 0xF0 { + if i + 3 >= len { + raise InvalidCharacter("truncated 4-byte UTF-8 sequence") + } + let b1 = data[i + 1].to_int() + let b2 = data[i + 2].to_int() + let b3 = data[i + 3].to_int() + let cp = ((b0 & 0x07) << 18) | + ((b1 & 0x3F) << 12) | + ((b2 & 0x3F) << 6) | + (b3 & 0x3F) + buf.write_char(cp.unsafe_to_char()) + i += 4 + } else { + raise InvalidCharacter("invalid UTF-8 lead byte: \{b0}") + } + } + buf.to_string() +} + +///| +let hex_digits : Bytes = b"0123456789abcdef" + +///| +/// Encodes `Bytes` as lowercase hexadecimal. +pub fn hex_encode(data : Bytes) -> String { + let buf = StringBuilder(capacity=data.length() * 2) + for i = 0; i < data.length(); i = i + 1 { + let b = data[i].to_int() + buf.write_char(hex_digits[b >> 4].to_int().unsafe_to_char()) + buf.write_char(hex_digits[b & 0x0F].to_int().unsafe_to_char()) + } + buf.to_string() +} + +///| +fn hex_nibble(c : Int32) -> Int32 raise EncodingError { + if c >= 48 && c <= 57 { + c - 48 + } else if c >= 97 && c <= 102 { + c - 87 + } else if c >= 65 && c <= 70 { + c - 55 + } else { + raise InvalidCharacter("invalid hex character code: \{c}") + } +} + +///| +/// Decodes a hexadecimal string (case-insensitive, ignoring ASCII whitespace) into `Bytes`. +pub fn hex_decode(s : String) -> Bytes raise EncodingError { + let chars : Array[Int32] = [] + for ch in s { + let c = ch.to_int() + if c == 32 || c == 9 || c == 10 || c == 13 { + continue + } + chars.push(c) + } + if chars.length() % 2 != 0 { + raise InvalidLength("hex string has odd length: \{chars.length()}") + } + let out = FixedArray::make(chars.length() / 2, b'\x00') + for i = 0; i < out.length(); i = i + 1 { + let hi = hex_nibble(chars[i * 2]) + let lo = hex_nibble(chars[i * 2 + 1]) + out[i] = ((hi << 4) | lo).to_byte() + } + Bytes::from_array(out) +} diff --git a/encoding/encoding_test.mbt b/encoding/encoding_test.mbt new file mode 100644 index 0000000..20fb8e2 --- /dev/null +++ b/encoding/encoding_test.mbt @@ -0,0 +1,81 @@ +///| +test "i2p base64 uses - and ~ instead of + and /" { + // 0xfb 0xff 0xfe -> 111110 111111 111111 111110 -> 62 63 63 62 -> "-~~-" + let raw = b"\xfb\xff\xfe" + let encoded = @encoding.base64_encode(raw) + assert_eq(encoded, "-~~-") + let decoded = @encoding.base64_decode(encoded) + assert_eq(decoded, raw) +} + +///| +test "i2p base64 padding round-trip" { + let cases : Array[(Bytes, String)] = [ + (b"", ""), + (b"f", "Zg=="), + (b"fo", "Zm8="), + (b"foo", "Zm9v"), + (b"foob", "Zm9vYg=="), + (b"fooba", "Zm9vYmE="), + (b"foobar", "Zm9vYmFy"), + ] + for item in cases { + let (raw, expected) = item + assert_eq(@encoding.base64_encode(raw), expected) + assert_eq(@encoding.base64_decode(expected), raw) + } +} + +///| +test "i2p base32 rfc4648 lowercase unpadded vectors" { + let cases : Array[(Bytes, String)] = [ + (b"", ""), + (b"f", "my"), + (b"fo", "mzxq"), + (b"foo", "mzxw6"), + (b"foob", "mzxw6yq"), + (b"fooba", "mzxw6ytb"), + (b"foobar", "mzxw6ytboi"), + ] + for item in cases { + let (raw, expected) = item + assert_eq(@encoding.base32_encode(raw), expected) + assert_eq(@encoding.base32_decode(expected), raw) + } +} + +///| +test "i2p base32 32-byte hash produces 52 chars" { + let zeros = Bytes::make(32, b'\x00') + let b32 = @encoding.base32_encode(zeros) + assert_eq(b32.length(), 52) + assert_eq(@encoding.base32_decode(b32), zeros) +} + +///| +test "binary reader and writer big-endian round-trip" { + let w = @encoding.Writer::new() + w.write_u8(b'\x42') + w.write_u16_be(0x1234U) + w.write_u32_be(0xDEADBEEFU) + w.write_u64_be(0x0102030405060708UL) + w.write_i2p_string("NTCP2") + w.write_bytes(b"\xAA\xBB") + let bytes = w.to_bytes() + + let r = @encoding.Reader::new(bytes) + assert_eq(r.read_u8(), b'\x42') + assert_eq(r.read_u16_be(), 0x1234U) + assert_eq(r.read_u32_be(), 0xDEADBEEFU) + assert_eq(r.read_u64_be(), 0x0102030405060708UL) + assert_eq(r.read_i2p_string(), "NTCP2") + assert_eq(r.read_bytes(2), b"\xAA\xBB") + assert_true(r.is_eof()) +} + +///| +test "hex encode and decode" { + let raw = b"\x00\x0f\xa5\xff" + assert_eq(@encoding.hex_encode(raw), "000fa5ff") + assert_eq(@encoding.hex_decode("000F a5ff"), raw) +} diff --git a/encoding/moon.pkg b/encoding/moon.pkg new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/encoding/moon.pkg @@ -0,0 +1 @@ + diff --git a/encoding/pkg.generated.mbti b/encoding/pkg.generated.mbti new file mode 100644 index 0000000..d80b208 --- /dev/null +++ b/encoding/pkg.generated.mbti @@ -0,0 +1,67 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/encoding" + +import { + "moonbitlang/core/debug", +} + +// Values +pub fn base32_decode(String) -> Bytes raise EncodingError + +pub fn base32_encode(Bytes) -> String + +pub fn base64_decode(String) -> Bytes raise EncodingError + +pub fn base64_encode(Bytes) -> String + +pub fn hex_decode(String) -> Bytes raise EncodingError + +pub fn hex_encode(Bytes) -> String + +pub fn string_to_utf8_bytes(String) -> Bytes + +pub fn utf8_bytes_to_string(Bytes) -> String raise EncodingError + +// Errors +#derive(Eq, @debug.Debug) +pub suberror EncodingError { + UnexpectedEof(String) + InvalidCharacter(String) + InvalidLength(String) + ValueOutOfRange(String) +} + +// Types and methods +pub struct Reader { + data : Bytes + mut pos : Int32 +} +pub fn Reader::is_eof(Self) -> Bool +pub fn Reader::new(Bytes) -> Self +pub fn Reader::position(Self) -> Int32 +pub fn Reader::read_bytes(Self, Int32) -> Bytes raise EncodingError +pub fn Reader::read_i2p_string(Self) -> String raise EncodingError +pub fn Reader::read_remaining(Self) -> Bytes +pub fn Reader::read_u16_be(Self) -> UInt32 raise EncodingError +pub fn Reader::read_u32_be(Self) -> UInt32 raise EncodingError +pub fn Reader::read_u64_be(Self) -> UInt64 raise EncodingError +pub fn Reader::read_u8(Self) -> Byte raise EncodingError +pub fn Reader::remaining(Self) -> Int32 +pub fn Reader::skip(Self, Int32) -> Unit raise EncodingError + +pub struct Writer { + buf : Array[Byte] +} +pub fn Writer::length(Self) -> Int32 +pub fn Writer::new(capacity? : Int32) -> Self +pub fn Writer::to_bytes(Self) -> Bytes +pub fn Writer::write_bytes(Self, Bytes) -> Unit +pub fn Writer::write_i2p_string(Self, String) -> Unit raise EncodingError +pub fn Writer::write_u16_be(Self, UInt32) -> Unit +pub fn Writer::write_u32_be(Self, UInt32) -> Unit +pub fn Writer::write_u64_be(Self, UInt64) -> Unit +pub fn Writer::write_u8(Self, Byte) -> Unit + +// Type aliases + +// Traits diff --git a/i2np/i2np_test.mbt b/i2np/i2np_test.mbt new file mode 100644 index 0000000..24ef51c --- /dev/null +++ b/i2np/i2np_test.mbt @@ -0,0 +1,96 @@ +///| +test "I2NP standard header checksum and Data message round-trip" { + let msg = @i2np.I2npPayload::Data(data=b"hello invisible internet") + let wire = @i2np.encode_standard_message(12345U, 1700000000000UL, msg) + // 16-byte header + 4-byte length + 24-byte payload = 44 bytes + assert_eq(wire.length(), 44) + let (hdr, decoded) = @i2np.decode_standard_message( + @encoding.Reader::new(wire), + ) + assert_eq(hdr.msg_type, Data) + assert_eq(hdr.msg_id, 12345U) + assert_eq(hdr.expiration_ms, 1700000000000UL) + assert_eq(decoded, msg) +} + +///| +test "I2NP standard header detects corrupted checksum" { + let msg = @i2np.I2npPayload::DeliveryStatus( + msg_id=99U, + timestamp_ms=1700000000123UL, + ) + let wire = @i2np.encode_standard_message(77U, 1700000010000UL, msg) + // Flip a bit in the payload + let tampered = FixedArray::make(wire.length(), b'\x00') + for i = 0; i < wire.length(); i = i + 1 { + tampered[i] = wire[i] + } + tampered[16] = (tampered[16].to_int() ^ 0xFF).to_byte() + let mut failed = false + try { + let _ = @i2np.decode_standard_message( + @encoding.Reader::new(Bytes::from_array(tampered)), + ) + } catch { + @i2np.I2npError::ChecksumMismatch(_, _) => failed = true + _ => () + } + assert_true(failed) +} + +///| +test "I2NP NTCP2 short 9-byte header round-trip for DatabaseStore and ShortTunnelBuild" { + let key = @common.Hash::from_bytes(Bytes::make(32, b'\x42')) + let gw = @common.Hash::from_bytes(Bytes::make(32, b'\x99')) + let store = @i2np.I2npPayload::DatabaseStore( + key~, + store_type=b'\x03', + reply_token=555U, + reply_tunnel_id=777U, + reply_gateway=Some(gw), + data=b"leaseset2-bytes", + ) + let wire = @i2np.encode_short_message(42U, 1700000500U, store) + let (hdr, decoded) = @i2np.decode_short_message(@encoding.Reader::new(wire)) + assert_eq(hdr.msg_type, DatabaseStore) + assert_eq(hdr.msg_id, 42U) + assert_eq(hdr.expiration_sec, 1700000500U) + assert_eq(decoded, store) + + // ShortTunnelBuild (Proposal 157: 218-byte records) + let stb = @i2np.I2npPayload::ShortTunnelBuild(records=[ + Bytes::make(218, b'\x01'), + Bytes::make(218, b'\x02'), + ]) + let stb_wire = @i2np.encode_short_message(101U, 1700000600U, stb) + let (stb_hdr, stb_dec) = @i2np.decode_short_message( + @encoding.Reader::new(stb_wire), + ) + assert_eq(stb_hdr.msg_type, ShortTunnelBuild) + assert_eq(stb_dec, stb) +} + +///| +test "I2NP TunnelData and DatabaseSearchReply round-trip" { + let td = @i2np.I2npPayload::TunnelData( + tunnel_id=0x11223344U, + data=Bytes::make(1024, b'\x7e'), + ) + let td_wire = @i2np.encode_short_message(5U, 1700000900U, td) + let (_, td_dec) = @i2np.decode_short_message(@encoding.Reader::new(td_wire)) + assert_eq(td_dec, td) + + let dsr = @i2np.I2npPayload::DatabaseSearchReply( + key=@common.Hash::from_bytes(Bytes::make(32, b'\x01')), + peer_hashes=[ + @common.Hash::from_bytes(Bytes::make(32, b'\x02')), + @common.Hash::from_bytes(Bytes::make(32, b'\x03')), + ], + from=@common.Hash::from_bytes(Bytes::make(32, b'\x04')), + ) + let dsr_wire = @i2np.encode_standard_message(6U, 1700000900000UL, dsr) + let (_, dsr_dec) = @i2np.decode_standard_message( + @encoding.Reader::new(dsr_wire), + ) + assert_eq(dsr_dec, dsr) +} diff --git a/i2np/message.mbt b/i2np/message.mbt new file mode 100644 index 0000000..874f967 --- /dev/null +++ b/i2np/message.mbt @@ -0,0 +1,483 @@ +///| +/// Errors raised when encoding, decoding, or validating I2NP messages. +#derive(Eq, Debug) +pub suberror I2npError { + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + ChecksumMismatch(Byte, Byte) + InvalidLength(String) +} + +///| +/// I2NP message type IDs (per I2P I2NP specification). +#derive(Eq, Debug) +pub(all) enum I2npMessageType { + DatabaseStore // 1 + DatabaseLookup // 2 + DatabaseSearchReply // 3 + DeliveryStatus // 10 + Garlic // 11 + TunnelData // 18 + TunnelGateway // 19 + Data // 20 + TunnelBuild // 21 + TunnelBuildReply // 22 + VariableTunnelBuild // 23 + VariableTunnelBuildReply // 24 + ShortTunnelBuild // 25 + ShortTunnelBuildReply // 26 + Unknown(Byte) +} + +///| +pub fn I2npMessageType::to_byte(self : I2npMessageType) -> Byte { + match self { + DatabaseStore => b'\x01' + DatabaseLookup => b'\x02' + DatabaseSearchReply => b'\x03' + DeliveryStatus => b'\x0a' + Garlic => b'\x0b' + TunnelData => b'\x12' + TunnelGateway => b'\x13' + Data => b'\x14' + TunnelBuild => b'\x15' + TunnelBuildReply => b'\x16' + VariableTunnelBuild => b'\x17' + VariableTunnelBuildReply => b'\x18' + ShortTunnelBuild => b'\x19' + ShortTunnelBuildReply => b'\x1a' + Unknown(b) => b + } +} + +///| +pub fn I2npMessageType::from_byte(b : Byte) -> I2npMessageType { + match b.to_int() { + 1 => DatabaseStore + 2 => DatabaseLookup + 3 => DatabaseSearchReply + 10 => DeliveryStatus + 11 => Garlic + 18 => TunnelData + 19 => TunnelGateway + 20 => Data + 21 => TunnelBuild + 22 => TunnelBuildReply + 23 => VariableTunnelBuild + 24 => VariableTunnelBuildReply + 25 => ShortTunnelBuild + 26 => ShortTunnelBuildReply + _ => Unknown(b) + } +} + +///| +/// Standard 16-byte I2NP header: +/// `type (1B) | msg_id (4B) | expiration_ms (8B) | size (2B) | checksum (1B)`. +/// Checksum is the first byte of `SHA-256(payload)`. +#derive(Eq, Debug) +pub(all) struct StandardHeader { + msg_type : I2npMessageType + msg_id : UInt32 + expiration_ms : UInt64 + size : UInt32 + checksum : Byte +} + +///| +pub fn StandardHeader::encode( + self : StandardHeader, + w : @encoding.Writer, +) -> Unit { + w.write_u8(self.msg_type.to_byte()) + w.write_u32_be(self.msg_id) + w.write_u64_be(self.expiration_ms) + w.write_u16_be(self.size) + w.write_u8(self.checksum) +} + +///| +pub fn StandardHeader::decode( + r : @encoding.Reader, +) -> StandardHeader raise I2npError { + let msg_type = I2npMessageType::from_byte( + r.read_u8() catch { + e => raise Encoding(e) + }, + ) + let msg_id = r.read_u32_be() catch { e => raise Encoding(e) } + let expiration_ms = r.read_u64_be() catch { e => raise Encoding(e) } + let size = r.read_u16_be() catch { e => raise Encoding(e) } + let checksum = r.read_u8() catch { e => raise Encoding(e) } + { msg_type, msg_id, expiration_ms, size, checksum, } +} + +///| +/// Short 9-byte NTCP2/SSU2 I2NP header: +/// `type (1B) | msg_id (4B) | expiration_sec (4B)`. +#derive(Eq, Debug) +pub(all) struct ShortHeader { + msg_type : I2npMessageType + msg_id : UInt32 + expiration_sec : UInt32 +} + +///| +pub fn ShortHeader::encode(self : ShortHeader, w : @encoding.Writer) -> Unit { + w.write_u8(self.msg_type.to_byte()) + w.write_u32_be(self.msg_id) + w.write_u32_be(self.expiration_sec) +} + +///| +pub fn ShortHeader::decode(r : @encoding.Reader) -> ShortHeader raise I2npError { + let msg_type = I2npMessageType::from_byte( + r.read_u8() catch { + e => raise Encoding(e) + }, + ) + let msg_id = r.read_u32_be() catch { e => raise Encoding(e) } + let expiration_sec = r.read_u32_be() catch { e => raise Encoding(e) } + { msg_type, msg_id, expiration_sec, } +} + +///| +/// Computes the 1-byte I2NP payload checksum: first byte of SHA-256(payload). +pub fn payload_checksum(payload : Bytes) -> Byte { + @crypto.sha256(payload)[0] +} + +///| +/// Core I2NP message payloads. +#derive(Eq, Debug) +pub(all) enum I2npPayload { + /// Type 1: DatabaseStore (stores a RouterInfo or LeaseSet in NetDB). + DatabaseStore( + key~ : @common.Hash, + store_type~ : Byte, + reply_token~ : UInt32, + reply_tunnel_id~ : UInt32, + reply_gateway~ : @common.Hash?, + data~ : Bytes, + ) + /// Type 2: DatabaseLookup (queries NetDB for a key). + DatabaseLookup( + key~ : @common.Hash, + from~ : @common.Hash, + flags~ : Byte, + reply_tunnel_id~ : UInt32?, + excluded_peers~ : Array[@common.Hash], + ) + /// Type 3: DatabaseSearchReply (floodfill returns closest router hashes). + DatabaseSearchReply( + key~ : @common.Hash, + peer_hashes~ : Array[@common.Hash], + from~ : @common.Hash, + ) + /// Type 10: DeliveryStatus (confirms delivery of a message or tunnel test). + DeliveryStatus(msg_id~ : UInt32, timestamp_ms~ : UInt64) + /// Type 11: Garlic (length-prefixed encrypted garlic cloves). + Garlic(data~ : Bytes) + /// Type 18: TunnelData (4-byte tunnel ID + 1024-byte encrypted tunnel data). + TunnelData(tunnel_id~ : UInt32, data~ : Bytes) + /// Type 19: TunnelGateway (4-byte tunnel ID + 2-byte length + I2NP message). + TunnelGateway(tunnel_id~ : UInt32, data~ : Bytes) + /// Type 20: Data (4-byte length + opaque payload). + Data(data~ : Bytes) + /// Type 25: ShortTunnelBuild (1-byte record count + N * 218-byte encrypted build records). + ShortTunnelBuild(records~ : Array[Bytes]) + /// Type 26: ShortTunnelBuildReply (1-byte record count + N * 218-byte encrypted reply records). + ShortTunnelBuildReply(records~ : Array[Bytes]) + /// Fallback for other/custom I2NP message types. + Raw(msg_type~ : I2npMessageType, data~ : Bytes) +} + +///| +pub fn I2npPayload::msg_type(self : I2npPayload) -> I2npMessageType { + match self { + DatabaseStore(..) => DatabaseStore + DatabaseLookup(..) => DatabaseLookup + DatabaseSearchReply(..) => DatabaseSearchReply + DeliveryStatus(..) => DeliveryStatus + Garlic(..) => Garlic + TunnelData(..) => TunnelData + TunnelGateway(..) => TunnelGateway + Data(..) => Data + ShortTunnelBuild(..) => ShortTunnelBuild + ShortTunnelBuildReply(..) => ShortTunnelBuildReply + Raw(msg_type~, ..) => msg_type + } +} + +///| +pub fn I2npPayload::encode_body(self : I2npPayload) -> Bytes raise I2npError { + let w = @encoding.Writer::new() + match self { + DatabaseStore( + key~, + store_type~, + reply_token~, + reply_tunnel_id~, + reply_gateway~, + data~, + ) => { + key.encode(w) + w.write_u8(store_type) + w.write_u32_be(reply_token) + if reply_token != 0U { + w.write_u32_be(reply_tunnel_id) + match reply_gateway { + Some(gw) => gw.encode(w) + None => + raise InvalidLength( + "DatabaseStore with non-zero reply_token requires reply_gateway", + ) + } + } + w.write_bytes(data) + } + DatabaseLookup(key~, from~, flags~, reply_tunnel_id~, excluded_peers~) => { + key.encode(w) + from.encode(w) + w.write_u8(flags) + if (flags.to_int() & 0x01) != 0 { + match reply_tunnel_id { + Some(tid) => w.write_u32_be(tid) + None => + raise InvalidLength( + "DatabaseLookup with tunnel delivery flag requires reply_tunnel_id", + ) + } + } + w.write_u16_be(excluded_peers.length().reinterpret_as_uint()) + for peer in excluded_peers { + peer.encode(w) + } + } + DatabaseSearchReply(key~, peer_hashes~, from~) => { + key.encode(w) + w.write_u8(peer_hashes.length().to_byte()) + for peer in peer_hashes { + peer.encode(w) + } + from.encode(w) + } + DeliveryStatus(msg_id~, timestamp_ms~) => { + w.write_u32_be(msg_id) + w.write_u64_be(timestamp_ms) + } + Garlic(data~) => { + w.write_u32_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + TunnelData(tunnel_id~, data~) => { + if data.length() != 1024 { + raise InvalidLength( + "TunnelData payload must be 1024 bytes, got \{data.length()}", + ) + } + w.write_u32_be(tunnel_id) + w.write_bytes(data) + } + TunnelGateway(tunnel_id~, data~) => { + if data.length() > 65535 { + raise InvalidLength("TunnelGateway payload exceeds 65535 bytes") + } + w.write_u32_be(tunnel_id) + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + Data(data~) => { + w.write_u32_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + ShortTunnelBuild(records~) | ShortTunnelBuildReply(records~) => { + w.write_u8(records.length().to_byte()) + for rec in records { + if rec.length() != 218 { + raise InvalidLength( + "ShortTunnelBuild record must be 218 bytes, got \{rec.length()}", + ) + } + w.write_bytes(rec) + } + } + Raw(data~, ..) => w.write_bytes(data) + } + w.to_bytes() +} + +///| +pub fn I2npPayload::decode_body( + msg_type : I2npMessageType, + body : Bytes, +) -> I2npPayload raise I2npError { + let r = @encoding.Reader::new(body) + match msg_type { + DatabaseStore => { + let key = @common.Hash::decode(r) catch { e => raise Common(e) } + let store_type = r.read_u8() catch { e => raise Encoding(e) } + let reply_token = r.read_u32_be() catch { e => raise Encoding(e) } + let (reply_tunnel_id, reply_gateway) = if reply_token != 0U { + let tid = r.read_u32_be() catch { e => raise Encoding(e) } + let gw = @common.Hash::decode(r) catch { e => raise Common(e) } + (tid, Some(gw)) + } else { + (0U, None) + } + let data = r.read_remaining() + DatabaseStore( + key~, + store_type~, + reply_token~, + reply_tunnel_id~, + reply_gateway~, + data~, + ) + } + DatabaseLookup => { + let key = @common.Hash::decode(r) catch { e => raise Common(e) } + let from = @common.Hash::decode(r) catch { e => raise Common(e) } + let flags = r.read_u8() catch { e => raise Encoding(e) } + let reply_tunnel_id = if (flags.to_int() & 0x01) != 0 { + Some(r.read_u32_be() catch { e => raise Encoding(e) }) + } else { + None + } + let excl_count = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let excluded_peers : Array[@common.Hash] = Array(capacity=excl_count) + for _i = 0; _i < excl_count; _i = _i + 1 { + excluded_peers.push( + @common.Hash::decode(r) catch { + e => raise Common(e) + }, + ) + } + DatabaseLookup(key~, from~, flags~, reply_tunnel_id~, excluded_peers~) + } + DatabaseSearchReply => { + let key = @common.Hash::decode(r) catch { e => raise Common(e) } + let count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let peer_hashes : Array[@common.Hash] = Array(capacity=count) + for _i = 0; _i < count; _i = _i + 1 { + peer_hashes.push(@common.Hash::decode(r) catch { e => raise Common(e) }) + } + let from = @common.Hash::decode(r) catch { e => raise Common(e) } + DatabaseSearchReply(key~, peer_hashes~, from~) + } + DeliveryStatus => { + let msg_id = r.read_u32_be() catch { e => raise Encoding(e) } + let timestamp_ms = r.read_u64_be() catch { e => raise Encoding(e) } + DeliveryStatus(msg_id~, timestamp_ms~) + } + Garlic => { + let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let data = r.read_bytes(len) catch { e => raise Encoding(e) } + Garlic(data~) + } + TunnelData => { + let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } + let data = r.read_bytes(1024) catch { e => raise Encoding(e) } + TunnelData(tunnel_id~, data~) + } + TunnelGateway => { + let tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } + let len = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let data = r.read_bytes(len) catch { e => raise Encoding(e) } + TunnelGateway(tunnel_id~, data~) + } + Data => { + let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let data = r.read_bytes(len) catch { e => raise Encoding(e) } + Data(data~) + } + ShortTunnelBuild => { + let count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let records : Array[Bytes] = Array(capacity=count) + for _i = 0; _i < count; _i = _i + 1 { + records.push(r.read_bytes(218) catch { e => raise Encoding(e) }) + } + ShortTunnelBuild(records~) + } + ShortTunnelBuildReply => { + let count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let records : Array[Bytes] = Array(capacity=count) + for _i = 0; _i < count; _i = _i + 1 { + records.push(r.read_bytes(218) catch { e => raise Encoding(e) }) + } + ShortTunnelBuildReply(records~) + } + _ => Raw(msg_type~, data=body) + } +} + +///| +/// Encodes a complete I2NP message with its 16-byte StandardHeader and SHA-256 checksum. +pub fn encode_standard_message( + msg_id : UInt32, + expiration_ms : UInt64, + payload : I2npPayload, +) -> Bytes raise I2npError { + let body = payload.encode_body() + if body.length() > 65535 { + raise InvalidLength("I2NP message body exceeds 65535 bytes") + } + let hdr : StandardHeader = { + msg_type: payload.msg_type(), + msg_id, + expiration_ms, + size: body.length().reinterpret_as_uint(), + checksum: payload_checksum(body), + } + let w = @encoding.Writer::new(capacity=16 + body.length()) + hdr.encode(w) + w.write_bytes(body) + w.to_bytes() +} + +///| +/// Decodes and checksum-verifies a standard 16-byte-header I2NP message. +pub fn decode_standard_message( + r : @encoding.Reader, +) -> (StandardHeader, I2npPayload) raise I2npError { + let hdr = StandardHeader::decode(r) + let body = r.read_bytes(hdr.size.reinterpret_as_int()) catch { + e => raise Encoding(e) + } + let actual = payload_checksum(body) + if actual != hdr.checksum { + raise ChecksumMismatch(hdr.checksum, actual) + } + let payload = I2npPayload::decode_body(hdr.msg_type, body) + (hdr, payload) +} + +///| +/// Encodes a complete I2NP message with the 9-byte NTCP2/SSU2 ShortHeader. +pub fn encode_short_message( + msg_id : UInt32, + expiration_sec : UInt32, + payload : I2npPayload, +) -> Bytes raise I2npError { + let body = payload.encode_body() + let hdr : ShortHeader = { + msg_type: payload.msg_type(), + msg_id, + expiration_sec, + } + let w = @encoding.Writer::new(capacity=9 + body.length()) + hdr.encode(w) + w.write_bytes(body) + w.to_bytes() +} + +///| +/// Decodes an NTCP2/SSU2 9-byte-header I2NP message (consuming remaining bytes in `r`). +pub fn decode_short_message( + r : @encoding.Reader, +) -> (ShortHeader, I2npPayload) raise I2npError { + let hdr = ShortHeader::decode(r) + let body = r.read_remaining() + let payload = I2npPayload::decode_body(hdr.msg_type, body) + (hdr, payload) +} diff --git a/i2np/moon.pkg b/i2np/moon.pkg new file mode 100644 index 0000000..72abb26 --- /dev/null +++ b/i2np/moon.pkg @@ -0,0 +1,5 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/common", +} diff --git a/i2np/pkg.generated.mbti b/i2np/pkg.generated.mbti new file mode 100644 index 0000000..cc75b9a --- /dev/null +++ b/i2np/pkg.generated.mbti @@ -0,0 +1,92 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/i2np" + +import { + "experiments/moon_i2p/common", + "experiments/moon_i2p/encoding", + "moonbitlang/core/debug", +} + +// Values +pub fn decode_short_message(@encoding.Reader) -> (ShortHeader, I2npPayload) raise I2npError + +pub fn decode_standard_message(@encoding.Reader) -> (StandardHeader, I2npPayload) raise I2npError + +pub fn encode_short_message(UInt32, UInt32, I2npPayload) -> Bytes raise I2npError + +pub fn encode_standard_message(UInt32, UInt64, I2npPayload) -> Bytes raise I2npError + +pub fn payload_checksum(Bytes) -> Byte + +// Errors +#derive(Eq, @debug.Debug) +pub suberror I2npError { + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + ChecksumMismatch(Byte, Byte) + InvalidLength(String) +} + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum I2npMessageType { + DatabaseStore + DatabaseLookup + DatabaseSearchReply + DeliveryStatus + Garlic + TunnelData + TunnelGateway + Data + TunnelBuild + TunnelBuildReply + VariableTunnelBuild + VariableTunnelBuildReply + ShortTunnelBuild + ShortTunnelBuildReply + Unknown(Byte) +} +pub fn I2npMessageType::from_byte(Byte) -> Self +pub fn I2npMessageType::to_byte(Self) -> Byte + +#derive(Eq, @debug.Debug) +pub(all) enum I2npPayload { + DatabaseStore(key~ : @common.Hash, store_type~ : Byte, reply_token~ : UInt32, reply_tunnel_id~ : UInt32, reply_gateway~ : @common.Hash?, data~ : Bytes) + DatabaseLookup(key~ : @common.Hash, from~ : @common.Hash, flags~ : Byte, reply_tunnel_id~ : UInt32?, excluded_peers~ : Array[@common.Hash]) + DatabaseSearchReply(key~ : @common.Hash, peer_hashes~ : Array[@common.Hash], from~ : @common.Hash) + DeliveryStatus(msg_id~ : UInt32, timestamp_ms~ : UInt64) + Garlic(data~ : Bytes) + TunnelData(tunnel_id~ : UInt32, data~ : Bytes) + TunnelGateway(tunnel_id~ : UInt32, data~ : Bytes) + Data(data~ : Bytes) + ShortTunnelBuild(records~ : Array[Bytes]) + ShortTunnelBuildReply(records~ : Array[Bytes]) + Raw(msg_type~ : I2npMessageType, data~ : Bytes) +} +pub fn I2npPayload::decode_body(I2npMessageType, Bytes) -> Self raise I2npError +pub fn I2npPayload::encode_body(Self) -> Bytes raise I2npError +pub fn I2npPayload::msg_type(Self) -> I2npMessageType + +#derive(Eq, @debug.Debug) +pub(all) struct ShortHeader { + msg_type : I2npMessageType + msg_id : UInt32 + expiration_sec : UInt32 +} +pub fn ShortHeader::decode(@encoding.Reader) -> Self raise I2npError +pub fn ShortHeader::encode(Self, @encoding.Writer) -> Unit + +#derive(Eq, @debug.Debug) +pub(all) struct StandardHeader { + msg_type : I2npMessageType + msg_id : UInt32 + expiration_ms : UInt64 + size : UInt32 + checksum : Byte +} +pub fn StandardHeader::decode(@encoding.Reader) -> Self raise I2npError +pub fn StandardHeader::encode(Self, @encoding.Writer) -> Unit + +// Type aliases + +// Traits diff --git a/moon.mod b/moon.mod new file mode 100644 index 0000000..751309e --- /dev/null +++ b/moon.mod @@ -0,0 +1,15 @@ +name = "experiments/moon_i2p" + +version = "0.1.0" + +readme = "README.md" + +repository = "https://git.site.latha.org/experiments/moon-i2p" + +license = "Apache-2.0" + +keywords = [ "i2p", "cryptography", "networking", "privacy", "noise", "ntcp2" ] + +preferred_target = "wasm" + +description = "Pure MoonBit port of the I2P (Invisible Internet Project) protocol suite" diff --git a/moon.pkg b/moon.pkg new file mode 100644 index 0000000..4a43523 --- /dev/null +++ b/moon.pkg @@ -0,0 +1,8 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/common", + "experiments/moon_i2p/i2np", + "experiments/moon_i2p/noise", + "experiments/moon_i2p/sam", +} diff --git a/moon_i2p.mbt b/moon_i2p.mbt new file mode 100644 index 0000000..a5d7de9 --- /dev/null +++ b/moon_i2p.mbt @@ -0,0 +1,56 @@ +///| +/// `moon-i2p`: Pure MoonBit implementation of the I2P (Invisible Internet Project) protocol suite. +/// +/// Packages: +/// - `experiments/moon_i2p/encoding` — I2P custom Base64 (`-`/`~`), Base32 (`.b32.i2p`), big-endian `Reader`/`Writer`, hex. +/// - `experiments/moon_i2p/crypto` — SHA-256, HMAC-SHA256, HKDF-SHA256, ChaCha20-Poly1305 AEAD, X25519, SipHash-2-4. +/// - `experiments/moon_i2p/common` — `Hash`, `Certificate`/`KeyCertificate`, `Mapping`, `Destination`, `RouterIdentity`, `RouterAddress`, `RouterInfo`, `Lease`/`Lease2`, `LeaseSet2`. +/// - `experiments/moon_i2p/i2np` — I2NP 16-byte standard & 9-byte NTCP2 short headers, checksums, and core messages. +/// - `experiments/moon_i2p/noise` — `Noise_XK_25519_ChaChaPoly_SHA256` handshake/transport + NTCP2 SipHash length masking. +/// - `experiments/moon_i2p/sam` — SAMv3 text protocol parser, serializer, and command builders. + +///| +pub fn version() -> String { + "0.1.0" +} + +///| +/// Convenience helper: derives the `.b32.i2p` address from raw X25519 & Ed25519 public keys. +pub fn derive_b32_address( + crypto_pub : Bytes, + signing_pub : Bytes, +) -> String raise @common.CommonError { + let dest = @common.Destination::new_x25519_ed25519(crypto_pub, signing_pub) + dest.b32_address() +} + +///| +/// Runs a self-contained protocol smoke check across encoding, crypto, common, I2NP, Noise_XK, and SAMv3. +pub fn demo_summary() -> String { + try { + let alice_s = @noise.KeyPair::from_private( + @encoding.hex_decode( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + ), + ) + let bob_s = @noise.KeyPair::from_private( + @encoding.hex_decode( + "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", + ), + ) + let dest = @common.Destination::new_x25519_ed25519( + alice_s.public_key, + bob_s.public_key, + ) + let msg = @i2np.encode_short_message( + 1U, + 1700000000U, + @i2np.I2npPayload::Data(data=b"moon-i2p"), + ) + let sam_hello = @sam.hello_version().serialize() + let digest = @encoding.hex_encode(@crypto.sha256(msg)) + "moon-i2p v\{version()} | b32=\{dest.b32_address()} | i2np_sha256=\{digest} | sam=\{sam_hello}" + } catch { + _ => "moon-i2p demo failed" + } +} diff --git a/moon_i2p_test.mbt b/moon_i2p_test.mbt new file mode 100644 index 0000000..a6b0d7f --- /dev/null +++ b/moon_i2p_test.mbt @@ -0,0 +1,12 @@ +///| +test "root facade derive_b32_address and demo_summary" { + let addr = @moon_i2p.derive_b32_address( + Bytes::make(32, b'\x01'), + Bytes::make(32, b'\x02'), + ) + assert_eq(addr.length(), 60) + assert_true(addr.has_suffix(".b32.i2p")) + let summary = @moon_i2p.demo_summary() + assert_true(summary.contains("moon-i2p v0.1.0")) + assert_true(summary.contains(".b32.i2p")) +} diff --git a/noise/moon.pkg b/noise/moon.pkg new file mode 100644 index 0000000..220652c --- /dev/null +++ b/noise/moon.pkg @@ -0,0 +1,7 @@ +import { + "experiments/moon_i2p/crypto", +} + +import { + "experiments/moon_i2p/encoding", +} for "test" diff --git a/noise/noise_test.mbt b/noise/noise_test.mbt new file mode 100644 index 0000000..7dc2d67 --- /dev/null +++ b/noise/noise_test.mbt @@ -0,0 +1,82 @@ +///| +test "Noise_XK_25519_ChaChaPoly_SHA256 full 3-message handshake and transport" { + let alice_s = @noise.KeyPair::from_private( + @encoding.hex_decode( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + ), + ) + let bob_s = @noise.KeyPair::from_private( + @encoding.hex_decode( + "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", + ), + ) + let alice_e = @noise.KeyPair::from_private( + @encoding.hex_decode( + "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", + ), + ) + let bob_e = @noise.KeyPair::from_private( + @encoding.hex_decode( + "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", + ), + ) + + let alice = @noise.HandshakeState::new_initiator( + alice_s, + bob_s.public_key, + protocol_name=@noise.ntcp2_protocol_name, + ) + let bob = @noise.HandshakeState::new_responder( + bob_s, + protocol_name=@noise.ntcp2_protocol_name, + ) + alice.set_ephemeral(alice_e) + bob.set_ephemeral(bob_e) + + // Message 1: -> e, es (SessionRequest) + let msg1 = alice.write_message(b"ntcp2-session-request-options") + let req_pt = bob.read_message(msg1) + assert_eq(req_pt, b"ntcp2-session-request-options") + + // Message 2: <- e, ee (SessionCreated) + let msg2 = bob.write_message(b"ntcp2-session-created-options") + let created_pt = alice.read_message(msg2) + assert_eq(created_pt, b"ntcp2-session-created-options") + + // Message 3: -> s, se (SessionConfirmed) + let msg3 = alice.write_message(b"alice-router-info-block") + let confirmed_pt = bob.read_message(msg3) + assert_eq(confirmed_pt, b"alice-router-info-block") + + // Split into transport sessions + let alice_tx = alice.into_transport() + let bob_tx = bob.into_transport() + + // Both sides derive identical handshake hash and authenticate peer static keys + assert_eq(alice_tx.handshake_hash(), bob_tx.handshake_hash()) + assert_eq(bob_tx.remote_static(), alice_s.public_key) + assert_eq(alice_tx.remote_static(), bob_s.public_key) + + // Bidirectional encrypted data phase + let ct1 = alice_tx.encrypt(b"hello bob over NTCP2") + assert_eq(bob_tx.decrypt(ct1), b"hello bob over NTCP2") + + let ct2 = bob_tx.encrypt(b"hello alice from floodfill") + assert_eq(alice_tx.decrypt(ct2), b"hello alice from floodfill") +} + +///| +test "NTCP2 SipHash-2-4 length obfuscation round-trip" { + let key = @encoding.hex_decode("000102030405060708090a0b0c0d0e0f") + let iv = @encoding.hex_decode("1122334455667788") + let sender = @noise.SipHashLengthMask::new(key, iv) + let receiver = @noise.SipHashLengthMask::new(key, iv) + + let lengths : Array[UInt32] = [48U, 1024U, 16384U, 65519U] + for orig in lengths { + let obf = sender.xor_length(orig) + assert_true(obf != orig) + let restored = receiver.xor_length(obf) + assert_eq(restored, orig) + } +} diff --git a/noise/noise_xk.mbt b/noise/noise_xk.mbt new file mode 100644 index 0000000..cd373d0 --- /dev/null +++ b/noise/noise_xk.mbt @@ -0,0 +1,529 @@ +///| +/// Errors raised by the Noise_XK_25519_ChaChaPoly_SHA256 / NTCP2 protocol engine. +#derive(Eq, Debug) +pub suberror NoiseError { + Crypto(@crypto.CryptoError) + InvalidState(String) + InvalidLength(String) + NonceOverflow +} + +///| +/// Noise Protocol Name used by I2P NTCP2 (`Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256` +/// or standard `Noise_XK_25519_ChaChaPoly_SHA256`). +pub let noise_xk_protocol_name : Bytes = b"Noise_XK_25519_ChaChaPoly_SHA256" + +///| +pub let ntcp2_protocol_name : Bytes = b"Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256" + +///| +fn make_noise_nonce(n : UInt64) -> Bytes { + // Noise ChaChaPoly nonce: 4 zero bytes followed by 64-bit little-endian counter + let buf = FixedArray::make(12, b'\x00') + for i = 0; i < 8; i = i + 1 { + buf[4 + i] = ((n >> (i * 8)) & 0xFFUL).to_byte() + } + Bytes::from_array(buf) +} + +///| +fn slice_bytes(data : Bytes, start : Int32, len : Int32) -> Bytes { + let out = FixedArray::make(len, b'\x00') + for i = 0; i < len; i = i + 1 { + out[i] = data[start + i] + } + Bytes::from_array(out) +} + +///| +fn concat_bytes(a : Bytes, b : Bytes) -> Bytes { + let out = FixedArray::make(a.length() + b.length(), b'\x00') + for i = 0; i < a.length(); i = i + 1 { + out[i] = a[i] + } + for i = 0; i < b.length(); i = i + 1 { + out[a.length() + i] = b[i] + } + Bytes::from_array(out) +} + +///| +/// Noise HKDF(chaining_key, input_key_material) -> (output1, output2) (each 32 bytes). +fn noise_hkdf2(ck : Bytes, ikm : Bytes) -> (Bytes, Bytes) { + let temp_key = @crypto.hmac_sha256(ck, ikm) + let out1 = @crypto.hmac_sha256(temp_key, b"\x01") + let out2 = @crypto.hmac_sha256(temp_key, concat_bytes(out1, b"\x02")) + (out1, out2) +} + +///| +/// Noise CipherState (ChaCha20-Poly1305 with 64-bit counter nonce). +pub struct CipherState { + mut key : Bytes? + mut nonce : UInt64 +} + +///| +pub fn CipherState::empty() -> CipherState { + { key: None, nonce: 0UL, } +} + +///| +pub fn CipherState::initialize_key(self : CipherState, key : Bytes) -> Unit { + self.key = Some(key) + self.nonce = 0UL +} + +///| +pub fn CipherState::has_key(self : CipherState) -> Bool { + self.key is Some(_) +} + +///| +pub fn CipherState::encrypt_with_ad( + self : CipherState, + ad : Bytes, + plaintext : Bytes, +) -> Bytes raise NoiseError { + match self.key { + None => plaintext + Some(k) => { + if self.nonce == 0xFFFFFFFFFFFFFFFFUL { + raise NonceOverflow + } + let nonce = make_noise_nonce(self.nonce) + self.nonce = self.nonce + 1UL + @crypto.aead_chacha20_poly1305_encrypt(k, nonce, ad, plaintext) catch { + e => raise Crypto(e) + } + } + } +} + +///| +pub fn CipherState::decrypt_with_ad( + self : CipherState, + ad : Bytes, + ciphertext : Bytes, +) -> Bytes raise NoiseError { + match self.key { + None => ciphertext + Some(k) => { + if self.nonce == 0xFFFFFFFFFFFFFFFFUL { + raise NonceOverflow + } + let nonce = make_noise_nonce(self.nonce) + let pt = @crypto.aead_chacha20_poly1305_decrypt(k, nonce, ad, ciphertext) catch { + e => raise Crypto(e) + } + self.nonce = self.nonce + 1UL + pt + } + } +} + +///| +/// Noise SymmetricState (chaining key `ck`, handshake hash `h`, and `CipherState`). +pub struct SymmetricState { + mut ck : Bytes + mut h : Bytes + cipher : CipherState +} + +///| +pub fn SymmetricState::initialize(protocol_name : Bytes) -> SymmetricState { + let h = if protocol_name.length() <= 32 { + let padded = FixedArray::make(32, b'\x00') + for i = 0; i < protocol_name.length(); i = i + 1 { + padded[i] = protocol_name[i] + } + Bytes::from_array(padded) + } else { + @crypto.sha256(protocol_name) + } + { ck: h, h, cipher: CipherState::empty(), } +} + +///| +pub fn SymmetricState::mix_key(self : SymmetricState, ikm : Bytes) -> Unit { + let (ck, temp_k) = noise_hkdf2(self.ck, ikm) + self.ck = ck + self.cipher.initialize_key(temp_k) +} + +///| +pub fn SymmetricState::mix_hash(self : SymmetricState, data : Bytes) -> Unit { + self.h = @crypto.sha256(concat_bytes(self.h, data)) +} + +///| +pub fn SymmetricState::encrypt_and_hash( + self : SymmetricState, + plaintext : Bytes, +) -> Bytes raise NoiseError { + let ct = self.cipher.encrypt_with_ad(self.h, plaintext) + self.mix_hash(ct) + ct +} + +///| +pub fn SymmetricState::decrypt_and_hash( + self : SymmetricState, + ciphertext : Bytes, +) -> Bytes raise NoiseError { + let pt = self.cipher.decrypt_with_ad(self.h, ciphertext) + self.mix_hash(ciphertext) + pt +} + +///| +pub fn SymmetricState::handshake_hash(self : SymmetricState) -> Bytes { + self.h +} + +///| +pub fn SymmetricState::split( + self : SymmetricState, +) -> (CipherState, CipherState) { + let (k1, k2) = noise_hkdf2(self.ck, b"") + let c1 = CipherState::empty() + let c2 = CipherState::empty() + c1.initialize_key(k1) + c2.initialize_key(k2) + (c1, c2) +} + +///| +/// X25519 static/ephemeral keypair for Noise_XK. +#derive(Eq, Debug) +pub(all) struct KeyPair { + private_key : Bytes + public_key : Bytes +} + +///| +pub fn KeyPair::from_private(private_key : Bytes) -> KeyPair raise NoiseError { + let public_key = @crypto.x25519_public_key(private_key) catch { + e => raise Crypto(e) + } + { private_key, public_key, } +} + +///| +/// Post-handshake bidirectional encrypted transport session. +pub struct TransportSession { + send_cipher : CipherState + recv_cipher : CipherState + handshake_hash : Bytes + remote_static : Bytes +} + +///| +pub fn TransportSession::encrypt( + self : TransportSession, + plaintext : Bytes, +) -> Bytes raise NoiseError { + self.send_cipher.encrypt_with_ad(b"", plaintext) +} + +///| +pub fn TransportSession::decrypt( + self : TransportSession, + ciphertext : Bytes, +) -> Bytes raise NoiseError { + self.recv_cipher.decrypt_with_ad(b"", ciphertext) +} + +///| +pub fn TransportSession::handshake_hash(self : TransportSession) -> Bytes { + self.handshake_hash +} + +///| +pub fn TransportSession::remote_static(self : TransportSession) -> Bytes { + self.remote_static +} + +///| +/// `Noise_XK_25519_ChaChaPoly_SHA256` HandshakeState: +/// ``` +/// <- s (pre-message: responder's static key known to initiator) +/// ... +/// -> e, es (Message 1: SessionRequest) +/// <- e, ee (Message 2: SessionCreated) +/// -> s, se (Message 3: SessionConfirmed) +/// ``` +pub struct HandshakeState { + symmetric : SymmetricState + initiator : Bool + s : KeyPair + mut e : KeyPair? + mut rs : Bytes? + mut re : Bytes? + mut step : Int32 // 0 -> msg1, 1 -> msg2, 2 -> msg3, 3 -> done +} + +///| +/// Initializes a `Noise_XK` initiator handshake state (knows responder's static key `rs`). +pub fn HandshakeState::new_initiator( + local_static : KeyPair, + remote_static : Bytes, + protocol_name~ : Bytes = noise_xk_protocol_name, + prologue~ : Bytes = b"", +) -> HandshakeState raise NoiseError { + if remote_static.length() != 32 { + raise InvalidLength("remote_static must be 32 bytes") + } + let sym = SymmetricState::initialize(protocol_name) + sym.mix_hash(prologue) + // Pre-message: <- s + sym.mix_hash(remote_static) + { + symmetric: sym, + initiator: true, + s: local_static, + e: None, + rs: Some(remote_static), + re: None, + step: 0, + } +} + +///| +/// Initializes a `Noise_XK` responder handshake state. +pub fn HandshakeState::new_responder( + local_static : KeyPair, + protocol_name~ : Bytes = noise_xk_protocol_name, + prologue~ : Bytes = b"", +) -> HandshakeState { + let sym = SymmetricState::initialize(protocol_name) + sym.mix_hash(prologue) + // Pre-message: <- s + sym.mix_hash(local_static.public_key) + { + symmetric: sym, + initiator: false, + s: local_static, + e: None, + rs: None, + re: None, + step: 0, + } +} + +///| +/// Sets the local ephemeral keypair before sending Message 1 (initiator) or Message 2 (responder). +pub fn HandshakeState::set_ephemeral( + self : HandshakeState, + ephemeral : KeyPair, +) -> Unit { + self.e = Some(ephemeral) +} + +///| +/// Writes the next handshake message (`-> e, es`, `<- e, ee`, or `-> s, se`). +pub fn HandshakeState::write_message( + self : HandshakeState, + payload : Bytes, +) -> Bytes raise NoiseError { + if self.step == 0 && self.initiator { + // Message 1: -> e, es + let ephem = match self.e { + Some(kp) => kp + None => + raise InvalidState("initiator ephemeral key must be set for msg 1") + } + let rs = match self.rs { + Some(k) => k + None => raise InvalidState("remote static key missing") + } + self.symmetric.mix_hash(ephem.public_key) + let dh_es = @crypto.x25519(ephem.private_key, rs) catch { + e => raise Crypto(e) + } + self.symmetric.mix_key(dh_es) + let enc_payload = self.symmetric.encrypt_and_hash(payload) + self.step = 1 + concat_bytes(ephem.public_key, enc_payload) + } else if self.step == 1 && !self.initiator { + // Message 2: <- e, ee + let ephem = match self.e { + Some(kp) => kp + None => + raise InvalidState("responder ephemeral key must be set for msg 2") + } + let re = match self.re { + Some(k) => k + None => raise InvalidState("remote ephemeral key missing") + } + self.symmetric.mix_hash(ephem.public_key) + let dh_ee = @crypto.x25519(ephem.private_key, re) catch { + e => raise Crypto(e) + } + self.symmetric.mix_key(dh_ee) + let enc_payload = self.symmetric.encrypt_and_hash(payload) + self.step = 2 + concat_bytes(ephem.public_key, enc_payload) + } else if self.step == 2 && self.initiator { + // Message 3: -> s, se + let re = match self.re { + Some(k) => k + None => raise InvalidState("remote ephemeral key missing") + } + let enc_s = self.symmetric.encrypt_and_hash(self.s.public_key) + let dh_se = @crypto.x25519(self.s.private_key, re) catch { + e => raise Crypto(e) + } + self.symmetric.mix_key(dh_se) + let enc_payload = self.symmetric.encrypt_and_hash(payload) + self.step = 3 + concat_bytes(enc_s, enc_payload) + } else { + raise InvalidState( + "write_message invalid for step=\{self.step}, initiator=\{self.initiator}", + ) + } +} + +///| +/// Reads and authenticates the next handshake message, returning its decrypted payload. +pub fn HandshakeState::read_message( + self : HandshakeState, + message : Bytes, +) -> Bytes raise NoiseError { + if self.step == 0 && !self.initiator { + // Message 1: -> e, es + if message.length() < 32 { + raise InvalidLength("msg 1 shorter than 32 bytes") + } + let re = slice_bytes(message, 0, 32) + self.re = Some(re) + self.symmetric.mix_hash(re) + let dh_es = @crypto.x25519(self.s.private_key, re) catch { + e => raise Crypto(e) + } + self.symmetric.mix_key(dh_es) + let pt = self.symmetric.decrypt_and_hash( + slice_bytes(message, 32, message.length() - 32), + ) + self.step = 1 + pt + } else if self.step == 1 && self.initiator { + // Message 2: <- e, ee + if message.length() < 32 { + raise InvalidLength("msg 2 shorter than 32 bytes") + } + let re = slice_bytes(message, 0, 32) + self.re = Some(re) + self.symmetric.mix_hash(re) + let ephem = match self.e { + Some(kp) => kp + None => raise InvalidState("initiator ephemeral key missing") + } + let dh_ee = @crypto.x25519(ephem.private_key, re) catch { + e => raise Crypto(e) + } + self.symmetric.mix_key(dh_ee) + let pt = self.symmetric.decrypt_and_hash( + slice_bytes(message, 32, message.length() - 32), + ) + self.step = 2 + pt + } else if self.step == 2 && !self.initiator { + // Message 3: -> s, se (encrypted static key is 32 + 16 = 48 bytes) + if message.length() < 48 { + raise InvalidLength("msg 3 shorter than 48 bytes") + } + let rs = self.symmetric.decrypt_and_hash(slice_bytes(message, 0, 48)) + self.rs = Some(rs) + let ephem = match self.e { + Some(kp) => kp + None => raise InvalidState("responder ephemeral key missing") + } + let dh_se = @crypto.x25519(ephem.private_key, rs) catch { + e => raise Crypto(e) + } + self.symmetric.mix_key(dh_se) + let pt = self.symmetric.decrypt_and_hash( + slice_bytes(message, 48, message.length() - 48), + ) + self.step = 3 + pt + } else { + raise InvalidState( + "read_message invalid for step=\{self.step}, initiator=\{self.initiator}", + ) + } +} + +///| +/// Completes the handshake and splits into a bidirectional `TransportSession`. +pub fn HandshakeState::into_transport( + self : HandshakeState, +) -> TransportSession raise NoiseError { + if self.step != 3 { + raise InvalidState("handshake not complete (step=\{self.step})") + } + let rs = match self.rs { + Some(k) => k + None => raise InvalidState("remote static key missing") + } + let (c1, c2) = self.symmetric.split() + let (send_cipher, recv_cipher) = if self.initiator { + (c1, c2) + } else { + (c2, c1) + } + { + send_cipher, + recv_cipher, + handshake_hash: self.symmetric.handshake_hash(), + remote_static: rs, + } +} + +///| +/// NTCP2 Data Phase frame length obfuscation using SipHash-2-4 (per NTCP2 specification). +/// Maintains a chaining 8-byte IV updated as `IV_n = SipHash-2-4(k, IV_{n-1})`. +pub struct SipHashLengthMask { + key : Bytes // 16-byte SipHash key + mut iv : Bytes // 8-byte running IV +} + +///| +pub fn SipHashLengthMask::new( + key : Bytes, + initial_iv : Bytes, +) -> SipHashLengthMask raise NoiseError { + if key.length() != 16 { + raise InvalidLength("NTCP2 SipHash key must be 16 bytes") + } + if initial_iv.length() != 8 { + raise InvalidLength("NTCP2 SipHash IV must be 8 bytes") + } + { key, iv: initial_iv, } +} + +///| +/// Advances the SipHash IV and returns the next 16-bit XOR length mask. +pub fn SipHashLengthMask::next_mask( + self : SipHashLengthMask, +) -> UInt32 raise NoiseError { + let h = @crypto.siphash_2_4(self.key, self.iv) catch { e => raise Crypto(e) } + let next_iv = FixedArray::make(8, b'\x00') + for i = 0; i < 8; i = i + 1 { + next_iv[i] = ((h >> (i * 8)) & 0xFFUL).to_byte() + } + self.iv = Bytes::from_array(next_iv) + // First 2 bytes of the SipHash output (big-endian uint16 mask) + ((next_iv[0].to_uint() << 8) | next_iv[1].to_uint()) & 0xFFFFU +} + +///| +/// Obfuscates or de-obfuscates a 16-bit NTCP2 frame length with the next SipHash mask. +pub fn SipHashLengthMask::xor_length( + self : SipHashLengthMask, + len : UInt32, +) -> UInt32 raise NoiseError { + (len ^ self.next_mask()) & 0xFFFFU +} diff --git a/noise/pkg.generated.mbti b/noise/pkg.generated.mbti new file mode 100644 index 0000000..571b8f3 --- /dev/null +++ b/noise/pkg.generated.mbti @@ -0,0 +1,91 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/noise" + +import { + "experiments/moon_i2p/crypto", + "moonbitlang/core/debug", +} + +// Values +pub let noise_xk_protocol_name : Bytes + +pub let ntcp2_protocol_name : Bytes + +// Errors +#derive(Eq, @debug.Debug) +pub suberror NoiseError { + Crypto(@crypto.CryptoError) + InvalidState(String) + InvalidLength(String) + NonceOverflow +} + +// Types and methods +pub struct CipherState { + mut key : Bytes? + mut nonce : UInt64 +} +pub fn CipherState::decrypt_with_ad(Self, Bytes, Bytes) -> Bytes raise NoiseError +pub fn CipherState::empty() -> Self +pub fn CipherState::encrypt_with_ad(Self, Bytes, Bytes) -> Bytes raise NoiseError +pub fn CipherState::has_key(Self) -> Bool +pub fn CipherState::initialize_key(Self, Bytes) -> Unit + +pub struct HandshakeState { + symmetric : SymmetricState + initiator : Bool + s : KeyPair + mut e : KeyPair? + mut rs : Bytes? + mut re : Bytes? + mut step : Int32 +} +pub fn HandshakeState::into_transport(Self) -> TransportSession raise NoiseError +pub fn HandshakeState::new_initiator(KeyPair, Bytes, protocol_name? : Bytes, prologue? : Bytes) -> Self raise NoiseError +pub fn HandshakeState::new_responder(KeyPair, protocol_name? : Bytes, prologue? : Bytes) -> Self +pub fn HandshakeState::read_message(Self, Bytes) -> Bytes raise NoiseError +pub fn HandshakeState::set_ephemeral(Self, KeyPair) -> Unit +pub fn HandshakeState::write_message(Self, Bytes) -> Bytes raise NoiseError + +#derive(Eq, @debug.Debug) +pub(all) struct KeyPair { + private_key : Bytes + public_key : Bytes +} +pub fn KeyPair::from_private(Bytes) -> Self raise NoiseError + +pub struct SipHashLengthMask { + key : Bytes + mut iv : Bytes +} +pub fn SipHashLengthMask::new(Bytes, Bytes) -> Self raise NoiseError +pub fn SipHashLengthMask::next_mask(Self) -> UInt32 raise NoiseError +pub fn SipHashLengthMask::xor_length(Self, UInt32) -> UInt32 raise NoiseError + +pub struct SymmetricState { + mut ck : Bytes + mut h : Bytes + cipher : CipherState +} +pub fn SymmetricState::decrypt_and_hash(Self, Bytes) -> Bytes raise NoiseError +pub fn SymmetricState::encrypt_and_hash(Self, Bytes) -> Bytes raise NoiseError +pub fn SymmetricState::handshake_hash(Self) -> Bytes +pub fn SymmetricState::initialize(Bytes) -> Self +pub fn SymmetricState::mix_hash(Self, Bytes) -> Unit +pub fn SymmetricState::mix_key(Self, Bytes) -> Unit +pub fn SymmetricState::split(Self) -> (CipherState, CipherState) + +pub struct TransportSession { + send_cipher : CipherState + recv_cipher : CipherState + handshake_hash : Bytes + remote_static : Bytes +} +pub fn TransportSession::decrypt(Self, Bytes) -> Bytes raise NoiseError +pub fn TransportSession::encrypt(Self, Bytes) -> Bytes raise NoiseError +pub fn TransportSession::handshake_hash(Self) -> Bytes +pub fn TransportSession::remote_static(Self) -> Bytes + +// Type aliases + +// Traits diff --git a/pkg.generated.mbti b/pkg.generated.mbti new file mode 100644 index 0000000..3c6ff1c --- /dev/null +++ b/pkg.generated.mbti @@ -0,0 +1,21 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p" + +import { + "experiments/moon_i2p/common", +} + +// Values +pub fn demo_summary() -> String + +pub fn derive_b32_address(Bytes, Bytes) -> String raise @common.CommonError + +pub fn version() -> String + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/sam/moon.pkg b/sam/moon.pkg new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/sam/moon.pkg @@ -0,0 +1 @@ + diff --git a/sam/pkg.generated.mbti b/sam/pkg.generated.mbti new file mode 100644 index 0000000..c1b7a49 --- /dev/null +++ b/sam/pkg.generated.mbti @@ -0,0 +1,45 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/sam" + +import { + "moonbitlang/core/debug", +} + +// Values +pub fn dest_generate(signature_type? : String) -> SamMessage + +pub fn hello_version(min? : String, max? : String) -> SamMessage + +pub fn naming_lookup(String) -> SamMessage + +pub fn session_create(String, String, destination? : String, signature_type? : String) -> SamMessage + +pub fn stream_accept(String, silent? : Bool) -> SamMessage + +pub fn stream_connect(String, String, silent? : Bool) -> SamMessage + +// Errors +#derive(Eq, @debug.Debug) +pub suberror SamError { + EmptyMessage + UnterminatedQuote + MalformedToken(String) +} + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct SamMessage { + verb : String + subcommand : String? + params : Array[(String, String)] +} +pub fn SamMessage::get(Self, String) -> String? +pub fn SamMessage::is_ok(Self) -> Bool +pub fn SamMessage::new(String, subcommand? : String?, params? : Array[(String, String)]) -> Self +pub fn SamMessage::parse(String) -> Self raise SamError +pub fn SamMessage::result(Self) -> String? +pub fn SamMessage::serialize(Self) -> String + +// Type aliases + +// Traits diff --git a/sam/sam.mbt b/sam/sam.mbt new file mode 100644 index 0000000..02b4616 --- /dev/null +++ b/sam/sam.mbt @@ -0,0 +1,282 @@ +///| +/// Errors raised when parsing SAMv3 protocol lines. +#derive(Eq, Debug) +pub suberror SamError { + EmptyMessage + UnterminatedQuote + MalformedToken(String) +} + +///| +/// A parsed SAMv3 protocol command or reply line: +/// `VERB [SUBCOMMAND] [KEY=VALUE ...]` terminated by `\n`. +#derive(Eq, Debug) +pub(all) struct SamMessage { + verb : String + subcommand : String? + params : Array[(String, String)] +} + +///| +pub fn SamMessage::new( + verb : String, + subcommand~ : String? = None, + params~ : Array[(String, String)] = [], +) -> SamMessage { + { verb, subcommand, params, } +} + +///| +pub fn SamMessage::get(self : SamMessage, key : String) -> String? { + for entry in self.params { + if entry.0 == key { + return Some(entry.1) + } + } + None +} + +///| +pub fn SamMessage::result(self : SamMessage) -> String? { + self.get("RESULT") +} + +///| +pub fn SamMessage::is_ok(self : SamMessage) -> Bool { + self.result() == Some("OK") +} + +///| +fn needs_quoting(s : String) -> Bool { + if s.length() == 0 { + return true + } + for ch in s { + if ch == ' ' || + ch == '\t' || + ch == '"' || + ch == '\\' || + ch == '\n' || + ch == '\r' { + return true + } + } + false +} + +///| +fn quote_value(s : String) -> String { + if !needs_quoting(s) { + return s + } + let buf = StringBuilder(capacity=s.length() + 2) + buf.write_char('"') + for ch in s { + if ch == '"' || ch == '\\' { + buf.write_char('\\') + } + buf.write_char(ch) + } + buf.write_char('"') + buf.to_string() +} + +///| +/// Serializes a `SamMessage` into a single `\n`-terminated SAMv3 wire line. +pub fn SamMessage::serialize(self : SamMessage) -> String { + let buf = StringBuilder() + buf.write_string(self.verb) + match self.subcommand { + Some(sub) => { + buf.write_char(' ') + buf.write_string(sub) + } + None => () + } + for entry in self.params { + buf.write_char(' ') + buf.write_string(entry.0) + buf.write_char('=') + buf.write_string(quote_value(entry.1)) + } + buf.write_char('\n') + buf.to_string() +} + +///| +/// Tokenizes a SAMv3 line respecting `"..."` quoted values and `\"` escapes. +fn tokenize_sam_line(line : String) -> Array[String] raise SamError { + let chars : Array[Char] = [] + for ch in line { + if ch != '\r' && ch != '\n' { + chars.push(ch) + } + } + let tokens : Array[String] = [] + let len = chars.length() + let mut i = 0 + while i < len { + while i < len && (chars[i] == ' ' || chars[i] == '\t') { + i += 1 + } + if i >= len { + break + } + let buf = StringBuilder() + let mut in_quotes = false + while i < len { + let c = chars[i] + if in_quotes { + if c == '\\' { + i += 1 + if i >= len { + raise UnterminatedQuote + } + buf.write_char(chars[i]) + i += 1 + } else if c == '"' { + in_quotes = false + i += 1 + } else { + buf.write_char(c) + i += 1 + } + } else if c == ' ' || c == '\t' { + break + } else if c == '"' { + in_quotes = true + i += 1 + } else { + buf.write_char(c) + i += 1 + } + } + if in_quotes { + raise UnterminatedQuote + } + tokens.push(buf.to_string()) + } + tokens +} + +///| +fn split_kv(token : String) -> (String, String)? { + let chars : Array[Char] = [] + for ch in token { + chars.push(ch) + } + let mut eq_idx = -1 + for i = 0; i < chars.length(); i = i + 1 { + if chars[i] == '=' { + eq_idx = i + break + } + } + if eq_idx <= 0 { + return None + } + let kbuf = StringBuilder(capacity=eq_idx) + for i = 0; i < eq_idx; i = i + 1 { + kbuf.write_char(chars[i]) + } + let vbuf = StringBuilder(capacity=chars.length() - eq_idx - 1) + for i = eq_idx + 1; i < chars.length(); i = i + 1 { + vbuf.write_char(chars[i]) + } + Some((kbuf.to_string(), vbuf.to_string())) +} + +///| +/// Parses a SAMv3 protocol line into a `SamMessage`. +pub fn SamMessage::parse(line : String) -> SamMessage raise SamError { + let tokens = tokenize_sam_line(line) + if tokens.length() == 0 { + raise EmptyMessage + } + let verb = tokens[0] + let mut idx = 1 + let mut subcommand : String? = None + if idx < tokens.length() { + match split_kv(tokens[idx]) { + None => { + subcommand = Some(tokens[idx]) + idx += 1 + } + Some(_) => () + } + } + let params : Array[(String, String)] = [] + while idx < tokens.length() { + match split_kv(tokens[idx]) { + Some(kv) => params.push(kv) + None => raise MalformedToken(tokens[idx]) + } + idx += 1 + } + { verb, subcommand, params, } +} + +///| +/// Builds `HELLO VERSION MIN=3.1 MAX=3.3`. +pub fn hello_version( + min~ : String = "3.1", + max~ : String = "3.3", +) -> SamMessage { + SamMessage::new("HELLO", subcommand=Some("VERSION"), params=[ + ("MIN", min), + ("MAX", max), + ]) +} + +///| +/// Builds `SESSION CREATE STYLE=