Skip to content

feat: add a wake gateway client module - #160

Merged
coreyphillips merged 9 commits into
masterfrom
feat/wake-client
Nov 2, 2026
Merged

coreyphillips merged 9 commits into
masterfrom
feat/wake-client

Conversation

@coreyphillips

@coreyphillips coreyphillips commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

feat: add a wake gateway client module

Summary

Adds src/modules/wake, the device side of the wake push gateway (synonymdev/wake), the service that replaces bitkit-notification-server. It covers what an app needs to receive wakes through the gateway, and to let peers wake it:

  • generate the device's encryption key pair, device secret and install id;
  • prepare a registration, sign it with the node (ln:) and pubky (pk:) identities, and register;
  • find and decrypt the wake in any delivered push, legacy (v0) or v1;
  • acknowledge wakes, report presence, change topics and unregister;
  • create, list and revoke grants that let a peer wake this device, and send a peer wake with a grant another device handed over.

The module is a port of the gateway's wake-proto crate, which bitkit-core cannot depend on. It has no database state and no cfg-gated exports. register_device and test_notification are unchanged, so nothing changes for the apps until they call the new functions.

API

fn wake_generate_keypair() -> Result<WakeKeyPair, WakeError>
fn wake_generate_device_secret() -> Result<WakeDeviceSecret, WakeError>
fn wake_generate_install_id() -> String
fn wake_prepare_registration(audience, app, install_id, platform, environment, push_token,
    encryption_public_key, secret_sha256, identities, topics, timestamp: Option<u64>)
    -> Result<WakeRegistrationRequest, WakeError>
fn wake_sign_pubky_proof(secret_key_hex, message) -> Result<String, WakeError>
fn wake_decrypt_push(secret_key_hex, push_json) -> Result<WakeEnvelope, WakeError>
fn wake_decrypt_v0(secret_key_hex, cipher, iv, tag, public_key) -> Result<WakeEnvelope, WakeError>
fn wake_decrypt_v1(secret_key_hex, container_json) -> Result<WakeEnvelope, WakeError>
async fn wake_server_info(gateway_url) -> Result<WakeServerInfo, WakeError>
async fn wake_register(gateway_url, request, proofs) -> Result<WakeRegistration, WakeError>
async fn wake_ack(gateway_url, device_secret, wake_id, outcome) -> Result<(), WakeError>
async fn wake_set_presence(gateway_url, device_secret, ttl_secs) -> Result<u64, WakeError>
async fn wake_clear_presence(gateway_url, device_secret) -> Result<(), WakeError>
async fn wake_set_topics(gateway_url, device_secret, topics) -> Result<Vec<String>, WakeError>
async fn wake_unregister(gateway_url, device_secret) -> Result<(), WakeError>
async fn wake_list_topics(gateway_url) -> Result<Vec<WakeTopic>, WakeError>
async fn wake_create_grant(gateway_url, device_secret, recipient, topics,
    per_hour: Option<u32>, per_day: Option<u32>, expires_in_days: Option<u32>)
    -> Result<WakeGrant, WakeError>
async fn wake_list_grants(gateway_url, device_secret) -> Result<Vec<WakeGrantSummary>, WakeError>
async fn wake_revoke_grant(gateway_url, device_secret, grant_id) -> Result<(), WakeError>
async fn wake_send_peer_wake(gateway_url, grant_token, topic) -> Result<(), WakeError>

The host signs WakeRegistrationRequest.message: ln: through ldk-node signMessage, pk: through wake_sign_pubky_proof, which refuses anything that is not a wake registration message so the pubky key cannot be used here to sign other data. wake_prepare_registration checks every field the way the gateway does, so a request the gateway would reject as invalid_request fails before anything is signed, and wake_register refuses a request whose fields no longer match its message.

The HTTP calls are pure build_* and parse_* functions around a thin reqwest executor (15 s timeout, no redirects). Every non-2xx response maps to WakeError::GatewayRejected { status, code, detail } (not message, which Kotlin exceptions already define) from the gateway's {"error","message"} body, with code unknown for any other body. Async exports use the existing ensure_runtime().spawn(...) pattern.

Grants and peer wakes

These follow the gateway's peer flow: a recipient creates a grant for one of its identities, hands the wkg_ token to a peer, and the peer sends POST /v1/peer/wakes. The push is content-free, quota-bound and revocable.

  • Grant routes take the device secret, and the peer wake takes the grant token. Each credential is checked for its own format before anything is sent, so one can't be sent in place of the other.
  • wake_create_grant checks what the gateway checks without its config: a canonical recipient, 1 to 16 topic names (a pattern is refused), and no zero quota or lifetime. Three checks are left to the gateway: whether each topic is a peer topic, whether the recipient is bound to the device, and whether per_day is at least per_hour. The gateway caps both quotas before comparing them.
  • A created grant's token must be well formed and name the grant's own id before it is returned. WakeGrant's Debug redacts the token, and errors never quote it.
  • wake_revoke_grant takes the id in any uuid spelling. Revoking twice is harmless, as on the gateway.

Crypto and wire compatibility

  • ECDH through bitcoin::secp256k1::ecdh::shared_secret_point, compressed to the 33-byte point (0x02 | y & 1) || x.
  • key = SHA256(SHA256(S33 || label)), computed as two plain sha256::Hash::hash calls, not with the sha256d type, whose display is byte-reversed.
  • AES-256-GCM through aes-gcm 0.10.3, no AAD, 16-byte tag; the IV must be 12 or 16 bytes.
  • v0 is the envelope deployed apps already decrypt (label bitkit-notifications, 16-byte IV). v1 uses label wake-v1 and a 12-byte IV. A container v other than 1 is UnsupportedEnvelope.
  • wake_decrypt_push accepts the four delivered shapes (APNs aps.alert.payload, flat FCM legacy data, APNs wake object, FCM wake JSON string) and returns fallback = true for a wake_fallback marker without decrypting.
  • The producer payload comes back as raw JSON, byte for byte (serde_json gains raw_value).

Dependency changes: aes-gcm = "0.10.3" (already in the lockfile through trezor-connect-rs) and the raw_value feature on serde_json. The only Cargo.lock change is the new direct dependency edge.

Vectors

src/modules/wake/test_vectors/*.json are copied byte for byte from the wake repository (crates/wake-proto/vectors, commit 782f66510c505b0331e6299e96c1233d3c263484, recorded in the module README). The tests assert them exactly:

  • the v0 server envelope (323 bytes), rebuilt byte for byte from its inputs;
  • the v0 client vector from bitkit-ios and bitkit-android, including S33 028ce542...80ee3 and key 3a9d552c...33b609b;
  • the v1 envelope, rebuilt byte for byte;
  • the registration preimage, its SHA-256, the pubky proof, and the ln proof reproduced by a local stand-in for ldk-node signMessage;
  • every case in pushes.json (all APNs and FCM shapes plus both fallbacks) through the push parser and wake_decrypt_push, including the FCM data-map-only view.

Negative cases cover a tampered tag or ciphertext, a wrong key, the wrong label, an 11-byte IV, unknown container and plaintext versions, unpadded base64, an off-curve ephemeral key, misplaced containers and every push shape the parser cannot place.

CI

A new workflow, .github/workflows/wake-tests.yml, runs cargo test --locked --lib modules::wake on every pull request, as the USDT job does for its module. Until now no workflow ran the wake tests or the vectors.

What is not included

  • No iOS or Android app changes.
  • The Paykit message that carries a grant to a linked peer (paykit.wake_capability in the gateway's anti-spam doc, section 8) is a Paykit spec change, not part of this module.

Wire format

The v1 wire format is experimental until the apps adopt it. The legacy (v0) envelope is unchanged and stable.

Tests run

At 0e0a379, after merging master at 70f7942:

  • cargo fmt --check
  • cargo clippy --locked --lib --tests: no warnings in the wake module or its exports
  • cargo test --locked --lib modules::wake: 46 passed, 2 ignored (the live gateway tests)
  • cargo test --locked --lib modules::usdt: 102 passed, 1 ignored, so the merged tree still passes the USDT job
  • The Swift interface files were regenerated from the host library the way build_ios.sh does. The diff from the merge is only the four grant functions and the two grant records.
  • WAKE_GATEWAY_URL=http://127.0.0.1:9010 WAKE_FAKE_PUSH_URL=http://127.0.0.1:9100 cargo test wake -- --ignored: both live tests passed against the wake repo's docker dev stack. The stack was built from the code of synonymdev/wake e7ede3c; the copy differed only in the repository URL, licence holder and CI branch name.
    • live_gateway_round_trip covers wake_server_info, a registration signed with an ln: and a pk: proof, presence set and clear, wake_list_topics, wake_set_topics (an unknown topic is dropped), and wake_unregister, after which the device secret is refused with 401.
    • live_gateway_grant_round_trip registers a pk: device, then checks the refusals: a grant on a non-peer topic is refused with topic_not_peer, and a grant for another identity with identity_not_bound. It creates a grant on paykit.sync and sends a peer wake with it. The fake APNs records the push, which decrypts to a v1 paykit.sync wake with a null payload and is acked handled. The grant then shows sent_1h = 1. Revoking it twice succeeds, and the token is then refused with grant_invalid.

Status

The gateway is not deployed yet. Its repository is synonymdev/wake, and nothing has run against the real APNs or FCM yet.

Adds src/modules/wake, the device side of the wake push gateway, as a
port of the gateway's wake-proto crate:

- key pair, device secret and install id generation;
- wake_prepare_registration builds the 12-line message every identity
  signs and checks each field the way the gateway does;
  wake_sign_pubky_proof signs it with the pubky key and refuses any
  other message;
- wake_decrypt_push finds the wake in any delivered APNs or FCM shape and
  decrypts legacy (v0) and v1 envelopes; a wake_fallback marker is
  returned without decrypting;
- register, ack, presence, topics, unregister, info and topic listing,
  as pure build and parse functions around a thin reqwest executor that
  does not follow redirects.

The AES key is SHA256(SHA256(S33 || label)) over the compressed ECDH
point, computed as two plain sha256 passes rather than the sha256d type,
whose display is byte-reversed. IVs must be 12 or 16 bytes.

The tests assert the wake-proto golden vectors byte for byte (copied
from wake commit 6037343), including rebuilding the v0 and v1 envelopes
and the ln proof, and run every pushes.json case through the parser.

Adds aes-gcm 0.10.3, already in the lockfile, and the serde_json
raw_value feature so payloads come back as the producer sent them.
register_device and test_notification are unchanged.
Generated the way build_ios.sh does: cargo build --release, then
uniffi-bindgen generate --library target/release/libbitkitcore.dylib
--language swift. Before the wake change the same steps reproduced the
committed files exactly, so the diff is only the wake functions and
types (additions only). module.modulemap is unchanged. Package.swift and
the version are untouched.
Kotlin exceptions already have a message property, so a field of that
name in an error variant breaks the Android bindings build.
Resolves the Cargo.toml and module list conflicts with the USDT work and
regenerates the Swift interface from the merged library.
@ovitrif

ovitrif commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

@coreyphillips can we get this open and ready pls? need it for better paykit features integration 🙏🏻

@coreyphillips

Copy link
Copy Markdown
Collaborator Author

Answered

  • @ovitrif: The code is done: the wake vectors pass, and the live round trip passed against a local gateway stack. It is in draft only because the gateway is not deployed and its repository is not published. The v1 wire format may also still change before the apps adopt it. Marking it ready is a call for the author or a maintainer. Until it merges, the Paykit work can build against this branch, because nothing changes for the apps until they call the new wake functions.

@coreyphillips
coreyphillips marked this pull request as ready for review October 28, 2026 17:13

@talosmachina talosmachina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings. Adds a wake module: device keys, secret and install id, the signed 12-line registration preimage, v0/v1 envelope decryption from every APNs/FCM push shape, and the gateway's device routes, exported through UniFFI with regenerated iOS bindings. Reviewed 4f52e1d, full tier, static.

What I checked, and 9 candidates I ruled out

Read in full: wake/crypto.rs, push.rs, registration.rs, client.rs, errors.rs, types.rs, mod.rs, README.md, the src/lib.rs exports, Cargo.toml, CHANGELOG.md; test names and vector loading in wake/tests.rs.
Bindings: bitkitcore.swift diff is +1715 lines and no removals once whitespace is ignored (git diff -w --diff-algorithm=histogram). Every type and func in the base file is still there, plus the 16 wake functions. A merge with current master is textually clean and gives 211 + 16 = 227 checksum entries in both bitkitcore.swift and bitkitcoreFFI.h.
Build: not built or tested here. The code-run gate could not confirm the author's write access, so this review reads the code only.
CI: green, but those runs are from 2026-09-30, and master has had about 50 commits since, including several binding regenerations. usdt-tests runs only cargo test --lib modules::usdt, so no workflow runs the 40 wake tests or the golden vectors.

Ruled out

  • ECDH parity byte: shared_secret_point returns x || y big-endian, so 0x02 | xy[63] & 1 is the correct compressed prefix.
  • 16-byte GCM nonce: AesGcm<Aes256, U16> derives J0 through GHASH, the same as Node's non-96-bit IV path, and the v0 server and client vectors pin it.
  • Registration body drifting from the signed message: build_register rebuilds the preimage from the request and refuses when it differs from message.
  • Preimage ambiguity: a newline in any scalar, and an empty entry or a comma in a list, are rejected before sorting and dedup.
  • APNs odd-length token: is_lower_hex(token, len / 2) needs the length to be exactly twice that, so odd lengths fail.
  • "v":null read as v0: the present deserializer turns an explicit null into Some(Null), which is UnsupportedEnvelope.
  • Legacy FCM map taken for a messages:send body: only an object-valued message switches to android.data/data, and the legacy alert text is a string.
  • Secrets in errors: JSON errors carry only the category and position, HttpRequest has no Debug, the bearer goes in a header (so not into reqwest's URL-bearing error text), and WakeKeyPair/WakeDeviceSecret redact in Debug.
  • wake_sign_pubky_proof as a general signer: it refuses any message without the wake-register-v1\n prefix, and the key comes through Keypair::from_secret, the same as the existing pubky module.

Merge confidence: 4/5, no findings, but the wake tests and vectors were not run, here or in CI, and CI predates the current master.

A device can now let peers wake it, and wake a peer that granted it the
right, which Paykit notifications and swap claim wakes both need.

- wake_create_grant, wake_list_grants and wake_revoke_grant call the
  gateway's grant routes with the device secret.
- wake_send_peer_wake calls POST /v1/peer/wakes with a wkg_ grant token.
- Grant requests are checked the way the gateway checks them, without its
  config: a canonical recipient, 1 to 16 topic names, no zero quota or
  lifetime. per_day against per_hour is left to the gateway, which caps
  both first.
- A created grant's token must be well formed and name the grant's own id
  before it is returned, and WakeGrant's Debug redacts it.
- A new ignored test runs the whole grant flow against a gateway, and with
  the docker stack's fake providers it decrypts and acks the peer wake.
No workflow ran the wake module's unit tests or the gateway's golden vectors. This job runs cargo test --lib modules::wake on every pull request, as the USDT job does for its module.

@ovi-reviewer ovi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: ✅ Approve

Findings: None.

QA for 0e0a379:

Wake protocol vectors and rejected inputs ✅ The locked wake module suite passed, including crypto vectors, push shapes, registration proofs, credential validation and HTTP execution checks.

Checked with cargo test --locked --lib modules::wake. Both ignored gateway tests were run separately below.

Register and manage a wake device ✅ The live gateway accepted both identity proofs and device updates, then rejected the secret after unregistering.

Checked by live_gateway_round_trip against the gateway's Docker dev stack at e7ede3c: ln: and pk: registration proofs, presence set/clear, topic discovery/replacement, unknown-topic removal, and HTTP 401 after unregistering.

Deliver and revoke a peer wake ✅ The live grant flow delivered and decrypted a peer wake, acknowledged it, and rejected its revoked token.

Checked by live_gateway_grant_round_trip with the fake push provider enabled. Non-peer topics and unbound identities were refused. The recorded fake APNs push decrypted to paykit.sync with no payload, its handled acknowledgement succeeded, grant usage increased, and revoking twice succeeded before the next send returned grant_invalid.

Check: Build the exported library and Swift bindings ✅ The library built, regenerated interfaces matched, and the Swift interface type-checked.

Built with cargo build --locked --lib, regenerated Swift/C bindings from that library, compared both files with the committed versions ignoring whitespace, and ran swiftc -typecheck against the generated FFI module.

Full review of 70f7942..0e0a379, covering the complete wake module and tests, exported runtime wrappers, generated binding additions, dependency changes and CI workflow. The six vectors also match the linked gateway source byte for byte. I read the earlier static review and independently reviewed this head.

No device run: this PR adds shared Android/iOS library APIs without changing an app caller or UI. The automated cases above were checked through test assertions and command results; there is no device video. Mobile app integration and real APNs/FCM delivery remain untested; live delivery here used fake APNs.


Reviewed by gpt-6.1-sol-high

@ovitrif ovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utAck

@coreyphillips
coreyphillips merged commit 8a72a0b into master Nov 2, 2026
7 checks passed
@coreyphillips
coreyphillips deleted the feat/wake-client branch November 2, 2026 18:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants