diff --git a/CHANGELOG.md b/CHANGELOG.md index cbadef715..8239b8e74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,33 @@ Questions about a release, or about upgrading to one? Ask in the ### Added +- **A reference gateway daemon, and with it LoRa** + ([ADR 0040](docs/adr/0040-a-reference-gateway-ships-with-the-sdk.md)). + The `reticulum` transport's device half has spoken the + [gateway contract](docs/spec/gateway-contract.md) since 0.25, but nothing in + the SDK answered it, so the transport never became available. + [`gateway/`](gateway/README.md) is the other half, in Python: devices attach + over local IP with a proof it checks through + `verify_gateway_address_proof`, and every submission gets exactly one + verdict. With a `[reticulum]` section it also carries frames and presence to + provisioned peer gateways over Reticulum, which is how an RNode's LoRa radio + reaches the SDK. No device-side change is needed: enable `reticulum` and + point its daemon address at the gateway. Two real engines pair over MLS and + exchange a message across two daemon processes joined by a Reticulum + backbone in its tests; it has not yet been run over radios. Expect a first + contact between two devices to cost about 20 backbone frames each: by + arithmetic, a few minutes on the example radio (SF8, 10 % airtime) and + hours at 1 %. A new gateway is unreachable while Reticulum mints its + one-time announce stamp. +- **A gateway daemon can verify a device's attach proof without building + it: `verify_gateway_address_proof(address, public_key, signature, + challenge)`**, instance-less, in every binding and over the C API's + instance-less call. It is the gateway half of + `gateway_address_declaration`: it checks the signature over the one + canonical payload ([the gateway contract](docs/spec/gateway-contract.md#attach)) + and that the key derives to the claimed address, and returns that address + or throws. A daemon still owns the third check, that the challenge is the + one it minted for this connection and has not been accepted before. - **A browser page can dial a native app on the same Wi-Fi network, or on the phone's own hotspot, from one code the app shows: WebRTC Direct** ([ADR 0039](docs/adr/0039-a-browser-dials-a-native-device-from-a-code.md)). @@ -55,6 +82,14 @@ Questions about a release, or about upgrading to one? Ask in the ### Changed +- **Media on the `reticulum` (gateway) transport is chunked at 64 KiB, the + peer-stream size, instead of 4 KiB.** The slot is a stream to a gateway + daemon over local IP, and the device never sizes frames to the backbone + behind it (ADR 0026). At 4 KiB every chunk slipped under a scarce + gateway's frame bound, so media crossed a LoRa backbone, which the gateway + contract says it MUST NOT; now every full chunk is refused + `frame_too_large` there, and a broad gateway carries transfers in fewer, + larger frames. - **The mesh `appId` is now `appLabel`** (`app_label` in Rust, Python, Ruby and the C API), so it is no longer mistaken for the App ID (`app_…`) the developer portal issues for telemetry. Only the name changed: the value diff --git a/CLAUDE.md b/CLAUDE.md index 4eb6c7a4e..54eafcc8b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,6 +25,7 @@ that are versioned, reviewable, and readable by people who are not an agent. | `offline-protocol-sealed`: the envelope codec, `derive_address`, canonical signing payloads, ratchet constants, the 1:1 control-frame prefixes, `KeyPackagePayload`, the identity assertion codec | ADR [0022](docs/adr/0022-one-sealed-layer-shared-with-the-leaf.md) (also dual std/no_std, and the one home for each) | | `offline-protocol-leaf`: anything a device does at pairing, on a frame, or with its store | ADR [0021](docs/adr/0021-a-leaf-node-speaks-mls.md) and [docs/spec/leaf-provisioning.md](docs/spec/leaf-provisioning.md) (a time source, real entropy, durable-before-emit and authorization are obligations, not suggestions) | | The fast link: bringing up Wi-Fi between two devices that meet over Bluetooth, the `__FAST_LINK__` frame, the bridges' host and join code | ADR [0038](docs/adr/0038-a-fast-link-is-offered-inside-the-session.md) and [the fast link state machine](docs/state-machines/fast-link.md) (credentials only ever travel sealed and ephemeral; the host admits only the invitee) | +| The gateway daemon: `gateway/`, the Reticulum (LoRa) backbone, `verify_gateway_address_proof` | ADR [0040](docs/adr/0040-a-reference-gateway-ships-with-the-sdk.md), [the gateway contract](docs/spec/gateway-contract.md) and [gateway/README.md](gateway/README.md) (the daemon never builds the proof payload itself; a backbone verdict waits for the peer gateway; the scarce burst must cover a first contact) | | Replicated documents: the store, sync frames, attachments | [docs/spec/data-sync.md](docs/spec/data-sync.md), [the replication state machine](docs/state-machines/data-replication.md), ADR [0018](docs/adr/0018-data-layer-engine-and-storage-seams.md) and [0019](docs/adr/0019-remote-document-imports-are-contained-not-trusted.md) | | Any binding: Swift, Kotlin, Python, TypeScript, C, Java, Ruby, the browser | [docs/bridges/](docs/bridges/README.md) | | The C API: `offline-protocol-uniffi/src/capi`, `bindings/c` | [docs/bridges/c.md](docs/bridges/c.md) (the dispatcher is generated from the UDL; the header is generated by cbindgen and committed) | diff --git a/bindings/c/include/offline_protocol.h b/bindings/c/include/offline_protocol.h index 47f9949b2..4d5d866b0 100644 --- a/bindings/c/include/offline_protocol.h +++ b/bindings/c/include/offline_protocol.h @@ -244,8 +244,9 @@ const char *offline_protocol_version(void); /** * Calls one of the definition's instance-less functions - * (`derive_address`, `parse_invite`, `verify_identity_assertion`), which - * need no engine and may run before `offline_protocol_create`. + * (`derive_address`, `parse_invite`, `verify_identity_assertion`, + * `verify_gateway_address_proof`), which need no engine and may run before + * `offline_protocol_create`. * * `params_json` is a JSON object keyed by the definition's parameter names, * or null for none. On success `*out_result` is the result as JSON, freed diff --git a/bindings/csharp/local_api_methods.txt b/bindings/csharp/local_api_methods.txt index 8ed403d4f..d272bbf99 100644 --- a/bindings/csharp/local_api_methods.txt +++ b/bindings/csharp/local_api_methods.txt @@ -208,6 +208,7 @@ update_dors_config update_relay_config update_retry_config update_transport_metrics +verify_gateway_address_proof verify_identity_assertion verify_signature verify_signature_bytes diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs index 9b3c68a50..856b8d3e8 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae +// UDL_SHA256 = 702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs index da83e9d6e..66461699a 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae +// UDL_SHA256 = 702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs index bf4ef7340..7c471024b 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae +// UDL_SHA256 = 702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs index e7328f5a5..87bc9fdb9 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae +// UDL_SHA256 = 702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs index 4bcc7cb3c..ef3743bfd 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae +// UDL_SHA256 = 702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs index 0ff21bc95..fb904986f 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae +// UDL_SHA256 = 702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs index e3eaf13d7..74b59b0b8 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae +// UDL_SHA256 = 702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b // Do not edit. #nullable enable @@ -19,6 +19,9 @@ public static Task DeriveAddressAsync(string? parametersJson = null, Can public static Task ParseInviteAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallStaticAsync("parse_invite", parametersJson, cancellationToken); + public static Task VerifyGatewayAddressProofAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallStaticAsync("verify_gateway_address_proof", parametersJson, cancellationToken); + public static Task VerifyIdentityAssertionAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallStaticAsync("verify_identity_assertion", parametersJson, cancellationToken); } diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java index 810b153cc..80047af6a 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java @@ -40,6 +40,9 @@ static void uniffiCheckApiChecksums() { if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance() != ((short) 20699)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof() != ((short) 21016)) { + throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); + } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion() != ((short) 61480)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolLib.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolLib.java index 27ea86df6..50f664c62 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolLib.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolLib.java @@ -68,6 +68,28 @@ public static java.lang.String runStorageConformance(ProtocolStateStorageProvide } + public static java.lang.String verifyGatewayAddressProof(java.lang.String address, java.util.List publicKey, java.util.List signature, java.util.List challenge) throws ProtocolException { + try { + return FfiConverterString.INSTANCE.lift( + UniffiHelpers.uniffiRustCallWithError(new ProtocolExceptionErrorHandler(), (_allocator, _status) -> { + return UniffiLib.uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof(_allocator, + FfiConverterString.INSTANCE.lower(address), FfiConverterSequenceByte.INSTANCE.lower(publicKey), FfiConverterSequenceByte.INSTANCE.lower(signature), FfiConverterSequenceByte.INSTANCE.lower(challenge), _status); + }) + ); + } catch (java.lang.RuntimeException _uniffi_ex) { + + if (ProtocolException.class.isInstance(_uniffi_ex.getCause())) { + throw (ProtocolException)_uniffi_ex.getCause(); + } + + if (InternalException.class.isInstance(_uniffi_ex.getCause())) { + throw (InternalException)_uniffi_ex.getCause(); + } + throw _uniffi_ex; + } + } + + public static java.lang.String verifyIdentityAssertion(java.util.List assertion) throws ProtocolException { try { return FfiConverterString.INSTANCE.lift( diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java index 884f9b774..3869e9f41 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java @@ -2396,6 +2396,15 @@ static java.lang.foreign.MemorySegment uniffi_offline_protocol_uniffi_fn_func_ru } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof", java.lang.foreign.FunctionDescriptor.of(RustBuffer.LAYOUT, RustBuffer.LAYOUT, RustBuffer.LAYOUT, RustBuffer.LAYOUT, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.ADDRESS)); + + static java.lang.foreign.MemorySegment uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof(java.lang.foreign.SegmentAllocator _allocator, java.lang.foreign.MemorySegment address, java.lang.foreign.MemorySegment publicKey, java.lang.foreign.MemorySegment signature, java.lang.foreign.MemorySegment challenge, java.lang.foreign.MemorySegment _uniffiOutErr) { + try { + return (java.lang.foreign.MemorySegment) MH_uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof.invokeExact(_allocator, address, publicKey, signature, challenge, _uniffiOutErr); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_fn_func_verify_identity_assertion private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_func_verify_identity_assertion = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_func_verify_identity_assertion", java.lang.foreign.FunctionDescriptor.of(RustBuffer.LAYOUT, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.ADDRESS)); @@ -2900,6 +2909,15 @@ static short uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformanc } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); + + static short uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof() { + try { + return (short) MH_uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof.invokeExact(); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); diff --git a/bindings/python/offline_protocol_sdk/local_api/dispatch.py b/bindings/python/offline_protocol_sdk/local_api/dispatch.py index 92b3df90a..25bfdf6e7 100644 --- a/bindings/python/offline_protocol_sdk/local_api/dispatch.py +++ b/bindings/python/offline_protocol_sdk/local_api/dispatch.py @@ -186,6 +186,7 @@ "derive_address", "parse_invite", "verify_identity_assertion", + "verify_gateway_address_proof", } ) @@ -338,7 +339,12 @@ #: The one group a client may call before ``hello``: nothing to stamp, #: nothing to route. BEFORE_HELLO: frozenset[str] = frozenset( - {"derive_address", "parse_invite", "verify_identity_assertion"} + { + "derive_address", + "parse_invite", + "verify_identity_assertion", + "verify_gateway_address_proof", + } ) #: Methods whose result is an identifier (or a list of them) that later diff --git a/bindings/python/offline_protocol_sdk/local_api/table.py b/bindings/python/offline_protocol_sdk/local_api/table.py index a15f4ac68..d5aad3d4d 100644 --- a/bindings/python/offline_protocol_sdk/local_api/table.py +++ b/bindings/python/offline_protocol_sdk/local_api/table.py @@ -9,7 +9,7 @@ from __future__ import annotations -UDL_SHA256 = "5d2c20ac6054a3ac6d1890f1d539f686f2fff6119beae596b682ba0569e1a9ae" +UDL_SHA256 = "702b40d0a44e0b060e63b9673cd10715a3a357d547724d42c7e9074af2d3c06b" TABLE = {'callbacks': ('MlsStorageProvider', 'ProtocolStateStorageProvider', @@ -604,6 +604,11 @@ 'run_storage_conformance': ((('storage', 'ProtocolStateStorageProvider'),), 'string'), + 'verify_gateway_address_proof': ((('address', 'string'), + ('public_key', 'sequence'), + ('signature', 'sequence'), + ('challenge', 'sequence')), + 'string'), 'verify_identity_assertion': ((('assertion', 'sequence'),), 'string')}}, 'records': {'AckConfig': (('default_timeout_ms', 'u64', False), diff --git a/bindings/python/offline_protocol_sdk/offline_protocol.py b/bindings/python/offline_protocol_sdk/offline_protocol.py index 51fc74f35..ceb84400b 100644 --- a/bindings/python/offline_protocol_sdk/offline_protocol.py +++ b/bindings/python/offline_protocol_sdk/offline_protocol.py @@ -561,6 +561,8 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance() != 20699: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof() != 21016: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion() != 61480: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_datastore_attachment_hash() != 10852: @@ -1097,6 +1099,9 @@ def _uniffi_check_api_checksums(lib): _UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance.restype = ctypes.c_uint16 +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof.argtypes = ( +) +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion.restype = ctypes.c_uint16 @@ -1859,6 +1864,14 @@ def _uniffi_check_api_checksums(lib): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_offline_protocol_uniffi_fn_func_run_storage_conformance.restype = _UniffiRustBuffer +_UniffiLib.uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof.restype = _UniffiRustBuffer _UniffiLib.uniffi_offline_protocol_uniffi_fn_func_verify_identity_assertion.argtypes = ( _UniffiRustBuffer, ctypes.POINTER(_UniffiRustCallStatus), @@ -15069,6 +15082,29 @@ def run_storage_conformance(storage: ProtocolStateStorageProvider) -> str: *_uniffi_lowered_args, ) return _uniffi_lift_return(_uniffi_ffi_result) +def verify_gateway_address_proof(address: str,public_key: typing.List[int],signature: typing.List[int],challenge: typing.List[int]) -> str: + + _UniffiFfiConverterString.check_lower(address) + + _UniffiFfiConverterSequenceUInt8.check_lower(public_key) + + _UniffiFfiConverterSequenceUInt8.check_lower(signature) + + _UniffiFfiConverterSequenceUInt8.check_lower(challenge) + _uniffi_lowered_args = ( + _UniffiFfiConverterString.lower(address), + _UniffiFfiConverterSequenceUInt8.lower(public_key), + _UniffiFfiConverterSequenceUInt8.lower(signature), + _UniffiFfiConverterSequenceUInt8.lower(challenge), + ) + _uniffi_lift_return = _UniffiFfiConverterString.lift + _uniffi_error_converter = _UniffiFfiConverterTypeProtocolError + _uniffi_ffi_result = _uniffi_rust_call_with_error( + _uniffi_error_converter, + _UniffiLib.uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof, + *_uniffi_lowered_args, + ) + return _uniffi_lift_return(_uniffi_ffi_result) def verify_identity_assertion(assertion: typing.List[int]) -> str: _UniffiFfiConverterSequenceUInt8.check_lower(assertion) @@ -15161,6 +15197,7 @@ def verify_identity_assertion(assertion: typing.List[int]) -> str: "derive_address", "parse_invite", "run_storage_conformance", + "verify_gateway_address_proof", "verify_identity_assertion", "DataStore", "DataStoreProtocol", diff --git a/bindings/python/tests/test_gateway_address_proof.py b/bindings/python/tests/test_gateway_address_proof.py new file mode 100644 index 000000000..1bd9c7d5c --- /dev/null +++ b/bindings/python/tests/test_gateway_address_proof.py @@ -0,0 +1,106 @@ +"""Both halves of the gateway attach proof, against the real library. + +A device signs with ``gateway_address_declaration(challenge)`` on its engine; +a gateway daemon, which runs no engine, checks the result with the +instance-less ``verify_gateway_address_proof``. Neither half builds the +payload in Python: it has one home, in the sealed crate, and this test is +what shows the two halves agree across the FFI. +""" + +from __future__ import annotations + +import os + +import pytest + +from offline_protocol_sdk.offline_protocol import ( + OfflineProtocol, + OverflowPolicy, + ProtocolConfig, + ProtocolError, + verify_gateway_address_proof, +) + +from conftest import InMemoryStorage + + +def _config(profile: str) -> ProtocolConfig: + return ProtocolConfig( + app_label="test-app", + profile=profile, + ble_enabled=False, + wifi_direct_enabled=False, + internet_enabled=False, + reticulum_enabled=True, + nostr_enabled=False, + prefer_online=True, + initial_ttl=3, + encryption_enabled=True, + auto_key_exchange=True, + store_pending=True, + require_encryption=False, + max_pending_per_peer=100, + max_pending_global=1000, + pending_ttl_ms=60000, + overflow_policy=OverflowPolicy.DROP_OLDEST, + ) + + +def _device(profile: str) -> OfflineProtocol: + protocol = OfflineProtocol(_config(profile)) + protocol.initialize_mls(InMemoryStorage(), InMemoryStorage()) + assert protocol.local_address() is not None + return protocol + + +def test_a_device_declaration_verifies_to_its_own_address() -> None: + device = _device("gateway-proof-device") + challenge = os.urandom(32) + declaration = device.gateway_address_declaration(list(challenge)) + bound = verify_gateway_address_proof( + declaration.address, + declaration.public_key, + declaration.signature, + list(challenge), + ) + assert bound == device.local_address() == declaration.address + + +def test_a_declaration_does_not_verify_on_another_connection() -> None: + device = _device("gateway-proof-replay") + declaration = device.gateway_address_declaration(list(os.urandom(32))) + with pytest.raises(ProtocolError): + verify_gateway_address_proof( + declaration.address, + declaration.public_key, + declaration.signature, + list(os.urandom(32)), + ) + + +def test_a_signature_cannot_claim_another_devices_address() -> None: + """The check that makes the binding mean anything: a valid signature + under the sender's own key, naming somebody else's address.""" + attacker = _device("gateway-proof-attacker") + victim = _device("gateway-proof-victim") + challenge = list(os.urandom(32)) + declaration = attacker.gateway_address_declaration(challenge) + with pytest.raises(ProtocolError): + verify_gateway_address_proof( + victim.local_address(), + declaration.public_key, + declaration.signature, + challenge, + ) + + +def test_a_tampered_signature_is_refused() -> None: + device = _device("gateway-proof-tamper") + challenge = list(os.urandom(32)) + declaration = device.gateway_address_declaration(challenge) + signature = list(declaration.signature) + signature[10] ^= 0x01 + with pytest.raises(ProtocolError): + verify_gateway_address_proof( + declaration.address, declaration.public_key, signature, challenge + ) diff --git a/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt b/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt index 940a83a0a..f69e6822b 100644 --- a/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt +++ b/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt @@ -871,6 +871,8 @@ internal object IntegrityCheckingUniffiLib { ): Int external fun uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance( ): Int + external fun uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof( + ): Int external fun uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion( ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_datastore_attachment_hash( @@ -1950,6 +1952,8 @@ internal object UniffiLib { ): RustBuffer.ByValue external fun uniffi_offline_protocol_uniffi_fn_func_run_storage_conformance(`storage`: Long,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue + external fun uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof(`address`: RustBuffer.ByValue,`publicKey`: RustBuffer.ByValue,`signature`: RustBuffer.ByValue,`challenge`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, + ): RustBuffer.ByValue external fun uniffi_offline_protocol_uniffi_fn_func_verify_identity_assertion(`assertion`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue external fun ffi_offline_protocol_uniffi_rustbuffer_alloc(`size`: Long,uniffi_out_err: UniffiRustCallStatus, @@ -2080,6 +2084,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) { if ((lib.uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance() and 0xFFFF) != 20699) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } + if ((lib.uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof() and 0xFFFF) != 21016) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } if ((lib.uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion() and 0xFFFF) != 61480) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } @@ -14319,6 +14326,21 @@ public object FfiConverterMapStringString: FfiConverterRustBuffer, `signature`: List, `challenge`: List): kotlin.String { + return FfiConverterString.lift( + uniffiRustCallWithError(ProtocolException) { _status -> + UniffiLib.uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof( + + + FfiConverterString.lower(`address`), + FfiConverterSequenceUByte.lower(`publicKey`), + FfiConverterSequenceUByte.lower(`signature`), + FfiConverterSequenceUByte.lower(`challenge`),_status) +} + ) + } + + @Throws(ProtocolException::class) fun `verifyIdentityAssertion`(`assertion`: List): kotlin.String { return FfiConverterString.lift( uniffiRustCallWithError(ProtocolException) { _status -> diff --git a/bindings/react-native/ios/Generated/offline_protocol.swift b/bindings/react-native/ios/Generated/offline_protocol.swift index 2da0f43f6..08bd67343 100644 --- a/bindings/react-native/ios/Generated/offline_protocol.swift +++ b/bindings/react-native/ios/Generated/offline_protocol.swift @@ -11751,6 +11751,17 @@ public func runStorageConformance(storage: ProtocolStateStorageProvider) -> Stri ) }) } +public func verifyGatewayAddressProof(address: String, publicKey: [UInt8], signature: [UInt8], challenge: [UInt8])throws -> String { + return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypeProtocolError_lift) { + uniffiCallStatus in + uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof( + FfiConverterString.lower(address), + FfiConverterSequenceUInt8.lower(publicKey), + FfiConverterSequenceUInt8.lower(signature), + FfiConverterSequenceUInt8.lower(challenge),uniffiCallStatus + ) +}) +} public func verifyIdentityAssertion(assertion: [UInt8])throws -> String { return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypeProtocolError_lift) { uniffiCallStatus in @@ -11784,6 +11795,9 @@ private let initializationResult: InitializationResult = { if (uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance() != 20699) { return InitializationResult.apiChecksumMismatch } + if (uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof() != 21016) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion() != 61480) { return InitializationResult.apiChecksumMismatch } diff --git a/bindings/react-native/ios/Generated/offline_protocolFFI.h b/bindings/react-native/ios/Generated/offline_protocolFFI.h index c699c4924..e853aaea5 100644 --- a/bindings/react-native/ios/Generated/offline_protocolFFI.h +++ b/bindings/react-native/ios/Generated/offline_protocolFFI.h @@ -1723,6 +1723,11 @@ RustBuffer uniffi_offline_protocol_uniffi_fn_func_parse_invite(RustBuffer blob, RustBuffer uniffi_offline_protocol_uniffi_fn_func_run_storage_conformance(uint64_t storage, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_FUNC_VERIFY_GATEWAY_ADDRESS_PROOF +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_FUNC_VERIFY_GATEWAY_ADDRESS_PROOF +RustBuffer uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof(RustBuffer address, RustBuffer public_key, RustBuffer signature, RustBuffer challenge, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_FUNC_VERIFY_IDENTITY_ASSERTION #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_FUNC_VERIFY_IDENTITY_ASSERTION RustBuffer uniffi_offline_protocol_uniffi_fn_func_verify_identity_assertion(RustBuffer assertion, RustCallStatus *_Nonnull out_status @@ -2004,6 +2009,12 @@ uint16_t uniffi_offline_protocol_uniffi_checksum_func_parse_invite(void #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_FUNC_RUN_STORAGE_CONFORMANCE uint16_t uniffi_offline_protocol_uniffi_checksum_func_run_storage_conformance(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_FUNC_VERIFY_GATEWAY_ADDRESS_PROOF +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_FUNC_VERIFY_GATEWAY_ADDRESS_PROOF +uint16_t uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_FUNC_VERIFY_IDENTITY_ASSERTION diff --git a/bindings/ruby/lib/offline_protocol.rb b/bindings/ruby/lib/offline_protocol.rb index 086dbf155..451c243d9 100644 --- a/bindings/ruby/lib/offline_protocol.rb +++ b/bindings/ruby/lib/offline_protocol.rb @@ -8136,6 +8136,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [:uint64, RustCallStatus.by_ref], RustBuffer.by_value + attach_function :uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof, + [RustBuffer.by_value, RustBuffer.by_value, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :uniffi_offline_protocol_uniffi_fn_func_verify_identity_assertion, [RustBuffer.by_value, RustCallStatus.by_ref], RustBuffer.by_value @@ -8360,6 +8364,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [], :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_func_verify_gateway_address_proof, + [], + :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_func_verify_identity_assertion, [], :uint16 @@ -11942,6 +11950,27 @@ def self.run_storage_conformance(storage) +def self.verify_gateway_address_proof(address, public_key, signature, challenge) + address = ::OfflineProtocol::uniffi_utf8(address) + + + public_key = public_key.map { |v| ::OfflineProtocol::uniffi_in_range(v, "u8", 0, 2**8) } + RustBuffer.check_lower_Sequenceu8(public_key) + + signature = signature.map { |v| ::OfflineProtocol::uniffi_in_range(v, "u8", 0, 2**8) } + RustBuffer.check_lower_Sequenceu8(signature) + + challenge = challenge.map { |v| ::OfflineProtocol::uniffi_in_range(v, "u8", 0, 2**8) } + RustBuffer.check_lower_Sequenceu8(challenge) + + result = ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_func_verify_gateway_address_proof,RustBuffer.alloc_from_string(address),RustBuffer.alloc_from_Sequenceu8(public_key),RustBuffer.alloc_from_Sequenceu8(signature),RustBuffer.alloc_from_Sequenceu8(challenge)) + return result.consume_into_string +end + + + + + def self.verify_identity_assertion(assertion) assertion = assertion.map { |v| ::OfflineProtocol::uniffi_in_range(v, "u8", 0, 2**8) } RustBuffer.check_lower_Sequenceu8(assertion) diff --git a/crates/offline-protocol-mls/src/gateway_proof.rs b/crates/offline-protocol-mls/src/gateway_proof.rs new file mode 100644 index 000000000..56b5ddbdb --- /dev/null +++ b/crates/offline-protocol-mls/src/gateway_proof.rs @@ -0,0 +1,263 @@ +//! Verifying the address declaration a device attaches to a gateway with. +//! +//! The device half lives in the engine: it signs +//! [`offline_protocol_sealed::gateway_address_proof_payload`] over its own +//! address and the gateway's challenge. This module is the gateway half, and +//! the one verifier of that proof. It exists so that a gateway daemon written +//! in any language checks the proof by calling the SDK rather than by building +//! the 103-byte payload itself: the layout has one home, in the sealed crate, +//! and a second builder is exactly the copy that drifts (a length written +//! little-endian, a challenge prefixed as if it were a second field) while its +//! own round-trip test keeps passing. +//! +//! # What this checks, and what it leaves to the gateway +//! +//! The gateway contract lists three checks a gateway makes before it answers +//! `AddressDeclared`. This function makes the first two: +//! +//! 1. the signature verifies over the canonical bytes under `public_key`; +//! 2. `address` is the address `public_key` derives to. +//! +//! The third, that `challenge` is the one this gateway minted for this +//! connection and has not been accepted before, is connection state, and only +//! the gateway holds it. A gateway that skips it turns one captured +//! declaration into a reusable credential, whatever this function returns. + +use offline_protocol_core::Address; +use offline_protocol_sealed::gateway_address_proof_payload; + +use crate::error::{MlsError, Result}; +use crate::manager::MlsManager; + +/// Verifies a gateway address declaration and returns the address it binds. +/// +/// In order, cheap before expensive: +/// +/// 1. the key parses as an Ed25519 verifying key and the signature is 64 +/// bytes; +/// 2. the signature verifies, under RFC 8032's strict rules, over +/// `gateway_address_proof_payload(address, challenge)`; +/// 3. the address `public_key` derives to equals `address` exactly. +/// +/// The signature is checked over the **claimed** address, because that is +/// what the device signed, and the derivation is checked after it. Both are +/// needed: without the derivation check a signature made under any key the +/// sender holds attaches the session to any address it cares to name. +/// +/// The challenge is passed to the payload builder unexamined. Its length is a +/// wire rule the gateway enforces when it mints one; the verifier must build +/// the same bytes the device signed for whatever challenge was actually sent. +/// +/// # Errors +/// +/// [`MlsError::InvalidPublicKey`] for a key that is not 32 bytes or not on the +/// curve, and [`MlsError::VerificationFailed`] for a signature that is not 64 +/// bytes, does not verify, or verifies under a key that derives to another +/// address. Every case means the gateway answers `AddressError` and binds +/// nothing. +pub fn verify_gateway_address_proof( + address: &str, + public_key: &[u8], + signature: &[u8], + challenge: &[u8], +) -> Result
{ + use ed25519_dalek::{Signature, VerifyingKey}; + + let key = VerifyingKey::try_from(public_key) + .map_err(|e| MlsError::InvalidPublicKey(format!("Invalid Ed25519 public key: {e}")))?; + let signature = Signature::try_from(signature) + .map_err(|e| MlsError::VerificationFailed(format!("Invalid signature format: {e}")))?; + let payload = gateway_address_proof_payload(address, challenge)?; + // Strict, for the reason `verify_identity_assertion` gives: the permissive + // check accepts a small-order key with a signature anyone can write down, + // and a declaration no private key ever produced must not bind a session. + key.verify_strict(&payload, &signature).map_err(|_| { + MlsError::VerificationFailed( + "Gateway address declaration does not verify under its public key".to_string(), + ) + })?; + let derived = MlsManager::derive_address(public_key)?; + if derived.to_string() != address { + return Err(MlsError::VerificationFailed(format!( + "Gateway address declaration names {address}, but its key derives to {derived}" + ))); + } + Ok(derived) +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::{Signer, SigningKey}; + + /// RFC 8032 section 7.1, test vector 1, secret half. Its public half + /// derives to the address the first conformance proof names. + const RFC8032_TV1_SK: &str = "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"; + /// RFC 8032 section 7.1, test vector 2, secret half. Its public half + /// derives to the address the second and third proofs name. + const RFC8032_TV2_SK: &str = "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb"; + + fn unhex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex")) + .collect() + } + + fn signing_key(hex: &str) -> SigningKey { + let bytes: [u8; 32] = unhex(hex).try_into().expect("32 bytes"); + SigningKey::from_bytes(&bytes) + } + + fn address_of(key: &SigningKey) -> String { + MlsManager::derive_address(&key.verifying_key().to_bytes()) + .expect("derive") + .to_string() + } + + /// What a device sends: its own address, signed over this challenge. + fn declare(key: &SigningKey, challenge: &[u8]) -> (String, Vec, Vec) { + let address = address_of(key); + let payload = gateway_address_proof_payload(&address, challenge).expect("payload"); + let signature = key.sign(&payload).to_bytes().to_vec(); + (address, key.verifying_key().to_bytes().to_vec(), signature) + } + + #[test] + fn an_honest_declaration_verifies_to_its_address() { + let key = signing_key(RFC8032_TV1_SK); + let challenge = [7u8; 32]; + let (address, public_key, signature) = declare(&key, &challenge); + let bound = verify_gateway_address_proof(&address, &public_key, &signature, &challenge) + .expect("verifies"); + assert_eq!(bound.to_string(), address); + } + + /// The check the contract calls the one that makes the binding mean + /// anything: a valid signature under the sender's own key, over somebody + /// else's address. + #[test] + fn a_signature_over_another_address_is_refused() { + let attacker = signing_key(RFC8032_TV1_SK); + let victim = address_of(&signing_key(RFC8032_TV2_SK)); + let challenge = [9u8; 32]; + let payload = gateway_address_proof_payload(&victim, &challenge).expect("payload"); + let signature = attacker.sign(&payload).to_bytes(); + let err = verify_gateway_address_proof( + &victim, + &attacker.verifying_key().to_bytes(), + &signature, + &challenge, + ) + .unwrap_err(); + assert!(matches!(err, MlsError::VerificationFailed(_)), "{err}"); + } + + /// A proof made for one connection does not verify on another. The + /// replay check itself is the gateway's; this is what makes it possible. + #[test] + fn a_proof_over_another_challenge_is_refused() { + let key = signing_key(RFC8032_TV1_SK); + let (address, public_key, signature) = declare(&key, &[1u8; 32]); + assert!(matches!( + verify_gateway_address_proof(&address, &public_key, &signature, &[2u8; 32]), + Err(MlsError::VerificationFailed(_)) + )); + } + + /// The relay's declaration has this payload's layout exactly, under + /// another domain. A proof harvested there must not attach here. + #[test] + fn a_relay_declaration_is_refused() { + let key = signing_key(RFC8032_TV1_SK); + let address = address_of(&key); + let challenge = [3u8; 32]; + // The relay's domain, spelled here the way the sealed crate's own + // non-prefixing test spells it; the layout is the shared builder's. + let mut relay_payload = offline_protocol_sealed::canonical_payload( + b"offline-relay-addr-v1", + &[address.as_bytes()], + ) + .expect("relay payload"); + relay_payload.extend_from_slice(&challenge); + let signature = key.sign(&relay_payload).to_bytes(); + assert!(matches!( + verify_gateway_address_proof( + &address, + &key.verifying_key().to_bytes(), + &signature, + &challenge + ), + Err(MlsError::VerificationFailed(_)) + )); + } + + #[test] + fn every_flipped_bit_of_the_signature_is_refused() { + let key = signing_key(RFC8032_TV2_SK); + let challenge = [0u8; 32]; + let (address, public_key, signature) = declare(&key, &challenge); + for byte in 0..signature.len() { + let mut tampered = signature.clone(); + tampered[byte] ^= 0x80; + assert!( + verify_gateway_address_proof(&address, &public_key, &tampered, &challenge).is_err(), + "flipping signature byte {byte} must not verify" + ); + } + } + + #[test] + fn malformed_keys_and_signatures_are_refused_before_any_cryptography() { + let key = signing_key(RFC8032_TV1_SK); + let challenge = [5u8; 32]; + let (address, public_key, signature) = declare(&key, &challenge); + assert!(matches!( + verify_gateway_address_proof(&address, &public_key[..31], &signature, &challenge), + Err(MlsError::InvalidPublicKey(_)) + )); + assert!(matches!( + verify_gateway_address_proof(&address, &public_key, &signature[..63], &challenge), + Err(MlsError::VerificationFailed(_)) + )); + } + + /// The conformance vectors, end to end. Their payloads were computed from + /// the chapter's construction and their addresses derive from RFC 8032 + /// keys, so signing each pinned payload with the matching RFC 8032 secret + /// and verifying it here checks this verifier against bytes it did not + /// build: a verifier whose payload drifted from the vector refuses them. + #[test] + fn the_conformance_payloads_verify_when_signed_by_their_rfc8032_keys() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../offline-protocol-sealed/tests/data/gateway-address-proof-v1.vectors.json"); + // Absent in a published .crate archive, present in the repo. + let Ok(text) = std::fs::read_to_string(&path) else { + eprintln!("sealed vector file not present, skipping"); + return; + }; + let v: serde_json::Value = serde_json::from_str(&text).expect("JSON"); + let keys = [signing_key(RFC8032_TV1_SK), signing_key(RFC8032_TV2_SK)]; + let proofs = v["proofs"].as_array().expect("proofs"); + assert_eq!(proofs.len(), 3); + for proof in proofs { + let name = proof["name"].as_str().expect("name"); + let address = proof["address"].as_str().expect("address"); + let challenge = unhex(proof["challenge_hex"].as_str().expect("challenge")); + let payload = unhex(proof["payload_hex"].as_str().expect("payload")); + let key = keys + .iter() + .find(|k| address_of(k) == address) + .unwrap_or_else(|| panic!("[{name}]: no RFC 8032 key derives to {address}")); + let signature = key.sign(&payload).to_bytes(); + let bound = verify_gateway_address_proof( + address, + &key.verifying_key().to_bytes(), + &signature, + &challenge, + ) + .unwrap_or_else(|e| panic!("[{name}]: {e}")); + assert_eq!(bound.to_string(), address, "[{name}]"); + } + } +} diff --git a/crates/offline-protocol-mls/src/lib.rs b/crates/offline-protocol-mls/src/lib.rs index bbde24c1c..eb6867308 100644 --- a/crates/offline-protocol-mls/src/lib.rs +++ b/crates/offline-protocol-mls/src/lib.rs @@ -35,6 +35,7 @@ pub mod discovery; pub mod error; +pub mod gateway_proof; pub mod group; pub mod identity_assertion; pub mod invite; @@ -50,6 +51,7 @@ pub mod types; // a public variant: matching on `LeafAddressMismatch { context, .. }` should not // need a deeper path than the error it came out of. pub use error::{LeafSource, MlsError, Result}; +pub use gateway_proof::verify_gateway_address_proof; pub use identity_assertion::verify_identity_assertion; pub use manager::{is_mls_framed, MlsManager, PushKeyPackage, MAX_PUSH_KEY_PACKAGES}; pub use session::SealMark; diff --git a/crates/offline-protocol-uniffi/src/capi/ffi.rs b/crates/offline-protocol-uniffi/src/capi/ffi.rs index eed36a12a..6d1ddf8de 100644 --- a/crates/offline-protocol-uniffi/src/capi/ffi.rs +++ b/crates/offline-protocol-uniffi/src/capi/ffi.rs @@ -217,8 +217,9 @@ pub extern "C" fn offline_protocol_version() -> *const c_char { } /// Calls one of the definition's instance-less functions -/// (`derive_address`, `parse_invite`, `verify_identity_assertion`), which -/// need no engine and may run before `offline_protocol_create`. +/// (`derive_address`, `parse_invite`, `verify_identity_assertion`, +/// `verify_gateway_address_proof`), which need no engine and may run before +/// `offline_protocol_create`. /// /// `params_json` is a JSON object keyed by the definition's parameter names, /// or null for none. On success `*out_result` is the result as JSON, freed diff --git a/crates/offline-protocol-uniffi/src/capi/generated.rs b/crates/offline-protocol-uniffi/src/capi/generated.rs index 84becf4ca..f7ec7ac94 100644 --- a/crates/offline-protocol-uniffi/src/capi/generated.rs +++ b/crates/offline-protocol-uniffi/src/capi/generated.rs @@ -2488,6 +2488,15 @@ pub fn call_namespace(method: &str, mut args: Fields<'_>) -> Result { + let arg_address = args.take("address")?; + let arg_public_key = args.take("public_key")?; + let arg_signature = args.take("signature")?; + let arg_challenge = args.take("challenge")?; + args.finish()?; + let result = crate::verify_gateway_address_proof(arg_address, arg_public_key, arg_signature, arg_challenge)?; + Ok(result.encode()) + } _ => Err(CallError::MethodNotFound(format!("no method {}{method}", ""))), } } @@ -4081,6 +4090,7 @@ pub const NAMESPACE: &[&str] = &[ "derive_address", "parse_invite", "verify_identity_assertion", + "verify_gateway_address_proof", ]; /// Declarations `call` does not dispatch, because a parameter is a callback diff --git a/crates/offline-protocol-uniffi/src/capi/mod.rs b/crates/offline-protocol-uniffi/src/capi/mod.rs index c0fd56684..ca0c288c0 100644 --- a/crates/offline-protocol-uniffi/src/capi/mod.rs +++ b/crates/offline-protocol-uniffi/src/capi/mod.rs @@ -150,7 +150,8 @@ impl Engine { } /// Calls one of the definition's instance-less functions (`derive_address`, -/// `parse_invite`, `verify_identity_assertion`), which need no engine. +/// `parse_invite`, `verify_identity_assertion`, +/// `verify_gateway_address_proof`), which need no engine. pub fn call_static(method: &str, params_json: Option<&str>) -> Result { refuse_hand_written(method)?; let args = Fields::params(parse_json(params_json, "the parameters")?, method)?; diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 0dd18a574..7d91a876b 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -166,6 +166,39 @@ pub fn verify_identity_assertion(assertion: Vec) -> Result, + signature: Vec, + challenge: Vec, +) -> Result { + offline_protocol_mls::verify_gateway_address_proof( + &address, + &public_key, + &signature, + &challenge, + ) + .map(|bound| bound.to_string()) + .map_err(|e| ProtocolError::MlsError(e.to_string())) +} + // --------------------------------------------------------------------------- // Poison-recovery utilities for non-Result methods. // diff --git a/crates/offline-protocol-uniffi/src/offline_protocol.udl b/crates/offline-protocol-uniffi/src/offline_protocol.udl index c69374186..9a4879fc7 100644 --- a/crates/offline-protocol-uniffi/src/offline_protocol.udl +++ b/crates/offline-protocol-uniffi/src/offline_protocol.udl @@ -52,6 +52,25 @@ namespace offline_protocol { [Throws=ProtocolError] string verify_identity_assertion(sequence assertion); + // Verify the address declaration a device attaches to a gateway with + // (docs/spec/gateway-contract.md, Attach) and return the address it binds. + // + // The gateway half of gateway_address_declaration. Instance-less, because + // a gateway daemon runs no engine: it checks the signature over the one + // canonical payload (offline-gateway-addr-v1, the claimed address and the + // challenge) and that the key derives to the claimed address. A daemon in + // any language calls this rather than building the payload itself. + // + // The third check, that the challenge is the one the gateway minted for + // this connection and has not been accepted before, is the caller's: only + // the gateway holds connection state. + // + // Throws for a key that is not 32 bytes or not on the curve, a signature + // that is not 64 bytes or does not verify, and a key that derives to + // another address. Every case means the gateway answers AddressError. + [Throws=ProtocolError] + string verify_gateway_address_proof(string address, sequence public_key, sequence signature, sequence challenge); + // Run the storage adapter conformance suite against a provider and return // the report as JSON: {"passed":[...],"failures":[{"check","detail"}]}. // diff --git a/crates/offline-protocol/src/protocol/send.rs b/crates/offline-protocol/src/protocol/send.rs index 0bc25ec18..c01e537a5 100644 --- a/crates/offline-protocol/src/protocol/send.rs +++ b/crates/offline-protocol/src/protocol/send.rs @@ -2926,9 +2926,16 @@ impl OfflineProtocol { (CHUNK_SIZE_PEER_STREAM, MEDIA_WINDOW_SIZE_PEER_STREAM) } TransportType::Reticulum => { - // Reticulum is low-bandwidth (LoRa); use BLE-like chunk sizes. - use crate::constants::{CHUNK_SIZE_BLE, MEDIA_WINDOW_SIZE_BLE}; - (CHUNK_SIZE_BLE, MEDIA_WINDOW_SIZE_BLE) + // The gateway slot is a stream to a daemon over local IP, so + // it is sized like the peer stream. Not like Bluetooth, as it + // was when the slot meant "LoRa": the device never sees the + // backbone (ADR 0026), and BLE-sized chunks slipped under a + // scarce gateway's frame bound, so media crossed a LoRa link + // the contract says it MUST NOT. A full chunk at this size is + // refused `frame_too_large` by every scarce gateway, and the + // pinned transfer fails, as the gateway contract describes. + use crate::constants::{CHUNK_SIZE_PEER_STREAM, MEDIA_WINDOW_SIZE_PEER_STREAM}; + (CHUNK_SIZE_PEER_STREAM, MEDIA_WINDOW_SIZE_PEER_STREAM) } TransportType::Nostr => { // Nostr relays have decent bandwidth; use Internet-like chunk sizes. diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index 79f1fc65e..f90ea0800 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -312,6 +312,61 @@ fn a_transfer_on_the_peer_stream_slot_keeps_512_kib_in_flight() { ); } +/// A transfer pinned to the gateway slot is chunked like the peer stream, at +/// 64 KiB, not like Bluetooth. At 4 KiB every chunk slipped under a scarce +/// gateway's frame bound and media crossed a LoRa backbone, which the gateway +/// contract says it MUST NOT. Three chunks of 64 KiB leave together; at +/// 4 KiB the same file would be 48 chunks, two at a time. +#[test] +fn a_transfer_on_the_gateway_slot_is_chunked_like_a_stream() { + use offline_protocol_core::ContentType; + + use crate::constants::{CHUNK_SIZE_PEER_STREAM, MEDIA_WINDOW_SIZE_PEER_STREAM}; + + let (mut alice, bob) = pair(); + let gateway = MockTransport::new(TransportType::Reticulum); + gateway.start().unwrap(); + alice + .protocol + .transport_manager_mut() + .add_transport(TransportType::Reticulum, Box::new(gateway.clone())); + // The case that matters: a device whose current carrier is the gateway, + // which is where media pins (the slot is left out of the fallback order). + alice + .protocol + .transport_manager_mut() + .send_via_transport( + &Message::new( + offline_protocol_core::UserId::new(&alice.address).unwrap(), + offline_protocol_core::UserId::new(&bob.address).unwrap(), + offline_protocol_core::AppId::new("test-app").unwrap(), + "warm", + ), + TransportType::Reticulum, + ) + .unwrap(); + assert_eq!( + alice.protocol.transport_manager().current_transport(), + Some(TransportType::Reticulum) + ); + gateway.sent_messages(); + alice.take_sent(); + + let file = vec![0x5a; CHUNK_SIZE_PEER_STREAM * 3]; + alice + .protocol + .send_media(&bob.address, file, "photo.jpg", ContentType::Image, None) + .unwrap(); + + let chunks = gateway + .sent_messages() + .into_iter() + .filter(|message| message.content_type == ContentType::FileChunk) + .count(); + assert_eq!(chunks, 3); + assert!(chunks < MEDIA_WINDOW_SIZE_PEER_STREAM); +} + /// A fast-link frame goes over Bluetooth LE when the peer is linked there, /// even though the engine prefers a peer stream for a direct link: the frame /// may be ending that very stream, and on two phones a close sent down it diff --git a/docs/adr/0040-a-reference-gateway-ships-with-the-sdk.md b/docs/adr/0040-a-reference-gateway-ships-with-the-sdk.md new file mode 100644 index 000000000..b5fbc9dee --- /dev/null +++ b/docs/adr/0040-a-reference-gateway-ships-with-the-sdk.md @@ -0,0 +1,136 @@ +# 0040. A reference gateway ships with the SDK + +**Status:** Proposed + +## Context + +The gateway contract had a complete device half, written three times (the +Swift, Kotlin and Python managers behind the `reticulum` slot), and no +gateway. The documentation said so: what answers on the daemon address "is a +deployment rather than something this SDK ships". So the slot never became +available anywhere, and every mention of LoRa in the SDK described a path +nobody could run. + +Three things made a gateway more than a weekend's port of the relay: + +- **The attach proof had one builder and no verifier outside the engine.** A + gateway daemon runs no engine. Building the 103-byte payload itself is the + second copy [ADR 0022](0022-one-sealed-layer-shared-with-the-leaf.md) + refuses, and the copy that drifts silently (a length written little-endian, + a challenge prefixed as if it were a second field) while its own round-trip + test passes. +- **The only mature Reticulum is Python.** A device has no Reticulum stack, + and the contract keeps it that way (ADR 0026). The gateway is where + Reticulum has to run, and `reticulum-rs` does not yet promise wire + compatibility with the reference. +- **The verdict has a deadline the backbone does not.** The reference clients + fail a frame with no verdict in 60 seconds. A round trip across a LoRa link + at long-range settings can approach that. + +## Decision + +1. **The SDK exposes the gateway half of the proof:** + `verify_gateway_address_proof(address, public_key, signature, challenge)`, + instance-less, in every binding. It checks the signature over the sealed + crate's payload under RFC 8032's strict rules and that the key derives to + the claimed address. The challenge's freshness stays the gateway's, + because only the gateway holds connection state. +2. **A reference gateway lives in this repository, under `gateway/`, in + Python**, beside the binding whose verifier it calls. It implements the + five verbs and Deliver, and nothing the contract leaves optional: no + mailbox, no push, so it never sets `stored` or `pushed`. +3. **Its backbone is Reticulum**, through a seam (`Backbone`) that an + in-process implementation also fills for tests. Each gateway announces one + destination under its own identity; peers are provisioned destination + hashes; frames travel as link requests, which Reticulum carries as + resources; presence is a snapshot on link-up and coalesced changes after. + There are two links per pair, one dialled by each side, because a + Reticulum request travels only from a link's initiator to the destination + it dialled. +4. **A backbone verdict waits for the peer gateway's answer, up to 45 + seconds**, then reports `backbone_timeout`, a plain failure the device + retries. It is never reported as `MessageSent` on the strength of a + hand-off alone: a frame the peer gateway never confirmed is one the device + must still retry, and the retry costs only a duplicate the core already + removes. +5. **The scarce class's budgets are sized from a measurement**, not a + guess: two SDK engines pairing over MLS and exchanging one message send + 18 to 20 backbone frames each, about 16 KB, the largest about 4 KB. Every + burst holds that first contact, and the backbone frame bound (6 KiB) + passes its largest frame. A broad backbone skips these budgets. +6. **The airtime toward a peer is budgeted in bytes, twice.** Once per peer + gateway, shared by every device, because the airtime toward a peer is the + scarce thing and many devices together can ask for more than the radio + carries. And once per source host, held below the shared budget by + validation, so one device cannot hold the shared budget at zero. The + second is per host rather than per address because addresses cost + nothing to mint: a host that re-keys would otherwise get a fresh burst + each time. The defaults fit the example radio (SF8 at 125 kHz, 10 % + airtime: about 1.5 KB a minute toward a peer), and a deployment on + another radio resizes them. +7. **Requests to a peer go one at a time, queued in the daemon.** Reticulum + sends one outgoing resource per link and cannot withdraw one it has + queued, so a frame left to queue there goes on air after its device has + been told it failed. Queued in the daemon, a frame whose time runs out + first is refused without reaching the radio. + +## Consequences + +- The `reticulum` slot works end to end: the tests run two real engines + through one gateway, across two gateways in one process, and across two + daemon processes joined by a real Reticulum backbone over TCP. Swapping TCP + for an RNode changes the Reticulum configuration, not the daemon. +- A first contact over LoRa is expensive, about 20 frames each way, from + about 200 bytes (an acknowledgement) to about 4 KB, about 16 KB in all. That is the SDK's session setup, not the gateway's, and + the gateway now makes the number visible instead of hiding it in a + hypothetical. By arithmetic from the radio settings, it is several minutes + on the example radio and hours at the 1 % duty cycle most of the EU + 868 MHz band allows. Nothing has been measured over radios yet. +- Media stays off a scarce backbone by size, the gateway's one signal. The + device now chunks the gateway slot at the peer-stream size (64 KiB), so + every full chunk is refused `frame_too_large`; at the Bluetooth size it + used before, every chunk slipped under the bound. A file small enough to + be one frame under the bound is indistinguishable from a message and + crosses. +- Reticulum 1.6 mints a proof-of-work stamp before a destination's first + announce. A new gateway is unreachable for seconds on a laptop and minutes + on a small board, once per identity. The daemon logs it; the README says it. +- A device reaches another gateway's devices only while both are attached + over IP. Re-originating backbone frames into a Bluetooth zone needs the + gateway to run an engine of its own, and is not done. +- The repository now ships a server-side component with its own deployment + story. The SDK's own CI does not run it yet. + +## Alternatives considered + +**A Rust gateway on `reticulum-rs`.** One language with the SDK, and the +verifier without an FFI hop. Rejected for now: interoperability with the +Python reference is the property a backbone needs, and it is not yet +promised. + +**Verdict on hand-off.** Answer `MessageSent` as soon as the frame is handed +to a live link whose peer claims the recipient, which keeps every verdict +well inside the clients' 60 seconds. Rejected: it reports a frame forwarded +that may never have arrived, and the device stops retrying on that report. +The peer's own answer costs one more packet and is the honest one. + +**Leave the gateway to deployments.** The contract alone is enough to build +one. But a contract with no implementation is not tested by anything, and the +first deployment would have found the 18-frame bootstrap and the announce +stamp in the field. + +## What would undo this + +A second builder of the proof payload in the gateway, in any language: the +verifier exists so that there is none. + +A verdict reported `MessageSent` before the peer gateway answered. + +A scarce-class burst smaller than a first contact, or a backbone frame bound +smaller than a first contact's largest frame. Either looks like a tighter +budget and is a pairing that stalls on its own frames: intermittently for +the burst, always for the bound. + +Handing Reticulum a second request on a link before the first resolves. It +works on TCP, where transfers finish before anything times out, and on a +radio it puts frames on air that their devices were told had failed. diff --git a/docs/adr/README.md b/docs/adr/README.md index cf8568cc5..7195c416f 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -50,6 +50,7 @@ silently undo it. Decisions that follow from the obvious default do not need one | [0037](0037-an-applications-users-are-visible-only-to-that-application.md) | An application's users are visible only to that application | Proposed | | [0038](0038-a-fast-link-is-offered-inside-the-session.md) | Two devices that meet over Bluetooth bring up Wi-Fi through their session | Accepted | | [0039](0039-a-browser-dials-a-native-device-from-a-code.md) | A browser dials a native device on its network from a code the device shows | Proposed | +| [0040](0040-a-reference-gateway-ships-with-the-sdk.md) | A reference gateway ships with the SDK | Proposed | ## Format diff --git a/docs/reticulum.md b/docs/reticulum.md index 31f6d4d19..d1498e674 100644 --- a/docs/reticulum.md +++ b/docs/reticulum.md @@ -6,7 +6,7 @@ The Reticulum transport provides long-range, resilient mesh networking via the [ Reticulum is one of five transports in the Offline Protocol SDK, alongside BLE, Wi-Fi Direct, Internet and Nostr. It is disabled by default because it requires external infrastructure (a running Reticulum instance, an RNode radio, or a gateway). -> **This repository ships the device half.** The Rust transport opens no Reticulum link of its own: it manages queues, metrics and the confirmation loop, and expects the platform to bridge to a real Reticulum stack. The two mobile managers and the Python `GatewayManager` speak [the gateway daemon contract](spec/gateway-contract.md) to a configurable address: they attach with a signed address declaration, settle each send on the gateway's verdict, and watch presence. What answers on the other end is a gateway daemon built to that contract, which is a deployment rather than something this SDK ships. With nothing listening at the daemon address, enabling Reticulum gives you a transport that never becomes available. The transport is named after its reference backbone, and that is all the name means: the daemon contract does not require Reticulum behind the daemon, the backbone is [the gateway's property](spec/gateway-contract.md#the-backbone), and this device learns of it only as a `backbone__v1` capability token that nothing in the SDK reads ([ADR 0026](adr/0026-the-backbone-is-a-gateway-property.md)). +> **This repository ships both halves.** The device half is the Rust transport, which opens no Reticulum link of its own (it manages queues, metrics and the confirmation loop), and the two mobile managers and the Python `GatewayManager`, which speak [the gateway daemon contract](spec/gateway-contract.md) to a configurable address: they attach with a signed address declaration, settle each send on the gateway's verdict, and watch presence. The gateway half is the reference daemon in [`gateway/`](../gateway/README.md) ([ADR 0040](adr/0040-a-reference-gateway-ships-with-the-sdk.md)), which runs Reticulum and carries frames between gateways over it, LoRa included. With nothing listening at the daemon address, enabling Reticulum gives you a transport that never becomes available. The transport is named after its reference backbone, and that is all the name means: the daemon contract does not require Reticulum behind the daemon, the backbone is [the gateway's property](spec/gateway-contract.md#the-backbone), and this device learns of it only as a `backbone__v1` capability token that nothing in the SDK reads ([ADR 0026](adr/0026-the-backbone-is-a-gateway-property.md)). ## When to Use Reticulum @@ -25,99 +25,36 @@ Reticulum is **not** suitable for: ## Architecture -The Offline Protocol SDK's `ReticulumTransport` manages message queues, delivery metrics, and the confirmation loop on the Rust side. The **platform layer** is responsible for bridging to an actual Reticulum instance. There are several ways to achieve this bridge, each with different trade-offs (see [Integration Strategies](#integration-strategies) below). +Reticulum runs on the gateway, never on the device. A device speaks newline-delimited JSON to a gateway daemon over local IP (venue Wi-Fi, or a hotspot the gateway box provides), and the daemon owns everything past that: its Reticulum identity, its links to other gateways, and the radio. ``` -┌──────────────────────┐ -│ Offline Protocol │ -│ (Rust Core) │ -│ │ -│ ReticulumTransport │◄── Transport trait implementation -│ - send_queue │ (same interface as BLE, WiFi, Internet) -│ - receive_queue │ -│ - pending_confirm │ -│ - metrics │ -└──────────┬───────────┘ - │ Platform Bridge (UniFFI) - ▼ -┌──────────────────────┐ -│ Platform Layer │ -│ (iOS/Android) │ -│ │ -│ Integration via: │ -│ - Embedded Python │◄── Most proven (Sideband pattern) -│ - reticulum-rs │◄── Pure Rust (emerging) -│ - HDLC IPC bridge │◄── Desktop/server only -│ - TCP gateway │◄── Via TCPClientInterface -└──────────┬───────────┘ - │ - ▼ -┌──────────────────────┐ -│ Reticulum Stack │ -│ │ -│ Interfaces: │ -│ - RNode (LoRa) │ -│ - TCP / UDP │ -│ - I2P │ -│ - Serial / KISS │ -│ - AutoInterface │ -└──────────────────────┘ +┌──────────────────────┐ local IP ┌──────────────────────┐ Reticulum ┌──────────────────┐ +│ Device (any SDK) │ gateway contract │ Gateway daemon │ (RNode/LoRa, │ Peer gateway │ +│ │ ──────────────────► │ gateway/ │ ◄───────────► │ and the devices │ +│ ReticulumTransport │ attach, submit, │ - attach proof │ TCP, I2P, │ attached to it │ +│ + platform manager │ verdict, deliver, │ - verdicts │ serial...) │ │ +│ │ presence │ - budgets │ │ │ +└──────────────────────┘ │ - Reticulum (RNS) │ └──────────────────┘ + └──────────────────────┘ ``` -## Important: Reticulum Integration Reality +On the device, `ReticulumTransport` manages message queues, delivery metrics, and the confirmation loop on the Rust side, and the platform manager holds the socket to the daemon. That is the whole device half, whatever stands behind the daemon. -Reticulum is a Python-first project. The [reference implementation](https://github.com/markqvist/Reticulum) (`pip install rns`) is the authoritative definition of the protocol. There is **no stable C API or documented wire protocol spec** for external programs to use. This has important implications for mobile integration. +## Where Reticulum runs -**How existing Reticulum apps work:** Every production Reticulum mobile app (notably [Sideband](https://github.com/markqvist/Sideband)) embeds the full Python runtime and RNS library into the app using frameworks like python-for-android. They do not connect to an external daemon via TCP. +Reticulum is a Python-first project. The [reference implementation](https://github.com/markqvist/Reticulum) (`pip install rns`) is the authoritative definition of the protocol, and there is no stable C API or documented wire protocol for other programs. Every production Reticulum mobile app (notably [Sideband](https://github.com/markqvist/Sideband)) embeds the Python runtime. -**The shared instance IPC** (`rnsd` daemon on port 37428) uses an internal protocol (HDLC-framed Reticulum packets over a Unix domain socket, with TCP as fallback). This is designed for multiple Python programs on the same host to share one Reticulum instance — not as a general-purpose API for non-Python apps. +That is why the SDK keeps Reticulum off the device: a phone would carry a Python runtime, and a per-device Reticulum destination would need either a Reticulum stack on every device or gateways holding device keys, which [the contract](spec/gateway-contract.md#gateway-owned-destinations) forbids. The reference gateway runs the Python reference in its own process. See [its README](../gateway/README.md) for flashing an RNode, provisioning peers and what to expect over LoRa. -This means the platform bridge you implement must choose one of the strategies described below, depending on your deployment target. +### Building a gateway another way -## Integration Strategies +A gateway is anything that speaks the contract, so the reference daemon is one choice. If you build your own, it still needs a Reticulum stack, and these are the ways to reach one: -### Strategy 1: Embedded Python (Most Proven — Mobile) +- **The Python reference, in process.** What the reference gateway does. Proven, and the only option with full protocol support. +- **`reticulum-rs`.** The [`reticulum`](https://crates.io/crates/reticulum) crate is a Rust port. Wire compatibility with the Python reference is not yet guaranteed, which is the property a backbone needs. +- **A shared `rnsd` instance.** A program on the same host can exchange HDLC-framed raw packets with `rnsd` over its shared-instance socket (`\0rns/default`, or TCP `127.0.0.1:37428`). This is packet-level access only: you would reimplement Reticulum's identities, links and cryptography yourself. -Embed the Python runtime and RNS library directly in your mobile app. This is how Sideband works and is the most battle-tested approach. - -**Android:** Use [Chaquopy](https://chaquo.com/chaquopy/) or [python-for-android](https://github.com/kivy/python-for-android) to embed a Python interpreter. Call `import RNS` from embedded Python and bridge to your native code. - -**iOS:** Use [Kivy-iOS](https://github.com/kivy/kivy-ios) or a similar Python embedding framework. Note that iOS Reticulum support is still maturing — currently limited to TCP and multicast UDP interfaces (no BLE/serial yet). - -**Pros:** Full Reticulum protocol support, proven by Sideband -**Cons:** Adds ~30MB+ for the Python runtime, complex build setup - -### Strategy 2: reticulum-rs Crate (Emerging — Pure Rust) - -The [`reticulum`](https://crates.io/crates/reticulum) crate by BeechatNetworkSystemsLtd is a Rust port of the Reticulum protocol stack. It was presented at FOSDEM 2026 and is under active development. - -If `reticulum-rs` achieves full wire-format compatibility with the Python reference, it could be linked directly into the Offline Protocol SDK with zero Python dependency. This is the ideal long-term path. - -**Pros:** Native Rust, no Python dependency, small binary (<1MB) -**Cons:** Still maturing; wire-format interoperability with the Python reference is not yet guaranteed - -### Strategy 3: HDLC Shared Instance Bridge (Desktop/Server) - -On desktop/server platforms where `rnsd` is running, a non-Python app can connect to the shared instance socket and exchange HDLC-framed raw Reticulum packets: - -- **Linux/macOS:** Unix domain socket (abstract socket `\0rns/default`) -- **TCP fallback:** `127.0.0.1:37428` (used when domain sockets are unavailable, or when `shared_instance_type = tcp` is set in config) - -The HDLC framing uses `0x7E` flag bytes with `0x7D` escape byte-stuffing. The payloads are raw Reticulum wire-format packets. - -**Critical caveat:** This gives you raw packet-level access only. You still need to implement Reticulum's cryptography (X25519, Ed25519, AES-256-CBC, HMAC-SHA256), identity management, destination resolution, and link establishment yourself. The shared instance is a packet relay, not a high-level messaging API. - -**Pros:** Lightweight, no Python in your process, uses system daemon -**Cons:** Desktop only, requires reimplementing Reticulum protocol logic, undocumented IPC protocol - -### Strategy 4: TCP Gateway (Simplest — Any Platform) - -Connect to a remote Reticulum transport node using Reticulum's `TCPClientInterface`. In this model, a Reticulum gateway server handles the protocol complexity, and your app communicates with it over a standard TCP connection. - -This requires a Reticulum node configured as a TCP server that your app connects to as a client. The Reticulum transport node handles identity, routing, and encryption. - -**Pros:** Standard TCP, works on any platform, no local daemon required -**Cons:** Requires a remote gateway server, adds network dependency +Whichever you pick, verify each device's attach proof with the SDK's `verify_gateway_address_proof` rather than building the signed payload yourself ([ADR 0022](adr/0022-one-sealed-layer-shared-with-the-leaf.md)). ## Configuration @@ -171,7 +108,7 @@ The longer timeouts reflect the high-latency reality of LoRa multi-hop paths. ## Platform Bridge Lifecycle -Regardless of which integration strategy you choose, the platform bridge interacts with `ReticulumTransport` through the same UniFFI API: +Whatever gateway answers on the daemon address, the platform bridge interacts with `ReticulumTransport` through the same UniFFI API: 1. **Initialize** your Reticulum integration (embedded Python, `reticulum-rs`, a gateway daemon connection, and so on) 2. **Attach**, if you speak the gateway contract: `gatewayAddressDeclaration(challenge)` builds the proof, `reticulumAddressDeclared(address)` and `reticulumAddressDeclarationRefused(reason)` report the answer, and `reticulumGatewayCapabilities(tokens)` hands over the advertisement @@ -193,9 +130,10 @@ Regardless of which integration strategy you choose, the platform bridge interac > > Note what this section does not say: **`rnsd` does not speak this protocol.** > Its own shared-instance IPC is HDLC-framed Reticulum packets over a Unix -> domain socket (Strategy 3 above), not this. A gateway daemon is a separate -> program that attaches to a Reticulum stack on one side and speaks this -> contract to devices on the other. +> domain socket (see [Building a gateway another way](#building-a-gateway-another-way)), +> not this. A gateway daemon is a separate program that attaches to a +> Reticulum stack on one side and speaks this contract to devices on the +> other; [`gateway/`](../gateway/README.md) is the reference one. The built-in clients, `ReticulumManager` on iOS and Android and `GatewayManager` in Python (`bindings/python/offline_protocol_sdk/gateway_manager.py`, configured with `daemon_address`), speak a newline-delimited JSON protocol over TCP to a configurable daemon address (default `localhost:4242`). All three implement the same message types, and the Rust guards that read the attach constants read all three sources. @@ -268,7 +206,7 @@ Unconfirmed messages expire after 120 seconds and are counted as failures. The b ### Example: Platform Bridge Skeleton (Android/Kotlin) -This shows the SDK-facing bridge logic. The actual Reticulum communication (`sendViaReticulum` / `receiveFromReticulum`) depends on your chosen integration strategy. +This shows the SDK-facing bridge logic, for a bridge written from scratch rather than one of the bundled managers. `sendViaReticulum` / `receiveFromReticulum` stand for the daemon socket: what the bridge writes is the gateway contract's JSON, never Reticulum packets. ```kotlin class ReticulumBridge( @@ -380,19 +318,19 @@ Reticulum will **not** be selected when: ## File Transfer Behavior -Reticulum uses BLE-like chunk sizes for file transfers due to its low bandwidth: +The daemon link is a stream over local IP, so a transfer on it is chunked like the peer stream, whatever stands behind the gateway: -| Parameter | Value | Comparison | -|-----------|-------|------------| -| Chunk size | BLE chunk size | Same as BLE (smaller chunks for low throughput) | -| Media window | BLE media window | Same as BLE | -| Media transfer eligibility | Excluded | Reticulum is not in the preferred transport list for media transfers | +| Parameter | Value | Why | +|-----------|-------|-----| +| Chunk size | 64 KiB (`CHUNK_SIZE_PEER_STREAM`) | The device never sizes frames to a backbone it cannot see ([ADR 0026](adr/0026-the-backbone-is-a-gateway-property.md)) | +| Media window | 8 (`MEDIA_WINDOW_SIZE_PEER_STREAM`) | As the peer stream | +| Media transfer eligibility | Only while the daemon link is the current carrier | It is absent from the media fallback order | -Large file transfers over Reticulum are technically possible but will be very slow. The SDK automatically excludes Reticulum from the preferred media transfer transport list. If Reticulum is the only available transport, transfers will still work but at LoRa speeds. +Media MUST NOT cross a scarce backbone, and size is how a gateway tells: every full 64 KiB chunk is past a scarce gateway's frame bound, so it is refused `frame_too_large` and the transfer fails on its retry ladder. A broad gateway, or one delivering to a device attached to it, carries the transfer. A file small enough to be one frame under the scarce bound cannot be told from a message and crosses. Until this release the slot used Bluetooth-sized 4 KiB chunks, which slipped under a scarce bound, so media crossed. ## Reticulum Setup -The Offline Protocol SDK does not include a Reticulum stack — you must provide one via your chosen integration strategy. Below is reference information for setting up the Python Reticulum daemon, which is useful for desktop deployments and as a gateway for mobile apps. +The SDK itself includes no Reticulum stack; the reference gateway runs one. Below is reference information for the Python Reticulum tools, which you also use to flash and inspect an RNode. ### Installing Reticulum diff --git a/docs/spec/gateway-contract.md b/docs/spec/gateway-contract.md index 69cb19cb3..32625737e 100644 --- a/docs/spec/gateway-contract.md +++ b/docs/spec/gateway-contract.md @@ -218,6 +218,13 @@ Both ends have something to verify, and neither check substitutes for the other. been accepted before. A challenge honoured twice turns one captured `DeclareAddress` into a reusable credential. +The SDK exposes the first two as one instance-less call, +`verify_gateway_address_proof(address, public_key, signature, challenge)`, +which returns the bound address or throws. A gateway built on the SDK calls it +rather than building the payload itself, because the payload has one home +([ADR 0022](../adr/0022-one-sealed-layer-shared-with-the-leaf.md)). The third +check is connection state and stays the gateway's. + A gateway that skips these attaches sessions under addresses the attaching device does not control, which is how a hostile device draws another device's inbound traffic to itself and poisons the presence answers given about it. @@ -426,6 +433,13 @@ provides three of the four fails in a way the device cannot see. transfer fails on its retry ladder; the device does not know the class (invariant 3), and that cost is the price of not knowing. + A gateway sees ciphertext only, so size is its one signal. The device + chunks media on the daemon link at the peer-stream size (64 KiB), far + above any scarce frame bound, so every full chunk is refused. A file + small enough to travel as one frame under the bound is indistinguishable + from a message and crosses; a scarce gateway cannot exclude it, and its + budgets are what bound the cost. + ### The backbone token A gateway advertises each backbone it can reach as one capability token of @@ -547,6 +561,10 @@ with **zero** gateways is a state the policy MUST be able to surface rather than hide: absent facts mean today's behaviour (invariant 3), which is exactly what a zone with no gateway should experience. +The reference gateway is [`gateway/`](../../gateway/README.md) +([ADR 0040](../adr/0040-a-reference-gateway-ships-with-the-sdk.md)), with +Reticulum as its backbone. + Operational guidance for anyone deploying: install two. One gateway per zone is a chokepoint, and nothing in this contract prevents a second. diff --git a/docs/spec/local-api.md b/docs/spec/local-api.md index 99838a062..72a4d1efa 100644 --- a/docs/spec/local-api.md +++ b/docs/spec/local-api.md @@ -550,6 +550,7 @@ nothing to route. | `derive_address` | `public_key b64` | string | | `parse_invite` | `blob` | `{InviteInfo}` | | `verify_identity_assertion` | `assertion b64` | string (the proved address) | +| `verify_gateway_address_proof` | `address`, `public_key b64`, `signature b64`, `challenge b64` | string (the bound address) | ## Platform operations diff --git a/gateway/.gitignore b/gateway/.gitignore new file mode 100644 index 000000000..64c75f73e --- /dev/null +++ b/gateway/.gitignore @@ -0,0 +1,4 @@ +.venv/ +__pycache__/ +*.egg-info/ +.pytest_cache/ diff --git a/gateway/README.md b/gateway/README.md new file mode 100644 index 000000000..558f7fda0 --- /dev/null +++ b/gateway/README.md @@ -0,0 +1,170 @@ +# Offline Protocol gateway daemon + +The reference implementation of the gateway half of +[the gateway contract](../docs/spec/gateway-contract.md). Devices running the +SDK attach to it over local IP through the transport the SDK calls +`reticulum` (the gateway slot, +[ADR 0026](../docs/adr/0026-the-backbone-is-a-gateway-property.md)). It carries +their sealed frames to each other and, over a Reticulum backbone, to devices +attached to other gateways. That backbone is how the SDK reaches LoRa: an +RNode on each gateway, and Reticulum between them. + +``` +phone ─Wi-Fi─► [gateway A + RNode] ~~~ LoRa (Reticulum) ~~~ [gateway B + RNode] ◄─Wi-Fi─ phone +``` + +Nothing in the SDK changes for this. A device enables the `reticulum` +transport, points it at the gateway's address, and sees one more carrier. It +never learns that LoRa is behind the gateway, except as a +`backbone_reticulum_v1` capability token it does not act on. + +## What it guarantees + +These are the contract's rules, and the tests in `tests/` pin each one. + +- **A session is bound only by a proof this gateway checked.** The device + signs its address and a 32-byte challenge minted for this connection. The + daemon verifies it with the SDK's own `verify_gateway_address_proof` (the + signature, and that the key derives to the address) and spends the + challenge, so a captured declaration cannot be replayed. +- **Every submission gets exactly one verdict**, correlated by the client's + id. `recipient_unreachable` when no gateway this one can reach has the + recipient; a plain failure (`budget_exceeded`, `frame_too_large`, + `backbone_timeout`, `attach_required`, `malformed_request`) otherwise. +- **A verdict is a claim, never settlement.** Only the recipient's end-to-end + acknowledgement settles a message. The daemon holds nothing and promises + nothing it does not do: it sets neither `pushed` nor `stored`. +- **Ciphertext only.** The daemon sees MLS ciphertext and routing metadata, + on the device link and on the backbone. +- **Budgets.** As token buckets: submissions per device; on a scarce + backbone, bytes per source host and bytes per peer gateway on the way out + (shared by every device, since the airtime toward a peer is the scarce + thing, and validated to stay above the per-host one); and frames per peer + gateway on the way in. Every burst holds a first contact (two engines + pairing and exchanging one message send 18 to 20 frames, about 16 KB, the + largest about 4 KB). +- **One request per peer at a time.** Reticulum cannot withdraw a transfer + it has queued, so the daemon queues instead: a frame whose time runs out + before its turn is answered `backbone_timeout` without reaching the radio. +- **Sessions.** Sockets that never attach have their own pool, and a + newcomer evicts the oldest of them, so they cannot lock devices out. One + host may hold at most 8 sessions; an IPv6 host is its /64, since a device + can hold as many addresses in its prefix as it likes. + +What it does not do yet: hold frames for an absent recipient (no +`mailbox_v1`), push to a sleeping phone, or re-originate backbone frames into +a Bluetooth zone. A device has to be attached to a gateway over IP to be +reached through it. When the recipient is not attached, the device's own +parking and mesh fallback apply, as they do with no gateway at all. + +## Install + +Python 3.11 or later. The SDK's Python package supplies the verifier; until a +release carries `verify_gateway_address_proof`, install the build from this +repository. + +```bash +cd gateway +python -m venv .venv +bash ../bindings/python/scripts/build-desktop.sh --release +.venv/bin/pip install -e ../bindings/python -e '.[reticulum,dev]' +``` + +## Run a local gateway + +With no `[reticulum]` section the daemon is a local gateway: every device +attached to it can reach every other, and nothing leaves the box. + +```bash +.venv/bin/offline-gateway --listen 0.0.0.0:4242 +``` + +On each device, enable the `reticulum` transport and set its daemon address +to the gateway's `HOST:PORT`: + +- React Native: `transports: { reticulum: { enabled: true, daemonAddress: "192.168.4.1:4242" } }` +- iOS and Android natively: `ReticulumManager.configure(daemonAddress: ...)` +- Python: `GatewayManager.configure(daemon_address=...)`, or `--gateway` for + the Python service + +The iOS and Android managers split the address on `:`, so give them an IPv4 +address or a host name, not an IPv6 literal. + +## Run a LoRa backbone + +1. **Flash a radio for each gateway.** Any RNode-compatible LoRa board: + `pip install rns`, plug it in, `rnodeconf --autoinstall`. +2. **Copy `examples/` to each gateway box** and set the radio in + `rns/config`: the port, and parameters that are legal where you are and + identical on every gateway. The example is EU868 with duty-cycle caps. +3. **Print each gateway's destination hash.** + `offline-gateway --config gateway.toml --print-destination` creates the + gateway's identity on first use and prints the hash its peers provision. +4. **Provision the peers.** Put each other gateway's hash in `peers`. + Gateways are provisioned, never discovered + ([ADR 0016](../docs/adr/0016-gateways-are-provisioned-not-emergent.md)): + a link from an unlisted gateway is torn down, and its requests refused. +5. **Start it.** `offline-gateway --config gateway.toml`. On its first start a + gateway mints its announce stamp, a one-time proof of work Reticulum + requires before it announces. That takes seconds on a laptop and minutes + on a small board. The stamp is stored, so later starts announce at once. + The log says when each backbone link comes up. + +How it uses Reticulum, in short: one destination per gateway +(`offline_gateway.backbone.v1`) under the gateway's own identity; one link +dialled by each side; frames as link requests, which Reticulum carries as +resources when they outgrow a packet; and presence as a snapshot when a link +comes up, then pushed changes, coalesced over two seconds. The module +docstring in `offline_gateway/reticulum.py` has the request shapes. + +## What to expect over LoRa + +LoRa is slow, and the SDK's messages are not small. One sealed direct message +is about 472 bytes on the wire at best, already more than one Reticulum +packet, and a first contact between two devices that have never met is +about 20 frames each way: connection request, key packages, the MLS Welcome, +acknowledgements. That last number is measured (`test_end_to_end.py`); the +rest of this section is arithmetic from the radio settings, not a +measurement over radios. + +With the example radio (`examples/rns/config`: SF8 at 125 kHz, about 3.1 +kbps, on the EU sub-band that allows 10 % airtime): + +- a full packet is about 1.3 s on air, and a sealed frame is three or so + transmissions from the sender, plus the peer's answers on its own airtime; +- 10 % is about 6 minutes of airtime an hour, so a gateway sustains about + 1.5 KB a minute toward a peer once Reticulum's overhead is paid, which is + what the default `peer_egress_bytes_per_minute` allows; +- a frame has to cross inside the 45 s verdict timeout, which the 50 % short + airtime cap allows up to about 6 KB: the default + `max_backbone_frame_bytes`, and enough for the largest frame of a pairing; +- a first contact (about 16 KB each way) takes a few minutes, and a later + message tens of seconds. + +At 1 % airtime, the rule on most of the EU 868 MHz band, everything is ten +times slower: a first contact takes hours. Divide the egress budget +by ten there, or the device's frames are accepted faster than the radio can +carry them. + +The daemon answers each submission within 45 seconds (the clients give up +at 60). On a slow or busy link a frame may be failed `backbone_timeout` and +retried by the device. Nothing is lost by that, only repeated, and the +timed-out transfer is cancelled, so the retry does not run beside it. + +## Tests + +```bash +.venv/bin/python -m pytest +``` + +- `test_gateway.py`: the device-facing contract, one rule at a time, with a + stand-in verifier. +- `test_backbone.py`: two gateways over the in-process backbone. +- `test_end_to_end.py`: real SDK engines, attached with the SDK's own + `GatewayManager`, pair over MLS and talk through one gateway and across two. +- `test_reticulum.py`: the same across two daemon processes joined by a real + Reticulum backbone over TCP, which is the LoRa deployment with the radio + swapped out. It lowers Reticulum's announce stamp so it does not wait for + two mints. +- `test_reticulum_unit.py`: the backbone's handler, presence and framing + rules, without a Reticulum instance. diff --git a/gateway/examples/gateway.toml b/gateway/examples/gateway.toml new file mode 100644 index 000000000..443679840 --- /dev/null +++ b/gateway/examples/gateway.toml @@ -0,0 +1,46 @@ +# A gateway with a LoRa backbone. Copy this directory to the gateway box, +# fill in `peers`, and run: +# +# offline-gateway --config gateway.toml +# +# Relative paths are relative to this file. + +# Phones reach the gateway over Wi-Fi, so it listens on the box's LAN or +# hotspot address. 127.0.0.1 would serve only an SDK running on the box. +listen_host = "0.0.0.0" +listen_port = 4242 + +# Every bound below has a default sized for a scarce backbone; these are the +# ones most deployments look at first. + +# Largest frame a device may hand this gateway, and the smaller bound for a +# frame that has to cross the backbone. A frame past the second is refused +# `frame_too_large`, which is how media stays off a LoRa-class link. The +# backbone bound has to cross the radio inside the 45 s verdict timeout and +# still pass the largest frame of a pairing (about 4 KB). +max_frame_bytes = 262144 +max_backbone_frame_bytes = 6144 + +# Frame bytes per minute toward each peer gateway, shared by every device +# attached here, and what each source host may spend of it. These are the +# budgets that have to match the radio: the defaults fit rns/config (10 % +# airtime at SF8); divide the rates by ten at 1 %. Each burst has to hold a +# first contact between two devices (about 16 KB each way, measured), or +# their pairing stalls. +peer_egress_bytes_per_minute = 1500.0 +peer_egress_burst_bytes = 24576.0 +host_backbone_bytes_per_minute = 500.0 +host_backbone_burst_bytes = 20480.0 + +[reticulum] +# Reticulum's own configuration: interfaces, the RNode's port and radio. +configdir = "rns" +# This gateway's Reticulum identity, created on first run. Keep it: peers +# provision the destination it derives, and whoever holds it can answer for +# every device attached here. +identity_path = "gateway.identity" +# Each peer gateway's destination hash. Get one by running +# `offline-gateway --config gateway.toml --print-destination` on that peer. +peers = [ + # "0123456789abcdef0123456789abcdef", +] diff --git a/gateway/examples/rns/config b/gateway/examples/rns/config new file mode 100644 index 000000000..61bb80bf1 --- /dev/null +++ b/gateway/examples/rns/config @@ -0,0 +1,45 @@ +# Reticulum configuration for a gateway with an RNode (a LoRa radio running +# RNode firmware, e.g. a Heltec LoRa32 V3 or a LilyGO T3S3 flashed with +# `rnodeconf --autoinstall`). +# +# The radio parameters MUST match on every gateway that should hear each +# other, and MUST be legal where you transmit. The values below are an EU868 +# example on the 869.40-869.65 MHz sub-band, where EU rules allow a 10 % duty +# cycle (the rest of the 868 MHz band mostly allows 1 %). Check your region's +# frequencies, power and duty-cycle rules before you key up a transmitter. +# +# What this carries: SF8 at 125 kHz is about 3.1 kbps, so a full 500-byte +# packet is about 1.3 s on air, and 10 % is about 6 minutes of airtime an +# hour. A sealed frame crosses as three or so packets. The gateway's default +# peer_egress budget (gateway.toml) is sized to this; at 1 % airtime, divide +# it by ten. + +[reticulum] + # A powered, stationary gateway is the kind of node Reticulum expects to + # route for others. Turn this off for a two-gateway deployment if you like. + enable_transport = Yes + # The daemon owns this Reticulum instance. If you already run rnsd on the + # box, point `configdir` at its configuration instead and the daemon + # attaches to it as a client. + share_instance = No + +[logging] + loglevel = 4 + +[interfaces] + [[RNode LoRa Interface]] + type = RNodeInterface + enabled = Yes + port = /dev/ttyUSB0 + frequency = 869525000 + bandwidth = 125000 + txpower = 14 + spreadingfactor = 8 + codingrate = 5 + # Airtime caps, in percent: over the last hour, and over the last 15 + # seconds. Reticulum holds traffic back past them. The long cap is the + # duty-cycle rule, which is measured over an hour. The short one only + # paces bursts: at 50 % a 6 KB frame (the gateway's backbone bound) + # crosses in about 35 s, inside the gateway's 45 s verdict timeout. + airtime_limit_long = 10 + airtime_limit_short = 50 diff --git a/gateway/offline_gateway/__init__.py b/gateway/offline_gateway/__init__.py new file mode 100644 index 000000000..93d33921c --- /dev/null +++ b/gateway/offline_gateway/__init__.py @@ -0,0 +1,25 @@ +"""The reference gateway daemon for the Offline Protocol SDK. + +It implements the device-facing half of ``docs/spec/gateway-contract.md`` +(attach, submit, verdict, deliver, presence, capabilities) and, optionally, a +Reticulum backbone between gateways, which is how a LoRa radio reaches the +SDK. See ``gateway/README.md``. +""" + +from .backbone import Backbone, BackboneFrame, ForwardResult, InMemoryBackbone, InMemoryNetwork +from .config import ConfigError, GatewayConfig, ReticulumConfig +from .gateway import Gateway + +__all__ = [ + "Backbone", + "BackboneFrame", + "ConfigError", + "ForwardResult", + "Gateway", + "GatewayConfig", + "InMemoryBackbone", + "InMemoryNetwork", + "ReticulumConfig", +] + +__version__ = "0.1.0" diff --git a/gateway/offline_gateway/__main__.py b/gateway/offline_gateway/__main__.py new file mode 100644 index 000000000..7fe247b4c --- /dev/null +++ b/gateway/offline_gateway/__main__.py @@ -0,0 +1,76 @@ +"""``python -m offline_gateway --config gateway.toml``""" + +from __future__ import annotations + +import argparse +import asyncio +import logging +import signal +import sys + +from .config import ConfigError, GatewayConfig, load +from .gateway import Gateway + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="offline-gateway", + description="The Offline Protocol reference gateway daemon (docs/spec/gateway-contract.md).", + ) + parser.add_argument("--config", help="a TOML file; see gateway/examples/gateway.toml") + parser.add_argument("--listen", help="HOST:PORT to listen on, overriding the file") + parser.add_argument("-v", "--verbose", action="store_true", help="debug logging") + parser.add_argument( + "--print-destination", + action="store_true", + help="print this gateway's Reticulum destination hash (what its peers provision) and exit", + ) + args = parser.parse_args(argv) + + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + ) + try: + config = load(args.config) if args.config else GatewayConfig() + if args.listen: + host, _, port = args.listen.rpartition(":") + config.listen_host = host.strip("[]") or config.listen_host + config.listen_port = int(port) + config.validate() + except (ConfigError, OSError, ValueError) as exc: + print(f"offline-gateway: {exc}", file=sys.stderr) + return 2 + if args.print_destination: + if config.reticulum is None: + print("offline-gateway: the config has no [reticulum] section", file=sys.stderr) + return 2 + from .reticulum import destination_hash_for + + print(destination_hash_for(config.reticulum.identity_path)) + return 0 + return asyncio.run(_run(config)) + + +async def _run(config: GatewayConfig) -> int: + backbone = None + if config.reticulum is not None: + from .reticulum import ReticulumBackbone + + backbone = ReticulumBackbone(config.reticulum, max_frame_bytes=config.max_backbone_frame_bytes) + gateway = Gateway(config, backbone=backbone) + await gateway.start() + stop = asyncio.Event() + loop = asyncio.get_running_loop() + for sig in (signal.SIGINT, signal.SIGTERM): + try: + loop.add_signal_handler(sig, stop.set) + except NotImplementedError: # pragma: no cover - Windows + pass + await stop.wait() + await gateway.stop() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/gateway/offline_gateway/backbone.py b/gateway/offline_gateway/backbone.py new file mode 100644 index 000000000..92afb3224 --- /dev/null +++ b/gateway/offline_gateway/backbone.py @@ -0,0 +1,375 @@ +"""What the daemon needs from a backbone, and the presence bookkeeping every +backbone shares. + +The backbone is the gateway's property (ADR 0026): a device never sees one, +and learns of it only as a ``backbone__v1`` capability token. This +module is the seam between the device-facing daemon (``gateway.py``) and +whatever carries frames between gateways. ``reticulum.py`` is the reference +implementation; ``InMemoryNetwork`` below joins gateways inside one process, +for tests. + +The contract's four obligations on a backbone ("What a backbone owes a +gateway") map onto this interface as: + +1. gateway-to-gateway presence: :meth:`Backbone.claim` answers from what peer + gateways pushed, and :meth:`Backbone.local_presence_changed` pushes ours; +2. arbitrary-size framing: :meth:`Backbone.forward` takes a whole frame, and + how it is segmented is the implementation's business; +3. a provisioned peer list: each implementation's own configuration; +4. a declared rate class: :attr:`Backbone.rate_class`, applied by the daemon + at its own egress. +""" + +from __future__ import annotations + +import abc +import asyncio +import time +from collections import OrderedDict +from dataclasses import dataclass +from enum import Enum +from typing import Callable, Protocol + + +#: ``admit(peer) -> bool``; see :meth:`Backbone.forward`. +Admit = Callable[[str], bool] + + +class ForwardResult(Enum): + """What a peer gateway said about a frame it was handed.""" + + #: Written to a session attached at the peer gateway. + DELIVERED = "delivered" + #: The peer gateway has no session for the recipient. + UNREACHABLE = "unreachable" + #: The peer gateway refused the frame (budget, size). A plain failure. + REFUSED = "refused" + #: No answer in time, or no link to the peer. A plain failure. + TIMEOUT = "timeout" + + +@dataclass(frozen=True) +class BackboneFrame: + """One device frame, as it crosses between gateways. + + ``content`` is the ciphertext the device submitted, untouched. The + gateways see it and the routing metadata around it, never a plaintext + (invariant 4). + """ + + recipient: str + sender: str + content: bytes + message_id: str | None + reply_to_msg: str | None + + +@dataclass(frozen=True) +class Claim: + """A peer gateway's statement that it has, or had, a session for an + address. A claim, never settlement: it may open a path, never close one.""" + + peer: str + online: bool + last_seen_ms: int | None + received_at: float + #: The claiming gateway's number for the change this claim reflects. + #: Later changes carry larger numbers; see :class:`PresenceTable`. + seq: int = 0 + + +class BackboneHooks(Protocol): + """What a backbone may ask of the daemon it serves.""" + + async def deliver_from_backbone(self, frame: BackboneFrame, peer: str) -> tuple[ForwardResult, str]: + """Hand a frame from ``peer`` to a local session. Returns the result + and, for a refusal, its reason token.""" + + #: Random per daemon process, so a peer can tell a restarted gateway's + #: numbering, which starts again from zero, from a stale message. + presence_epoch: str + + def local_snapshot(self) -> tuple[int, dict[str, int]]: + """The current presence number, and every address with a bound + session here mapped to the number of the change that bound it.""" + + def remote_presence_changed(self, address: str) -> None: + """A peer gateway's claim about ``address`` changed.""" + + +class Backbone(abc.ABC): + """A wide-area carrier between gateways.""" + + #: The ```` in the ``backbone__v1`` token, lowercase. + kind: str + #: ``"scarce"`` or ``"broad"``, per the contract's table of kinds. A kind + #: not in that table is scarce. + rate_class: str = "scarce" + + @abc.abstractmethod + async def start(self, hooks: BackboneHooks) -> None: ... + + @abc.abstractmethod + async def stop(self) -> None: ... + + @abc.abstractmethod + def claim(self, address: str) -> Claim | None: + """The freshest claim any peer gateway has made about ``address``.""" + + @abc.abstractmethod + async def forward( + self, frame: BackboneFrame, timeout: float, admit: Admit | None = None + ) -> tuple[ForwardResult, str]: + """Carry ``frame`` to the peer gateway that claims its recipient. + + Answers within ``timeout`` seconds: the daemon owes the device a + verdict, and the reference clients fail a frame that has none in 60. + + ``admit(peer)`` is called once, at the moment the frame is about to + be put on the backbone toward ``peer``, and nowhere else: it charges + the scarce budgets, so a frame that never reaches the backbone + (queued past its time, no link, no claim) is never charged. When it + returns ``False`` the frame is not sent and the answer is + ``REFUSED`` with ``budget_exceeded``. + """ + + @abc.abstractmethod + def local_presence_changed(self, address: str, online: bool, last_seen_ms: int | None, seq: int) -> None: + """Tell the peer gateways that ``address`` attached here or left, as + change number ``seq``.""" + + +class PresenceTable: + """Claims received from peer gateways, keyed by address and by peer. + + **Ordering.** Presence messages from one peer can arrive out of order: + Reticulum runs each request on a thread of its own, and a snapshot large + enough to travel as a resource lands after a one-packet update sent later. + Applied in arrival order, a snapshot taken before an attach would erase it + and leave an offline claim that closes a path the contract says a gateway + may only open. So every change carries the sending gateway's number for + it, every snapshot carries the number current when it was taken, and a + claim is replaced only by something newer: an entry with a larger number, + or, for an address the snapshot omits, a snapshot taken after the change + that claim reflects. The numbers restart with the sending process, so + each peer's messages also carry an epoch, and a new epoch discards + everything that peer said before. + + Every claim a peer made is dropped when the link to that peer goes, + because a claim from a gateway this one can no longer reach opens no path. + Bounded: past ``capacity`` addresses the least recently updated go. + """ + + def __init__(self, capacity: int = 65536, clock: Callable[[], float] = time.monotonic) -> None: + self._claims: OrderedDict[str, dict[str, Claim]] = OrderedDict() + self._epochs: dict[str, str] = {} + #: Per peer, the newest snapshot applied. A snapshot speaks for every + #: address, including ones it holds no claim about (forgotten when a + #: link dropped, or never heard of), so nothing older than it may + #: create a claim: a late resend of an old attach would otherwise + #: bring back a device that has since left. + self._floors: dict[str, int] = {} + self._capacity = capacity + self._clock = clock + + def update( + self, + peer: str, + address: str, + online: bool, + last_seen_ms: int | None, + seq: int, + epoch: str = "", + *, + _in_snapshot: bool = False, + ) -> list[str]: + """Records a claim unless one at least as new is held. Returns the + addresses whose best claim changed as a result.""" + changed = self._enter_epoch(peer, epoch) + held = self._claims.get(address, {}).get(peer) + if held is not None and held.seq >= seq: + return changed + # A snapshot's own entries are current by definition, whatever their + # number: one listing a device that attached long ago must restore it + # after its claim was forgotten. + if held is None and not _in_snapshot and seq <= self._floors.get(peer, 0): + return changed + before = self.claim(address) + by_peer = self._claims.pop(address, {}) + by_peer[peer] = Claim(peer, online, last_seen_ms, self._clock(), seq) + self._claims[address] = by_peer + while len(self._claims) > self._capacity: + self._claims.popitem(last=False) + if _differs(before, self.claim(address)): + changed.append(address) + return changed + + def snapshot(self, peer: str, online: dict[str, int], snapshot_seq: int, epoch: str = "") -> list[str]: + """Applies ``peer``'s full list of attached addresses, each with the + number of the change that attached it, taken at ``snapshot_seq``. + Returns the addresses whose best claim changed.""" + changed = self._enter_epoch(peer, epoch) + for address in [a for a, by in self._claims.items() if peer in by and a not in online]: + claim = self._claims[address][peer] + # Newer than the snapshot: the change it reflects happened after + # the snapshot was taken, so the snapshot's silence says nothing. + if not claim.online or claim.seq >= snapshot_seq: + continue + before = self.claim(address) + self._claims[address][peer] = Claim(peer, False, claim.last_seen_ms, self._clock(), snapshot_seq) + if _differs(before, self.claim(address)): + changed.append(address) + for address, seq in online.items(): + changed += self.update(peer, address, True, None, seq, epoch, _in_snapshot=True) + # Raised after the snapshot's own entries, which are all numbered at + # or below it, are in. + self._floors[peer] = max(self._floors.get(peer, 0), snapshot_seq) + return changed + + def drop_peer(self, peer: str) -> list[str]: + """Forgets every claim ``peer`` made. Returns the addresses whose best + claim changed.""" + changed = [] + for address in [a for a, by in self._claims.items() if peer in by]: + before = self.claim(address) + by_peer = self._claims[address] + del by_peer[peer] + if not by_peer: + del self._claims[address] + if _differs(before, self.claim(address)): + changed.append(address) + return changed + + def claim(self, address: str) -> Claim | None: + """An online claim if any peer makes one (the newest such), otherwise + the newest offline one.""" + by_peer = self._claims.get(address) + if not by_peer: + return None + online = [c for c in by_peer.values() if c.online] + pool = online or list(by_peer.values()) + return max(pool, key=lambda c: c.received_at) + + def _enter_epoch(self, peer: str, epoch: str) -> list[str]: + if self._epochs.get(peer) == epoch: + return [] + self._epochs[peer] = epoch + self._floors.pop(peer, None) + return self.drop_peer(peer) + + +def _differs(a: Claim | None, b: Claim | None) -> bool: + if a is None or b is None: + return (a is None) != (b is None) + return (a.online, a.peer) != (b.online, b.peer) + + +# -- An in-process backbone, for tests --------------------------------------- + + +class InMemoryNetwork: + """Joins in-process backbones as if every pair had a live link. Tests cut + and restore a pair's link with :meth:`cut` and :meth:`join`.""" + + def __init__(self) -> None: + self.members: dict[str, "InMemoryBackbone"] = {} + self._cut: set[frozenset[str]] = set() + + def linked(self, a: str, b: str) -> bool: + return a != b and frozenset((a, b)) not in self._cut and a in self.members and b in self.members + + def cut(self, a: str, b: str) -> None: + self._cut.add(frozenset((a, b))) + for x, y in ((a, b), (b, a)): + member = self.members.get(x) + if member is not None: + member._link_lost(y) + + def join(self, a: str, b: str) -> None: + self._cut.discard(frozenset((a, b))) + for x, y in ((a, b), (b, a)): + member = self.members.get(x) + if member is not None: + member._link_up(y) + + +class InMemoryBackbone(Backbone): + kind = "memory" + rate_class = "broad" + + def __init__(self, network: InMemoryNetwork, name: str, rate_class: str = "broad") -> None: + self.network = network + self.name = name + self.rate_class = rate_class + self.table = PresenceTable() + self.hooks: BackboneHooks | None = None + #: Seconds each forward waits before it is carried, to exercise the + #: daemon's timeout handling. + self.delay = 0.0 + + async def start(self, hooks: BackboneHooks) -> None: + self.hooks = hooks + self.network.members[self.name] = self + for other in list(self.network.members): + if self.network.linked(self.name, other): + self._link_up(other) + self.network.members[other]._link_up(self.name) + + async def stop(self) -> None: + self.network.members.pop(self.name, None) + for other in list(self.network.members.values()): + other._link_lost(self.name) + self.hooks = None + + def claim(self, address: str) -> Claim | None: + return self.table.claim(address) + + async def forward( + self, frame: BackboneFrame, timeout: float, admit: Admit | None = None + ) -> tuple[ForwardResult, str]: + claim = self.table.claim(frame.recipient) + if claim is None or not claim.online or not self.network.linked(self.name, claim.peer): + return ForwardResult.UNREACHABLE, "no peer gateway claims the recipient" + if admit is not None and not admit(claim.peer): + return ForwardResult.REFUSED, "budget_exceeded" + peer = self.network.members[claim.peer] + try: + return await asyncio.wait_for(peer._receive(frame, self.name), timeout) + except asyncio.TimeoutError: + return ForwardResult.TIMEOUT, "no answer from the peer gateway" + + def local_presence_changed(self, address: str, online: bool, last_seen_ms: int | None, seq: int) -> None: + assert self.hooks is not None + epoch = self.hooks.presence_epoch + for other in list(self.network.members.values()): + if self.network.linked(self.name, other.name): + other._claimed(self.name, address, online, last_seen_ms, seq, epoch) + + async def _receive(self, frame: BackboneFrame, sender: str) -> tuple[ForwardResult, str]: + if self.delay: + await asyncio.sleep(self.delay) + if self.hooks is None: + return ForwardResult.TIMEOUT, "stopped" + return await self.hooks.deliver_from_backbone(frame, sender) + + def _claimed( + self, peer: str, address: str, online: bool, last_seen_ms: int | None, seq: int, epoch: str + ) -> None: + for changed in self.table.update(peer, address, online, last_seen_ms, seq, epoch): + if self.hooks is not None: + self.hooks.remote_presence_changed(changed) + + def _link_up(self, peer: str) -> None: + other = self.network.members.get(peer) + if other is None or other.hooks is None or self.hooks is None: + return + snapshot_seq, online = other.hooks.local_snapshot() + for address in self.table.snapshot(peer, online, snapshot_seq, other.hooks.presence_epoch): + self.hooks.remote_presence_changed(address) + + def _link_lost(self, peer: str) -> None: + if self.hooks is None: + return + for address in self.table.drop_peer(peer): + self.hooks.remote_presence_changed(address) + diff --git a/gateway/offline_gateway/budget.py b/gateway/offline_gateway/budget.py new file mode 100644 index 000000000..3809f3d3f --- /dev/null +++ b/gateway/offline_gateway/budget.py @@ -0,0 +1,83 @@ +"""Token buckets: the per-device and per-peer-gateway budgets the contract +requires ("Abuse and exhaustion"). + +A gateway that does not bound what one attached device can consume hands that +device the backbone. On a scarce backbone (LoRa-class links, a duty cycle) one +chatty device starves every other device behind the same gateway, and a +device cannot tell from the outside that its gateway applies no budget at all. +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass, field +from typing import Callable + + +@dataclass +class TokenBucket: + """``rate`` tokens per second, up to ``burst`` held. + + ``take`` is all-or-nothing: a refused request costs nothing, so a device + that backs off is not punished for the attempt. + """ + + rate: float + burst: float + clock: Callable[[], float] = time.monotonic + _tokens: float = field(init=False) + _at: float = field(init=False) + + def __post_init__(self) -> None: + if self.rate < 0 or self.burst <= 0: + raise ValueError("a bucket needs a non-negative rate and a positive burst") + self._tokens = self.burst + self._at = self.clock() + + def take(self, amount: float = 1.0) -> bool: + if not self.has(amount): + return False + self._tokens -= amount + return True + + def has(self, amount: float = 1.0) -> bool: + """Whether ``take(amount)`` would succeed, spending nothing. Lets a + caller check two buckets before charging either.""" + now = self.clock() + self._tokens = min(self.burst, self._tokens + (now - self._at) * self.rate) + self._at = now + return amount <= self._tokens + + +class BucketMap: + """One bucket per key, made on first use, with the oldest dropped past + ``capacity`` so a stream of fresh keys cannot grow it without bound.""" + + def __init__( + self, + rate: float, + burst: float, + capacity: int = 4096, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._rate = rate + self._burst = burst + self._capacity = capacity + self._clock = clock + self._buckets: dict[str, TokenBucket] = {} + + def take(self, key: str, amount: float = 1.0) -> bool: + return self._bucket(key).take(amount) + + def has(self, key: str, amount: float = 1.0) -> bool: + return self._bucket(key).has(amount) + + def _bucket(self, key: str) -> TokenBucket: + bucket = self._buckets.pop(key, None) + if bucket is None: + bucket = TokenBucket(self._rate, self._burst, self._clock) + while len(self._buckets) >= self._capacity: + self._buckets.pop(next(iter(self._buckets))) + # Re-inserted at the end: the dict's order is the use order. + self._buckets[key] = bucket + return bucket diff --git a/gateway/offline_gateway/config.py b/gateway/offline_gateway/config.py new file mode 100644 index 000000000..4e5168827 --- /dev/null +++ b/gateway/offline_gateway/config.py @@ -0,0 +1,210 @@ +"""The daemon's configuration, read from TOML. + +A gateway is provisioned (ADR 0016): a person installs it and writes this +file. Every bound has a default, and every default is chosen for a scarce +backbone, because that is the kind this reference daemon ships with. +""" + +from __future__ import annotations + +import tomllib +from dataclasses import dataclass, field, fields +from pathlib import Path +from typing import Any + +from . import wire + +#: The reference clients' attach timeout. The verdict-only grace may not be +#: shorter, or a client whose declaration is merely slow is announced out +#: from under it, and the contract lets it close on that. +CLIENT_ATTACH_TIMEOUT = 10.0 +#: The reference clients' verdict timeout. A backbone verdict that takes +#: longer arrives after the client has already failed the frame. +CLIENT_VERDICT_TIMEOUT = 60.0 + + +class ConfigError(ValueError): + pass + + +@dataclass +class ReticulumConfig: + """The Reticulum backbone. Absent from the file means no backbone.""" + + #: Reticulum's own configuration directory (its interfaces, an RNode's + #: port and radio parameters). ``None`` is Reticulum's default. + configdir: str | None = None + #: Where this gateway's Reticulum identity is kept. Created on first run. + #: The destination its peers provision is derived from it, so losing it + #: means re-provisioning every peer. + identity_path: str = "gateway.identity" + #: Peer gateways' destination hashes, hex, as each one prints at start. + peers: list[str] = field(default_factory=list) + #: Seconds between announces of this gateway's destination. + announce_interval: float = 1800.0 + #: Seconds between attempts to (re)open a link to a peer. + reconnect_interval: float = 30.0 + #: Reticulum log level, 0 (critical) to 7 (extreme). + loglevel: int = 2 + + +@dataclass +class GatewayConfig: + listen_host: str = "127.0.0.1" + listen_port: int = 4242 + #: Seconds an undeclared session waits before it is announced + #: verdict-only. ``0`` never announces one. + attach_grace: float = 15.0 + #: Concurrent device connections. + max_sessions: int = 256 + #: Of those, sessions that have not proved an address. A newcomer evicts + #: the oldest of them when this or ``max_sessions`` is full, so sockets + #: that never attach cannot lock devices out. + max_unbound_sessions: int = 32 + #: Sessions from one source address. Each device on a hotspot or venue + #: network has its own; a device reconnecting while its old socket is + #: still open needs two. + max_sessions_per_host: int = 8 + #: Frames waiting to be written to one device before it is dropped as + #: too slow to serve. + max_queued_frames: int = 512 + #: Largest frame a device may submit, in bytes, before base64. + max_frame_bytes: int = 256 * 1024 + #: Largest frame carried over a scarce backbone, refused + #: ``frame_too_large`` past it. It is also how media stays off: the + #: device chunks media on this link at 64 KiB, so every full chunk is + #: past the bound (a file small enough to be one frame under it cannot be + #: told from a message, and crosses). A broad backbone carries anything + #: up to ``max_frame_bytes``. It has + #: to cross inside ``backbone_verdict_timeout``: roughly bitrate / 8 x + #: the short airtime cap x 45 s x about 0.7 for Reticulum's overhead, + #: which on the example radio (3.1 kbps, 50 % short cap) is about 6 KB. + #: It also has to pass the largest frame of a first contact, measured at + #: about 4 KB (``test_end_to_end.py``), or two devices cannot pair. + max_backbone_frame_bytes: int = 6 * 1024 + #: Submissions per minute per device, and the burst it may spend at once. + device_per_minute: float = 120.0 + device_burst: float = 30.0 + #: Frame bytes per minute each source host may send across the backbone, + #: on a scarce backbone only. Per host rather than per address, because + #: addresses cost nothing to mint and a host that re-keys would get a + #: fresh burst each time; each device on a hotspot has an address of its + #: own. Below the shared per-peer budget, so one device cannot hold it at + #: zero. The burst has to cover a first contact: two SDK engines pairing + #: over MLS and exchanging one message send 18 to 20 frames, about 16 KB + #: each (measured), and a smaller burst refuses the pairing's own frames + #: and stalls it on the retry ladder. + host_backbone_bytes_per_minute: float = 500.0 + host_backbone_burst_bytes: float = 20480.0 + #: Frame bytes per minute this gateway sends toward each peer gateway, + #: shared by every device attached here, on a scarce backbone only. The + #: budget that matches the radio: size it to what the link carries. + #: The default fits the example RNode (EU868 869.525 MHz, SF8/125 kHz at + #: about 3.1 kbps, 10 % airtime): about 6 minutes on air an hour is about + #: 140 KB, roughly 1.5 KB a minute once Reticulum's overhead is paid. The + #: burst holds a first contact with room to spare. At 1 % airtime, + #: divide the rate by ten. + peer_egress_bytes_per_minute: float = 1500.0 + peer_egress_burst_bytes: float = 24576.0 + #: Frames per minute each peer gateway may hand this one. The burst + #: covers two first contacts arriving at once. + peer_per_minute: float = 60.0 + peer_burst: float = 48.0 + #: Seconds a backbone forward may take before the device is told + #: ``backbone_timeout``. Must leave the client's 60 s room for the answer. + backbone_verdict_timeout: float = 45.0 + reticulum: ReticulumConfig | None = None + + def validate(self) -> None: + if not 0 <= self.listen_port < 65536: + raise ConfigError("listen_port must be 0 (any free port) to 65535") + if self.attach_grace and self.attach_grace < CLIENT_ATTACH_TIMEOUT: + raise ConfigError( + f"attach_grace must be 0 or at least {CLIENT_ATTACH_TIMEOUT:g} s, the clients' attach timeout" + ) + if not 1 <= self.max_unbound_sessions <= self.max_sessions: + raise ConfigError("max_unbound_sessions must be 1 to max_sessions") + if not 1 <= self.max_sessions_per_host < self.max_unbound_sessions: + # Equal or larger, one host can fill the unbound pool alone and, + # by reconnecting, keep evicting every device partway through its + # attach. + raise ConfigError("max_sessions_per_host must be at least 1 and below max_unbound_sessions") + if self.max_frame_bytes <= 0 or self.max_backbone_frame_bytes <= 0: + raise ConfigError("frame limits must be positive") + # A MessageReceived carries the frame base64-encoded inside JSON, and + # the whole line must fit the clients' 1 MiB bound. + if self.max_frame_bytes * 4 // 3 + 4096 > wire.MAX_LINE_BYTES: + raise ConfigError("max_frame_bytes is too large to deliver inside a 1 MiB line") + if not 0 < self.backbone_verdict_timeout < CLIENT_VERDICT_TIMEOUT - 5: + raise ConfigError( + f"backbone_verdict_timeout must be under {CLIENT_VERDICT_TIMEOUT - 5:g} s, " + "or the client fails the frame before the verdict arrives" + ) + for name in ("device_burst", "host_backbone_burst_bytes", "peer_burst", "peer_egress_burst_bytes"): + if getattr(self, name) <= 0: + raise ConfigError(f"{name} must be positive") + for name in ( + "device_per_minute", + "host_backbone_bytes_per_minute", + "peer_per_minute", + "peer_egress_bytes_per_minute", + ): + if getattr(self, name) < 0: + # A bucket is made on first use, so a bad rate would surface + # as an exception on some device's first frame, which drops + # that connection without the verdict the frame is owed. + raise ConfigError(f"{name} must not be negative") + if min(self.peer_egress_burst_bytes, self.host_backbone_burst_bytes) < self.max_backbone_frame_bytes: + raise ConfigError("the backbone bursts must each hold at least one max_backbone_frame_bytes frame") + if ( + self.host_backbone_bytes_per_minute > self.peer_egress_bytes_per_minute + or self.host_backbone_burst_bytes > self.peer_egress_burst_bytes + ): + # Otherwise one device can hold the shared budget at zero and + # every other device behind this gateway is refused. + raise ConfigError("the per-host backbone budget must not exceed the per-peer egress budget") + if self.reticulum is not None: + for peer in self.reticulum.peers: + try: + if len(bytes.fromhex(peer)) != 16: + raise ValueError + except ValueError: + raise ConfigError(f"peer {peer!r} is not a 16-byte destination hash in hex") from None + + +def load(path: str | Path) -> GatewayConfig: + """Reads a config file. Relative paths in it are relative to the file, so + a gateway's directory can be moved whole.""" + with open(path, "rb") as f: + data = tomllib.load(f) + config = from_dict(data) + base = Path(path).resolve().parent + if config.reticulum is not None: + r = config.reticulum + r.identity_path = str(base / r.identity_path) + if r.configdir is not None: + r.configdir = str(base / r.configdir) + return config + + +def from_dict(data: dict[str, Any]) -> GatewayConfig: + data = dict(data) + reticulum = data.pop("reticulum", None) + config = GatewayConfig(**_known(GatewayConfig, data, "gateway")) + if reticulum is not None: + if not isinstance(reticulum, dict): + raise ConfigError("[reticulum] must be a table") + config.reticulum = ReticulumConfig(**_known(ReticulumConfig, reticulum, "reticulum")) + config.validate() + return config + + +def _known(cls: type, data: dict[str, Any], section: str) -> dict[str, Any]: + names = {f.name for f in fields(cls)} - {"reticulum"} + unknown = set(data) - names + if unknown: + # A misspelled bound silently falling back to its default is a + # budget nobody applies, so a key this daemon does not know refuses + # the file. + raise ConfigError(f"unknown key(s) in [{section}]: {', '.join(sorted(unknown))}") + return data diff --git a/gateway/offline_gateway/gateway.py b/gateway/offline_gateway/gateway.py new file mode 100644 index 000000000..b5268cef1 --- /dev/null +++ b/gateway/offline_gateway/gateway.py @@ -0,0 +1,618 @@ +"""The device-facing gateway daemon: the five verbs plus Deliver, over the +wire in ``wire.py`` (``docs/spec/gateway-contract.md``). + +Invariants this module keeps. Each is a rule of the contract, and each names +what breaking it costs: + +* **A session is bound only by a proof this gateway checked.** The signature, + the derivation (both inside the SDK's ``verify_gateway_address_proof``) and + a challenge minted for this connection and spent once. Skip one and a + device draws another device's traffic to itself. +* **Every ``SendMessage`` gets exactly one verdict.** Silence turns a routing + decision into a client timeout, and a second verdict settles an id twice. +* **``StatusUpdate(connected)`` follows ``Capabilities`` and is never sent + while a declaration is unanswered.** A client may treat a session + announced before it is bound as a failed attach. +* **An unbound session is never a recipient.** Nothing is delivered over it, + and it may only submit and be told ``attach_required``. +* **A verdict is a claim about routing, never about delivery.** Only the + recipient's end-to-end acknowledgement settles a message, so this daemon + holds nothing and promises nothing it cannot keep: no ``pushed``, no + ``stored``. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import ipaddress +import logging +import os +import time +import uuid +from collections import OrderedDict +from typing import Any, Callable + +from . import wire +from .backbone import Backbone, BackboneFrame, ForwardResult +from .budget import BucketMap +from .config import GatewayConfig + +logger = logging.getLogger(__name__) + +#: ``verify(address, public_key, signature, challenge)`` returns the bound +#: address or raises. The default is the SDK's. +Verifier = Callable[[str, bytes, bytes, bytes], str] + +#: Declarations a session may get wrong before it is dropped. A real client +#: makes one; a session that keeps guessing is probing. +MAX_DECLARE_FAILURES = 3 +#: Peers one session may be watching at once. +MAX_WATCHED = 256 +#: Addresses whose last-seen time is remembered after they leave. +MAX_LAST_SEEN = 65536 +#: Frame types logged at debug level as they are queued: the routing trail. +_TRACED = frozenset({"MessageSent", "DeliveryError", "MessageReceived"}) + + +def sdk_verifier() -> Verifier: + """The SDK's verifier, imported on first use so the daemon's own tests + need no native library.""" + try: + from offline_protocol_sdk.offline_protocol import verify_gateway_address_proof + except ImportError as exc: # pragma: no cover - depends on the install + raise RuntimeError( + "the offline-protocol-sdk package with verify_gateway_address_proof is required; " + "install the SDK build from this repository (bindings/python)" + ) from exc + + def verify(address: str, public_key: bytes, signature: bytes, challenge: bytes) -> str: + return verify_gateway_address_proof(address, list(public_key), list(signature), list(challenge)) + + return verify + + +def host_key(peer_name: Any) -> str | None: + """What the per-host caps and budgets are keyed by. + + An IPv4 address as it is. An IPv6 address by its /64, because a device + may hold as many addresses in its prefix as it likes (privacy addresses + rotate by design), and keyed by the exact address one device would be + as many hosts as it cared to be. An IPv4-mapped IPv6 address is its IPv4. + """ + if not isinstance(peer_name, tuple) or not peer_name: + return None + host = str(peer_name[0]).split("%", 1)[0] + try: + ip = ipaddress.ip_address(host) + except ValueError: + return host + if ip.version == 6: + if ip.ipv4_mapped is not None: + return str(ip.ipv4_mapped) + return str(ipaddress.ip_network(f"{ip}/64", strict=False)) + return str(ip) + + +class Session: + """One device connection.""" + + _ids = 0 + + def __init__(self, gateway: "Gateway", writer: asyncio.StreamWriter, max_queued: int) -> None: + Session._ids += 1 + self.id = Session._ids + self.gateway = gateway + self.writer = writer + self.peer_name = writer.get_extra_info("peername") + self.host = host_key(self.peer_name) + #: Minted at connect and spent by the one declaration it binds. + self.challenge = os.urandom(wire.CHALLENGE_LENGTH) + self.challenge_sent = False + self.challenge_spent = False + self.declare_failures = 0 + #: The proved address, once bound. + self.address: str | None = None + #: ``StatusUpdate(connected)`` has been sent. + self.announced = False + self.watching: OrderedDict[str, None] = OrderedDict() + self.closed = False + self._queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue(max_queued) + self._tasks: set[asyncio.Task[Any]] = set() + + def __repr__(self) -> str: + return f"" + + def send(self, frame: dict[str, Any]) -> bool: + """Queues a frame. ``False`` when the session is gone or so far behind + that it is dropped: a device that cannot keep up must not hold memory + for every frame addressed to it.""" + if self.closed: + return False + if logger.isEnabledFor(logging.DEBUG) and frame.get("type") in _TRACED: + logger.debug( + "%r <- %s %s %s", + self, + frame["type"], + frame.get("message_id"), + frame.get("reason") or frame.get("sender") or "", + ) + try: + self._queue.put_nowait(frame) + except asyncio.QueueFull: + logger.warning("%r is not reading; dropping it", self) + self.close() + return False + return True + + def spawn(self, coro: Any) -> None: + task = asyncio.ensure_future(coro) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + + def close(self) -> None: + """Stops the session. Frames already queued are still written (a + refusal's reason is worth delivering), then the socket closes. A + session too far behind to take the sentinel is aborted instead.""" + if self.closed: + return + self.closed = True + for task in list(self._tasks): + task.cancel() + try: + self._queue.put_nowait(None) + except asyncio.QueueFull: + self.writer.transport.abort() + + async def write_loop(self) -> None: + try: + while True: + frame = await self._queue.get() + if frame is None: + return + line = wire.encode(frame) + if len(line) > wire.MAX_LINE_BYTES: + # The clients abandon the connection past this, so a + # longer line would cost the session, not just the frame. + logger.error("refusing to write a %d-byte line to %r", len(line), self) + continue + self.writer.write(line) + await self.writer.drain() + except (ConnectionError, OSError): + pass + finally: + self.closed = True + # Closing the transport is also what ends the read loop, which is + # blocked reading and never sees the flag. + self.writer.close() + + +class Gateway: + def __init__( + self, + config: GatewayConfig, + verifier: Verifier | None = None, + backbone: Backbone | None = None, + wall_clock: Callable[[], float] = time.time, + ) -> None: + config.validate() + self.config = config + self._verify = verifier or sdk_verifier() + self.backbone = backbone + self._wall_clock = wall_clock + self.sessions: set[Session] = set() + #: Address to the one session bound to it. + self.bound: dict[str, Session] = {} + self._last_seen: OrderedDict[str, int] = OrderedDict() + #: Presence numbering for the backbone: every bind and unbind is one + #: change, numbered in order, so a peer can tell a late message from + #: a current one (``PresenceTable``). The epoch tells a peer this + #: process's numbering from a previous run's. + self.presence_epoch = os.urandom(8).hex() + self._presence_seq = 0 + self._bound_seq: dict[str, int] = {} + self._device_budget = BucketMap(config.device_per_minute / 60.0, config.device_burst) + self._backbone_budget = BucketMap(config.host_backbone_bytes_per_minute / 60.0, config.host_backbone_burst_bytes) + self._peer_budget = BucketMap(config.peer_per_minute / 60.0, config.peer_burst) + self._egress_budget = BucketMap(config.peer_egress_bytes_per_minute / 60.0, config.peer_egress_burst_bytes) + self._server: asyncio.base_events.Server | None = None + self._connections: set[asyncio.Task[Any]] = set() + #: Backbone forwards in flight. Held by the gateway, not the session: + #: a device that disconnects mid-forward does not cancel it. The frame + #: is partly on air already, finishing it is what reaches the + #: recipient, and the device's retry of it is a duplicate the core + #: removes. Cancelling would throw that airtime away and spend it + #: again on the retry. + self._forwards: set[asyncio.Task[Any]] = set() + + # -- Lifecycle ------------------------------------------------------- + + @property + def capability_tokens(self) -> list[str]: + tokens = ["gateway_v1"] + if self.backbone is not None: + tokens.append(f"backbone_{self.backbone.kind}_v1") + return tokens + + async def start(self) -> int: + """Starts listening and the backbone. Returns the bound port.""" + if self.backbone is not None: + await self.backbone.start(self) + self._server = await asyncio.start_server( + self._accept, + self.config.listen_host, + self.config.listen_port, + # One byte over the line bound, so a line of exactly the bound + # with its newline is read and anything longer overruns. + limit=wire.MAX_LINE_BYTES + 1, + ) + port = self._server.sockets[0].getsockname()[1] + logger.info( + "gateway listening on %s:%d, capabilities %s", + self.config.listen_host, + port, + ",".join(self.capability_tokens), + ) + return port + + async def stop(self) -> None: + if self._server is not None: + self._server.close() + for session in list(self.sessions): + session.close() + for task in list(self._forwards): + task.cancel() + for task in list(self._connections): + task.cancel() + if self._connections: + await asyncio.gather(*self._connections, return_exceptions=True) + if self._server is not None: + with contextlib.suppress(Exception): + await self._server.wait_closed() + if self.backbone is not None: + await self.backbone.stop() + + # -- A connection ---------------------------------------------------- + + async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + task = asyncio.current_task() + if task is not None: + self._connections.add(task) + try: + if not self._admit(writer): + writer.close() + return + session = Session(self, writer, self.config.max_queued_frames) + self.sessions.add(session) + writer_task = asyncio.ensure_future(session.write_loop()) + if self.config.attach_grace: + session.spawn(self._grace(session)) + try: + await self._read_loop(session, reader) + finally: + session.close() + self.sessions.discard(session) + self._unbind(session) + await asyncio.gather(writer_task, return_exceptions=True) + logger.debug("%r closed", session) + finally: + if task is not None: + self._connections.discard(task) + + def _admit(self, writer: asyncio.StreamWriter) -> bool: + """Whether a new connection may open, making room for it if it can. + + A session that has proved nothing must not be able to hold a slot a + device needs: anyone on the venue network can open sockets, and the + verdict-only grace keeps an idle one alive indefinitely. So unbound + sessions have their own, smaller pool, and when it or the whole table + is full a newcomer evicts the oldest unbound session rather than + being refused. A device that attaches leaves that pool. Each host is + also capped, since every device on a hotspot has an address of its + own and one host holding many sessions is not many devices. + """ + host = host_key(writer.get_extra_info("peername")) + if host is not None: + from_host = sum(1 for s in self.sessions if s.host == host and not s.closed) + if from_host >= self.config.max_sessions_per_host: + logger.warning("refusing a connection from %s: %d sessions open from it", host, from_host) + return False + unbound = sorted((s for s in self.sessions if s.address is None and not s.closed), key=lambda s: s.id) + open_sessions = sum(1 for s in self.sessions if not s.closed) + while unbound and ( + len(unbound) >= self.config.max_unbound_sessions or open_sessions >= self.config.max_sessions + ): + oldest = unbound.pop(0) + logger.info("evicting %r to make room", oldest) + oldest.close() + open_sessions -= 1 + if open_sessions >= self.config.max_sessions: + logger.warning("refusing a connection: %d bound sessions open", open_sessions) + return False + return True + + async def _read_loop(self, session: Session, reader: asyncio.StreamReader) -> None: + while not session.closed: + try: + line = await reader.readuntil(b"\n") + except asyncio.LimitOverrunError: + logger.warning("%r sent a line over %d bytes; closing", session, wire.MAX_LINE_BYTES) + return + except (asyncio.IncompleteReadError, ConnectionError, OSError): + return + frame = wire.decode(line) + if frame is None: + continue + handler = self._handlers.get(frame["type"]) + if handler is not None: + handler(self, session, frame) + + async def _grace(self, session: Session) -> None: + """Announces a session that never declared, verdict-only, so a client + that does not attach can still submit and be told why it is refused.""" + await asyncio.sleep(self.config.attach_grace) + if not session.announced and session.address is None and not session.closed: + session.send(wire.capabilities(self.capability_tokens)) + session.send(wire.status_update("connected")) + session.announced = True + + # -- Attach ---------------------------------------------------------- + + def _on_identify(self, session: Session, frame: dict[str, Any]) -> None: + if session.challenge_spent: + return + session.challenge_sent = True + session.send(wire.challenge(session.challenge)) + + def _on_declare(self, session: Session, frame: dict[str, Any]) -> None: + # Every path below answers synchronously, with no await between the + # declaration and its answer, so the grace timer cannot announce the + # session while the declaration is unanswered. + if session.address is not None: + session.send(wire.address_error("this session is already bound")) + return + if not session.challenge_sent or session.challenge_spent: + session.send(wire.address_error("no challenge outstanding: send Identify first")) + return + address = wire.address_field(frame.get("address")) + public_key = wire.b64decode(frame.get("public_key")) + signature = wire.b64decode(frame.get("signature")) + if address is None or public_key is None or signature is None: + self._refuse_declaration(session, "malformed declaration") + return + try: + bound = self._verify(address, public_key, signature, session.challenge) + except Exception as exc: # the SDK raises its own error type + logger.info("%r: declaration for %s refused: %s", session, address, exc) + self._refuse_declaration(session, "address proof does not verify") + return + if bound != address: # the verifier returns the claimed address or raises + self._refuse_declaration(session, "address proof does not verify") + return + session.challenge_spent = True + self._bind(session, address) + session.send(wire.address_declared(address)) + session.send(wire.capabilities(self.capability_tokens)) + session.send(wire.status_update("connected")) + session.announced = True + logger.info("%r bound", session) + + def _refuse_declaration(self, session: Session, reason: str) -> None: + session.declare_failures += 1 + session.send(wire.address_error(reason)) + if session.declare_failures >= MAX_DECLARE_FAILURES: + logger.warning("%r: %d refused declarations; closing", session, session.declare_failures) + session.close() + + def _bind(self, session: Session, address: str) -> None: + previous = self.bound.get(address) + self.bound[address] = session + session.address = address + if previous is not None and previous is not session: + # The same key proved itself on a new connection: the old one is a + # socket the device has already given up on. Closing it here, after + # the rebind, means its own teardown finds the address taken and + # leaves it alone. + logger.info("%s reattached; closing %r", address, previous) + previous.close() + return + self._presence_seq += 1 + self._bound_seq[address] = self._presence_seq + self._presence_changed(address) + if self.backbone is not None: + self.backbone.local_presence_changed(address, True, None, self._presence_seq) + + def _unbind(self, session: Session) -> None: + address = session.address + if address is None or self.bound.get(address) is not session: + return + del self.bound[address] + now = self._now_ms() + self._last_seen.pop(address, None) + self._last_seen[address] = now + while len(self._last_seen) > MAX_LAST_SEEN: + self._last_seen.popitem(last=False) + self._presence_seq += 1 + self._bound_seq.pop(address, None) + self._presence_changed(address) + if self.backbone is not None: + self.backbone.local_presence_changed(address, False, now, self._presence_seq) + + # -- Submit and Verdict ---------------------------------------------- + + def _on_send(self, session: Session, frame: dict[str, Any]) -> None: + message_id = wire.message_id_field(frame.get("message_id")) or uuid.uuid4().hex + recipient = wire.address_field(frame.get("recipient")) + if recipient is None: + session.send(wire.delivery_error(message_id, None, f"{wire.MALFORMED_REQUEST}: no recipient")) + return + if session.address is None: + session.send(wire.delivery_error(message_id, recipient, wire.ATTACH_REQUIRED)) + return + content = wire.content_field(frame) + if content is None: + session.send(wire.delivery_error(message_id, recipient, f"{wire.MALFORMED_REQUEST}: no content")) + return + if len(content) > self.config.max_frame_bytes: + session.send(wire.delivery_error(message_id, recipient, wire.FRAME_TOO_LARGE)) + return + if not self._device_budget.take(session.address): + session.send(wire.delivery_error(message_id, recipient, wire.BUDGET_EXCEEDED)) + return + reply_to = wire.message_id_field(frame.get("reply_to_msg")) + + target = self.bound.get(recipient) + if target is not None and target.address is not None: + delivered = target.send(wire.message_received(session.address, content, message_id, reply_to)) + if delivered: + session.send(wire.message_sent(message_id, recipient)) + return + + claim = self.backbone.claim(recipient) if self.backbone is not None else None + if self.backbone is None or claim is None or not claim.online: + where = "this gateway" if self.backbone is None else "this gateway or its peers" + session.send( + wire.delivery_error( + message_id, recipient, f"{wire.RECIPIENT_UNREACHABLE}: not attached to {where}" + ) + ) + return + # The scarce class's bound, which is also how media stays off it. A + # broad backbone carries whatever the device link accepted. + if self.backbone.rate_class != "broad" and len(content) > self.config.max_backbone_frame_bytes: + session.send(wire.delivery_error(message_id, recipient, wire.FRAME_TOO_LARGE)) + return + # The scarce class's own budgets, in bytes. A broad backbone carries + # what the device budget above already admitted. Two of them, because + # the scarce thing is the airtime toward one peer, which every device + # here shares: the per-host budget, which validation keeps below the + # per-peer one, stops one device taking all of it, and the per-peer + # budget stops all of them together asking for more than the link + # carries. Both are checked before either is charged, so a refusal + # costs the device nothing. + # + # Checked here, charged by ``admit`` only when the frame is about to + # go on the backbone: a frame that never gets there (queued past its + # time, the link gone) costs nothing, and its retry is not charged + # twice. + admit = None + if self.backbone.rate_class != "broad": + sender = session.host or session.address + size = len(content) + if not (self._backbone_budget.has(sender, size) and self._egress_budget.has(claim.peer, size)): + session.send(wire.delivery_error(message_id, recipient, wire.BUDGET_EXCEEDED)) + return + + def admit(peer: str, sender: str = sender, size: int = size) -> bool: + if not (self._backbone_budget.has(sender, size) and self._egress_budget.has(peer, size)): + return False + self._backbone_budget.take(sender, size) + self._egress_budget.take(peer, size) + return True + + backbone_frame = BackboneFrame(recipient, session.address, content, message_id, reply_to) + task = asyncio.ensure_future(self._forward(session, backbone_frame, admit)) + self._forwards.add(task) + task.add_done_callback(self._forwards.discard) + + async def _forward(self, session: Session, frame: BackboneFrame, admit: Any = None) -> None: + assert self.backbone is not None + message_id = frame.message_id or uuid.uuid4().hex + try: + result, reason = await self.backbone.forward(frame, self.config.backbone_verdict_timeout, admit) + except asyncio.CancelledError: + raise + except Exception: + logger.exception("backbone forward failed") + result, reason = ForwardResult.TIMEOUT, "backbone error" + if result is ForwardResult.DELIVERED: + session.send(wire.message_sent(message_id, frame.recipient)) + elif result is ForwardResult.UNREACHABLE: + session.send( + wire.delivery_error(message_id, frame.recipient, f"{wire.RECIPIENT_UNREACHABLE}: {reason}") + ) + elif result is ForwardResult.REFUSED: + # The peer's own token (budget_exceeded, frame_too_large): a plain + # failure, never the unreachable verdict. + token = reason if reason in (wire.BUDGET_EXCEEDED, wire.FRAME_TOO_LARGE) else "peer_refused" + session.send(wire.delivery_error(message_id, frame.recipient, token)) + else: + session.send(wire.delivery_error(message_id, frame.recipient, f"{wire.BACKBONE_TIMEOUT}: {reason}")) + + # -- Presence -------------------------------------------------------- + + def _on_check_presence(self, session: Session, frame: dict[str, Any]) -> None: + # Presence answers say who is in the zone. A session that has not + # proved an address is told nothing. + if session.address is None: + return + peers = frame.get("peers") + if not isinstance(peers, list): + return + asked: list[str] = [] + for peer in peers[: wire.MAX_PRESENCE_PEERS]: + address = wire.address_field(peer) + if address is not None and address not in asked: + asked.append(address) + for address in asked: + session.watching.pop(address, None) + session.watching[address] = None + while len(session.watching) > MAX_WATCHED: + session.watching.popitem(last=False) + session.send(self._presence_frame(address)) + + def _presence_frame(self, address: str) -> dict[str, Any]: + if address in self.bound: + return wire.presence_status(address, True, self._now_ms()) + claim = self.backbone.claim(address) if self.backbone is not None else None + if claim is not None and claim.online: + return wire.presence_status(address, True, self._now_ms()) + seen = self._last_seen.get(address) + if claim is not None and claim.last_seen_ms is not None: + seen = max(seen or 0, claim.last_seen_ms) + return wire.presence_status(address, False, seen) + + def _presence_changed(self, address: str) -> None: + """Pushes the current answer to every session watching ``address``.""" + frame: dict[str, Any] | None = None + for session in list(self.sessions): + if address in session.watching and session.address is not None: + frame = frame or self._presence_frame(address) + session.send(frame) + + def _now_ms(self) -> int: + return int(self._wall_clock() * 1000) + + _handlers: dict[str, Callable[["Gateway", Session, dict[str, Any]], None]] = { + "Identify": _on_identify, + "DeclareAddress": _on_declare, + "SendMessage": _on_send, + "CheckPresence": _on_check_presence, + } + + # -- Backbone hooks -------------------------------------------------- + + async def deliver_from_backbone(self, frame: BackboneFrame, peer: str) -> tuple[ForwardResult, str]: + if not self._peer_budget.take(peer): + return ForwardResult.REFUSED, wire.BUDGET_EXCEEDED + bound = self.config.max_frame_bytes + if self.backbone is not None and self.backbone.rate_class != "broad": + bound = self.config.max_backbone_frame_bytes + if len(frame.content) > bound: + return ForwardResult.REFUSED, wire.FRAME_TOO_LARGE + target = self.bound.get(frame.recipient) + if target is None: + return ForwardResult.UNREACHABLE, "not attached to the peer gateway" + # Re-originated as an ordinary frame from the device that sent it, + # attributed by the gateway that forwarded it. The sender is a claim: + # what authenticates the frame is the frame (MLS), on this carrier as + # on every other. + if target.send(wire.message_received(frame.sender, frame.content, frame.message_id, frame.reply_to_msg)): + return ForwardResult.DELIVERED, "" + return ForwardResult.UNREACHABLE, "the recipient's session closed" + + def local_snapshot(self) -> tuple[int, dict[str, int]]: + return self._presence_seq, dict(self._bound_seq) + + def remote_presence_changed(self, address: str) -> None: + self._presence_changed(address) diff --git a/gateway/offline_gateway/reticulum.py b/gateway/offline_gateway/reticulum.py new file mode 100644 index 000000000..7c626aafd --- /dev/null +++ b/gateway/offline_gateway/reticulum.py @@ -0,0 +1,718 @@ +"""The Reticulum backbone: how gateways reach each other over LoRa (through an +RNode), packet radio, TCP, I2P or anything else Reticulum carries. + +This is the subsection "The Reticulum backbone" of the gateway contract, made +concrete: + +* **Destinations.** Each gateway announces exactly one destination, under its + own Reticulum identity (``offline_gateway.backbone.v1``). No device has a + Reticulum identity and no gateway holds a device key, so a device is + reachable across the backbone only through the gateway it is attached to. +* **Peers** are provisioned destination hashes. A link from anyone else is + torn down once it identifies, and every request handler refuses a caller + that is not a provisioned peer. +* **Framing.** Frames routinely exceed the 465-byte Reticulum MDU, so they + travel as link requests, which Reticulum carries as resources (sequenced, + checked, any size) whenever they do not fit one packet. +* **Presence** is the contract's Presence verb between gateways: a snapshot + of attached addresses when a link comes up, then pushed changes. +* **Rate class** ``scarce``: the daemon applies the per-device backbone + budget and the backbone frame bound at its own egress. + +Two links per pair, one dialled by each side, because a Reticulum request +travels only from a link's initiator to the destination it dialled: each +gateway makes its requests on the link it opened, and serves the peer's on +the link the peer opened. + +Gateway-to-gateway requests (msgpack, by Reticulum): + +``/forward`` ``{"r": recipient, "s": sender, "c": bytes, "m": id, "p": reply_to}`` + -> ``{"o": "delivered" | "unreachable" | "refused", "w": reason}`` +``/presence`` ``{"e": epoch, "snap": bool, "q": seq, "on": [[address, seq]], + "off": [[address, last_seen_ms, seq]]}`` -> ``True`` +``/snapshot`` ``None`` -> ``{"e": epoch, "q": seq, "on": [[address, seq]]}``, + every address attached at the callee + +``seq`` numbers the sending gateway's presence changes, and ``q`` is the +number current when a snapshot was taken. They are what lets a receiver +apply messages that arrive out of order (``PresenceTable``). + +Reticulum calls back on its own threads. Everything that touches the daemon +or this module's tables hops onto the event loop first. +""" + +from __future__ import annotations + +import asyncio +import logging +import os +import time +from typing import Any, Callable + +from .backbone import Admit, Backbone, BackboneFrame, BackboneHooks, Claim, ForwardResult, PresenceTable +from .config import ReticulumConfig +from . import wire + +logger = logging.getLogger(__name__) +rns_logger = logging.getLogger("RNS") + +APP_NAME = "offline_gateway" +#: The Reticulum release series this module's assumptions were checked +#: against (see :meth:`ReticulumBackbone.start`). pyproject pins the same. +TESTED_RNS_SERIES = "1.6." +ASPECTS = ("backbone", "v1") + +PATH_FORWARD = "/forward" +PATH_PRESENCE = "/presence" +PATH_SNAPSHOT = "/snapshot" + +#: Seconds to wait for a path to a peer after asking for one. +PATH_WAIT = 20.0 +#: Seconds a link may take to come up. Long: a LoRa link request and its +#: proof are two packets at a few hundred bits per second, plus any hops. +LINK_ESTABLISH_WAIT = 90.0 +#: Seconds presence changes are gathered before one request carries them, so +#: a burst of attaches costs one packet per peer rather than one each. +PRESENCE_COALESCE = 2.0 +#: Seconds a request handler waits for the event loop to answer it. +HANDLER_WAIT = 10.0 +#: Seconds a request must still have when its turn on a link comes, or it is +#: refused unsent: a frame handed to the radio with less than this cannot +#: be answered in time and would only spend airtime. +MIN_TRANSFER_WINDOW = 5.0 +#: Longest wait between attempts to reach a peer that stays away. +MAX_DIAL_BACKOFF = 600.0 +#: Seconds an inbound link has to identify as a provisioned peer before it +#: is closed. As long as a link takes to come up, since the identify is one +#: more packet on the same path. +IDENTIFY_WAIT = LINK_ESTABLISH_WAIT +#: A forward's refusal reason when the caller has not identified as a +#: provisioned peer on this link. +NOT_A_PEER = "not a provisioned peer" + + +class BudgetRefused(Exception): + """The scarce budgets had no room for a frame when its turn came. Nothing + of it went on air.""" + + +class QueuedTooLong(asyncio.TimeoutError): + """A request's time ran out while it waited for its turn on a link. It + never reached Reticulum, so nothing of it is on air.""" + + +class ReticulumBackbone(Backbone): + kind = "reticulum" + rate_class = "scarce" + + def __init__(self, config: ReticulumConfig, max_frame_bytes: int = 16 * 1024) -> None: + self.config = config + self.max_frame_bytes = max_frame_bytes + self.peers: set[bytes] = {bytes.fromhex(p) for p in config.peers} + self.table = PresenceTable() + self.hooks: BackboneHooks | None = None + self.destination_hash: bytes | None = None + self._loop: asyncio.AbstractEventLoop | None = None + self._identity: Any = None + self._destination: Any = None + #: The link this gateway dialled to each peer, which carries its requests. + self._out: dict[bytes, Any] = {} + #: Links peers dialled to this gateway, by the peer they identified as. + self._in: dict[bytes, Any] = {} + self._tasks: list[asyncio.Task[Any]] = [] + #: One lane per outbound link; see :meth:`_request`. + self._lanes: dict[int, asyncio.Lock] = {} + self._pending_on: dict[str, int] = {} + self._pending_off: dict[str, tuple[int | None, int]] = {} + self._flush: asyncio.TimerHandle | None = None + self._running = False + + # -- Lifecycle ------------------------------------------------------- + + async def start(self, hooks: BackboneHooks) -> None: + import RNS + + self.hooks = hooks + self._loop = asyncio.get_running_loop() + self._running = True + version = getattr(RNS, "__version__", "") + if not version.startswith(TESTED_RNS_SERIES): + # This module leans on Reticulum internals that only this series + # was checked against: a resource parked on a busy link cannot be + # withdrawn, a request's resource hangs off its receipt, and a + # request's response clock starts when its resource completes. + logger.warning( + "this gateway was tested with rns %sx, and rns %s is installed; " + "check reticulum.py's assumptions about resource queueing before trusting it", + TESTED_RNS_SERIES, + version or "(unknown)", + ) + RNS.Reticulum( + configdir=self.config.configdir, + loglevel=self.config.loglevel, + logdest=lambda line: rns_logger.info("%s", line), + ) + self._identity = _load_identity(RNS, self.config.identity_path) + self._destination = RNS.Destination( + self._identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, *ASPECTS + ) + self.destination_hash = self._destination.hash + # A forward carries one frame and its routing, msgpack-encoded; past + # this it is not a frame the daemon would have accepted. + self._destination.set_max_request_size(self.max_frame_bytes + 1024) + self._destination.set_link_established_callback(self._inbound_link) + for path, handler in ( + (PATH_FORWARD, self._handle_forward), + (PATH_PRESENCE, self._handle_presence), + (PATH_SNAPSHOT, self._handle_snapshot), + ): + self._destination.register_request_handler(path, handler, allow=RNS.Destination.ALLOW_ALL) + logger.info( + "reticulum backbone up: this gateway's destination is %s; %d peer(s) provisioned", + self._destination.hash.hex(), + len(self.peers), + ) + if getattr(RNS.Transport, "STAMP_DESTINATIONS", False) and self._destination.stamp is None: + # Reticulum mints it on its own worker thread and stores it, so + # this costs one wait per identity, not one per start. + logger.info( + "minting this gateway's announce stamp, a one-time proof of work: " + "peers cannot find this gateway until it is done (seconds to minutes, by CPU)" + ) + self._tasks.append(asyncio.ensure_future(self._announce_loop())) + for peer in self.peers: + self._tasks.append(asyncio.ensure_future(self._dial_loop(peer))) + + async def stop(self) -> None: + self._running = False + for task in self._tasks: + task.cancel() + await asyncio.gather(*self._tasks, return_exceptions=True) + self._tasks.clear() + if self._flush is not None: + self._flush.cancel() + for link in list(self._out.values()) + list(self._in.values()): + try: + link.teardown() + except Exception: # pragma: no cover - best effort at shutdown + pass + self._out.clear() + self._in.clear() + self.hooks = None + + # -- Routing --------------------------------------------------------- + + def claim(self, address: str) -> Claim | None: + return self.table.claim(address) + + async def forward( + self, frame: BackboneFrame, timeout: float, admit: Admit | None = None + ) -> tuple[ForwardResult, str]: + claim = self.table.claim(frame.recipient) + if claim is None or not claim.online: + return ForwardResult.UNREACHABLE, "no peer gateway claims the recipient" + link = self._active_out(bytes.fromhex(claim.peer)) + if link is None: + return ForwardResult.TIMEOUT, "no link to the peer gateway" + request = { + "r": frame.recipient, + "s": frame.sender, + "c": frame.content, + "m": frame.message_id, + "p": frame.reply_to_msg, + } + try: + response = await self._request( + link, + PATH_FORWARD, + request, + timeout, + admit=(lambda: admit(claim.peer)) if admit is not None else None, + ) + except BudgetRefused: + return ForwardResult.REFUSED, wire.BUDGET_EXCEEDED + except QueuedTooLong: + return ForwardResult.TIMEOUT, "queued behind other frames to the peer gateway" + except asyncio.TimeoutError: + return ForwardResult.TIMEOUT, "no answer from the peer gateway" + if not isinstance(response, dict): + return ForwardResult.TIMEOUT, "unreadable answer from the peer gateway" + outcome = response.get("o") + reason = response.get("w") if isinstance(response.get("w"), str) else "" + if outcome == ForwardResult.REFUSED.value and reason == NOT_A_PEER: + # The peer does not know who this link is: the identify was lost. + link.teardown() + return ForwardResult.TIMEOUT, "the peer gateway did not recognise this link; redialling" + for result in ForwardResult: + if result.value == outcome and result is not ForwardResult.TIMEOUT: + return result, reason + return ForwardResult.TIMEOUT, "unreadable answer from the peer gateway" + + def local_presence_changed(self, address: str, online: bool, last_seen_ms: int | None, seq: int) -> None: + if online: + self._pending_off.pop(address, None) + self._pending_on[address] = seq + else: + self._pending_on.pop(address, None) + self._pending_off[address] = (last_seen_ms, seq) + if self._flush is None and self._loop is not None: + self._flush = self._loop.call_later(PRESENCE_COALESCE, self._flush_presence) + + def _flush_presence(self) -> None: + self._flush = None + if not (self._pending_on or self._pending_off): + return + assert self.hooks is not None + update = { + "e": self.hooks.presence_epoch, + "snap": False, + "on": [[a, q] for a, q in sorted(self._pending_on.items())], + "off": [[a, t, q] for a, (t, q) in sorted(self._pending_off.items())], + } + self._pending_on.clear() + self._pending_off.clear() + for peer in list(self.peers): + link = self._active_out(peer) + if link is not None: + self._spawn(self._send_presence(link, peer, update)) + + async def _send_presence(self, link: Any, peer: bytes, update: dict[str, Any]) -> None: + """Delivers one presence update, resending it while the link lasts. + + A presence update is usually a single packet, which Reticulum does not + retransmit and a radio may lose. Lost and left alone, an attach would + stay unknown to the peer, which would answer recipient_unreachable for + a device attached here for as long as the link stays up, possibly + days. Resending is harmless: the numbering drops anything not newer + than what the peer holds. A new link re-snapshots instead. + """ + delay = self.config.reconnect_interval + while self._active_out(peer) is link: + try: + await self._request(link, PATH_PRESENCE, update, LINK_ESTABLISH_WAIT) + return + except asyncio.TimeoutError: + logger.warning("presence update to %s went unanswered; resending in %.0f s", peer.hex(), delay) + await asyncio.sleep(delay) + delay = min(delay * 2, MAX_DIAL_BACKOFF) + + # -- Links ----------------------------------------------------------- + + async def _announce_loop(self) -> None: + while self._running: + try: + self._destination.announce() + except Exception: + logger.exception("announcing this gateway's destination failed; trying again later") + await asyncio.sleep(self.config.announce_interval) + + async def _dial_loop(self, peer: bytes) -> None: + """Keeps one outbound link to ``peer`` open, and keeps doing so. + + An unexpected error from Reticulum would otherwise end the task, and + with it every attempt to reach this peer, silently, for the life of + the process. + """ + while self._running: + try: + await self._dial(peer) + except asyncio.CancelledError: + raise + except Exception: + logger.exception("dialling peer gateway %s failed; starting over", peer.hex()) + await asyncio.sleep(MAX_DIAL_BACKOFF / 10) + + async def _dial(self, peer: bytes) -> None: + import RNS + + # Every attempt is a path request or a link request on the air, so a + # peer that stays away is asked less and less often, not every few + # seconds forever on a duty-cycled link. + backoff = self.config.reconnect_interval + while self._running: + if self._active_out(peer) is not None: + await asyncio.sleep(self.config.reconnect_interval) + continue + if not RNS.Transport.has_path(peer): + RNS.Transport.request_path(peer) + deadline = time.monotonic() + PATH_WAIT + while not RNS.Transport.has_path(peer) and time.monotonic() < deadline: + await asyncio.sleep(0.5) + identity = RNS.Identity.recall(peer) + if identity is None: + logger.info("no path to peer gateway %s yet; next try in %.0f s", peer.hex(), backoff) + await asyncio.sleep(backoff) + backoff = min(backoff * 2, MAX_DIAL_BACKOFF) + continue + destination = RNS.Destination(identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, *ASPECTS) + established = asyncio.Event() + loop = self._loop + assert loop is not None + + def on_established(link: Any, established: asyncio.Event = established) -> None: + loop.call_soon_threadsafe(established.set) + + def on_closed(link: Any, peer: bytes = peer) -> None: + loop.call_soon_threadsafe(self._out_link_closed, peer, link) + + link = RNS.Link(destination, established_callback=on_established, closed_callback=on_closed) + try: + await asyncio.wait_for(established.wait(), LINK_ESTABLISH_WAIT) + except asyncio.TimeoutError: + logger.info("link to peer gateway %s did not come up; next try in %.0f s", peer.hex(), backoff) + link.teardown() + await asyncio.sleep(backoff) + backoff = min(backoff * 2, MAX_DIAL_BACKOFF) + continue + link.identify(self._identity) + self._out[peer] = link + logger.info("backbone link to %s established", peer.hex()) + if await self._exchange_snapshots(link, peer): + backoff = self.config.reconnect_interval + else: + # A peer that takes the link and answers nothing, most often + # one that has not provisioned this gateway yet, would + # otherwise be redialled at once, every time, indefinitely: + # half a dozen packets on air per attempt. + await asyncio.sleep(backoff) + backoff = min(backoff * 2, MAX_DIAL_BACKOFF) + + async def _exchange_snapshots(self, link: Any, peer: bytes) -> bool: + """Swaps snapshots on a new link. Returns whether the peer answered.""" + assert self.hooks is not None + mine = self._snapshot_message() + try: + await self._request(link, PATH_PRESENCE, mine, LINK_ESTABLISH_WAIT) + theirs = await self._request(link, PATH_SNAPSHOT, None, LINK_ESTABLISH_WAIT) + except asyncio.TimeoutError: + # Most likely the identify packet was lost, and the peer refuses + # every request on a link it cannot attribute. Nothing on this + # link would ever be answered, so it goes, and the dial loop + # opens a fresh one that identifies again. + logger.warning("snapshot exchange with %s went unanswered; redialling", peer.hex()) + link.teardown() + return False + if isinstance(theirs, dict): + self._apply(peer, {**theirs, "snap": True, "off": []}) + return True + + def _out_link_closed(self, peer: bytes, link: Any) -> None: + self._lanes.pop(id(link), None) + if self._out.get(peer) is link: + del self._out[peer] + logger.info("backbone link to %s closed", peer.hex()) + self._forget(peer) + + def _inbound_link(self, link: Any) -> None: + """A peer dialled in. It is served once it identifies as a + provisioned peer, and torn down if it identifies as anyone else.""" + loop = self._loop + assert loop is not None + + def on_identified(link: Any, identity: Any) -> None: + loop.call_soon_threadsafe(self._inbound_identified, link, identity) + + def on_closed(link: Any) -> None: + loop.call_soon_threadsafe(self._inbound_closed, link) + + link.set_remote_identified_callback(on_identified) + link.set_link_closed_callback(on_closed) + # Every request on a link that never identifies is refused, but the + # link itself would stay open for as long as its keepalives answer. + loop.call_soon_threadsafe(loop.call_later, IDENTIFY_WAIT, self._drop_if_anonymous, link) + + def _drop_if_anonymous(self, link: Any) -> None: + if not any(held is link for held in self._in.values()): + logger.info("an inbound link never identified as a provisioned peer; closing it") + link.teardown() + + def _inbound_identified(self, link: Any, identity: Any) -> None: + peer = self._peer_of(identity) + if peer is None: + logger.warning("a link identified as an unprovisioned gateway; closing it") + link.teardown() + return + previous = self._in.get(peer) + self._in[peer] = link + if previous is not None and previous is not link: + previous.teardown() + + def _inbound_closed(self, link: Any) -> None: + for peer, held in list(self._in.items()): + if held is link: + del self._in[peer] + # The peer can no longer push changes, so what it claimed is + # going stale. Forgetting it costs a re-snapshot on the next + # link; keeping it opens paths on stale claims. + self._forget(peer) + + def _active_out(self, peer: bytes) -> Any: + import RNS + + link = self._out.get(peer) + if link is not None and link.status == RNS.Link.ACTIVE: + return link + return None + + def _peer_of(self, identity: Any) -> bytes | None: + import RNS + + if identity is None: + return None + peer = RNS.Destination.hash(identity, APP_NAME, *ASPECTS) + return peer if peer in self.peers else None + + # -- Requests -------------------------------------------------------- + + async def _request( + self, link: Any, path: str, data: Any, timeout: float, admit: Callable[[], bool] | None = None + ) -> Any: + """One request on ``link``, answered within ``timeout`` seconds. + + Requests on a link go one at a time. Reticulum sends one outgoing + resource per link and parks the rest in a loop that never looks at + whether they were cancelled, so a request queued there cannot be + withdrawn: cancelled or not, it goes on air once the link frees up. + Queued here instead, a request whose time runs out before its turn + is refused without ever reaching Reticulum, and one that does reach + it is the only transfer on the link, which a cancel actually stops. + """ + loop = self._loop + assert loop is not None + if _fits_one_packet(link, path, data): + # Reticulum sends a one-packet request at once and never queues + # it, so it needs no turn. Made to wait anyway, a presence update + # whose packet was lost would hold the lane for its whole timeout + # and fail every frame queued behind it. + if admit is not None and not admit(): + raise BudgetRefused() + return await self._send_request(link, path, data, timeout) + deadline = loop.time() + timeout + lane = self._lanes.setdefault(id(link), asyncio.Lock()) + try: + await asyncio.wait_for(lane.acquire(), timeout) + except asyncio.TimeoutError: + raise QueuedTooLong() from None + try: + remaining = deadline - loop.time() + if remaining < MIN_TRANSFER_WINDOW: + raise QueuedTooLong() + # Charged here, at the moment it goes to the radio, and not when + # it was submitted: a frame that waited out its time above was + # never sent, and charging it would spend the budget twice once + # the device retries. + if admit is not None and not admit(): + raise BudgetRefused() + return await self._send_request(link, path, data, remaining) + finally: + lane.release() + + async def _send_request(self, link: Any, path: str, data: Any, timeout: float) -> Any: + loop = self._loop + assert loop is not None + future: asyncio.Future[Any] = loop.create_future() + + def settle(value: Any, failed: bool) -> None: + if future.done(): + return + if failed: + future.set_exception(asyncio.TimeoutError()) + else: + future.set_result(value) + + def failed(r: Any) -> None: + _cancel_transfer(r) + loop.call_soon_threadsafe(settle, None, True) + + receipt = link.request( + path, + data=data, + response_callback=lambda r: loop.call_soon_threadsafe(settle, r.response, False), + failed_callback=failed, + timeout=timeout, + ) + if receipt is False: + raise asyncio.TimeoutError() + try: + return await asyncio.wait_for(future, timeout + 1) + except (asyncio.TimeoutError, asyncio.CancelledError): + _cancel_transfer(receipt) + raise + + def _spawn(self, coro: Any) -> None: + task = asyncio.ensure_future(coro) + self._tasks.append(task) + task.add_done_callback(lambda t: self._tasks.remove(t) if t in self._tasks else None) + + # Request handlers. Reticulum runs each on a thread of its own; each hops + # onto the event loop for anything it reads or changes. + + def _handle_forward(self, path, data, request_id, link_id, remote_identity, requested_at): + peer = self._peer_of(remote_identity) + if peer is None: + return {"o": ForwardResult.REFUSED.value, "w": NOT_A_PEER} + frame = _frame_from(data) + if frame is None: + return {"o": ForwardResult.REFUSED.value, "w": wire.MALFORMED_REQUEST} + result, reason = self._on_loop(self._deliver(frame, peer), (ForwardResult.REFUSED, "busy")) + return {"o": result.value, "w": reason} + + async def _deliver(self, frame: BackboneFrame, peer: bytes) -> tuple[ForwardResult, str]: + if self.hooks is None: + return ForwardResult.REFUSED, "stopping" + return await self.hooks.deliver_from_backbone(frame, peer.hex()) + + def _handle_presence(self, path, data, request_id, link_id, remote_identity, requested_at): + peer = self._peer_of(remote_identity) + if peer is None or not isinstance(data, dict): + return None + assert self._loop is not None + self._loop.call_soon_threadsafe(self._apply, peer, data) + return True + + def _handle_snapshot(self, path, data, request_id, link_id, remote_identity, requested_at): + if self._peer_of(remote_identity) is None: + return None + return self._on_loop(self._snapshot_on_loop(), None) + + async def _snapshot_on_loop(self) -> dict[str, Any] | None: + return self._snapshot_message() if self.hooks is not None else None + + def _snapshot_message(self) -> dict[str, Any]: + assert self.hooks is not None + seq, bound = self.hooks.local_snapshot() + return { + "e": self.hooks.presence_epoch, + "snap": True, + "q": seq, + "on": [[a, q] for a, q in sorted(bound.items())], + "off": [], + } + + def _on_loop(self, coro: Any, fallback: Any) -> Any: + assert self._loop is not None + future = asyncio.run_coroutine_threadsafe(coro, self._loop) + try: + return future.result(HANDLER_WAIT) + except Exception: + future.cancel() + return fallback + + # -- Presence bookkeeping (on the loop) ------------------------------ + + def _apply(self, peer: bytes, data: dict[str, Any]) -> None: + key = peer.hex() + epoch = data.get("e") if isinstance(data.get("e"), str) else "" + changed: list[str] = [] + online: dict[str, int] = {} + for entry in _list(data.get("on")): + if isinstance(entry, list) and len(entry) == 2 and wire.address_field(entry[0]) is not None: + if _is_int(entry[1]): + online[entry[0]] = entry[1] + if data.get("snap") is True: + if not _is_int(data.get("q")): + return + changed += self.table.snapshot(key, online, data["q"], epoch) + else: + for address, seq in online.items(): + changed += self.table.update(key, address, True, None, seq, epoch) + for entry in _list(data.get("off")): + if isinstance(entry, list) and len(entry) == 3 and wire.address_field(entry[0]) is not None: + if not _is_int(entry[2]): + continue + seen = entry[1] if _is_int(entry[1]) else None + changed += self.table.update(key, entry[0], False, seen, entry[2], epoch) + self._announce_changes(changed) + + def _forget(self, peer: bytes) -> None: + self._announce_changes(self.table.drop_peer(peer.hex())) + + def _announce_changes(self, addresses: list[str]) -> None: + if self.hooks is None: + return + for address in dict.fromkeys(addresses): + self.hooks.remote_presence_changed(address) + + +def _fits_one_packet(link: Any, path: str, data: Any) -> bool: + """Whether Reticulum will send this request as a single packet rather + than as a resource: the same packing and the same test as + ``RNS.Link.request``.""" + mdu = getattr(link, "mdu", None) + if not isinstance(mdu, int): + return False + import RNS + from RNS.vendor import umsgpack + + path_hash = RNS.Identity.truncated_hash(path.encode("utf-8")) + return len(umsgpack.packb([time.time(), path_hash, data])) <= mdu + + +def _cancel_transfer(receipt: Any) -> None: + """Stops the resource a request travels as, if it is still moving. + + Reticulum's own request timeout marks the receipt failed and leaves the + resource transferring. A frame the device has already been told failed + would keep spending airtime, and the device's retry would start a second + transfer of it beside the first: on a scarce link, timeouts would breed + the traffic that causes them. + """ + import RNS + + resource = getattr(receipt, "resource", None) + if resource is not None and resource.status < RNS.Resource.COMPLETE: + try: + resource.cancel() + except Exception: # pragma: no cover - best effort on a dying link + logger.debug("cancelling a backbone transfer failed", exc_info=True) + + +def _load_identity(RNS: Any, path: str) -> Any: + if os.path.exists(path): + identity = RNS.Identity.from_file(path) + if identity is None: + raise RuntimeError(f"{path} is not a Reticulum identity") + return identity + identity = RNS.Identity() + directory = os.path.dirname(os.path.abspath(path)) + os.makedirs(directory, exist_ok=True) + identity.to_file(path) + # The private key of this gateway's backbone identity: whoever holds it + # can answer for every device attached here. + os.chmod(path, 0o600) + logger.info("created a new gateway identity at %s", path) + return identity + + +def _is_int(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +def _list(value: Any) -> list[Any]: + return value if isinstance(value, list) else [] + + +def _frame_from(data: Any) -> BackboneFrame | None: + if not isinstance(data, dict): + return None + recipient = wire.address_field(data.get("r")) + sender = wire.address_field(data.get("s")) + content = data.get("c") + if recipient is None or sender is None or not isinstance(content, (bytes, bytearray)): + return None + return BackboneFrame( + recipient=recipient, + sender=sender, + content=bytes(content), + message_id=wire.message_id_field(data.get("m")), + reply_to_msg=wire.message_id_field(data.get("p")), + ) + + +def destination_hash_for(identity_path: str) -> str: + """The destination hash a gateway with this identity file announces: what + its peers put in their ``peers`` list. Creates the identity if absent.""" + import RNS + + identity = _load_identity(RNS, identity_path) + return RNS.Destination.hash(identity, APP_NAME, *ASPECTS).hex() diff --git a/gateway/offline_gateway/wire.py b/gateway/offline_gateway/wire.py new file mode 100644 index 000000000..9bf978972 --- /dev/null +++ b/gateway/offline_gateway/wire.py @@ -0,0 +1,193 @@ +"""The device-facing wire: newline-delimited JSON, as the gateway contract +specifies it (``docs/spec/gateway-contract.md``, "Gateway-daemon contract v1"). + +Everything here is a function of its arguments, so the frame shapes can be +tested without a socket. The daemon (``gateway.py``) owns connections and +state. + +The bounds below mirror the reference clients' own +(``bindings/python/offline_protocol_sdk/gateway_attach_policy.py``), because a +gateway that emits what a client refuses is not speaking the contract. They +are not hand-mirrored constants of the SDK's (C5): a daemon may choose +tighter ones, and the contract states each as a rule rather than a number. +""" + +from __future__ import annotations + +import base64 +import binascii +import json +import re +from typing import Any + +#: The contract version this daemon speaks, sent on ``Challenge``. +PROTOCOL_VERSION = 1 + +#: Bytes of challenge minted per connection. The reference clients sign +#: nothing else. +CHALLENGE_LENGTH = 32 + +#: Longest line this daemon reads or writes. The contract says a gateway +#: MUST NOT emit a longer line than the clients accept, and the reference +#: clients abandon a connection past 1 MiB. Reading is held to the same bound: +#: a line past it cannot be resynchronised, so the connection goes. +MAX_LINE_BYTES = 1 << 20 + +#: Peers answered per ``CheckPresence``; the rest of a longer list is ignored. +MAX_PRESENCE_PEERS = 64 + +#: Longest address this daemon accepts anywhere. A real one is 44 +#: characters; the bound keeps a hostile string out of logs and maps. +MAX_ADDRESS_BYTES = 128 + +#: What a client-chosen message id must look like to be echoed verbatim. +#: The shape both reference implementations use; a UUID satisfies it. +MESSAGE_ID_PATTERN = re.compile(r"\A[A-Za-z0-9._-]{1,64}\Z") + +#: The verdict prefix the SDK classifier matches. It parks the message, +#: offers it to the mesh and starts the escalating probe. Text after it is +#: for human logs only. +RECIPIENT_UNREACHABLE = "recipient_unreachable" + +# Plain failures: the SDK retries on each and reads nothing else in the text. +ATTACH_REQUIRED = "attach_required" +BUDGET_EXCEEDED = "budget_exceeded" +FRAME_TOO_LARGE = "frame_too_large" +MALFORMED_REQUEST = "malformed_request" +BACKBONE_TIMEOUT = "backbone_timeout" + + +def encode(frame: dict[str, Any]) -> bytes: + """One frame as one line. Compact, ASCII-only JSON, so a line's length in + bytes is its length in characters and no client meets a surrogate.""" + return json.dumps(frame, separators=(",", ":"), ensure_ascii=True).encode("ascii") + b"\n" + + +def decode(line: bytes) -> dict[str, Any] | None: + """A received line as a frame, or ``None`` for anything that is not a JSON + object carrying a string ``type``. + + ``None`` is ignored by the caller, never answered with a close: the + contract's unknown-type tolerance is what lets either side add messages + without a flag day, and a line that does not parse is the same case from + a newer peer's point of view. + """ + try: + frame = json.loads(line) + except (UnicodeDecodeError, ValueError): + return None + if not isinstance(frame, dict) or not isinstance(frame.get("type"), str): + return None + return frame + + +def b64decode(value: Any) -> bytes | None: + """Strict standard base64, or ``None``.""" + if not isinstance(value, str): + return None + try: + return base64.b64decode(value, validate=True) + except (binascii.Error, ValueError): + return None + + +def b64encode(data: bytes) -> str: + return base64.b64encode(data).decode("ascii") + + +def address_field(value: Any) -> str | None: + """An address-shaped string, or ``None``. + + Shape only: what makes an address mean something is the attach proof, and + a recipient is routed by exact string match against addresses that were + proved. This only keeps arbitrary strings out of the routing tables. + """ + if not isinstance(value, str) or not value.startswith("off1"): + return None + if len(value.encode("utf-8", "surrogatepass")) > MAX_ADDRESS_BYTES: + return None + if not value.isascii() or not value.isalnum(): + return None + return value + + +def message_id_field(value: Any) -> str | None: + """A client-chosen id this daemon will echo verbatim, or ``None`` when it + must mint one instead.""" + if isinstance(value, str) and MESSAGE_ID_PATTERN.match(value): + return value + return None + + +def content_field(frame: dict[str, Any]) -> bytes | None: + """The frame's payload bytes. ``encoding`` absent means UTF-8 text; the + reference clients always send ``base64``.""" + content = frame.get("content") + encoding = frame.get("encoding") + if encoding is None: + return content.encode("utf-8") if isinstance(content, str) else None + if encoding == "base64": + return b64decode(content) + return None + + +# -- Frames this daemon writes ------------------------------------------------ + + +def challenge(nonce: bytes) -> dict[str, Any]: + return {"type": "Challenge", "challenge": b64encode(nonce), "protocol_version": PROTOCOL_VERSION} + + +def address_declared(address: str) -> dict[str, Any]: + return {"type": "AddressDeclared", "address": address} + + +def address_error(reason: str) -> dict[str, Any]: + return {"type": "AddressError", "reason": reason} + + +def capabilities(tokens: list[str]) -> dict[str, Any]: + return {"type": "Capabilities", "tokens": list(tokens)} + + +def status_update(status: str) -> dict[str, Any]: + return {"type": "StatusUpdate", "status": status} + + +def message_sent(message_id: str, recipient: str | None) -> dict[str, Any]: + # ``pushed`` and ``stored`` default to false when absent, and this daemon + # implements neither, so it omits both rather than asserting false. + frame: dict[str, Any] = {"type": "MessageSent", "message_id": message_id} + if recipient is not None: + frame["recipient"] = recipient + return frame + + +def delivery_error(message_id: str, recipient: str | None, reason: str) -> dict[str, Any]: + frame: dict[str, Any] = {"type": "DeliveryError", "message_id": message_id, "reason": reason} + if recipient is not None: + frame["recipient"] = recipient + return frame + + +def message_received( + sender: str, content: bytes, message_id: str | None, reply_to_msg: str | None +) -> dict[str, Any]: + frame: dict[str, Any] = { + "type": "MessageReceived", + "sender": sender, + "content": b64encode(content), + "encoding": "base64", + } + if message_id is not None: + frame["message_id"] = message_id + if reply_to_msg is not None: + frame["reply_to_msg"] = reply_to_msg + return frame + + +def presence_status(peer: str, online: bool, last_seen_ms: int | None) -> dict[str, Any]: + frame: dict[str, Any] = {"type": "PresenceStatus", "peer": peer, "online": online} + if last_seen_ms is not None: + frame["last_seen_ms"] = last_seen_ms + return frame diff --git a/gateway/pyproject.toml b/gateway/pyproject.toml new file mode 100644 index 000000000..3d2947280 --- /dev/null +++ b/gateway/pyproject.toml @@ -0,0 +1,34 @@ +[build-system] +requires = ["setuptools>=77", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "offline-protocol-gateway" +version = "0.1.0" +description = "Reference gateway daemon for the Offline Protocol SDK: the gateway contract, with an optional Reticulum (LoRa) backbone" +readme = "README.md" +license = "AGPL-3.0-only" +requires-python = ">=3.11" +authors = [{ name = "Offline Protocol, Inc." }] +# The SDK supplies verify_gateway_address_proof, the one verifier of the +# attach proof. It is imported on first use, so the daemon's unit tests run +# without the native library. +dependencies = ["offline-protocol-sdk"] + +[project.optional-dependencies] +# The Reticulum backbone, and with it LoRa through an RNode. Pinned to the +# series reticulum.py was checked against (TESTED_RNS_SERIES): it relies on +# how that series queues and times resources. +reticulum = ["rns>=1.6,<1.7"] +dev = ["pytest>=7.0", "pytest-asyncio>=0.21"] + +[project.scripts] +offline-gateway = "offline_gateway.__main__:main" + +[tool.setuptools] +packages = ["offline_gateway"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" +testpaths = ["tests"] diff --git a/gateway/tests/conftest.py b/gateway/tests/conftest.py new file mode 100644 index 000000000..3c5bedddf --- /dev/null +++ b/gateway/tests/conftest.py @@ -0,0 +1,166 @@ +"""A scripted device client and a stand-in verifier, so the daemon's own rules +are tested without the native library. ``test_end_to_end.py`` runs real SDK +engines against it instead.""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import sys +import threading +from pathlib import Path +from typing import Any + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from offline_gateway import Gateway, GatewayConfig # noqa: E402 + +#: Stand-in keys: an address's "public key" is fixed, and a "signature" is a +#: hash over key, address and challenge. Enough to exercise every branch of +#: the daemon's attach handling; the real proof is pinned in the SDK. +KEYS: dict[str, bytes] = {} + + +def address(n: int) -> str: + name = f"off1q{n:0>10}testaddressxx" + KEYS.setdefault(name, hashlib.sha256(name.encode()).digest()) + return name + + +def fake_sign(addr: str, challenge: bytes) -> tuple[bytes, bytes]: + key = KEYS[addr] + return key, hashlib.sha256(key + addr.encode() + challenge).digest() * 2 + + +def fake_verify(addr: str, public_key: bytes, signature: bytes, challenge: bytes) -> str: + if KEYS.get(addr) != public_key: + raise ValueError("key does not derive to the address") + if signature != hashlib.sha256(public_key + addr.encode() + challenge).digest() * 2: + raise ValueError("signature does not verify") + return addr + + +class Client: + def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + self.reader = reader + self.writer = writer + + @classmethod + async def connect(cls, port: int) -> "Client": + reader, writer = await asyncio.open_connection("127.0.0.1", port, limit=1 << 21) + return cls(reader, writer) + + async def send(self, frame: dict[str, Any]) -> None: + self.writer.write(json.dumps(frame).encode() + b"\n") + await self.writer.drain() + + async def recv(self, timeout: float = 2.0) -> dict[str, Any]: + line = await asyncio.wait_for(self.reader.readline(), timeout) + if not line: + raise EOFError("connection closed") + return json.loads(line) + + async def expect(self, frame_type: str, timeout: float = 2.0) -> dict[str, Any]: + frame = await self.recv(timeout) + assert frame["type"] == frame_type, frame + return frame + + async def nothing_for(self, seconds: float) -> bool: + try: + line = await asyncio.wait_for(self.reader.readline(), seconds) + except asyncio.TimeoutError: + return True + raise AssertionError(f"expected silence, got {line!r}") + + async def closed(self, timeout: float = 2.0) -> bool: + while True: + line = await asyncio.wait_for(self.reader.readline(), timeout) + if not line: + return True + + async def attach(self, addr: str) -> list[dict[str, Any]]: + await self.send({"type": "Identify", "device_id": addr, "protocol_version": 1}) + challenge = base64.b64decode((await self.expect("Challenge"))["challenge"]) + key, sig = fake_sign(addr, challenge) + await self.send( + { + "type": "DeclareAddress", + "address": addr, + "public_key": base64.b64encode(key).decode(), + "signature": base64.b64encode(sig).decode(), + } + ) + return [await self.recv() for _ in range(3)] + + async def submit(self, recipient: str, content: bytes, message_id: str | None = "m1") -> None: + frame: dict[str, Any] = { + "type": "SendMessage", + "recipient": recipient, + "content": base64.b64encode(content).decode(), + "encoding": "base64", + } + if message_id is not None: + frame["message_id"] = message_id + await self.send(frame) + + def close(self) -> None: + self.writer.close() + + +class _MemorySecrets: + """The SDK's ``SecureStorage`` stand-in, as its own suite defines one: + keys in memory, never in the platform keychain (which on macOS prompts on + every access). Locked, because the engine calls it from its own threads.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._data: dict[tuple[str, str], bytes] = {} + self._lock = threading.Lock() + + def store(self, key_type: str, key_id: str, data: list[int]) -> None: + with self._lock: + self._data[(key_type, key_id)] = bytes(data) + + def load(self, key_type: str, key_id: str) -> list[int] | None: + with self._lock: + raw = self._data.get((key_type, key_id)) + return None if raw is None else list(raw) + + def delete(self, key_type: str, key_id: str) -> None: + with self._lock: + self._data.pop((key_type, key_id), None) + + def list_keys(self, key_type: str) -> list[str]: + with self._lock: + return [kid for (kt, kid) in self._data if kt == key_type] + + +@pytest.fixture(autouse=True) +def _isolate_sdk_storage(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """Keeps an SDK engine started by a test off the real keychain and out of + any shared state directory, as the SDK's own suite does.""" + try: + from offline_protocol_sdk import protocol_manager as pm_module + except ImportError: + return + monkeypatch.setattr(pm_module, "SecureStorage", _MemorySecrets) + monkeypatch.setenv("OFFLINE_PROTOCOL_STATE_ROOT", str(tmp_path / "protocol-state")) + + +@pytest.fixture +def config() -> GatewayConfig: + return GatewayConfig(listen_port=0, attach_grace=0) + + +@pytest.fixture +async def gateway(config): + gw = Gateway(config, verifier=fake_verify) + port = await gw.start() + gw.port = port # type: ignore[attr-defined] + try: + yield gw + finally: + await gw.stop() diff --git a/gateway/tests/test_backbone.py b/gateway/tests/test_backbone.py new file mode 100644 index 000000000..e22477855 --- /dev/null +++ b/gateway/tests/test_backbone.py @@ -0,0 +1,372 @@ +"""Two gateways joined by the in-process backbone: the routing and presence +rules every backbone shares, without a radio.""" + +from __future__ import annotations + +import asyncio +import base64 + +import pytest + +from conftest import Client, address, fake_verify +from offline_gateway import Gateway, GatewayConfig, InMemoryBackbone, InMemoryNetwork +from offline_gateway.backbone import PresenceTable + + +@pytest.fixture +async def pair(): + network = InMemoryNetwork() + gateways = [] + for name in ("a", "b"): + gw = Gateway( + GatewayConfig(listen_port=0, attach_grace=0), + verifier=fake_verify, + backbone=InMemoryBackbone(network, name), + ) + gw.port = await gw.start() # type: ignore[attr-defined] + gateways.append(gw) + try: + yield network, gateways[0], gateways[1] + finally: + for gw in gateways: + await gw.stop() + + +async def test_the_backbone_is_advertised_as_a_token(pair): + _, a, _ = pair + c = await Client.connect(a.port) + frames = await c.attach(address(1)) + assert frames[1]["tokens"] == ["gateway_v1", "backbone_memory_v1"] + + +async def test_a_frame_crosses_to_the_peer_gateway(pair): + _, a, b = pair + alice, bob = await Client.connect(a.port), await Client.connect(b.port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await alice.submit(address(2), b"sealed", message_id="x-1") + verdict = await alice.expect("MessageSent") + assert verdict["message_id"] == "x-1" and verdict["recipient"] == address(2) + got = await bob.expect("MessageReceived") + assert got["sender"] == address(1) + assert base64.b64decode(got["content"]) == b"sealed" + assert got["message_id"] == "x-1" + + +async def test_presence_follows_a_device_at_the_peer_gateway(pair): + _, a, b = pair + alice = await Client.connect(a.port) + await alice.attach(address(1)) + await alice.send({"type": "CheckPresence", "peers": [address(2)]}) + assert (await alice.expect("PresenceStatus"))["online"] is False + + bob = await Client.connect(b.port) + await bob.attach(address(2)) + assert (await alice.expect("PresenceStatus"))["online"] is True + + bob.close() + left = await alice.expect("PresenceStatus") + assert left["online"] is False and isinstance(left["last_seen_ms"], int) + + +async def test_a_lost_link_withdraws_the_peers_claims(pair): + network, a, b = pair + alice, bob = await Client.connect(a.port), await Client.connect(b.port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await alice.send({"type": "CheckPresence", "peers": [address(2)]}) + assert (await alice.expect("PresenceStatus"))["online"] is True + + network.cut("a", "b") + assert (await alice.expect("PresenceStatus"))["online"] is False + await alice.submit(address(2), b"x") + assert (await alice.expect("DeliveryError"))["reason"].startswith("recipient_unreachable") + + # Back up: the snapshot on link-up restores the claim, and watchers hear it. + network.join("a", "b") + assert (await alice.expect("PresenceStatus"))["online"] is True + await alice.submit(address(2), b"y", message_id="again") + assert (await alice.expect("MessageSent"))["message_id"] == "again" + + +async def test_a_slow_peer_is_backbone_timeout_a_plain_failure(pair): + _, a, b = pair + a.config.backbone_verdict_timeout = 0.2 + b.backbone.delay = 1.0 + alice, bob = await Client.connect(a.port), await Client.connect(b.port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await alice.submit(address(2), b"x") + reason = (await alice.expect("DeliveryError"))["reason"] + assert reason.startswith("backbone_timeout") + assert not reason.startswith("recipient_unreachable") + + +async def test_the_scarce_frame_bound_applies_to_backbone_frames_only(): + """The bound is per backbone frame on a scarce backbone; a frame to a + device on the same gateway never meets it. Real media against the real + default is test_end_to_end's.""" + network = InMemoryNetwork() + gws = [] + try: + for name in ("a", "b"): + gw = Gateway( + GatewayConfig( + listen_port=0, attach_grace=0, max_backbone_frame_bytes=64, peer_egress_burst_bytes=64, + host_backbone_burst_bytes=64, + ), + verifier=fake_verify, + backbone=InMemoryBackbone(network, name, rate_class="scarce"), + ) + gw.port = await gw.start() # type: ignore[attr-defined] + gws.append(gw) + alice, bob = await Client.connect(gws[0].port), await Client.connect(gws[1].port) + local = await Client.connect(gws[0].port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await local.attach(address(3)) + await alice.submit(address(2), b"m" * 65) + assert (await alice.expect("DeliveryError"))["reason"] == "frame_too_large" + # The same frame to a device on this gateway is not a backbone frame. + await alice.submit(address(3), b"m" * 65, message_id="local") + assert (await alice.expect("MessageSent"))["message_id"] == "local" + finally: + for gw in gws: + await gw.stop() + + +async def test_the_per_host_backbone_budget_is_budget_exceeded(): + gws = await _scarce_pair( + max_backbone_frame_bytes=100, host_backbone_bytes_per_minute=0.0001, host_backbone_burst_bytes=200 + ) + try: + alice, bob = await Client.connect(gws[0].port), await Client.connect(gws[1].port) + await alice.attach(address(1)) + await bob.attach(address(2)) + for i in range(3): + await alice.submit(address(2), b"x" * 100, message_id=f"q{i}") + frames = [await alice.recv() for _ in range(3)] + by_id = {f["message_id"]: f for f in frames} + assert by_id["q0"]["type"] == by_id["q1"]["type"] == "MessageSent" + assert by_id["q2"]["reason"] == "budget_exceeded" + finally: + for gw in gws: + await gw.stop() + + +async def test_a_host_that_re_keys_does_not_get_a_fresh_budget(): + """Addresses cost nothing to mint. The backbone budget follows the host, + so a second identity from the same host shares what the first spent.""" + gws = await _scarce_pair( + max_backbone_frame_bytes=100, host_backbone_bytes_per_minute=0.0001, host_backbone_burst_bytes=100 + ) + try: + first, again = await Client.connect(gws[0].port), await Client.connect(gws[0].port) + bob = await Client.connect(gws[1].port) + await first.attach(address(1)) + await again.attach(address(3)) + await bob.attach(address(2)) + await first.submit(address(2), b"x" * 100, message_id="spent") + await first.expect("MessageSent") + await again.submit(address(2), b"x" * 10, message_id="fresh-key") + assert (await again.expect("DeliveryError"))["reason"] == "budget_exceeded" + finally: + for gw in gws: + await gw.stop() + + +async def test_a_peer_gateway_over_its_budget_is_refused_as_a_plain_failure(pair): + _, a, b = pair + b._peer_budget = type(b._peer_budget)(0.0001, 1) + alice, bob = await Client.connect(a.port), await Client.connect(b.port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await alice.submit(address(2), b"x", message_id="p0") + await alice.submit(address(2), b"x", message_id="p1") + frames = {f["message_id"]: f for f in [await alice.recv(), await alice.recv()]} + assert frames["p0"]["type"] == "MessageSent" + assert frames["p1"]["reason"] == "budget_exceeded" + + +def test_an_online_claim_beats_an_offline_one_and_a_dropped_peer_forgets(): + clock = [0.0] + table = PresenceTable(clock=lambda: clock[0]) + assert table.update("p1", address(5), True, None, 1, "e1") == [address(5)] + clock[0] = 1 + table.update("p2", address(5), False, 123, 1, "e2") + assert table.claim(address(5)).online and table.claim(address(5)).peer == "p1" + assert table.drop_peer("p1") == [address(5)] + claim = table.claim(address(5)) + assert claim.online is False and claim.last_seen_ms == 123 + assert table.snapshot("p2", {address(5): 2}, 2, "e2") == [address(5)] + assert table.claim(address(5)).online + assert table.snapshot("p2", {}, 3, "e2") == [address(5)] + assert not table.claim(address(5)).online + + +def test_a_snapshot_that_lands_late_does_not_undo_a_newer_attach(): + """The race the numbering exists for: a snapshot taken before X attached + (number 4) arrives after the one-packet update that announced X (number + 5). Applied in arrival order it would mark X offline and close the path.""" + table = PresenceTable() + table.update("p", address(1), True, None, 3, "e") + assert table.update("p", address(9), True, None, 5, "e") == [address(9)] + assert table.snapshot("p", {address(1): 3}, 4, "e") == [] + assert table.claim(address(9)).online + + +def test_a_late_update_does_not_undo_a_newer_one(): + table = PresenceTable() + table.update("p", address(2), False, 100, 7, "e") + assert table.update("p", address(2), True, None, 6, "e") == [] + assert not table.claim(address(2)).online + # A snapshot taken before the leave does not bring it back either. + assert table.snapshot("p", {address(2): 6}, 6, "e") == [] + assert not table.claim(address(2)).online + + +def test_a_restarted_peer_is_believed_although_its_numbers_start_again(): + table = PresenceTable() + table.update("p", address(3), True, None, 40, "old") + assert table.snapshot("p", {address(4): 1}, 1, "new") == [address(3), address(4)] + assert table.claim(address(3)) is None + assert table.claim(address(4)).online + + +async def _scarce_pair(**budgets): + network = InMemoryNetwork() + gws = [] + for name in ("a", "b"): + gw = Gateway( + GatewayConfig(listen_port=0, attach_grace=0, **budgets), + verifier=fake_verify, + backbone=InMemoryBackbone(network, name, rate_class="scarce"), + ) + gw.port = await gw.start() # type: ignore[attr-defined] + gws.append(gw) + return gws + + +async def test_the_egress_budget_toward_a_peer_is_shared_by_every_device(): + """The scarce thing is the airtime toward one peer. Two devices each well + inside their own budget still share that one.""" + gws = await _scarce_pair( + max_backbone_frame_bytes=100, + peer_egress_bytes_per_minute=0.0001, + peer_egress_burst_bytes=150, + host_backbone_bytes_per_minute=0.0001, + host_backbone_burst_bytes=150, + ) + # Every test client is 127.0.0.1, so lift the per-host budget out of the + # way to see the shared one on its own. + from offline_gateway.budget import BucketMap + + gws[0]._backbone_budget = BucketMap(1000.0, 100000.0) + try: + alice, carol = await Client.connect(gws[0].port), await Client.connect(gws[0].port) + bob = await Client.connect(gws[1].port) + await alice.attach(address(1)) + await carol.attach(address(3)) + await bob.attach(address(2)) + await alice.submit(address(2), b"x" * 100, message_id="a1") + assert (await alice.expect("MessageSent"))["message_id"] == "a1" + await carol.submit(address(2), b"x" * 100, message_id="c1") + assert (await carol.expect("DeliveryError"))["reason"] == "budget_exceeded" + # Smaller frames still fit what is left. + await carol.submit(address(2), b"x" * 40, message_id="c2") + assert (await carol.expect("MessageSent"))["message_id"] == "c2" + finally: + for gw in gws: + await gw.stop() + + +async def test_a_frame_the_egress_budget_refuses_costs_the_device_nothing(): + gws = await _scarce_pair( + max_backbone_frame_bytes=100, + peer_egress_bytes_per_minute=0.0001, + peer_egress_burst_bytes=100, + host_backbone_bytes_per_minute=0.0001, + host_backbone_burst_bytes=100, + ) + from offline_gateway.budget import BucketMap + + # A host budget with room for both frames and no refill, so what is left + # afterwards says exactly what the refused frame was charged. + gws[0]._backbone_budget = BucketMap(0.0, 1000.0) + try: + alice, bob = await Client.connect(gws[0].port), await Client.connect(gws[1].port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await alice.submit(address(2), b"x" * 90, message_id="ok") + await alice.expect("MessageSent") + await alice.submit(address(2), b"x" * 90, message_id="refused") + assert (await alice.expect("DeliveryError"))["reason"] == "budget_exceeded" + # Only the first frame was charged: 1000 - 90 left, not 1000 - 180. + assert gws[0]._backbone_budget.has("127.0.0.1", 910) + finally: + for gw in gws: + await gw.stop() + + +def test_negative_rates_are_refused_at_load(): + from offline_gateway import ConfigError + + for name in ("device_per_minute", "host_backbone_bytes_per_minute", "peer_per_minute", "peer_egress_bytes_per_minute"): + with pytest.raises(ConfigError): + GatewayConfig(**{name: -1}).validate() + + +def test_one_host_may_not_be_allowed_more_than_the_link_toward_a_peer(): + from offline_gateway import ConfigError + + with pytest.raises(ConfigError): + GatewayConfig(host_backbone_bytes_per_minute=2000, peer_egress_bytes_per_minute=1500).validate() + with pytest.raises(ConfigError): + GatewayConfig(host_backbone_burst_bytes=30000, peer_egress_burst_bytes=24576).validate() + + +async def test_a_forward_outlives_the_device_that_sent_it(pair): + """A device that disconnects mid-forward does not cancel a frame already + on its way: finishing it is what reaches the recipient.""" + _, a, b = pair + b.backbone.delay = 0.3 + alice, bob = await Client.connect(a.port), await Client.connect(b.port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await alice.submit(address(2), b"in flight", message_id="orphan") + await asyncio.sleep(0.05) + alice.close() + got = await bob.expect("MessageReceived", timeout=2) + assert base64.b64decode(got["content"]) == b"in flight" + + +def test_a_forgotten_address_is_not_revived_by_a_late_resend(): + """Our link to the peer dropped and its claims were forgotten. The new + snapshot no longer lists X, which left meanwhile. A resend of X's old + attach, still in flight on the peer's own link, must not bring it back.""" + table = PresenceTable() + table.update("p", address(7), True, None, 2, "e") + table.drop_peer("p") + table.snapshot("p", {}, 9, "e") + assert table.update("p", address(7), True, None, 2, "e") == [] + assert table.claim(address(7)) is None + # A change newer than the snapshot is still news. + assert table.update("p", address(7), True, None, 10, "e") == [address(7)] + + +def test_a_snapshot_still_applies_its_own_entries(): + table = PresenceTable() + table.snapshot("p", {address(1): 3}, 5, "e") + table.snapshot("p", {address(1): 3, address(2): 6}, 8, "e") + assert table.claim(address(1)).online and table.claim(address(2)).online + + +def test_a_snapshot_restores_a_long_attached_device_after_a_dropped_link(): + """X attached at 3 and is still attached. The link dropped (claims + forgotten) after a snapshot at 5; the next snapshot lists X at 3 again + and must bring it back, floor or no floor.""" + table = PresenceTable() + table.snapshot("p", {address(3): 3}, 5, "e") + table.drop_peer("p") + assert table.snapshot("p", {address(3): 3}, 7, "e") == [address(3)] + assert table.claim(address(3)).online diff --git a/gateway/tests/test_end_to_end.py b/gateway/tests/test_end_to_end.py new file mode 100644 index 000000000..c8d703cec --- /dev/null +++ b/gateway/tests/test_end_to_end.py @@ -0,0 +1,232 @@ +"""Real SDK engines, through the real client, through this daemon. + +Two ``ProtocolManager``s with only the gateway slot enabled attach with the +SDK's own ``GatewayManager``, pair over MLS and exchange a message. The daemon +checks each attach proof with the SDK's ``verify_gateway_address_proof``. The +second case puts the two devices on two gateways joined by the in-process +backbone, which is the shape of a LoRa deployment with the radio left out. + +Skipped when the SDK build in this environment lacks the verifier. +""" + +from __future__ import annotations + +import asyncio +import contextlib + +import pytest + +sdk = pytest.importorskip("offline_protocol_sdk.offline_protocol") +if not hasattr(sdk, "verify_gateway_address_proof"): # pragma: no cover + pytest.skip("this SDK build has no verify_gateway_address_proof", allow_module_level=True) + +from offline_protocol_sdk.offline_protocol import ( # noqa: E402 + ContentType, + MessagePriority, + OverflowPolicy, + ProtocolConfig, +) +from offline_protocol_sdk.protocol_manager import ProtocolManager # noqa: E402 + +from offline_gateway import Gateway, GatewayConfig, InMemoryBackbone, InMemoryNetwork # noqa: E402 + + +def _config(profile: str) -> ProtocolConfig: + return ProtocolConfig( + app_label="gateway-e2e", + profile=profile, + ble_enabled=False, + wifi_direct_enabled=False, + internet_enabled=False, + reticulum_enabled=True, + nostr_enabled=False, + prefer_online=True, + initial_ttl=3, + encryption_enabled=True, + auto_key_exchange=True, + store_pending=True, + require_encryption=True, + max_pending_per_peer=100, + max_pending_global=1000, + pending_ttl_ms=60_000, + overflow_policy=OverflowPolicy.DROP_OLDEST, + ) + + +class Device: + """The app's side of pairing, run outside the event callback.""" + + def __init__(self, profile: str, port: int) -> None: + self.profile = profile + self.port = port + self.pending: list[dict] = [] + self.seen: list[dict] = [] + self.pm = ProtocolManager(_config(profile), event_handler=self.pending.append) + self.address = "" + + async def start(self) -> None: + await self.pm.start() + self.address = self.pm.local_address or "" + assert self.address + assert self.pm.gateway is not None + self.pm.gateway.configure(daemon_address=f"127.0.0.1:{self.port}") + await self.pm.gateway.start() + + async def stop(self) -> None: + await self.pm.stop() + + def key_package(self) -> list[int]: + return list(self.pm.protocol.mls_get_or_create_key_package().key_package_data) + + def handle_events(self) -> None: + p = self.pm.protocol + while self.pending: + e = self.pending.pop(0) + self.seen.append(e) + t = e.get("type") + if t == "connection_request_received": + if e.get("key_package"): + p.mls_import_key_package(e["sender"], e["key_package"]) + p.accept_connection_request(e["sender"], self.profile, self.key_package()) + with contextlib.suppress(Exception): + p.establish_secure_session(e["sender"]) + elif t == "connection_accepted": + if e.get("key_package"): + p.mls_import_key_package(e["accepted_by"], e["key_package"]) + with contextlib.suppress(Exception): + p.establish_secure_session(e["accepted_by"]) + + def events(self, kind: str) -> list[dict]: + return [e for e in self.seen if e.get("type") == kind] + + +async def settle(devices: list[Device], cond, what: str, secs: int = 30) -> None: + for _ in range(secs * 20): + for d in devices: + d.handle_events() + if cond(): + return + await asyncio.sleep(0.05) + trail = {d.profile: [e.get("type") for e in d.seen] for d in devices} + raise AssertionError(f"timed out: {what}; events seen: {trail}") + + +async def _attached(gateway: Gateway, devices: list[Device]) -> None: + await settle(devices, lambda: all(d.address in gateway.bound for d in devices), "attach", secs=10) + + +async def _pair_and_talk(alice: Device, bob: Device, secs: int = 30) -> None: + devices = [alice, bob] + alice.pm.protocol.send_connection_request(bob.address, alice.profile, alice.key_package(), None) + await settle( + devices, + lambda: alice.events("connection_accepted") + and alice.pm.protocol.has_pending_key_package(bob.address), + "pairing", + secs, + ) + alice.pm.protocol.send_message(bob.address, "over the gateway", MessagePriority.HIGH, None) + + def received() -> list[dict]: + return [e for e in bob.events("message_received") if e.get("content") == "over the gateway"] + + await settle(devices, received, "delivery", secs) + assert received()[0]["sender"] == alice.address + + +async def test_two_engines_pair_and_talk_through_one_gateway() -> None: + gateway = Gateway(GatewayConfig(listen_port=0)) + port = await gateway.start() + alice, bob = Device("e2e-alice", port), Device("e2e-bob", port) + try: + for d in (alice, bob): + await d.start() + await _attached(gateway, [alice, bob]) + await _pair_and_talk(alice, bob) + finally: + for d in (alice, bob): + await d.stop() + await gateway.stop() + + +@pytest.mark.parametrize("rate_class", ["broad", "scarce"]) +async def test_two_engines_talk_across_two_gateways(rate_class: str) -> None: + """Under the scarce class the default per-device backbone budget applies, + and a first contact has to fit inside it.""" + network = InMemoryNetwork() + a = Gateway(GatewayConfig(listen_port=0), backbone=InMemoryBackbone(network, "a", rate_class)) + b = Gateway(GatewayConfig(listen_port=0), backbone=InMemoryBackbone(network, "b", rate_class)) + port_a, port_b = await a.start(), await b.start() + alice, bob = Device("e2e-far-alice", port_a), Device("e2e-far-bob", port_b) + try: + for d in (alice, bob): + await d.start() + await _attached(a, [alice]) + await _attached(b, [bob]) + await _pair_and_talk(alice, bob) + finally: + for d in (alice, bob): + await d.stop() + await a.stop() + await b.stop() + + +class _Recording(InMemoryBackbone): + """Records the size of every frame handed to the backbone.""" + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.carried: list[int] = [] + + async def forward(self, frame, timeout, admit=None): + self.carried.append(len(frame.content)) + return await super().forward(frame, timeout, admit) + + +@pytest.mark.parametrize("rate_class", ["broad", "scarce"]) +async def test_media_crosses_a_broad_backbone_and_never_a_scarce_one(rate_class: str, caplog) -> None: + """The contract: media MUST be excluded from a scarce backbone. The + gateway sees only ciphertext, so the exclusion is by size: the device + chunks the gateway slot at 64 KiB, and every full chunk is past the + scarce frame bound and refused `frame_too_large`. A broad backbone + carries the same transfer to the end.""" + import logging + + caplog.set_level(logging.DEBUG, logger="offline_gateway.gateway") + network = InMemoryNetwork() + backbone_a = _Recording(network, "a", rate_class) + a = Gateway(GatewayConfig(listen_port=0), backbone=backbone_a) + b = Gateway(GatewayConfig(listen_port=0), backbone=InMemoryBackbone(network, "b", rate_class)) + port_a, port_b = await a.start(), await b.start() + alice, bob = Device(f"e2e-media-alice-{rate_class}", port_a), Device(f"e2e-media-bob-{rate_class}", port_b) + try: + for d in (alice, bob): + await d.start() + await _attached(a, [alice]) + await _attached(b, [bob]) + await _pair_and_talk(alice, bob) + photo = bytes(range(256)) * 80 # 20 KB, one chunk at the slot's size + alice.pm.protocol.send_media(bob.address, list(photo), "photo.jpg", ContentType.IMAGE, None) + + def received() -> list[dict]: + return bob.events("file_received") + + if rate_class == "broad": + await settle([alice, bob], received, "media over a broad backbone") + else: + await settle( + [alice, bob], + lambda: any("frame_too_large" in r.getMessage() for r in caplog.records), + "a scarce gateway refusing the chunk", + ) + await asyncio.sleep(1) + for d in (alice, bob): + d.handle_events() + assert not received() + bound = GatewayConfig().max_backbone_frame_bytes + assert max(backbone_a.carried) <= bound + finally: + for d in (alice, bob): + await d.stop() + await a.stop() + await b.stop() diff --git a/gateway/tests/test_gateway.py b/gateway/tests/test_gateway.py new file mode 100644 index 000000000..5216904d4 --- /dev/null +++ b/gateway/tests/test_gateway.py @@ -0,0 +1,376 @@ +"""The device-facing contract, one MUST at a time.""" + +from __future__ import annotations + +import asyncio +import base64 + +import pytest + +from conftest import Client, address, fake_sign, fake_verify +from offline_gateway import Gateway, GatewayConfig + + +async def test_attach_runs_in_the_contracts_order(gateway): + alice = await Client.connect(gateway.port) + frames = await alice.attach(address(1)) + assert [f["type"] for f in frames] == ["AddressDeclared", "Capabilities", "StatusUpdate"] + assert frames[0]["address"] == address(1) + assert frames[1]["tokens"] == ["gateway_v1"] + assert frames[2]["status"] == "connected" + assert address(1) in gateway.bound + + +async def test_the_challenge_is_fresh_per_connection_and_32_bytes(gateway): + seen = set() + for _ in range(3): + c = await Client.connect(gateway.port) + await c.send({"type": "Identify", "device_id": "x", "protocol_version": 1}) + frame = await c.expect("Challenge") + assert frame["protocol_version"] == 1 + nonce = base64.b64decode(frame["challenge"]) + assert len(nonce) == 32 + seen.add(nonce) + c.close() + assert len(seen) == 3 + + +async def test_a_declaration_without_a_challenge_is_refused(gateway): + c = await Client.connect(gateway.port) + key, sig = fake_sign(address(1), b"\x00" * 32) + await c.send( + { + "type": "DeclareAddress", + "address": address(1), + "public_key": base64.b64encode(key).decode(), + "signature": base64.b64encode(sig).decode(), + } + ) + await c.expect("AddressError") + assert not gateway.bound + + +async def test_a_proof_for_another_address_is_refused(gateway): + """The attack the derivation check exists for: a valid signature under the + sender's own key, naming somebody else's address.""" + c = await Client.connect(gateway.port) + await c.send({"type": "Identify", "device_id": "x", "protocol_version": 1}) + challenge = base64.b64decode((await c.expect("Challenge"))["challenge"]) + key, sig = fake_sign(address(1), challenge) + await c.send( + { + "type": "DeclareAddress", + "address": address(2), + "public_key": base64.b64encode(key).decode(), + "signature": base64.b64encode(sig).decode(), + } + ) + await c.expect("AddressError") + assert not gateway.bound + # Refused means unbound: it may not even submit. + await c.submit(address(1), b"x") + verdict = await c.expect("DeliveryError") + assert verdict["reason"] == "attach_required" + + +async def test_a_challenge_is_spent_by_the_declaration_it_binds(gateway): + c = await Client.connect(gateway.port) + await c.attach(address(1)) + # A second Identify on the same connection gets no fresh challenge, and a + # replayed declaration is refused. + await c.send({"type": "Identify", "device_id": "x", "protocol_version": 1}) + await c.nothing_for(0.2) + key, sig = fake_sign(address(1), b"\x00" * 32) + await c.send( + { + "type": "DeclareAddress", + "address": address(1), + "public_key": base64.b64encode(key).decode(), + "signature": base64.b64encode(sig).decode(), + } + ) + await c.expect("AddressError") + + +async def test_repeated_bad_declarations_close_the_session(gateway): + c = await Client.connect(gateway.port) + await c.send({"type": "Identify", "device_id": "x", "protocol_version": 1}) + await c.expect("Challenge") + for _ in range(3): + await c.send({"type": "DeclareAddress", "address": address(1), "public_key": "AA==", "signature": "AA=="}) + await c.expect("AddressError") + assert await c.closed() + + +async def test_unknown_types_and_garbage_lines_are_ignored_not_fatal(gateway): + c = await Client.connect(gateway.port) + c.writer.write(b"not json\n[1,2]\n{\"no\":\"type\"}\n") + await c.send({"type": "SomethingFromTheFuture", "x": 1}) + frames = await c.attach(address(1)) + assert frames[0]["type"] == "AddressDeclared" + + +async def test_a_line_over_the_bound_closes_the_connection(gateway): + c = await Client.connect(gateway.port) + c.writer.write(b"x" * ((1 << 20) + 10)) + await c.writer.drain() + assert await c.closed(5.0) + + +async def test_a_local_frame_is_delivered_and_answered_message_sent(gateway): + alice, bob = await Client.connect(gateway.port), await Client.connect(gateway.port) + await alice.attach(address(1)) + await bob.attach(address(2)) + await alice.send( + { + "type": "SendMessage", + "recipient": address(2), + "content": base64.b64encode(b"ciphertext").decode(), + "encoding": "base64", + "message_id": "abc-1", + "reply_to_msg": "abc-0", + } + ) + verdict = await alice.expect("MessageSent") + assert verdict == {"type": "MessageSent", "message_id": "abc-1", "recipient": address(2)} + delivered = await bob.expect("MessageReceived") + assert delivered["sender"] == address(1) + assert base64.b64decode(delivered["content"]) == b"ciphertext" + assert delivered["encoding"] == "base64" + assert delivered["message_id"] == "abc-1" + assert delivered["reply_to_msg"] == "abc-0" + + +async def test_an_absent_recipient_is_recipient_unreachable(gateway): + alice = await Client.connect(gateway.port) + await alice.attach(address(1)) + await alice.submit(address(9), b"x", message_id="m-9") + verdict = await alice.expect("DeliveryError") + assert verdict["message_id"] == "m-9" + assert verdict["recipient"] == address(9) + assert verdict["reason"].startswith("recipient_unreachable") + assert "stored" not in verdict + + +async def test_ids_are_echoed_when_valid_and_minted_otherwise(gateway): + alice = await Client.connect(gateway.port) + await alice.attach(address(1)) + await alice.submit(address(9), b"x", message_id=None) + minted = (await alice.expect("DeliveryError"))["message_id"] + assert minted + await alice.submit(address(9), b"x", message_id="not a valid id!") + assert (await alice.expect("DeliveryError"))["message_id"] not in ("not a valid id!", minted) + await alice.submit(address(9), b"x", message_id="u" * 64) + assert (await alice.expect("DeliveryError"))["message_id"] == "u" * 64 + + +async def test_every_submission_gets_exactly_one_verdict(gateway): + alice, bob = await Client.connect(gateway.port), await Client.connect(gateway.port) + await alice.attach(address(1)) + await bob.attach(address(2)) + for i in range(10): + await alice.submit(address(2) if i % 2 else address(9), b"x", message_id=f"id{i}") + verdicts = [await alice.recv() for _ in range(10)] + assert sorted(v["message_id"] for v in verdicts) == sorted(f"id{i}" for i in range(10)) + await alice.nothing_for(0.2) + + +async def test_malformed_submissions_are_plain_failures(gateway): + alice = await Client.connect(gateway.port) + await alice.attach(address(1)) + await alice.send({"type": "SendMessage", "recipient": address(2), "message_id": "a"}) + assert (await alice.expect("DeliveryError"))["reason"].startswith("malformed_request") + await alice.send({"type": "SendMessage", "recipient": "nobody", "content": "AA==", "encoding": "base64", "message_id": "b"}) + frame = await alice.expect("DeliveryError") + assert frame["reason"].startswith("malformed_request") + assert not frame["reason"].startswith("recipient_unreachable") + + +async def test_an_oversized_frame_is_frame_too_large(): + gw = Gateway(GatewayConfig(listen_port=0, attach_grace=0, max_frame_bytes=100), verifier=fake_verify) + port = await gw.start() + try: + alice = await Client.connect(port) + await alice.attach(address(1)) + await alice.submit(address(1), b"x" * 101) + assert (await alice.expect("DeliveryError"))["reason"] == "frame_too_large" + finally: + await gw.stop() + + +async def test_the_device_budget_refuses_with_budget_exceeded(): + gw = Gateway( + GatewayConfig(listen_port=0, attach_grace=0, device_per_minute=0.0001, device_burst=3), + verifier=fake_verify, + ) + port = await gw.start() + try: + alice = await Client.connect(port) + await alice.attach(address(1)) + for i in range(4): + await alice.submit(address(9), b"x", message_id=f"b{i}") + reasons = [(await alice.recv())["reason"] for _ in range(4)] + assert reasons[:3] == ["recipient_unreachable: not attached to this gateway"] * 3 + assert reasons[3] == "budget_exceeded" + finally: + await gw.stop() + + +async def test_presence_answers_and_watches(gateway): + alice = await Client.connect(gateway.port) + await alice.attach(address(1)) + await alice.send({"type": "CheckPresence", "peers": [address(2)]}) + offline = await alice.expect("PresenceStatus") + assert offline["peer"] == address(2) and offline["online"] is False + assert "last_seen_ms" not in offline + + bob = await Client.connect(gateway.port) + await bob.attach(address(2)) + pushed = await alice.expect("PresenceStatus") + assert pushed["peer"] == address(2) and pushed["online"] is True + + bob.close() + left = await alice.expect("PresenceStatus") + assert left["online"] is False and isinstance(left["last_seen_ms"], int) + + +async def test_an_unbound_session_learns_nothing_from_presence(gateway): + c = await Client.connect(gateway.port) + await c.send({"type": "CheckPresence", "peers": [address(1)]}) + await c.nothing_for(0.2) + + +async def test_presence_answers_at_most_64_peers(gateway): + alice = await Client.connect(gateway.port) + await alice.attach(address(1)) + await alice.send({"type": "CheckPresence", "peers": [address(100 + i) for i in range(70)]}) + for _ in range(64): + await alice.expect("PresenceStatus") + await alice.nothing_for(0.2) + + +async def test_a_reattach_supersedes_the_old_session(gateway): + first = await Client.connect(gateway.port) + await first.attach(address(1)) + second = await Client.connect(gateway.port) + await second.attach(address(1)) + assert await first.closed() + sender = await Client.connect(gateway.port) + await sender.attach(address(2)) + await sender.submit(address(1), b"hi") + await sender.expect("MessageSent") + assert base64.b64decode((await second.expect("MessageReceived"))["content"]) == b"hi" + assert address(1) in gateway.bound + + +async def test_an_undeclared_session_is_announced_verdict_only_after_the_grace(): + gw = Gateway(GatewayConfig(listen_port=0, attach_grace=10), verifier=fake_verify) + gw.config.attach_grace = 0.2 # past validation, to keep the test fast + port = await gw.start() + try: + c = await Client.connect(port) + await c.expect("Capabilities", timeout=2) + await c.expect("StatusUpdate", timeout=2) + await c.submit(address(2), b"x") + assert (await c.expect("DeliveryError"))["reason"] == "attach_required" + finally: + await gw.stop() + + +def test_a_grace_shorter_than_the_clients_attach_timeout_is_refused(): + from offline_gateway import ConfigError + + with pytest.raises(ConfigError): + GatewayConfig(attach_grace=5).validate() + + +def test_a_backbone_verdict_timeout_past_the_clients_is_refused(): + from offline_gateway import ConfigError + + with pytest.raises(ConfigError): + GatewayConfig(backbone_verdict_timeout=58).validate() + + +async def test_a_slow_reader_is_dropped_rather_than_buffered(gateway): + gateway.config.max_queued_frames = 4 + reader = await Client.connect(gateway.port) + await reader.attach(address(2)) + session = gateway.bound[address(2)] + for _ in range(100): + if not session.send({"type": "Filler", "x": "y" * 1000}): + break + assert session.closed or session._queue.qsize() <= 512 + + +async def test_idle_sockets_cannot_lock_a_device_out(): + """Anyone on the network can open sockets that never attach. Past the + unbound pool, the oldest of them is evicted, and a device still attaches.""" + gw = Gateway( + GatewayConfig(listen_port=0, attach_grace=0, max_sessions=6, max_unbound_sessions=3, max_sessions_per_host=2), + verifier=fake_verify, + ) + # Every test client is 127.0.0.1, so the per-host cap is lifted past + # validation to exercise the unbound pool from one host. + gw.config.max_sessions_per_host = 64 + port = await gw.start() + try: + idle = [await Client.connect(port) for _ in range(10)] + await asyncio.sleep(0.1) + assert sum(1 for s in gw.sessions if not s.closed) <= 3 + assert await idle[0].closed() + device = await Client.connect(port) + frames = await device.attach(address(1)) + assert frames[0]["type"] == "AddressDeclared" + finally: + await gw.stop() + + +async def test_bound_devices_are_never_evicted_for_newcomers(): + gw = Gateway( + GatewayConfig(listen_port=0, attach_grace=0, max_sessions=2, max_unbound_sessions=2, max_sessions_per_host=1), + verifier=fake_verify, + ) + gw.config.max_sessions_per_host = 64 + gw.config.max_unbound_sessions = 1 + port = await gw.start() + try: + a = await Client.connect(port) + await a.attach(address(1)) + b = await Client.connect(port) + await b.attach(address(2)) + late = await Client.connect(port) + assert await late.closed() + await a.submit(address(2), b"still here") + await a.expect("MessageSent") + finally: + await gw.stop() + + +async def test_one_host_cannot_hold_more_than_its_share(): + gw = Gateway( + GatewayConfig(listen_port=0, attach_grace=0, max_sessions_per_host=2), + verifier=fake_verify, + ) + port = await gw.start() + try: + first, second = await Client.connect(port), await Client.connect(port) + await first.attach(address(1)) + await second.attach(address(2)) + third = await Client.connect(port) + assert await third.closed() + finally: + await gw.stop() + + +def test_hosts_are_keyed_by_ipv4_address_or_ipv6_prefix(): + from offline_gateway.gateway import host_key + + assert host_key(("192.168.4.20", 5000)) == "192.168.4.20" + # Two privacy addresses in one /64 are one host. + a = host_key(("2001:db8:1:2:aaaa::1", 5000, 0, 0)) + b = host_key(("2001:db8:1:2:bbbb::9", 5001, 0, 0)) + assert a == b == "2001:db8:1:2::/64" + assert host_key(("2001:db8:1:3::1", 5000, 0, 0)) != a + assert host_key(("::ffff:10.0.0.5", 5000, 0, 0)) == "10.0.0.5" + assert host_key(("fe80::1%en0", 5000, 0, 1)) == "fe80::/64" + assert host_key(None) is None diff --git a/gateway/tests/test_reticulum.py b/gateway/tests/test_reticulum.py new file mode 100644 index 000000000..1d662ccc1 --- /dev/null +++ b/gateway/tests/test_reticulum.py @@ -0,0 +1,196 @@ +"""Two daemon processes, each with its own Reticulum instance, joined by a +Reticulum TCP interface, and two real SDK engines attached one to each. + +This is a LoRa deployment with the radio swapped for TCP: everything above +the interface (identities, announces, paths, links, resources, the request +handlers, presence snapshots) is what runs over an RNode. Reticulum is one +instance per process, which is why the daemons are subprocesses. + +Skipped without ``rns`` or without an SDK build that has the verifier. +""" + +from __future__ import annotations + +import asyncio +import os +import socket +import sys +import textwrap +from pathlib import Path + +import pytest + +RNS = pytest.importorskip("RNS") +sdk = pytest.importorskip("offline_protocol_sdk.offline_protocol") +if not hasattr(sdk, "verify_gateway_address_proof"): # pragma: no cover + pytest.skip("this SDK build has no verify_gateway_address_proof", allow_module_level=True) + +from offline_gateway.reticulum import APP_NAME, ASPECTS # noqa: E402 + +from test_end_to_end import Device, _pair_and_talk # noqa: E402 + +GATEWAY_ROOT = Path(__file__).resolve().parent.parent + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def _identity(path: Path) -> str: + identity = RNS.Identity() + identity.to_file(str(path)) + return RNS.Destination.hash(identity, APP_NAME, *ASPECTS).hex() + + +def _rns_config(directory: Path, interface: str) -> None: + directory.mkdir(parents=True) + (directory / "config").write_text( + textwrap.dedent( + """\ + [reticulum] + enable_transport = No + share_instance = No + panic_on_interface_error = No + + [logging] + loglevel = 4 + + # A real gateway keeps Reticulum's default announce stamp, a + # proof of work it mints once and stores (seconds to minutes, + # depending on the CPU). A test cannot wait for two of them. + [stamps] + destination_value = 8 + destination_cost = 8 + + [interfaces] + """ + ) + + textwrap.indent(textwrap.dedent(interface), " ") + ) + + +def _gateway_config(directory: Path, port: int, peer: str) -> Path: + path = directory / "gateway.toml" + path.write_text( + textwrap.dedent( + f"""\ + listen_host = "127.0.0.1" + listen_port = {port} + + [reticulum] + configdir = "rns" + identity_path = "gateway.identity" + peers = ["{peer}"] + reconnect_interval = 2.0 + announce_interval = 30.0 + loglevel = 4 + """ + ) + ) + return path + + +class Daemon: + def __init__(self, config: Path) -> None: + self.config = config + self.lines: list[str] = [] + self.proc: asyncio.subprocess.Process | None = None + self._reader: asyncio.Task[None] | None = None + + async def start(self) -> None: + env = dict(os.environ, PYTHONPATH=str(GATEWAY_ROOT), PYTHONUNBUFFERED="1") + self.proc = await asyncio.create_subprocess_exec( + sys.executable, + "-m", + "offline_gateway", + "--config", + str(self.config), + "-v", + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.STDOUT, + env=env, + ) + self._reader = asyncio.ensure_future(self._read()) + + async def _read(self) -> None: + assert self.proc is not None and self.proc.stdout is not None + while line := await self.proc.stdout.readline(): + self.lines.append(line.decode(errors="replace").rstrip()) + + async def wait_for(self, text: str, secs: float) -> None: + for _ in range(int(secs * 10)): + if any(text in line for line in self.lines): + return + if self.proc is not None and self.proc.returncode is not None: + break + await asyncio.sleep(0.1) + raise AssertionError(f"{self.config.parent.name} never logged {text!r}:\n" + "\n".join(self.lines[-40:])) + + async def stop(self) -> None: + if self.proc is not None and self.proc.returncode is None: + self.proc.terminate() + try: + await asyncio.wait_for(self.proc.wait(), 10) + except asyncio.TimeoutError: + self.proc.kill() + if self._reader is not None: + await asyncio.gather(self._reader, return_exceptions=True) + + +async def test_two_engines_talk_across_a_reticulum_backbone(tmp_path: Path) -> None: + a_dir, b_dir = tmp_path / "a", tmp_path / "b" + a_dir.mkdir() + b_dir.mkdir() + a_hash = _identity(a_dir / "gateway.identity") + b_hash = _identity(b_dir / "gateway.identity") + rns_port = _free_port() + _rns_config( + a_dir / "rns", + f"""\ + [[Backbone]] + type = TCPServerInterface + enabled = Yes + listen_ip = 127.0.0.1 + listen_port = {rns_port} + """, + ) + _rns_config( + b_dir / "rns", + f"""\ + [[Backbone]] + type = TCPClientInterface + enabled = Yes + target_host = 127.0.0.1 + target_port = {rns_port} + """, + ) + a_port, b_port = _free_port(), _free_port() + a = Daemon(_gateway_config(a_dir, a_port, b_hash)) + b = Daemon(_gateway_config(b_dir, b_port, a_hash)) + alice, bob = Device("rns-alice", a_port), Device("rns-bob", b_port) + try: + await a.start() + await b.start() + await a.wait_for(f"destination is {a_hash}", 20) + await b.wait_for(f"destination is {b_hash}", 20) + await a.wait_for(f"backbone link to {b_hash} established", 60) + await b.wait_for(f"backbone link to {a_hash} established", 60) + + for d in (alice, bob): + await d.start() + await a.wait_for("bound", 15) + await b.wait_for("bound", 15) + await _pair_and_talk(alice, bob, secs=90) + # The frames crossed the backbone, not some other path. + assert any("MessageReceived" in line for line in b.lines) + except AssertionError: + print("--- gateway a ---\n" + "\n".join(a.lines[-80:])) + print("--- gateway b ---\n" + "\n".join(b.lines[-80:])) + raise + finally: + for d in (alice, bob): + await d.stop() + await a.stop() + await b.stop() diff --git a/gateway/tests/test_reticulum_unit.py b/gateway/tests/test_reticulum_unit.py new file mode 100644 index 000000000..d5c4f82c3 --- /dev/null +++ b/gateway/tests/test_reticulum_unit.py @@ -0,0 +1,548 @@ +"""The Reticulum backbone's own rules, without a Reticulum instance: who may +call the request handlers, what a forward must carry, and how presence +requests change the table.""" + +from __future__ import annotations + +import asyncio + +import pytest + +RNS = pytest.importorskip("RNS") + +from conftest import address # noqa: E402 +from offline_gateway.backbone import ForwardResult # noqa: E402 +from offline_gateway.config import ReticulumConfig # noqa: E402 +from offline_gateway.reticulum import APP_NAME, ASPECTS, ReticulumBackbone, _frame_from # noqa: E402 + + +class Hooks: + def __init__(self) -> None: + self.changed: list[str] = [] + self.delivered: list = [] + + async def deliver_from_backbone(self, frame, peer): + self.delivered.append((frame, peer)) + return ForwardResult.DELIVERED, "" + + presence_epoch = "test-epoch" + + def local_snapshot(self): + return 1, {address(1): 1} + + def remote_presence_changed(self, addr): + self.changed.append(addr) + + +def _peer() -> tuple[object, str]: + identity = RNS.Identity() + return identity, RNS.Destination.hash(identity, APP_NAME, *ASPECTS).hex() + + +def _backbone(peers: list[str]) -> tuple[ReticulumBackbone, Hooks]: + backbone = ReticulumBackbone(ReticulumConfig(peers=peers)) + hooks = Hooks() + backbone.hooks = hooks + return backbone, hooks + + +def test_a_forward_needs_addresses_and_bytes(): + good = {"r": address(1), "s": address(2), "c": b"\x00\x01", "m": "id-1", "p": None} + frame = _frame_from(good) + assert frame is not None and frame.content == b"\x00\x01" and frame.message_id == "id-1" + assert _frame_from({**good, "c": "text, not bytes"}) is None + assert _frame_from({**good, "r": "nobody"}) is None + assert _frame_from({**good, "s": None}) is None + assert _frame_from([good]) is None + # An id the daemon would not echo is dropped, not carried. + assert _frame_from({**good, "m": "not valid!"}).message_id is None + + +def test_an_unprovisioned_caller_is_refused_by_every_handler(): + _, provisioned = _peer() + stranger, _ = _peer() + backbone, hooks = _backbone([provisioned]) + request = {"r": address(1), "s": address(2), "c": b"x"} + answer = backbone._handle_forward("/forward", request, b"id", b"link", stranger, 0) + assert answer["o"] == ForwardResult.REFUSED.value + assert backbone._handle_forward("/forward", request, b"id", b"link", None, 0)["o"] == "refused" + assert backbone._handle_presence("/presence", {"snap": True, "on": []}, b"id", b"link", stranger, 0) is None + assert backbone._handle_snapshot("/snapshot", None, b"id", b"link", stranger, 0) is None + assert not hooks.delivered + + +async def test_presence_requests_update_the_table_and_tell_the_daemon(): + identity, peer_hex = _peer() + backbone, hooks = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + peer = bytes.fromhex(peer_hex) + + backbone._apply(peer, {"e": "x", "snap": True, "q": 1, "on": [[address(5), 1], ["garbage", 1]], "off": []}) + assert backbone.claim(address(5)).online + assert backbone.claim("garbage") is None + assert hooks.changed == [address(5)] + + backbone._apply(peer, {"e": "x", "snap": False, "on": [], "off": [[address(5), 1234, 2]]}) + claim = backbone.claim(address(5)) + assert not claim.online and claim.last_seen_ms == 1234 + + backbone._apply( + peer, + {"e": "x", "snap": False, "on": [[address(6), 3]], "off": [[address(7), True, 4], "bad", [address(8), 1]]}, + ) + assert backbone.claim(address(6)).online + assert backbone.claim(address(7)).last_seen_ms is None # a bool is not a time + assert backbone.claim(address(8)) is None # an entry with no number is dropped + + # A snapshot with no number of its own cannot be ordered, so it is refused. + backbone._apply(peer, {"e": "x", "snap": True, "on": [], "off": []}) + assert backbone.claim(address(6)).online + + # Losing the peer's link withdraws everything it claimed. + hooks.changed.clear() + backbone._forget(peer) + assert backbone.claim(address(6)) is None + assert set(hooks.changed) == {address(5), address(6), address(7)} + + +async def test_the_snapshot_this_gateway_serves_carries_its_numbering(): + identity, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + assert backbone._snapshot_message() == { + "e": "test-epoch", + "snap": True, + "q": 1, + "on": [[address(1), 1]], + "off": [], + } + + +async def test_a_forward_with_no_claim_is_unreachable_without_touching_a_link(): + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + from offline_gateway.backbone import BackboneFrame + + result, _ = await backbone.forward(BackboneFrame(address(9), address(1), b"x", "m", None), 5) + assert result is ForwardResult.UNREACHABLE + + +async def test_presence_changes_are_coalesced_into_one_update(): + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + sent: list[dict] = [] + backbone._active_out = lambda peer: object() # type: ignore[method-assign] + + async def capture(link, peer, update): + sent.append(update) + + backbone._send_presence = capture # type: ignore[method-assign] + import offline_gateway.reticulum as module + + original = module.PRESENCE_COALESCE + module.PRESENCE_COALESCE = 0.05 + try: + backbone.local_presence_changed(address(1), True, None, 1) + backbone.local_presence_changed(address(2), True, None, 2) + backbone.local_presence_changed(address(1), False, 99, 3) + await asyncio.sleep(0.2) + finally: + module.PRESENCE_COALESCE = original + assert sent == [{"e": "test-epoch", "snap": False, "on": [[address(2), 2]], "off": [[address(1), 99, 3]]}] + + +def test_peers_must_be_destination_hashes(): + from offline_gateway import ConfigError, GatewayConfig + + with pytest.raises(ConfigError): + GatewayConfig(reticulum=ReticulumConfig(peers=["not hex"])).validate() + with pytest.raises(ConfigError): + GatewayConfig(reticulum=ReticulumConfig(peers=["ab" * 8])).validate() + GatewayConfig(reticulum=ReticulumConfig(peers=["ab" * 16])).validate() + + +def test_the_example_config_loads(): + from pathlib import Path + + from offline_gateway.config import load + + config = load(Path(__file__).resolve().parent.parent / "examples" / "gateway.toml") + assert config.listen_host == "0.0.0.0" and config.listen_port == 4242 + assert config.reticulum is not None + assert config.reticulum.configdir.endswith("examples/rns") + assert config.reticulum.identity_path.endswith("examples/gateway.identity") + + +async def test_a_link_the_peer_cannot_attribute_is_torn_down_for_a_redial(): + """A lost identify packet leaves a link every request on which is + refused. A forward refused for that reason drops the link rather than + failing every frame on it from then on.""" + from offline_gateway.backbone import BackboneFrame + from offline_gateway.reticulum import NOT_A_PEER + + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + backbone.table.update(peer_hex, address(2), True, None, 1) + + class Link: + torn = False + + def teardown(self): + self.torn = True + + link = Link() + backbone._active_out = lambda peer: link # type: ignore[method-assign] + + async def refused(link, path, data, timeout, admit=None): + return {"o": "refused", "w": NOT_A_PEER} + + backbone._request = refused # type: ignore[method-assign] + result, _ = await backbone.forward(BackboneFrame(address(2), address(1), b"x", "m", None), 5) + assert result is ForwardResult.TIMEOUT + assert link.torn + + +class _Resource: + def __init__(self, status): + self.status = status + self.cancelled = False + + def cancel(self): + self.cancelled = True + + +class _Receipt: + def __init__(self, resource): + self.resource = resource + + +async def test_a_request_that_times_out_cancels_its_transfer(monkeypatch): + import offline_gateway.reticulum as module + + monkeypatch.setattr(module, "MIN_TRANSFER_WINDOW", 0.0) + """A frame the device was told failed must stop spending airtime, or its + retry runs a second transfer beside the first.""" + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + resource = _Resource(RNS.Resource.TRANSFERRING) + + class SilentLink: + def request(self, path, data, response_callback, failed_callback, timeout): + return _Receipt(resource) + + with pytest.raises(asyncio.TimeoutError): + await backbone._request(SilentLink(), "/forward", {}, 0.05) + assert resource.cancelled + + +async def test_reticulums_own_timeout_also_cancels_the_transfer(monkeypatch): + import offline_gateway.reticulum as module + + monkeypatch.setattr(module, "MIN_TRANSFER_WINDOW", 0.0) + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + resource = _Resource(RNS.Resource.TRANSFERRING) + + class FailingLink: + def request(self, path, data, response_callback, failed_callback, timeout): + receipt = _Receipt(resource) + failed_callback(receipt) + return receipt + + with pytest.raises(asyncio.TimeoutError): + await backbone._request(FailingLink(), "/forward", {}, 5) + assert resource.cancelled + + +async def test_a_finished_transfer_is_left_alone(): + from offline_gateway.reticulum import _cancel_transfer + + done = _Resource(RNS.Resource.COMPLETE) + _cancel_transfer(_Receipt(done)) + _cancel_transfer(_Receipt(None)) + assert not done.cancelled + + +async def test_an_inbound_link_that_never_identifies_is_closed(): + identity, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + + class Link: + torn = False + + def teardown(self): + self.torn = True + + anonymous, known = Link(), Link() + backbone._in[bytes.fromhex(peer_hex)] = known + backbone._drop_if_anonymous(anonymous) + backbone._drop_if_anonymous(known) + assert anonymous.torn and not known.torn + + +async def test_requests_on_a_link_go_one_at_a_time_and_a_late_one_never_reaches_reticulum(monkeypatch): + """Reticulum parks a second resource on a link and cannot withdraw it. + The daemon holds it instead: a frame whose time runs out before its turn + is refused without ever being handed over.""" + import offline_gateway.reticulum as module + from offline_gateway.reticulum import QueuedTooLong + + monkeypatch.setattr(module, "MIN_TRANSFER_WINDOW", 0.0) + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + handed_over: list[str] = [] + answers: list = [] + + class OneAtATimeLink: + def request(self, path, data, response_callback, failed_callback, timeout): + handed_over.append(data) + receipt = _Receipt(_Resource(RNS.Resource.TRANSFERRING)) + receipt.response = "ok" + answers.append(lambda: response_callback(receipt)) + return receipt + + link = OneAtATimeLink() + first = asyncio.ensure_future(backbone._request(link, "/forward", "first", 5)) + await asyncio.sleep(0.05) + with pytest.raises(QueuedTooLong): + await backbone._request(link, "/forward", "late", 0.1) + assert handed_over == ["first"] + + # Once the first is answered the lane frees, and the next one goes. + answers[0]() + assert await first == "ok" + second = asyncio.ensure_future(backbone._request(link, "/forward", "second", 5)) + await asyncio.sleep(0.05) + assert handed_over == ["first", "second"] + answers[1]() + assert await second == "ok" + + +async def test_a_frame_queued_too_long_is_a_backbone_timeout(): + from offline_gateway.backbone import BackboneFrame + from offline_gateway.reticulum import QueuedTooLong + + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + backbone.table.update(peer_hex, address(2), True, None, 1) + backbone._active_out = lambda peer: object() # type: ignore[method-assign] + + async def queued(link, path, data, timeout, admit=None): + raise QueuedTooLong() + + backbone._request = queued # type: ignore[method-assign] + result, reason = await backbone.forward(BackboneFrame(address(2), address(1), b"x", "m", None), 5) + assert result is ForwardResult.TIMEOUT and "queued" in reason + + +async def test_a_lost_presence_update_is_resent_while_the_link_lasts(): + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone.config.reconnect_interval = 0.01 + backbone._loop = asyncio.get_running_loop() + link = object() + active = {"link": link} + backbone._active_out = lambda peer: active["link"] # type: ignore[method-assign] + attempts: list = [] + + async def lossy(l, path, data, timeout): + attempts.append(data) + if len(attempts) < 3: + raise asyncio.TimeoutError() + return True + + backbone._request = lossy # type: ignore[method-assign] + await backbone._send_presence(link, bytes.fromhex(peer_hex), {"on": []}) + assert len(attempts) == 3 + + # A link that has gone is not retried on; the next one re-snapshots. + attempts.clear() + + async def silent(l, path, data, timeout): + attempts.append(data) + active["link"] = None + raise asyncio.TimeoutError() + + backbone._request = silent # type: ignore[method-assign] + await backbone._send_presence(link, bytes.fromhex(peer_hex), {"on": []}) + assert len(attempts) == 1 + + +async def test_a_peer_that_never_answers_is_redialled_less_and_less_often(monkeypatch): + """One-sided provisioning: the peer takes the link and refuses everything. + Without backoff that is a redial, and half a dozen packets, every time.""" + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone.config.reconnect_interval = 0.01 + backbone._identity = RNS.Identity() + backbone._loop = asyncio.get_running_loop() + backbone._running = True + dials: list[float] = [] + + class FakeLink: + def __init__(self, destination, established_callback, closed_callback): + dials.append(asyncio.get_running_loop().time()) + self.status = RNS.Link.ACTIVE + established_callback(self) + + def identify(self, identity): + pass + + def teardown(self): + self.status = RNS.Link.CLOSED + + monkeypatch.setattr(RNS.Transport, "has_path", staticmethod(lambda h: True)) + monkeypatch.setattr(RNS.Identity, "recall", staticmethod(lambda h: object())) + monkeypatch.setattr(RNS, "Destination", type("D", (), {"OUT": 0, "SINGLE": 0, "__init__": lambda self, *a: None})) + monkeypatch.setattr(RNS, "Link", type("L", (FakeLink,), {"ACTIVE": RNS.Link.ACTIVE, "CLOSED": RNS.Link.CLOSED})) + + async def refused(link, peer): + link.teardown() + return False + + backbone._exchange_snapshots = refused # type: ignore[method-assign] + task = asyncio.ensure_future(backbone._dial_loop(bytes.fromhex(peer_hex))) + await asyncio.sleep(0.4) + backbone._running = False + task.cancel() + await asyncio.gather(task, return_exceptions=True) + # 0.01, 0.02, 0.04, 0.08, 0.16 s apart: a handful, not hundreds. + assert 3 <= len(dials) <= 7 + gaps = [b - a for a, b in zip(dials, dials[1:])] + assert gaps == sorted(gaps) + + +async def test_an_unexpected_error_does_not_end_the_dial_loop(monkeypatch): + import offline_gateway.reticulum as module + + monkeypatch.setattr(module, "MAX_DIAL_BACKOFF", 0.01) + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._running = True + calls: list[int] = [] + + async def flaky(peer): + calls.append(1) + if len(calls) == 1: + raise RuntimeError("reticulum had a bad day") + backbone._running = False + + backbone._dial = flaky # type: ignore[method-assign] + await asyncio.wait_for(backbone._dial_loop(bytes.fromhex(peer_hex)), 2) + assert len(calls) == 2 + + +def test_one_host_may_not_fill_the_unbound_pool(): + from offline_gateway import ConfigError, GatewayConfig + + with pytest.raises(ConfigError): + GatewayConfig(max_unbound_sessions=8, max_sessions_per_host=8).validate() + GatewayConfig(max_unbound_sessions=8, max_sessions_per_host=7).validate() + + +async def test_a_one_packet_request_does_not_wait_behind_a_transfer(): + """A presence update is one packet, which Reticulum sends at once. It + must not queue behind a frame on the lane, or a lost one would hold the + lane for its whole timeout and time out every frame behind it.""" + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + handed_over: list = [] + + class Link: + mdu = 400 + + def request(self, path, data, response_callback, failed_callback, timeout): + handed_over.append(path) + receipt = _Receipt(None) + receipt.response = True + if path == "/presence": + response_callback(receipt) + return receipt + + link = Link() + big = asyncio.ensure_future(backbone._request(link, "/forward", {"c": b"x" * 2000}, 30)) + await asyncio.sleep(0.05) + answer = await asyncio.wait_for(backbone._request(link, "/presence", {"on": [[address(1), 1]]}, 5), 1) + assert answer is True + assert handed_over == ["/forward", "/presence"] + big.cancel() + await asyncio.gather(big, return_exceptions=True) + + +def test_the_one_packet_test_matches_reticulums_own(): + from offline_gateway.reticulum import _fits_one_packet + + class Link: + mdu = 400 + + assert _fits_one_packet(Link(), "/presence", {"on": [[address(1), 1]]}) + assert not _fits_one_packet(Link(), "/forward", {"c": b"x" * 500}) + assert not _fits_one_packet(object(), "/presence", None) # no mdu: assume not + + +async def test_a_frame_that_never_reaches_the_radio_is_never_charged(monkeypatch): + """Charging at submission spent the budgets on frames that then waited out + their time in the queue, and charged their retries again.""" + import offline_gateway.reticulum as module + from offline_gateway.backbone import BackboneFrame + + monkeypatch.setattr(module, "MIN_TRANSFER_WINDOW", 0.0) + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + backbone.table.update(peer_hex, address(2), True, None, 1) + charged: list[str] = [] + + class Link: + status = RNS.Link.ACTIVE + mdu = 400 + + def request(self, path, data, response_callback, failed_callback, timeout): + return _Receipt(_Resource(RNS.Resource.TRANSFERRING)) # never answers + + link = Link() + backbone._active_out = lambda peer: link # type: ignore[method-assign] + + def admit(peer): + charged.append(peer) + return True + + frame = BackboneFrame(address(2), address(1), b"x" * 1000, "m", None) + first = asyncio.ensure_future(backbone.forward(frame, 5, admit)) + await asyncio.sleep(0.05) + result, reason = await backbone.forward(frame, 0.1, admit) + assert result is ForwardResult.TIMEOUT and "queued" in reason + assert charged == [peer_hex] # only the frame that went to the radio + first.cancel() + await asyncio.gather(first, return_exceptions=True) + + +async def test_a_frame_the_budgets_refuse_at_its_turn_is_not_sent(): + from offline_gateway.backbone import BackboneFrame + + _, peer_hex = _peer() + backbone, _ = _backbone([peer_hex]) + backbone._loop = asyncio.get_running_loop() + backbone.table.update(peer_hex, address(2), True, None, 1) + sent: list = [] + + class Link: + status = RNS.Link.ACTIVE + mdu = 400 + + def request(self, *args, **kwargs): + sent.append(args) + return False + + backbone._active_out = lambda peer: Link() # type: ignore[method-assign] + frame = BackboneFrame(address(2), address(1), b"x" * 1000, "m", None) + result, reason = await backbone.forward(frame, 30, lambda peer: False) + assert (result, reason) == (ForwardResult.REFUSED, "budget_exceeded") + assert not sent