diff --git a/.changeset/profile-disclose.md b/.changeset/profile-disclose.md new file mode 100644 index 0000000000..cbd957daf2 --- /dev/null +++ b/.changeset/profile-disclose.md @@ -0,0 +1,75 @@ +--- +"@parity/truapi": minor +"@parity/truapi-host": minor +--- + +Add `profile.disclose`, `profile.retract` and `profile.presentContact`. A product discloses one opaque reference to the +user's chat contacts and may withdraw it; a product names a contact by peer identity and the host presents the reference +that contact disclosed, so no product holds a contact's reference. The first `disclose` from a product asks the user +once through `userConfirmation.confirmPermission` with a new `ProfileDisclosure` review, remembered as the +`ProfileDisclosure` permission; a refusal is `PermissionDenied`. Hosts must render that review. + +This change includes the Chat relay. In legacy `ChatApps` mode the host sends the disclosure to every ready Chat v2 +contact as a host-private app-scoped message and keeps, per contact, the newest frame their host sent back, withdrawals +included, whatever order the chat product opens them in. Both live in wallet- and network-scoped core storage +(`ProfileDisclosure`, `ProfileReferencesReceived`). The host queues the disclosure when the chat product initializes or reconciles, in the +response to a Chat request in which a contact became ready, and, without delaying the call, as soon as `disclose` or +`retract` changes it while a Chat of the same wallet is open; the chat product still has to run to submit it. Delivery +is best effort: relayed references never take outbox room from other Chat traffic, and one that lapses unacknowledged +after a statement lifetime is signed again for a ready contact, at most three frames per contact and disclosure. Every +`disclose` call is a new disclosure, even with the reference already held: a profile whose record changed behind the +same reference is sent to the selected ready recipients again, with a fresh attempt count. + +Add `profile.placeContactAvatars`. A chat App tells the host where it draws contacts' avatars (surface size and, per +avatar, a slot id, peer identity, square rect and clip), and the host draws the photo and mood ring of each contact who +shared a profile with it on its own layer. The core filters the placement to contacts with a current reference, hands +them with their references and `sharedAt` (Unix ms of the contact's share) to the new +`ProfilePlatform.placeContactAvatars(product, placed)` callback, and redraws the remembered placement when a reference +arrives, is re-shared or is withdrawn; a larger `sharedAt` for the same reference tells the host its cached profile is +stale; it clears it when the connection goes away. +The product is answered `Ok` whoever shared; only a malformed placement (more than 64 slots, a surface side outside 1 to +16384, a non-square avatar or one outside 1 to 1024 a side, a repeated slot) is refused, and a host that cannot draw +answers `Unsupported`. A JS host that supplies a `profile` group must implement the callback; the Rust trait's default +draws nothing. + +Add `profile.ownStatus` and `profile.presentOwn`, and an optional `own` slot in version 2 of +`profile.placeContactAvatars`. A chat product can report whether its signed-in user has configured a profile and ask +the host to present it without receiving the bearer reference. The core fills the own slot from the user's disclosure +and hands it to the existing callback in the same replacement set as the contact avatars, redraws it when the user +discloses or retracts, and still reveals nothing per slot. Version 1 placements keep working unchanged. +The avatar regression suite also exercises version-1 response downgrading alongside the version-2 own-profile slot. + +Version 2 of `profile.disclose` adds explicit `ChatApps`, `App { productId }`, and +`Contacts { handles }` audiences. App-scoped and selected-contact personal grants coexist: personal grants are +host-renderable across products, never returned to them. All handles are verified against the host Contacts lookup +before committing the replacement; empty audiences configure only the user's own profile. Existing V1 calls retain +their app-scoped all-Chat behavior. Groups remain product-owned sets of opaque handles, not a new host group API. + +Personal relay uses distinct Chat content 22 (scope 1) and wallet/network-scoped +`ProfilePersonalReferencesReceived` storage. App content 21 is unchanged. Durable revisions, separate scoped +watermarks and withdrawal tombstones prevent an older personal share delivered through another app from reviving a +withdrawn grant. Removing one audience does not revoke an overlapping grant in another scope. Delivery still requires +a ready authenticated Chat channel and a running transport product; Contacts membership alone creates neither. + +Version 2 of `profile.presentContact` accepts either a peer identity or a Contacts handle and hides profile +availability, including host rendering failures. V1 retains its app-only lookup and errors, so it cannot probe new +cross-app personal grants. Version 3 of `profile.placeContactAvatars` accepts the same selectors alongside the own slot; +V1/V2 placement bytes and replies remain compatible. Contacts-change notifications invalidate cached handle lookups +and refresh remembered avatars. App-specific references take precedence over personal ones; personal updates redraw +all affected wallet placements. +Personal revisions also advance the host-rendered freshness timestamp when a newer share arrives through an actor +whose clock is older, preventing a same-reference update from leaving stale cached profile contents. + +Add `contacts.pickMany` with preselected opaque handles and explicit picked, dismissed, and no-contacts outcomes. +Add `contacts.placeLabels` so Apps can reserve host-rendered contact names without receiving those names or profile +availability. The core validates bounded placements and wallet-scoped handles, refreshes labels after Contacts changes, +and releases them when the connection closes. Hosts without a label surface return `Unsupported`; Worker products +cannot place labels. Clearing a session serializes removal of its remembered contact labels with pending refreshes. +Host-side interruption returns a Contacts domain error, reserving wire `Cancelled` for a peer's explicit cancellation. +Failed directory lookups preserve the prior label surface and report a retryable error instead of clearing it as if +the contacts were missing. + +Integrate canonical permission administration from the Chat runtime. Profile +disclosure remains separately authorized and participates in pending-prompt +cancellation and stale-decision fencing, while profile roster, privacy and +avatar/session boundaries coexist with the upstream game and card capabilities. diff --git a/.changeset/profile-present-contact-attribution.md b/.changeset/profile-present-contact-attribution.md new file mode 100644 index 0000000000..01f939f440 --- /dev/null +++ b/.changeset/profile-present-contact-attribution.md @@ -0,0 +1,14 @@ +--- +"@parity/truapi-host": minor +--- + +Name the contact in host-owned profile presentation, including a friendly empty state when no live reference has arrived. +`ProfilePlatform.presentContactProfile(product, presented)` receives `peerIdentity`, optional verified `username`, +and optional `shared: { reference, sharedAt }`. Absence of `shared` requests empty-profile feedback without a fetch. +The product-facing V2 reply does not reveal whether any information was available or displayed. +The username is the one the product's Chat roster verified for that contact, else the contact's verified dotNS name, +looked up for at most 2 seconds; it never comes from the product. It names who sent the reference, not whose profile it +is: the record is not signed by its owner, and a contact can forward someone else's reference. The default adapter +can present a shared reference through `presentProfile`; empty-profile feedback requires `presentContactProfile`. +Storage errors, invalid references and invalid handles are not misrepresented as absent sharing. The product-facing +Profile wire is unchanged. diff --git a/.changeset/profile-present.md b/.changeset/profile-present.md new file mode 100644 index 0000000000..44abd291ac --- /dev/null +++ b/.changeset/profile-present.md @@ -0,0 +1,11 @@ +--- +"@parity/truapi": minor +"@parity/truapi-host": minor +--- + +Add the `profile` service. `profile.present({ reference })` asks the host to show a referenced profile in host-owned +UI; the host resolves, decrypts and renders it, and nothing but acceptance returns to the product. Hosts opt in with the +optional `profile` callbacks (`ProfilePlatform`); a host that supplies none answers `Unsupported`. + +Keep the optional profile bindings available under the consolidated native +`runtime` feature, and use the shared host clock for disclosure revisions. diff --git a/README.md b/README.md index 7ce39ddea9..7c6e1346fc 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ TypeScript client, and hosts and products implement against the same shared type - [TrUAPI reference](https://docs.polkadot.com/reference/apps/protocol/truapi/) - [Rust API reference](https://paritytech.github.io/trinity-user-agents/) - [Draft: Host-owned native Chat and main-purse payments](docs/rfcs/native-chat-main-purse.md) +- [Draft: Profile disclosure audiences and host-rendered contacts](docs/rfcs/profile-disclosure.md) @@ -131,6 +132,19 @@ authenticated, ready peers from authorized native Chat products, scopes them to and never exposes a product or SSO directory method. Actors opened on this version are durably indexed; historical unindexed Chat products must be opened once before their peers can appear. Pairing hosts do not supply this directory. +Contacts trait 20 retains the single picker at method 0, adds `pickMany({ selected })` at method 1, and +`placeLabels({ surfaceWidth, surfaceHeight, slots })` at method 2. Multi-select confirmation returns only +wallet-scoped handles, including a confirmed empty selection; dismissal never edits the audience. Host-owned +labels show directory usernames or account fallbacks independently of Profile photos, without returning names, +accounts or per-slot availability. Selections and placements are bounded to 256 entries; unresolved initial +selections fail closed. Hosts implement `pickContacts(product, ContactSelection)` and +`placeContactLabels(product, PlacedContactLabels)` through the canonical native/WASM/worker callbacks. + +Profile V2 presentation opens host-owned feedback even when no live contact reference has arrived. +`PresentedContactProfile.shared` holds the reference and freshness timestamp when present; `None` requests an +empty-profile view. The host receives the verified contact name, while the product receives the same success reply +for shared and absent information. Storage failures and invalid handles are not presented as an empty profile. + The [native Chat/main-purse RFC](docs/rfcs/native-chat-main-purse.md) specifies the method 12 request/response and compatibility contract, device eligibility, custody-before-ACK rule, and delivery versus clearing semantics. It is a draft for review in #709, not an approved standard or a release claim. It builds on diff --git a/android/truapi-host/src/main/kotlin/io/parity/truapi/TrUAPIHost.kt b/android/truapi-host/src/main/kotlin/io/parity/truapi/TrUAPIHost.kt index 6e586ee30f..ee798b6358 100644 --- a/android/truapi-host/src/main/kotlin/io/parity/truapi/TrUAPIHost.kt +++ b/android/truapi-host/src/main/kotlin/io/parity/truapi/TrUAPIHost.kt @@ -106,6 +106,10 @@ import uniffi.truapi.ProductExecutionConfig import uniffi.truapi.HostContactLookup import uniffi.truapi.HostContactMatches import uniffi.truapi.HostContactPick +import uniffi.truapi.ContactSelection +import uniffi.truapi.HostContactsPick +import uniffi.truapi.PlacedContactLabels +import uniffi.truapi.HostContactsPlaceLabelsException import uniffi.truapi.NativeContactsCallbacks import uniffi.truapi.SsoRequestOutcome import uniffi.truapi.HostScan @@ -894,6 +898,17 @@ interface ContactsHostBridge { */ @Throws(HostRejection::class) suspend fun pickContact(productId: String): HostContactPick + + /** Edit the complete audience; cancelling does not confirm an empty one. */ + @Throws(HostRejection::class) + suspend fun pickContacts(productId: String, selection: ContactSelection): HostContactsPick = + HostContactsPick.Unsupported + + /** Replace names on the host surface without exposing them to products. */ + @Throws(HostContactsPlaceLabelsException::class) + suspend fun placeContactLabels(productId: String, placed: PlacedContactLabels) { + throw HostContactsPlaceLabelsException.Unsupported() + } } private class ContactsCallbackAdapter(private val bridge: ContactsHostBridge) : NativeContactsCallbacks { @@ -902,6 +917,19 @@ private class ContactsCallbackAdapter(private val bridge: ContactsHostBridge) : override suspend fun pickContact(productId: String): HostContactPick = withHostRejection { bridge.pickContact(productId) } + + override suspend fun pickContacts(productId: String, selection: ContactSelection): HostContactsPick = + withHostRejection { bridge.pickContacts(productId, selection) } + + override suspend fun placeContactLabels(productId: String, placed: PlacedContactLabels) { + try { + bridge.placeContactLabels(productId, placed) + } catch (error: HostContactsPlaceLabelsException) { + throw error + } catch (error: Throwable) { + throw HostContactsPlaceLabelsException.Unknown("contact label callback failed") + } + } } /** diff --git a/docs/rfcs/contacts-api.md b/docs/rfcs/contacts-api.md index 81364c6098..36fac6f24c 100644 --- a/docs/rfcs/contacts-api.md +++ b/docs/rfcs/contacts-api.md @@ -11,10 +11,11 @@ status: draft _How the implemented pieces fit together is in [Contacts Pick, End to End](../design/contacts-pick-end-to-end.md)._ -A product asks the Host to let the user pick a contact. The Host renders an overlay from its Chat -workers' chat lists, the user selects one person, and the product receives one opaque handle — never -the list, a name, or an account. The handle is not an address: the core resolves it when building a -transaction. +A product asks the Host to let the user pick one or more contacts. The Host renders the +picker from its contact directory and returns opaque handles, never the list, names or +accounts. The handle is not an address: the core resolves it when building a transaction. +Host-owned name labels let users recognize selected handles without sharing the names +or requiring a Profile photo. ## Motivation @@ -49,12 +50,34 @@ names it as the recipient and the core substitutes the account when it builds th product-scoped address is not derivable at all, which is why the handle is resolvable rather than directly usable. +### Multi-select audiences + +Trait 20 method 0 remains `pick`. Method 1, `pickMany({ selected })`, edits a complete +selection of at most 256 handles. The core deduplicates and resolves the initial +selection before opening the picker; any unresolved handle rejects the whole request. +The host callback `pickContacts(product, ContactSelection { selected })` receives +accounts only inside the trusted host boundary. Confirming an empty selection returns +`Picked { handles: [] }`; closing the picker returns `Dismissed`. Session or directory +invalidation during resolution or confirmation cancels the change. + +### Host-owned contact labels + +Method 2, `placeLabels({ surfaceWidth, surfaceHeight, slots })`, replaces at most 256 +name rectangles. Each slot supplies `{ slot, handle, rect, clip }`, reusing `AvatarRect`. +The host resolves handles and draws directory usernames, or account fallbacks, on its +own layer. Names do not depend on Profile disclosure. Missing contacts leave no label +and produce the same success response; products never receive names or availability. +Surfaces and rectangle sides are bounded to 16384 units, clip sides may be zero, and +slot ids must be unique. Empty slots, connection teardown and session changes clear +the layer. On same-wallet directory invalidation, the host clears stale names and +refreshes the latest live placement without another product request. + + ## Trade-offs - A host that serves no picker answers `Unsupported`, which a product cannot retry its way out of. - `NoContacts` reveals whether the user has any contacts — zero-or-not, never a count. -- No product-rendered contact UI, every selection is a user interaction, one contact per call, - read-only. +- No product-rendered contact directory: every selection is a host-owned user interaction. - Dropped: returning the list scoped per product (`display_name` was a correlator no scoping fixed, and it needed a permission over the whole social graph); per-product handles (forfeit a durable shared id, break under contact sync); returning the chat account (transactable, but a global @@ -67,11 +90,9 @@ A product declares the handles its call names, on the transaction payload, and t Substitution happens before the confirmation, so the signing overlay is drawn from a call that names an account the Host can put a name to. That is what closes the display gap for the flow that matters: a product renders a neutral chip, and the user sees who they are paying in trusted UI at the moment of consent. -## Open questions +## Recognition outside signing -How a product shows the user which contact they picked outside a signature. A product holds 32 bytes and no name, so it -renders a neutral chip. Two parts close that, and neither is specified here: the Host redraws the name -in its own signing confirmation, which knows the account and is where consent is given, so a product -never needs the name for the flow to be safe; and a product labels the handle itself, letting the user -name those 32 bytes once. A user-supplied label keeps the Host from handing back the correlator that -ruled out `display_name`. +A product holds only handles and reserves rectangles for `placeLabels`. The host +draws names in those rectangles without returning a global correlator. Profile avatar +slots remain separate and photo-only, so users can recognize a contact even when that +contact has never shared a profile. diff --git a/docs/rfcs/profile-disclosure.md b/docs/rfcs/profile-disclosure.md new file mode 100644 index 0000000000..1eb0bc29ba --- /dev/null +++ b/docs/rfcs/profile-disclosure.md @@ -0,0 +1,274 @@ +--- +title: "Profile disclosure to chat contacts" +owner: "@corey-hathaway" +status: draft +--- + +# RFC — Profile disclosure to chat contacts + +## Summary + +A product hands the host one opaque profile reference and an audience policy. The host relays app-scoped grants or +personal grants to selected Contacts handles over authenticated Chat v2 channels, and keeps received references +inside the host. An app-scoped grant is renderable in that app; a personal grant is renderable across apps on the +recipient's host. Products request host-owned drawers and avatar overlays by peer identity or opaque handle, never +receive another user's reference, and cannot inspect the host's rendering. + +## Motivation + +`profile.present` shows a profile from a reference the calling product already holds. A chat product has no honest way +to hold one for a contact: the reference is a bearer capability, so a product that carries it can read, keep and forward +the profile, and can show any reference against any contact. The reference has to travel host to host and stay inside +the hosts, and Chat v2 leaves ordinary delivery to products. + +## Requirements + +- **Blind:** products may retain selected opaque handles, but receive no contact names, accounts or contact enumeration. +- **Sealed:** no product reads a reference in transit or at rest, on either side. +- **Bound:** a presented profile is the one that contact's host sent, not one a product chose. +- **Stable:** a change to the referenced profile does not require relaying again. +- **Withdrawable:** narrowing an audience withdraws its grant; recipients stop rendering it once the withdrawal arrives. +- **Unobservable:** a product that shows contacts' avatars cannot tell which contacts shared a profile. + +## Approach + +The design has six parts: + +- The `Profile` trait gains `disclose`, `retract`, `present_contact` and `place_contact_avatars`. +- `disclose` asks the user once per product before anything is stored. +- Core storage holds the user's disclosure, app-scoped received references and wallet-wide personal received references. +- The Chat v2 actor relays disclosures through its host-private outbox. +- `present_contact` hands the host the stored reference and the contact who sent it. +- `place_contact_avatars` substitutes stored references into a host-drawn avatar layer. + +### Trait + +`Profile` uses wire trait **69**. This change preserves that address and the existing method IDs. + +| Method | ID | Request versions | +| --- | --- | --- | +| `present` | 0 | V1: reference supplied by the caller | +| `disclose` | 1 | V1: reference; V2: reference plus audiences | +| `retract` | 2 | V1 | +| `present_contact` | 3 | V1: peer identity; V2: peer or Contacts handle | +| `place_contact_avatars` | 4 | V1: peer slots; V2: optional own slot; V3: peer/handle slots plus own | +| `own_status` | 5 | V1 | +| `present_own` | 6 | V1 | + +The canonical payloads are in `truapi::latest`; wire envelopes are in `truapi::versioned::profile`. +The new audience and selector shapes are: + +```rust +pub enum ProfileAudience { + ChatApps, + App { product_id: String }, + Contacts { handles: Vec }, +} +pub struct HostProfileDiscloseRequest { + pub reference: String, + pub audiences: Vec, +} +pub enum ProfileContact { + Peer { peer_identity: [u8; 32] }, + Handle { handle: ContactHandle }, +} +pub struct HostProfilePresentContactRequest { + pub contact: ProfileContact, +} +pub struct ContactAvatarSlot { + pub slot: u32, + pub contact: ProfileContact, + pub rect: AvatarRect, + pub clip: AvatarRect, +} +``` + +V1 disclosure maps to `ChatApps`: app-scoped sharing with ready peers of each Chat app, not a wallet-wide personal +grant. `App` selects one normalized product ID. `Contacts` selects personal recipients by opaque handle. A request may +combine these; an empty list retains the own profile without granting delivery. Calls replace the previous audience +policy. At most 64 audience entries and 4096 handles are accepted; duplicates are coalesced. + +The core resolves handles using the same verified Contacts lookup as transaction recipient substitution, rehashes +returned accounts, and rejects the entire disclosure if any handle is invalid or the session/cache generation changes. +It never guesses a translation between a payment account, device key and Chat root identity: a resolved account must +exactly match an authenticated ready peer identity. A Contacts entry does not establish such a channel. + +Seity groups can be sets of handles whose union is passed as `Contacts`. Group names, labels and membership editing +are not host Profile state. Handles are stable pseudonyms across apps and hosts for one user, not unlinkable identities. + +### Consent + +The first `disclose` from a product raises `UserConfirmationReview::ProfileDisclosure { product_id }` through the host's +`confirm_permission`, beside `ChatAuthority`; the answer is remembered per product as +`PermissionAuthorizationRequest::ProfileDisclosure`. A refusal is `PermissionDenied` with nothing stored. +The current review authorizes the disclosing product, not each audience mutation. A product must explain the difference +between sharing inside an app and personal sharing across apps; audience-specific host consent remains a rollout +question. `retract` never asks: it withdraws all grants of the current disclosure. + +### Storage + +Three secret core-storage slots are scoped to the signed-in wallet and People network: + +- `ProfileDisclosure { root_public_key, genesis_hash }`: discloser, reference, audience policy and durable revision. + Retraction retains a revision tombstone, so the next share cannot reuse an older sequence after restart. +- `ProfileReferencesReceived { root_public_key, genesis_hash, product_id }`: app-scoped received grants and withdrawals. +- `ProfilePersonalReferencesReceived { root_public_key, genesis_hash }`: personal received grants and withdrawals, + shared across recipient apps but isolated from other wallets and networks. + +Legacy disclosure and watermark records migrate to app-scoped behavior, never to personal grants. A live app-specific +reference takes precedence over a personal one. An app withdrawal removes only that grant, allowing a personal grant +to remain visible; a personal withdrawal leaves app grants intact. + +### Relay + +App grants retain Chat v2 content **21**, `ProfileReference { discloser_product_id, reference: Option }`, byte for byte. +Personal grants use distinct content **22**, with validated personal scope byte **1**, a nonzero durable disclosure +revision, the disclosing product and optional reference. `None` withdraws in that scope only. +The Chat actor seals frames to ready peer devices through the host-private outbox. The product submits opaque +ciphertext, cannot prepare profile content itself, and receives no profile content in opened history. +Per-peer, per-scope watermarks track shares, replacements and withdrawals. Personal frames are addressed only to selected +resolved accounts. Frames from compacted history are dropped. + +A Chat actor publishes: + +- when the chat product initializes; +- at the start of each reconcile, which heals any trigger that was missed; +- after any Chat request in which a peer became ready, such as the acknowledgement that completes a device handover, so + that request's response already carries the reference; +- when `disclose` or `retract` changes the disclosure while the chat is open. The core stores the change, answers the + call, and asks every open Chat actor of the same wallet and network, whatever its product, to publish on a task of its + own, so the call never waits on it. + +A wallet/network profile-state gate serializes disclosure replacement, publication and received-store updates. +Without a new disclosure and with nothing lapsed, publication reads the disclosure and checks watermarks. +Narrowing an audience removes obsolete unsent frames, even for peers that are no longer ready, and retains withdrawal +watermarks for later delivery. Already returned signed frames cannot be recalled. +A device-roster change also supersedes pending profile statements before they are returned to the product. Watermarks +retain the roster revision, so a ready replacement device receives a freshly sealed frame even when the disclosure +itself did not change. Legacy watermarks inherit the pending statement's roster, or the snapshot's current peer roster +when already delivered. Public profile request ids are salted with the actor's private secret, not a guessable reference +digest. + +App frames retain timestamp ordering. Personal frames use the durable disclosure revision across actors: independent +app clocks must not allow an old share to undo a newer withdrawal. Received withdrawals remain tombstones, so replaying +an older share cannot restore it after the newer withdrawal has been received. +Live profile frames accompanying a compacted-history import are recorded before the history delivery receipt is +committed. A failed profile write therefore remains retryable instead of permanently skipping a grant or withdrawal. + +Delivery is best effort. References share the existing bounded profile outbox budget, with separate entries per peer +and scope, and never take slots reserved for payments or rich files. A frame that finds no room waits for a later +publish. An unacknowledged frame lapsing after one statement lifetime is signed again for a ready peer, up to three +frames per scope and disclosure; a new disclosure starts a fresh count. Hosts predating a content type reject it and +never acknowledge it. Migration retains existing app watermarks and pending withdrawals. + +The host only prepares statements: the chat product submits them. A publish outside the product's own requests, after +`disclose` or `retract`, queues the reference while the chat actor is open, and it reaches the contact once the chat +product next runs and submits what its responses offer. + +A reference may name a mutable record. Every `disclose`, even with an unchanged reference, advances the durable +revision and starts a new round for the selected recipients with fresh attempt counts. Initialize, reconcile and +readiness-triggered publishes do not resend a round already delivered. A pre-revision disclosure reads as revision 0 +and preserves its legacy app digest, so migration alone does not broaden or resend it. + +### Presentation + +V1 `present_contact` reads only the caller's app-scoped grant and preserves its existing errors. It cannot probe personal +grants through `NotShared`. V2 accepts a peer or verified Contacts handle, selects the live app grant then personal +fallback, and answers uniformly for an absent, unknown or unreadable profile, including host drawing failures. +Neither path returns the reference. The core calls +`ProfilePlatform::present_contact_profile(product, PresentedContactProfile { shared, peer_identity, username })`. +`shared` is `Some(SharedContactProfile { reference, shared_at })` for a live reference and `None` for a genuinely absent +or retracted V2 reference. The host opens friendly empty-profile feedback for `None`, without claiming that unreadable +storage or an invalid reference means nothing was shared. `shared_at` is a frame freshness timestamp; personal grants +advance it monotonically even when a newer revision arrives from an actor with an older clock. `username` is the host's +own name for the contact, never one from +the product: the name the calling product's Chat roster holds for +that peer, verified when the contact was bound or first authenticated, else the peer's verified dotNS name. The core +waits at most 2 seconds for it and passes `None` when it knows none, so a slow directory never holds the drawer back; the +host then names the contact generically, never by address. The default can call `present_profile` for a shared reference; +empty-profile feedback requires the contact presenter. The core rechecks the wallet and handle generation before either +presentation, so a late lookup cannot open another wallet's contact. + +### Provenance + +The host stores a received reference only when it arrives over the authenticated Chat v2 channel from that peer's own +device, so when `present_contact` opens the drawer the host knows who sent it: it can say "shared with you by +over Chat" and name that contact, not the product that asked. That is all it guarantees. The contacts record behind the +reference is not signed by its owner, so the reference proves who delivered it, not whose profile it is: a contact can +forward another person's reference as their own. Nor can copies be erased: a reference is a bearer capability, so +whoever received it, directly or forwarded, keeps it and what it resolved; a retraction only stops a receiving host from +presenting it. + +`own_status` reports only whether the signed-in wallet has a current disclosure. `present_own` resolves that disclosure +and hands it to the same host presenter. Neither method returns the reference or profile contents to the product. +Both reads retain the authority session selected before storage access and recheck it before answering or presenting, +so a wallet switch during a delayed read cannot report or open the preceding wallet's profile. + +### Placed avatars + +A chat product draws its own conversation list and header, so only it knows where each contact's avatar sits. It sends +`place_contact_avatars` with its surface size and, per avatar, a slot id, the contact's peer identity, the circle's +square bounding box and the region it is cut to, in surface units. Each call replaces the product's placement. + +The core keeps only slots with an effective live app or personal reference, withdrawals excluded, and hands them to +`ProfilePlatform::place_contact_avatars(product, PlacedAvatars { surface_width, surface_height, avatars })`. +Each avatar carries `shared_at`, a monotonically advancing freshness timestamp within its grant scope. A newer value +for the same reference means the host should drop cached profile contents. The host draws each photo and mood ring, when +they have one, on a layer over the product that lets pointer input through; a tap still reaches the product, which +opens the profile with `present_contact`. The default callback draws nothing, so a host draws avatars only once it +implements it. +Every placement, including raw-peer and own-avatar slots, retains its authority session. The core rechecks that session +after asynchronous profile reads and before drawing. Session changes clear and forget stationary placements; a queued +clear from an older session cannot erase a placement submitted by the new session. + +The core remembers the last placement per product connection, in memory. When a reference for that product arrives, is +re-shared in a newer frame or is withdrawn it filters the same geometry again and calls the host again, so avatars appear and disappear without the +product sending anything. Disposing the connection, or a placement made after the user signed out, clears what the host +drew. + +Version 2 of `place_contact_avatars` adds an optional `own` slot for where the product draws the signed-in user's own +avatar. The core fills it from the wallet's current disclosure, with `shared_at` set to the disclosure's revision, and +hands it to the host in the same `PlacedAvatars` set as the contact avatars, so one placement never replaces another's +overlay. Slot ids are unique across `own` and the contact slots. Disclosing or retracting redraws every remembered +placement for that wallet, as a contact's reference change does. A version 1 placement is one with no own slot. + +Version 3 retains the own slot and accepts `ProfileContact` selectors for contact slots. V1/V2 requests and replies +remain compatible. Handle placements revalidate the session and Contacts cache generation on redraw. +`notifyContactsChanged` clears stale handle resolution and clears the old overlay before resolving it again, so +removed handles cannot leave old avatars visible. Personal receives and withdrawals refresh all wallet placements. +Removing a Contacts entry invalidates lookup but does not itself edit an already approved disclosure's recipient set. + +No leak: the product must not learn who shared a profile. The core answers `Ok` to any well-formed placement from a +signed-in user however many avatars, if any, are drawn; it returns nothing per slot, logs nothing about slots, and +treats a host drawing failure as success, since it could depend on which avatars were drawn. Only what the product +itself controls is refused: more than 64 slots, a surface side outside 1 to 16384, an avatar that is not square or is +outside 1 to 1024 a side, or a repeated slot id. The one host answer passed on is `Unsupported`, a property of the host +rather than of any contact. Nothing drawn is posted back to the product; the host renders it where the product cannot +read it. + +## Trade-offs + +- One reference is shared by all audiences. A narrower audience withdraws rendering only for the removed grants; + overlapping grants remain effective. It cannot invalidate copies of the bearer reference. +- A retraction cannot make a contact's host forget a reference it already resolved. +- The watermark advances when the message is queued. A message that never arrives is sent again only when it lapses + unacknowledged, three frames at most per disclosure and recipient roster revision. A changed roster restarts delivery + to the current devices; without a disclosure or roster change, a contact that misses all three is not sent it again. +- The chat product must run to submit what the host prepares. A disclosure changed while no chat product runs is relayed + when one next initializes. +- The host layer covers the product's own drawing, so a product that animates or scrolls between placements shows the + avatar a frame late; the product re-sends its placement when the list moves. +- Dropped: carrying the reference in ordinary chat content, which puts a bearer capability in product hands. + +## Open questions + +- Chat content indices 21 (app) and 22 (personal) require coordination with native Chat before rollout. +- Several disclosing products. There is one `ProfileDisclosure` slot, so the last product to disclose replaces the + others and the earlier one can no longer retract. The alternative is one slot per product, with the host relaying the + one from a product the user designates, as RFC 0024 designates a personhood provider. +- Consent covers the product, not each audience mutation: once allowed, a product may replace its disclosure without + asking. Selected-contact and cross-app personal-sharing review must be agreed with the host Contacts owner. +- Devices. Only the host that took `disclose` knows the disclosure, so contacts that reach the user's other devices are + not sent it. +- Resolution. Hosts parse references today; a shared resolver in the core would need the reference format specified here + rather than by the publishing product. diff --git a/hosts/android/README.md b/hosts/android/README.md index 7426b79aca..b02b5f8018 100644 --- a/hosts/android/README.md +++ b/hosts/android/README.md @@ -224,6 +224,13 @@ revocations write to the shared Rust authorization store, not an Android-only grant. These operations obtain consent through the canonical runtime confirmation flow; the legacy permission guard only observes their stored authorization. +Profile sharing is a separate canonical permission, displayed and revocable per +product in settings. Neither Chat identity access nor trusted remote defaults +grant profile-disclosure authority. The native confirmation identifies the +requesting product and asks before sharing a profile reference with all Chat +contacts. Permission and single-action callbacks both await user review; prompt +failures propagate rather than becoming a persisted permission decision. + GitHub Actions validate pull requests. The remaining workflows are the maintainers' own build and distribution flows; a fork does not need them. Build-time configuration and the steps to sign and publish the app are documented in diff --git a/hosts/android/bindings/truapi-host/src/androidTest/kotlin/io/parity/truapi/InertHostBridge.kt b/hosts/android/bindings/truapi-host/src/androidTest/kotlin/io/parity/truapi/InertHostBridge.kt index 6ebdbd897a..a29f3fff0d 100644 --- a/hosts/android/bindings/truapi-host/src/androidTest/kotlin/io/parity/truapi/InertHostBridge.kt +++ b/hosts/android/bindings/truapi-host/src/androidTest/kotlin/io/parity/truapi/InertHostBridge.kt @@ -20,6 +20,8 @@ class InertHostBridge( context.getSharedPreferences("truapi_inert_bridge_core", Context.MODE_PRIVATE), ) + override fun permissionAuthorizationsChanged(productId: String) = Unit + override suspend fun navigateTo(url: String) = Unit override suspend fun devicePermission( diff --git a/hosts/android/common/src/main/res/values/strings.xml b/hosts/android/common/src/main/res/values/strings.xml index 6daebbdfb3..8af9302e99 100644 --- a/hosts/android/common/src/main/res/values/strings.xml +++ b/hosts/android/common/src/main/res/values/strings.xml @@ -851,6 +851,9 @@ Chat identity access %1$s wants to use your Chat identity Bind and use your wallet-held Chat identity. Revoking access prevents this product from using that authority. + Profile sharing + %1$s wants to share your profile with your Chat contacts + Share a reference to your profile with all your Chat contacts so they can read it. This permission is separate from Chat identity access. Statement Store allowance — %1$s %1$s wants to ensure Statement Store quota Ensure existing Statement Store quota for this account, without increasing it. This does not grant statement submission permission. @@ -979,6 +982,7 @@ Create proof? Share your identity? Allow Chat identity access? + Share your profile with all your Chat contacts so they can read it? Allocate resources? Submit preimage? Approve main-purse payment? diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/CanonicalProductPermissions.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/CanonicalProductPermissions.kt index b0691e571e..f4b1f65084 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/CanonicalProductPermissions.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/CanonicalProductPermissions.kt @@ -17,6 +17,7 @@ internal fun ProductPermission.canonicalRequest(): PermissionAuthorizationReques ProductPermission.BalanceAccess -> null ProductPermission.UserIdentityAccess -> PermissionAuthorizationRequest.IdentityDisclosure ProductPermission.ChatAuthority -> PermissionAuthorizationRequest.ChatAuthority + ProductPermission.ProfileDisclosure -> PermissionAuthorizationRequest.ProfileDisclosure is ProductPermission.StatementStoreAllowance -> PermissionAuthorizationRequest.StatementStoreAllowance( when (val selector = derivationIndex) { null -> null @@ -36,11 +37,13 @@ internal fun ProductPermission.canonicalRequest(): PermissionAuthorizationReques })) } +/** `null` for a cross-product signature approval, which the core keeps per execution and never lists. */ internal fun PermissionAuthorizationRequest.legacyPermission(): ProductPermission? = when (this) { is PermissionAuthorizationRequest.Device -> ProductPermission.DeviceCapability(DeviceCapabilityType.entries.single { it.native() == v1 }) is PermissionAuthorizationRequest.AccountAccess -> ProductPermission.AccountAccess(targetProductId) PermissionAuthorizationRequest.IdentityDisclosure -> ProductPermission.UserIdentityAccess PermissionAuthorizationRequest.ChatAuthority -> ProductPermission.ChatAuthority + PermissionAuthorizationRequest.ProfileDisclosure -> ProductPermission.ProfileDisclosure is PermissionAuthorizationRequest.StatementStoreAllowance -> ProductPermission.StatementStoreAllowance( when (val selector = derivationIndex) { null -> null @@ -48,7 +51,6 @@ internal fun PermissionAuthorizationRequest.legacyPermission(): ProductPermissio is DerivationIndex.Raw -> AllowanceAccountSelector.Raw(selector.v1.toDataByteArray()) } ) - is PermissionAuthorizationRequest.CrossProductSignature -> null is PermissionAuthorizationRequest.Remote -> when (val remote = v1.permission) { is RemotePermission.Remote -> { val domains = remote.domains.map(::canonicalDomain).distinct().sorted() @@ -61,6 +63,7 @@ internal fun PermissionAuthorizationRequest.legacyPermission(): ProductPermissio RemotePermission.StatementSubmit -> ProductPermission.RemotePermission.StatementSubmitAccess RemotePermission.PreimageSubmit -> ProductPermission.RemotePermission.PreimageSubmitAccess } + is PermissionAuthorizationRequest.CrossProductSignature -> null } private fun DeviceCapabilityType.native(): HostDevicePermissionRequest = when (this) { diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionGuard.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionGuard.kt index d252ce6c16..4ca24989d0 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionGuard.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionGuard.kt @@ -94,7 +94,10 @@ class RealProductPermissionGuard @Inject constructor( } override suspend fun consumePermission(productId: ProductId, permission: ProductPermission): Boolean { - if (permission == ProductPermission.ChatAuthority || permission is ProductPermission.StatementStoreAllowance) { + if (permission == ProductPermission.ChatAuthority || + permission == ProductPermission.ProfileDisclosure || + permission is ProductPermission.StatementStoreAllowance + ) { return check(productId, permission) } if (repository.consumeOneTimeGrant(productId, permission)) return true @@ -111,7 +114,10 @@ class RealProductPermissionGuard @Inject constructor( } override suspend fun check(productId: ProductId, permission: ProductPermission): Boolean { - if (permission == ProductPermission.ChatAuthority || permission is ProductPermission.StatementStoreAllowance) { + if (permission == ProductPermission.ChatAuthority || + permission == ProductPermission.ProfileDisclosure || + permission is ProductPermission.StatementStoreAllowance + ) { return repository.isGranted(productId, permission) } if (repository.isDenied(productId, permission)) return false @@ -124,6 +130,7 @@ class RealProductPermissionGuard @Inject constructor( is ProductPermission.DeviceCapability -> deviceCapabilityHandler.isGranted(productId, permission) is ProductPermission.UserIdentityAccess -> userIdentityAccessHandler.isGranted(productId, permission) ProductPermission.ChatAuthority, + ProductPermission.ProfileDisclosure, is ProductPermission.StatementStoreAllowance -> repository.isGranted(productId, permission) } } @@ -147,6 +154,7 @@ class RealProductPermissionGuard @Inject constructor( // These operations prompt through the canonical runtime's confirmation flow. // The legacy guard may observe authority, but must not issue a local grant. ProductPermission.ChatAuthority, + ProductPermission.ProfileDisclosure, is ProductPermission.StatementStoreAllowance -> repository.isGranted(productId, permission) } } diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/models/ProductPermission.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/models/ProductPermission.kt index bb884cb326..9085d5f660 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/models/ProductPermission.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/models/ProductPermission.kt @@ -95,6 +95,12 @@ sealed interface ProductPermission { override val key: String get() = "" } + data object ProfileDisclosure : ProductPermission { + const val TYPE_NAME = "profile_disclosure" + override val typeName: String get() = TYPE_NAME + override val key: String get() = "" + } + /** Null is the legacy allowance account, not product account zero. */ data class StatementStoreAllowance(val derivationIndex: AllowanceAccountSelector?) : ProductPermission { override val typeName: String get() = TYPE_NAME @@ -117,6 +123,7 @@ sealed interface ProductPermission { BalanceAccess.TYPE_NAME -> BalanceAccess UserIdentityAccess.TYPE_NAME -> UserIdentityAccess ChatAuthority.TYPE_NAME -> ChatAuthority + ProfileDisclosure.TYPE_NAME -> ProfileDisclosure StatementStoreAllowance.TYPE_NAME -> StatementStoreAllowance( when { key == "legacy" -> null diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMapping.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMapping.kt index de162b2707..ac89150571 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMapping.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMapping.kt @@ -101,6 +101,9 @@ fun UserConfirmationReview.toConfirmation(callingProductId: String): TrUAPIConfi is UserConfirmationReview.ProductSubtree -> TrUAPIConfirmation.ProductSubtree(requesterProductId = v1.productId) + + is UserConfirmationReview.ProfileDisclosure -> + TrUAPIConfirmation.ProfileDisclosure(requesterProductId = v1.productId) } @OptIn(ExperimentalStdlibApi::class) diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridge.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridge.kt index 5681ee5459..7a5e457fc3 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridge.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridge.kt @@ -223,6 +223,9 @@ class ProductTrUAPIHostBridge @AssistedInject constructor( override suspend fun confirmUserAction(review: UserConfirmationReview): Boolean = confirmationLauncher.decide(review, requesterFallback = callingProductId.value) + override suspend fun confirmPermission(review: UserConfirmationReview): TrUAPIPermissionDecision = + confirmationLauncher.decidePermission(review, requesterFallback = callingProductId.value) + override suspend fun devicePermission( product: ProductExecutionConfig, request: HostDevicePermissionRequest, @@ -433,6 +436,18 @@ internal suspend fun TrUAPIConfirmationLauncher.decide( return awaitDecision(confirmation) } +/** Only an explicit user answer becomes authority; mapping and prompt failures propagate. */ +internal suspend fun TrUAPIConfirmationLauncher.decidePermission( + review: UserConfirmationReview, + requesterFallback: String, +): TrUAPIPermissionDecision { + return if (awaitDecision(review.toConfirmation(requesterFallback))) { + TrUAPIPermissionDecision.ALLOW_ALWAYS + } else { + TrUAPIPermissionDecision.DENY + } +} + // Reports the theme name the native host's `themeSubscribe` already sends, so a // product reads the same theme on either runtime. private fun ProductTheme.toNativeTheme(): HostThemeSubscribeItem = HostThemeSubscribeItem( diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIConfirmation.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIConfirmation.kt index 1e757bfdc1..cafee15ea8 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIConfirmation.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIConfirmation.kt @@ -57,6 +57,11 @@ sealed interface TrUAPIConfirmation { override val requesterProductId: String, ) : TrUAPIConfirmation.Prompt + /** Share a profile reference with the user's Chat contacts. */ + class ProfileDisclosure( + override val requesterProductId: String, + ) : TrUAPIConfirmation.Prompt + /** Allocate host resources to the product. */ class ResourceAllocation( override val requesterProductId: String, diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIHostRuntimeProvider.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIHostRuntimeProvider.kt index 6d21972465..50ddb32419 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIHostRuntimeProvider.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/TrUAPIHostRuntimeProvider.kt @@ -258,6 +258,9 @@ class TrUAPIHostRuntimeProvider @Inject constructor( override suspend fun confirmUserAction(review: UserConfirmationReview): Boolean = confirmationLauncher.decide(review, requesterFallback = HOST_REQUESTER) + override suspend fun confirmPermission(review: UserConfirmationReview): PermissionDecision = + confirmationLauncher.decidePermission(review, requesterFallback = HOST_REQUESTER) + override suspend fun featureSupported(request: HostFeatureSupportedRequest): Boolean = when (request) { is HostFeatureSupportedRequest.Chain -> cachedChains.get().canDial(request.genesisHash) diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/permissionPrompt/compose/PermissionMapping.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/permissionPrompt/compose/PermissionMapping.kt index 1680499fda..fa20299ca3 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/permissionPrompt/compose/PermissionMapping.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/permissionPrompt/compose/PermissionMapping.kt @@ -30,6 +30,7 @@ internal val ProductPermission.icon: ImageVector is ProductPermission.BalanceAccess -> NovaIcons.Dollar is ProductPermission.UserIdentityAccess -> NovaIcons.PeopleOutline ProductPermission.ChatAuthority -> NovaIcons.PeopleOutline + ProductPermission.ProfileDisclosure -> NovaIcons.PeopleOutline is ProductPermission.StatementStoreAllowance -> NovaIcons.CloudOn is ProductPermission.RemotePermission.NetworkAccess -> NovaIcons.WiFi is ProductPermission.RemotePermission.NetworkAccessSet -> NovaIcons.WiFi @@ -59,6 +60,7 @@ internal fun ProductPermission.title(productId: String): String { is ProductPermission.BalanceAccess -> stringResource(RCommon.string.product_permission_balance_title, productId) is ProductPermission.UserIdentityAccess -> stringResource(RCommon.string.product_permission_user_identity_title, productId) ProductPermission.ChatAuthority -> stringResource(RCommon.string.product_permission_chat_authority_title, productId) + ProductPermission.ProfileDisclosure -> stringResource(RCommon.string.product_permission_profile_disclosure_title, productId) is ProductPermission.StatementStoreAllowance -> stringResource(RCommon.string.product_permission_allowance_title, productId) is ProductPermission.DeviceCapability -> capability.title(productId) is ProductPermission.RemotePermission.NetworkAccess -> stringResource(RCommon.string.product_permission_network_title, productId, domain) @@ -94,6 +96,7 @@ internal fun ProductPermission.subtitle(): String { is ProductPermission.BalanceAccess -> stringResource(RCommon.string.product_permission_balance_subtitle, manageLater) is ProductPermission.UserIdentityAccess -> stringResource(RCommon.string.product_permission_user_identity_subtitle, manageLater) ProductPermission.ChatAuthority -> stringResource(RCommon.string.product_permission_chat_authority_description) + ProductPermission.ProfileDisclosure -> stringResource(RCommon.string.product_permission_profile_disclosure_description) is ProductPermission.StatementStoreAllowance -> stringResource(RCommon.string.product_permission_allowance_description) is ProductPermission.DeviceCapability -> capability.subtitle(manageLater) is ProductPermission.RemotePermission.NetworkAccess -> stringResource(RCommon.string.product_permission_network_subtitle, manageLater) diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/productPermissions/compose/components/ProductPermissionItem.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/productPermissions/compose/components/ProductPermissionItem.kt index 769185bd05..02c7e141ea 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/productPermissions/compose/components/ProductPermissionItem.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/productPermissions/compose/components/ProductPermissionItem.kt @@ -61,6 +61,7 @@ private fun ProductPermission.displayName(): String { is ProductPermission.BalanceAccess -> stringResource(RCommon.string.product_permission_type_balance_access) is ProductPermission.UserIdentityAccess -> stringResource(RCommon.string.product_permission_type_user_identity_access) ProductPermission.ChatAuthority -> stringResource(RCommon.string.product_permission_type_chat_authority) + ProductPermission.ProfileDisclosure -> stringResource(RCommon.string.product_permission_type_profile_disclosure) is ProductPermission.StatementStoreAllowance -> { val account = when (val selector = derivationIndex) { null -> stringResource(RCommon.string.product_permission_allowance_legacy_account) @@ -103,6 +104,7 @@ private fun ProductPermission.descriptionRes(): Int = when (this) { is ProductPermission.BalanceAccess -> RCommon.string.product_permission_type_balance_access_description is ProductPermission.UserIdentityAccess -> RCommon.string.product_permission_type_user_identity_access_description ProductPermission.ChatAuthority -> RCommon.string.product_permission_chat_authority_description + ProductPermission.ProfileDisclosure -> RCommon.string.product_permission_profile_disclosure_description is ProductPermission.StatementStoreAllowance -> RCommon.string.product_permission_allowance_description is ProductPermission.RemotePermission.NetworkAccess -> RCommon.string.product_permission_type_network_access is ProductPermission.RemotePermission.NetworkAccessSet -> RCommon.string.product_permission_type_network_access diff --git a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/truapiConfirm/TrUAPIConfirmationUiMapping.kt b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/truapiConfirm/TrUAPIConfirmationUiMapping.kt index 73e0767c48..3d71c9365b 100644 --- a/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/truapiConfirm/TrUAPIConfirmationUiMapping.kt +++ b/hosts/android/feature/products/impl/src/main/java/io/paritytech/polkadotapp/feature_products_impl/presentation/truapiConfirm/TrUAPIConfirmationUiMapping.kt @@ -36,6 +36,10 @@ fun TrUAPIConfirmation.Prompt.toUiState(): TrUAPIConfirmationUiState = when (thi RCommon.string.truapi_confirm_title_chat_authority, ) + is TrUAPIConfirmation.ProfileDisclosure -> build( + RCommon.string.truapi_confirm_title_profile_disclosure, + ) + is TrUAPIConfirmation.ResourceAllocation -> build( RCommon.string.truapi_confirm_title_resource_allocation, *resources.map { detail(RCommon.string.truapi_confirm_label_resource, it) }.toTypedArray(), diff --git a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionRepositoryTest.kt b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionRepositoryTest.kt index 5fd5d372b7..c62bec964d 100644 --- a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionRepositoryTest.kt +++ b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/ProductPermissionRepositoryTest.kt @@ -48,12 +48,13 @@ class ProductPermissionRepositoryTest { fun `feature permissions preserve canonical tags bytes and local keys`() { val requests = listOf( PermissionAuthorizationRequest.ChatAuthority, + PermissionAuthorizationRequest.ProfileDisclosure, PermissionAuthorizationRequest.StatementStoreAllowance(null), PermissionAuthorizationRequest.StatementStoreAllowance(DerivationIndex.Index(0u)), PermissionAuthorizationRequest.StatementStoreAllowance(DerivationIndex.Index(UInt.MAX_VALUE)), PermissionAuthorizationRequest.StatementStoreAllowance(DerivationIndex.Raw(ByteArray(32) { it.toByte() })), ) - val permissions = requests.map { it.legacyPermission() } + val permissions = requests.map { requireNotNull(it.legacyPermission()) } assertEquals(requests.size, permissions.toSet().size) permissions.forEach { permission -> val restored = ProductPermission.fromLocal(permission.typeName, permission.key) @@ -61,7 +62,7 @@ class ProductPermissionRepositoryTest { assertEquals(permission.hashCode(), restored.hashCode()) assertEquals(permission, restored.canonicalRequest()!!.legacyPermission()) } - assertEquals(requests.take(4), permissions.take(4).map { it.canonicalRequest() }) + assertEquals(requests.dropLast(1), permissions.dropLast(1).map { it.canonicalRequest() }) val raw = permissions.last().canonicalRequest() as PermissionAuthorizationRequest.StatementStoreAllowance assertArrayEquals(ByteArray(32) { it.toByte() }, (raw.derivationIndex as DerivationIndex.Raw).v1) assertTrue(runCatching { ProductPermission.fromLocal("statement_store_allowance", "raw:0x01") }.isFailure) @@ -74,6 +75,7 @@ class ProductPermissionRepositoryTest { val f = Fixture() val permissions = listOf( ProductPermission.ChatAuthority, + ProductPermission.ProfileDisclosure, ProductPermission.StatementStoreAllowance(null), ProductPermission.StatementStoreAllowance(AllowanceAccountSelector.Index(0u)), ProductPermission.StatementStoreAllowance(AllowanceAccountSelector.Raw(ByteArray(32) { it.toByte() }.toDataByteArray())), @@ -97,6 +99,35 @@ class ProductPermissionRepositoryTest { coVerify(exactly = 0) { f.dao.insert(any()) } } + @Test + fun `profile disclosure is not implied by Chat allowance or trusted remote grants`() = runTest { + val f = Fixture() + val profile = ProductPermission.ProfileDisclosure + assertEquals("profile_disclosure", profile.typeName) + assertEquals("", profile.key) + val independent = listOf( + ProductPermission.ChatAuthority, + ProductPermission.StatementStoreAllowance(null), + ProductPermission.StatementStoreAllowance(AllowanceAccountSelector.Index(0u)), + ProductPermission.StatementStoreAllowance(AllowanceAccountSelector.Raw(ByteArray(32).toDataByteArray())), + ProductPermission.RemotePermission.NetworkAccess("*"), + ProductPermission.RemotePermission.WebRtcAccess, + ProductPermission.RemotePermission.ChainSubmitAccess, + ProductPermission.RemotePermission.StatementSubmitAccess, + ProductPermission.RemotePermission.PreimageSubmitAccess, + ) + independent.forEach { f.saved(product)[it.canonicalRequest()!!] = authorized } + f.saved(other)[profile.canonicalRequest()!!] = authorized + + assertFalse(f.repository.isGranted(product, profile)) + assertFalse(f.repository.isDenied(product, profile)) + assertTrue(f.repository.isGranted(other, profile)) + f.saved(product)[profile.canonicalRequest()!!] = denied + assertFalse(f.repository.isGranted(product, profile)) + assertTrue(f.repository.isDenied(product, profile)) + assertTrue(independent.all { f.repository.isGranted(product, it) }) + } + @Test fun `old native grants and legacy-only rows are visible and canonical deny wins migration`() = runTest { val f = Fixture() diff --git a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/RealProductPermissionGuardTest.kt b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/RealProductPermissionGuardTest.kt index af5b77ee9b..6465d84bcb 100644 --- a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/RealProductPermissionGuardTest.kt +++ b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/permissions/RealProductPermissionGuardTest.kt @@ -52,9 +52,15 @@ class RealProductPermissionGuardTest { @Test fun `canonical feature authority never uses local one-time grants or legacy prompts`() = runBlocking { - val permissions = listOf(ProductPermission.ChatAuthority, ProductPermission.StatementStoreAllowance(null)) + val permissions = listOf( + ProductPermission.ChatAuthority, + ProductPermission.ProfileDisclosure, + ProductPermission.StatementStoreAllowance(null), + ) coEvery { repository.hasOneTimeGrant(any(), any()) } returns true coEvery { repository.consumeOneTimeGrant(any(), any()) } returns true + whenever(remoteHandler.isGranted(any(), any())).thenReturn(true) + whenever(remoteHandler.request(any(), any())).thenReturn(true) for (feature in permissions) { coEvery { repository.isGranted(productId, feature) } returns false assertFalse(guard.check(productId, feature)) @@ -68,6 +74,9 @@ class RealProductPermissionGuardTest { coVerify(exactly = 0) { repository.grant(any(), any()) } coVerify(exactly = 0) { repository.grantOneTime(any(), any()) } coVerify(exactly = 0) { repository.consumeOneTimeGrant(any(), any()) } + coVerify(exactly = 0) { repository.hasOneTimeGrant(any(), any()) } + verify(remoteHandler, never()).isGranted(any(), any()) + verify(remoteHandler, never()).request(any(), any()) } @Test diff --git a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMappingTest.kt b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMappingTest.kt index 704914f1d7..e285fc5e45 100644 --- a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMappingTest.kt +++ b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ConfirmationReviewMappingTest.kt @@ -5,6 +5,8 @@ import io.paritytech.polkadotapp.feature_account_api.domain.derivation.Derivatio import io.paritytech.polkadotapp.feature_products_api.model.ProductAccountId import io.paritytech.polkadotapp.feature_products_api.model.signing.RawPayloadContent import io.paritytech.polkadotapp.feature_products_api.model.signing.SigningRequestBody +import io.paritytech.polkadotapp.feature_products_impl.presentation.truapiConfirm.toUiState +import io.paritytech.polkadotapp.common.R as RCommon import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertThrows @@ -27,6 +29,7 @@ import uniffi.truapi.CreateTransactionReview import uniffi.truapi.IdentityDisclosureReview import uniffi.truapi.PreimageSubmitReview import uniffi.truapi.ProductSubtreeReview +import uniffi.truapi.ProfileDisclosureReview import uniffi.truapi.ResourceAllocationReview import uniffi.truapi.SignPayloadReview import uniffi.truapi.SignRawReview @@ -308,6 +311,19 @@ class ConfirmationReviewMappingTest { assertEquals("discloser.dot", confirmation.requesterProductId) } + @Test + fun `profile disclosure identifies the reviewed product and renders its own prompt`() { + val review = UserConfirmationReview.ProfileDisclosure( + ProfileDisclosureReview(productId = "seity.paseo"), + ) + + val confirmation = review.toConfirmation(caller) as TrUAPIConfirmation.ProfileDisclosure + assertEquals("seity.paseo", confirmation.requesterProductId) + val ui = confirmation.toUiState() + assertEquals("seity.paseo", ui.productId) + assertEquals(RCommon.string.truapi_confirm_title_profile_disclosure, ui.titleRes) + } + @Test fun `preimage submit carries its size`() { val review = UserConfirmationReview.PreimageSubmit(PreimageSubmitReview(size = 4096uL)) diff --git a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridgeTest.kt b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridgeTest.kt index 72436543b8..50cff16568 100644 --- a/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridgeTest.kt +++ b/hosts/android/feature/products/impl/src/test/java/io/paritytech/polkadotapp/feature_products_impl/domain/truapi/ProductTrUAPIHostBridgeTest.kt @@ -1,7 +1,14 @@ package io.paritytech.polkadotapp.feature_products_impl.domain.truapi import android.content.Context +import uniffi.truapi.AccountAccessReview +import uniffi.truapi.PermissionDecision +import uniffi.truapi.ProfileDisclosureReview +import uniffi.truapi.UserConfirmationReview import dagger.Lazy +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.mockk import io.paritytech.polkadotapp.feature_products_impl.domain.permissions.PermissionAuthorizationChanges import io.paritytech.polkadotapp.feature_products_impl.domain.permissions.ProductPermissionRepository import io.paritytech.polkadotapp.feature_settings_api.domain.language.AppLanguageProvider @@ -18,12 +25,16 @@ import io.paritytech.polkadotapp.feature_products_impl.domain.hostApi.navigation import io.paritytech.polkadotapp.feature_products_impl.domain.pocket.PocketCardStore import io.paritytech.polkadotapp.feature_products_impl.presentation.spaHost.ExpandedCardFace import io.paritytech.polkadotapp.test_shared.whenever +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import okhttp3.OkHttpClient import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.fail import org.junit.Assert.assertTrue import org.junit.Test import org.mockito.Mockito.mock @@ -39,11 +50,13 @@ class ProductTrUAPIHostBridgeTest { private val gameReminder = mock(ProductGameReminder::class.java) private val game = ProductId.fromStoredValue("game.dot") - private fun TestScope.bridge() = ProductTrUAPIHostBridge( + private fun TestScope.bridge( + launcher: TrUAPIConfirmationLauncher = mock(TrUAPIConfirmationLauncher::class.java), + ) = ProductTrUAPIHostBridge( hostApiInteractor = mock(HostApiInteractor::class.java), chainHttpClient = OkHttpClient(), encryptedPreferences = mock(EncryptedPreferences::class.java), - confirmationLauncher = mock(TrUAPIConfirmationLauncher::class.java), + confirmationLauncher = launcher, appLifecycleObserver = mock(AppLifecycleObserver::class.java), dotNsTldProvider = mock(DotNsTldProvider::class.java), pocketCardStore = mock(PocketCardStore::class.java), @@ -72,6 +85,92 @@ class ProductTrUAPIHostBridgeTest { assertTrue(outcome.isFailure) } + private suspend fun TestScope.callbacks(launcher: TrUAPIConfirmationLauncher): HostBridge { + var callbacks: HostBridge? = null + val runtime = mock(TrUAPIHostRuntime::class.java, Answer { invocation -> + callbacks = invocation.arguments.filterIsInstance().single() + throw IllegalStateException("captured callbacks without opening a native execution") + }) + val outcome = bridge(launcher).attach( + runtime = runtime, + productId = ProductId.fromStoredValue("game.dot"), + chains = EMPTY_CHAINS, + navigationPolicy = NavigationPolicy.DeeplinkNavigation(onDeeplinkNavigation = {}), + kind = ProductExecutionKind.APP, + onPermissionRevoked = {}, + onReadyToInject = {}, + ) + assertTrue(outcome.isFailure) + return checkNotNull(callbacks) + } + + @Test + fun `profile permission and action callbacks await explicit review without optimistic approval`() = runTest { + val review = UserConfirmationReview.ProfileDisclosure(ProfileDisclosureReview("seity.paseo")) + for (permissionCallback in listOf(true, false)) { + for (approved in listOf(true, false)) { + val launcher = mockk() + val prompted = CompletableDeferred() + val answer = CompletableDeferred() + coEvery { launcher.awaitDecision(any()) } coAnswers { + prompted.complete(firstArg()) + answer.await() + } + val callbacks = callbacks(launcher) + val pending = async { + if (permissionCallback) callbacks.confirmPermission(review) else callbacks.confirmUserAction(review) + } + + val confirmation = prompted.await() as TrUAPIConfirmation.ProfileDisclosure + assertEquals("seity.paseo", confirmation.requesterProductId) + assertFalse(pending.isCompleted) + answer.complete(approved) + val expected: Any = if (permissionCallback) { + if (approved) PermissionDecision.ALLOW_ALWAYS else PermissionDecision.DENY + } else { + approved + } + assertEquals(expected, pending.await()) + coVerify(exactly = 1) { launcher.awaitDecision(any()) } + } + } + } + + @Test + fun `profile prompt failure propagates rather than becoming a durable permission decision`() = runTest { + val launcher = mockk() + coEvery { launcher.awaitDecision(any()) } throws HostRejection.Rejected("review unavailable") + val callbacks = callbacks(launcher) + val review = UserConfirmationReview.ProfileDisclosure(ProfileDisclosureReview("seity.paseo")) + + try { + callbacks.confirmPermission(review) + fail("A failed prompt must not return a permission decision") + } catch (failure: HostRejection.Rejected) { + assertEquals("review unavailable", failure.reason) + } + coVerify(exactly = 1) { launcher.awaitDecision(any()) } + } + + @Test + fun `supported permission preserves explicit approval and denial through product callbacks`() = runTest { + val review = UserConfirmationReview.AccountAccess(AccountAccessReview("game.dot", "target.dot")) + for (approved in listOf(true, false)) { + val prompts = mutableListOf() + val launcher = mockk() + coEvery { launcher.awaitDecision(capture(prompts)) } returns approved + val callbacks = callbacks(launcher) + + assertEquals( + if (approved) PermissionDecision.ALLOW_ALWAYS else PermissionDecision.DENY, + callbacks.confirmPermission(review), + ) + val prompt = prompts.single() as TrUAPIConfirmation.AccountAccess + assertEquals("game.dot", prompt.requesterProductId) + assertEquals("target.dot", prompt.targetProductId) + } + } + private suspend fun TestScope.attachCapturingBridge(card: ExpandedCardFace?): HostBridge { var opened: HostBridge? = null val runtime = mock(TrUAPIHostRuntime::class.java, Answer { invocation -> diff --git a/hosts/ios/Packages/Products/Sources/Products/Permissions/Guard/ProductPermissionGuard.swift b/hosts/ios/Packages/Products/Sources/Products/Permissions/Guard/ProductPermissionGuard.swift index 3122bbbe79..9d35d2645e 100644 --- a/hosts/ios/Packages/Products/Sources/Products/Permissions/Guard/ProductPermissionGuard.swift +++ b/hosts/ios/Packages/Products/Sources/Products/Permissions/Guard/ProductPermissionGuard.swift @@ -80,6 +80,7 @@ public final class ProductPermissionGuard: ProductPermissionGuarding, @unchecked .statementSubmitAccess, .userIdentityAccess, .chatAuthority, + .profileDisclosure, .statementStoreAllowance: try await remoteHandler.request(productId: productId, permission: permission) } @@ -171,6 +172,7 @@ public final class ProductPermissionGuard: ProductPermissionGuarding, @unchecked .statementSubmitAccess, .userIdentityAccess, .chatAuthority, + .profileDisclosure, .statementStoreAllowance: try await remoteHandler.isGranted(productId: productId, permission: permission) } diff --git a/hosts/ios/Packages/Products/Sources/Products/Permissions/Model/ProductPermission.swift b/hosts/ios/Packages/Products/Sources/Products/Permissions/Model/ProductPermission.swift index 832e74cfe6..e1d1e3e6d9 100644 --- a/hosts/ios/Packages/Products/Sources/Products/Permissions/Model/ProductPermission.swift +++ b/hosts/ios/Packages/Products/Sources/Products/Permissions/Model/ProductPermission.swift @@ -15,6 +15,7 @@ public enum ProductPermission: Equatable, Sendable { public static let statementSubmitAccessTypeName = "statement_submit" public static let userIdentityAccessTypeName = "user_identity_access" public static let chatAuthorityTypeName = "chat_authority" + public static let profileDisclosureTypeName = "profile_disclosure" public static let statementStoreAllowanceTypeName = "statement_store_allowance" case deviceCapability(DeviceCapabilityType) @@ -29,6 +30,7 @@ public enum ProductPermission: Equatable, Sendable { case statementSubmitAccess case userIdentityAccess case chatAuthority + case profileDisclosure /// `nil` is the legacy allowance account, distinct from every product selector. case statementStoreAllowance(derivationIndex: ProductAccountSelector?) @@ -37,9 +39,9 @@ public enum ProductPermission: Equatable, Sendable { /// /// The distinction exists because the core grants a first-party product /// every remote permission without prompting, and nothing else. Device - /// capabilities, account access, balance, identity disclosure, Chat authority - /// and Statement Store allowance always prompt, whoever asks, so they must not ride along on - /// that trust. + /// capabilities, account access, balance, identity disclosure, Chat authority, + /// profile disclosure and Statement Store allowance always prompt, whoever asks, + /// so they must not ride along on that trust. public var isRemoteAccess: Bool { switch self { case .networkAccess, @@ -50,7 +52,7 @@ public enum ProductPermission: Equatable, Sendable { .statementSubmitAccess: true case .deviceCapability, .accountAccess, .balanceAccess, .userIdentityAccess, - .chatAuthority, .statementStoreAllowance: + .chatAuthority, .profileDisclosure, .statementStoreAllowance: false } } @@ -79,6 +81,8 @@ public enum ProductPermission: Equatable, Sendable { Self.userIdentityAccessTypeName case .chatAuthority: Self.chatAuthorityTypeName + case .profileDisclosure: + Self.profileDisclosureTypeName case .statementStoreAllowance: Self.statementStoreAllowanceTypeName } @@ -109,7 +113,8 @@ public enum ProductPermission: Equatable, Sendable { .preimageSubmitAccess, .statementSubmitAccess, .userIdentityAccess, - .chatAuthority: + .chatAuthority, + .profileDisclosure: "" } } @@ -141,6 +146,8 @@ public enum ProductPermission: Equatable, Sendable { return .userIdentityAccess case chatAuthorityTypeName: return .chatAuthority + case profileDisclosureTypeName: + return .profileDisclosure case statementStoreAllowanceTypeName: if key == "legacy" { return .statementStoreAllowance(derivationIndex: nil) diff --git a/hosts/ios/Packages/Products/Tests/ProductsTests/TrustedRemoteProductPermissionRequesterTests.swift b/hosts/ios/Packages/Products/Tests/ProductsTests/TrustedRemoteProductPermissionRequesterTests.swift index 1d4d6ae675..423103a651 100644 --- a/hosts/ios/Packages/Products/Tests/ProductsTests/TrustedRemoteProductPermissionRequesterTests.swift +++ b/hosts/ios/Packages/Products/Tests/ProductsTests/TrustedRemoteProductPermissionRequesterTests.swift @@ -52,6 +52,7 @@ struct TrustedRemoteProductPermissionRequesterTests { .balanceAccess, .userIdentityAccess, .chatAuthority, + .profileDisclosure, .statementStoreAllowance(derivationIndex: nil), .statementStoreAllowance(derivationIndex: .index(7)), .statementStoreAllowance(derivationIndex: .raw(Data(repeating: 9, count: 32))) @@ -107,6 +108,17 @@ struct TrustedRemoteProductPermissionRequesterTests { #expect(wrapped.promptBatchedCalls.count == 1) } + @Test("Trusted remote batches cannot implicitly grant profile disclosure") + func profileDisclosureInRemoteBatchStillPrompts() async { + let (sut, wrapped) = makeSUT() + let decision = await sut.promptBatched( + productId: trusted, + permissions: Self.remotePermissions + [.profileDisclosure] + ) + #expect(decision == .deny) + #expect(wrapped.promptBatchedCalls.count == 1) + } + @Test("An empty batch asks for nothing and is not granted") func anEmptyBatchIsNotGranted() async { let (sut, wrapped) = makeSUT() diff --git a/hosts/ios/README.md b/hosts/ios/README.md index 09c3aa974a..0aedfacf24 100644 --- a/hosts/ios/README.md +++ b/hosts/ios/README.md @@ -35,6 +35,20 @@ If you experience problems with any product or service that was built on or depl - **Manual backups** — Keep your account stored only in the secure enclave storage locally. - **Customization** — Fully customizable UI design system with 5 default themes. +### Native profile permission settings + +Profile sharing is a separate, product-scoped permission, not part of Chat +identity authority or trusted outbound network access. Native settings enumerate +its canonical grant or denial and revoke that exact permission; the persisted +`profile_disclosure` case has an empty key. Revocation invalidates pending consent +and one-time grants without changing another product's authority. A failed write +leaves the existing settings row and authority intact. + +Profile disclosure reviews use the native permission prompt and preserve explicit +allow-once, allow-always and deny choices. Missing presentation or cancellation +throws instead of recording a user denial. Runtime/session consent checks remain +authoritative. + ## Getting started For the in-tree Host build and Chat product, follow the @@ -125,6 +139,7 @@ Consent prompts and app settings share permission descriptions and icon metadata - There is no custodian, and nobody (including the developers) can freeze, recover, or move your account. If you lose your device and have no backup, the account is gone. - It does **not** route your chats and calls through any 1st or 3rd party messaging servers — messages travel through the public chain, voice and video calls go peer-to-peer. - It is **not** a production-hardened product — treat it as a reference implementation (see the warning at the top). +- Seity profile-disclosure consent has no native prompt yet. Its permission callback returns an error, leaving an unanswered authorization `NotDetermined` rather than recording a user denial. Single-action confirmation still fails closed. ### Under the hood diff --git a/hosts/ios/polkadot-app/Common/Storage/UserDataModel.xcdatamodeld/.xccurrentversion b/hosts/ios/polkadot-app/Common/Storage/UserDataModel.xcdatamodeld/.xccurrentversion index 8f3453851d..00ca9e5b86 100644 --- a/hosts/ios/polkadot-app/Common/Storage/UserDataModel.xcdatamodeld/.xccurrentversion +++ b/hosts/ios/polkadot-app/Common/Storage/UserDataModel.xcdatamodeld/.xccurrentversion @@ -3,6 +3,6 @@ _XCCurrentVersionName - UserDataModel54.xcdatamodel + UserDataModel55.xcdatamodel diff --git a/hosts/ios/polkadot-app/Common/Storage/UserDataModel.xcdatamodeld/UserDataModel55.xcdatamodel/contents b/hosts/ios/polkadot-app/Common/Storage/UserDataModel.xcdatamodeld/UserDataModel55.xcdatamodel/contents new file mode 100644 index 0000000000..65276a4fec --- /dev/null +++ b/hosts/ios/polkadot-app/Common/Storage/UserDataModel.xcdatamodeld/UserDataModel55.xcdatamodel/contents @@ -0,0 +1,409 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hosts/ios/polkadot-app/Common/Storage/UserDataStorageFacade.swift b/hosts/ios/polkadot-app/Common/Storage/UserDataStorageFacade.swift index 3b42b80ffc..9c3e61e8f0 100644 --- a/hosts/ios/polkadot-app/Common/Storage/UserDataStorageFacade.swift +++ b/hosts/ios/polkadot-app/Common/Storage/UserDataStorageFacade.swift @@ -14,7 +14,7 @@ enum UserStorageParams { /// and implement migration policy; /// - update mappings between CoreData Entities and App Models; /// - switch version of UserStorageParams.modelVersion; - static let modelVersion: UserStorageVersion = .version54 + static let modelVersion: UserStorageVersion = .version55 static let modelDirectory: String = "UserDataModel.momd" static let databaseName = "UserDataModel_v3.sqlite" diff --git a/hosts/ios/polkadot-app/Localization/Products.xcstrings b/hosts/ios/polkadot-app/Localization/Products.xcstrings index 513601dbdd..7bd3082573 100644 --- a/hosts/ios/polkadot-app/Localization/Products.xcstrings +++ b/hosts/ios/polkadot-app/Localization/Products.xcstrings @@ -276,6 +276,23 @@ } } }, + "app.permission.profileDisclosure.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Profile sharing" + } + }, + "es-ES": { + "stringUnit": { + "state": "translated", + "value": "Compartir perfil" + } + } + } + }, "app.permission.chatAuthority.title": { "extractionState": "manual", "localizations": { @@ -601,6 +618,23 @@ } } }, + "permission.body.profileDisclosure": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Allows this product to share a reference to your profile with every Chat contact. Contacts who receive it can read your profile." + } + }, + "es-ES": { + "stringUnit": { + "state": "translated", + "value": "Permite que este producto comparta una referencia a tu perfil con todos tus contactos de Chat. Los contactos que la reciban podrán leer tu perfil." + } + } + } + }, "permission.body.chatAuthority": { "extractionState": "manual", "localizations": { @@ -860,6 +894,23 @@ } } }, + "permission.title.profileDisclosure": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%1$(productId)@ would like to share your profile" + } + }, + "es-ES": { + "stringUnit": { + "state": "translated", + "value": "%1$(productId)@ quiere compartir tu perfil" + } + } + } + }, "permission.title.chatAuthority": { "extractionState": "manual", "localizations": { diff --git a/hosts/ios/polkadot-app/Modules/Products/Permissions/Repository/ProductPermissionRepository.swift b/hosts/ios/polkadot-app/Modules/Products/Permissions/Repository/ProductPermissionRepository.swift index 6bfea7a2a3..01b2f5c327 100644 --- a/hosts/ios/polkadot-app/Modules/Products/Permissions/Repository/ProductPermissionRepository.swift +++ b/hosts/ios/polkadot-app/Modules/Products/Permissions/Repository/ProductPermissionRepository.swift @@ -379,6 +379,8 @@ extension ProductPermission { return .identityDisclosure case .chatAuthority: return .chatAuthority + case .profileDisclosure: + return .profileDisclosure case let .statementStoreAllowance(derivationIndex): return .statementStoreAllowance(derivationIndex: try derivationIndex.map(Self.authorizationSelector)) case .balanceAccess: @@ -433,11 +435,14 @@ extension ProductPermission { return [.userIdentityAccess] case .chatAuthority: return [.chatAuthority] + case .profileDisclosure: + return [.profileDisclosure] case let .statementStoreAllowance(derivationIndex): return [try .statementStoreAllowance(derivationIndex: derivationIndex?.toSelector())] case let .accountAccess(targetProductId): return [.accountAccess(targetProductId: bareProductLabel(targetProductId))] case .crossProductSignature: + // The core keeps these per execution and never lists them. return [] } } diff --git a/hosts/ios/polkadot-app/Modules/Products/ProductPermissionPrompt/ProductPermissionPromptViewFactory.swift b/hosts/ios/polkadot-app/Modules/Products/ProductPermissionPrompt/ProductPermissionPromptViewFactory.swift index 6d40425840..8b723bccc3 100644 --- a/hosts/ios/polkadot-app/Modules/Products/ProductPermissionPrompt/ProductPermissionPromptViewFactory.swift +++ b/hosts/ios/polkadot-app/Modules/Products/ProductPermissionPrompt/ProductPermissionPromptViewFactory.swift @@ -94,6 +94,8 @@ private extension ProductPermissionPromptViewFactory { title = String(localized: .Products.permissionTitleRemote(productId: productId)) case .chatAuthority: title = String(localized: .Products.permissionTitleChatAuthority(productId: productId)) + case .profileDisclosure: + title = String(localized: .Products.permissionTitleProfileDisclosure(productId: productId)) case .statementStoreAllowance: title = String(localized: .Products.permissionTitleStatementStoreAllowance(productId: productId)) } diff --git a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/Confirmation/TrUAPIReviewPromptMapper.swift b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/Confirmation/TrUAPIReviewPromptMapper.swift index 5e45ea75b0..34ec3e1c3c 100644 --- a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/Confirmation/TrUAPIReviewPromptMapper.swift +++ b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/Confirmation/TrUAPIReviewPromptMapper.swift @@ -21,6 +21,7 @@ struct TrUAPIAllowanceRequest: Equatable { protocol TrUAPIReviewPromptMapping: Sendable { func makePermissionRequest(from review: IdentityDisclosureReview) -> TrUAPIPermissionRequest func makePermissionRequest(from review: ChatAuthorityReview) -> TrUAPIPermissionRequest + func makePermissionRequest(from review: ProfileDisclosureReview) -> TrUAPIPermissionRequest func makeActionRequest(from review: PreimageSubmitReview, requester: ProductId) -> TrUAPIActionConfirmationRequest func makePermissionRequest(from review: AccountAccessReview) -> TrUAPIPermissionRequest func makeActionRequest(from review: ProductSubtreeReview) -> TrUAPIActionConfirmationRequest @@ -48,6 +49,13 @@ struct TrUAPIReviewPromptMapper: TrUAPIReviewPromptMapping { ) } + func makePermissionRequest(from review: ProfileDisclosureReview) -> TrUAPIPermissionRequest { + TrUAPIPermissionRequest( + productId: review.productId, + permissions: [.profileDisclosure] + ) + } + func makeActionRequest( from review: PreimageSubmitReview, requester: ProductId diff --git a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustHostRuntimeBridge.swift b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustHostRuntimeBridge.swift index 0c157ba6e4..fae3a57102 100644 --- a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustHostRuntimeBridge.swift +++ b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustHostRuntimeBridge.swift @@ -141,7 +141,7 @@ final class RustHostRuntimeBridge: HostBridge, @unchecked Sendable { } func confirmPermission(review: UserConfirmationReview) async throws -> TrUAPIPermissionDecision { - await confirmationPresenter.confirmPermission(review: review, from: "host") + try await confirmationPresenter.confirmPermission(review: review, from: "host") } func identityUsernameCandidates(username: String, peopleChainGenesisHash: Data) async throws -> [Data] { diff --git a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustProductExecutionBridge.swift b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustProductExecutionBridge.swift index 4f086c799d..104e43c9f0 100644 --- a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustProductExecutionBridge.swift +++ b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/RustProductExecutionBridge.swift @@ -180,7 +180,7 @@ class RustProductExecutionBridge: HostBridge, @unchecked Sendable { } func confirmPermission(review: UserConfirmationReview) async throws -> TrUAPIPermissionDecision { - await dependencies.confirmationPresenter.confirmPermission(review: review, from: dependencies.productId) + try await dependencies.confirmationPresenter.confirmPermission(review: review, from: dependencies.productId) } func chainConnect(genesisHash: Data) throws -> UInt32? { diff --git a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/TrUAPIConfirmationPresenter.swift b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/TrUAPIConfirmationPresenter.swift index 5b232eacfe..adf98e6118 100644 --- a/hosts/ios/polkadot-app/Modules/Products/TrUAPI/TrUAPIConfirmationPresenter.swift +++ b/hosts/ios/polkadot-app/Modules/Products/TrUAPI/TrUAPIConfirmationPresenter.swift @@ -12,15 +12,15 @@ protocol TrUAPIConfirmationPresenting: Sendable { func confirmPermission( review: UserConfirmationReview, from requesterName: String - ) async -> TrUAPIPermissionDecision + ) async throws -> TrUAPIPermissionDecision } /// Routes core-reviewed actions to the native confirmation surfaces exposed /// through `ProductRoutersFacadeProtocol`, keyed off the typed /// `UserConfirmationReview` so the full payload reaches each prompt. /// Cancellation-aware: the rust core dropping its future (e.g. the product -/// closed mid-prompt) denies immediately; an already presented prompt -/// stays up and its late decision is discarded. +/// closed mid-prompt) rejects immediately (throws for permission decisions); +/// an already presented prompt stays up and its late decision is discarded. final class TrUAPIConfirmationPresenter: TrUAPIConfirmationPresenting, @unchecked Sendable { private let routerFacade: ProductRoutersFacadeProtocol private let promptMapper: TrUAPIReviewPromptMapping @@ -55,24 +55,28 @@ final class TrUAPIConfirmationPresenter: TrUAPIConfirmationPresenting, @unchecke func confirmPermission( review: UserConfirmationReview, from _: String - ) async -> TrUAPIPermissionDecision { + ) async throws -> TrUAPIPermissionDecision { switch review { case let .identityDisclosure(identityReview): - await presentPermission( + try await presentPermission( promptMapper.makePermissionRequest(from: identityReview) ) case let .accountAccess(accessReview): - await presentPermission( + try await presentPermission( promptMapper.makePermissionRequest(from: accessReview) ) case let .accountAlias(aliasReview): - await presentPermission( + try await presentPermission( promptMapper.makePermissionRequest(from: aliasReview) ) case let .chatAuthority(chatReview): - await presentPermission( + try await presentPermission( promptMapper.makePermissionRequest(from: chatReview) ) + case let .profileDisclosure(profileReview): + try await presentPermission( + promptMapper.makePermissionRequest(from: profileReview) + ) default: .deny } @@ -98,11 +102,13 @@ private extension TrUAPIConfirmationPresenter { ) case let .productSubtree(subtreeReview): await confirmAction(promptMapper.makeActionRequest(from: subtreeReview)) + // Unsupported permission reviews throw; `confirm` still fails closed for single actions. case .identityDisclosure, .chatAuthority, .accountAccess, - .accountAlias: - await confirmPermission(review: review, from: requesterName) != .deny + .accountAlias, + .profileDisclosure: + try await confirmPermission(review: review, from: requesterName) != .deny case let .createProof(proofReview): try await confirmCreateProof( promptMapper.makeCreateProofRequest(from: proofReview) @@ -172,19 +178,30 @@ private extension TrUAPIConfirmationPresenter { } } - func presentPermission(_ request: TrUAPIPermissionRequest) async -> TrUAPIPermissionDecision { - await awaitDecision(cancelled: .deny) { [routerFacade] in + func presentPermission(_ request: TrUAPIPermissionRequest) async throws -> TrUAPIPermissionDecision { + let result: Result = await awaitDecision( + cancelled: .failure(.Rejected(reason: "permission prompt cancelled")) + ) { [routerFacade] in + var presented = false let decision: Products.PermissionDecision = await withCheckedContinuation { continuation in let context = ProductPermissionContext( productId: request.productId, permissions: request.permissions ) context.setContinuation(continuation) - routerFacade.productsRouter.showPrompt(context: context) + let prompt = ProductPermissionPromptViewFactory.createView(context: context) + presented = routerFacade.productsRouter.present(view: prompt) + if !presented { + // Resolve the UI continuation without turning failure into a user denial. + context.deliver(.deny) + } } - - return decision.hostDecision + guard presented else { + return .failure(.Rejected(reason: "permission prompt presentation unavailable")) + } + return .success(decision.hostDecision) } + return try result.get() } func confirmAction(_ request: TrUAPIActionConfirmationRequest) async -> Bool { @@ -259,7 +276,7 @@ private extension TrUAPIConfirmationPresenter { /// Resume-once state for one confirmation. All mutable state is /// MainActor-confined; a cancellation racing ahead of `begin` resolves the -/// incoming continuation with denial instead of leaking it. +/// incoming continuation with its cancellation result instead of leaking it. @MainActor private final class PendingDecision { private var isFinished = false diff --git a/hosts/ios/polkadot-app/Modules/Settings/Apps/Permissions/Helpers/AppPermissionsViewModelFactory.swift b/hosts/ios/polkadot-app/Modules/Settings/Apps/Permissions/Helpers/AppPermissionsViewModelFactory.swift index 278b7d8841..fcacdf910b 100644 --- a/hosts/ios/polkadot-app/Modules/Settings/Apps/Permissions/Helpers/AppPermissionsViewModelFactory.swift +++ b/hosts/ios/polkadot-app/Modules/Settings/Apps/Permissions/Helpers/AppPermissionsViewModelFactory.swift @@ -41,6 +41,7 @@ extension ProductPermission { case .statementSubmitAccess: String(localized: .Products.permissionBodyStatementSubmit) case .userIdentityAccess: String(localized: .Products.permissionBodyUserIdentityAccess) case .chatAuthority: String(localized: .Products.permissionBodyChatAuthority) + case .profileDisclosure: String(localized: .Products.permissionBodyProfileDisclosure) case let .statementStoreAllowance(derivationIndex): ProductPermission.statementStoreAllowanceDescription(derivationIndex: derivationIndex) } @@ -58,6 +59,7 @@ extension ProductPermission { case .statementSubmitAccess: "text.bubble" case .userIdentityAccess: "person.text.rectangle" case .chatAuthority: "message.badge.shield" + case .profileDisclosure: "person.crop.square" case .statementStoreAllowance: "externaldrive.badge.plus" } } @@ -74,6 +76,7 @@ extension ProductPermission { case .statementSubmitAccess: String(localized: .Products.appPermissionStatementSubmitTitle) case .userIdentityAccess: String(localized: .Products.appPermissionUserIdentityTitle) case .chatAuthority: String(localized: .Products.appPermissionChatAuthorityTitle) + case .profileDisclosure: String(localized: .Products.appPermissionProfileDisclosureTitle) case .statementStoreAllowance: String(localized: .Products.appPermissionStatementStoreAllowanceTitle) } } diff --git a/hosts/ios/polkadot-appTests/Products/ProductPermissionRepositoryTests.swift b/hosts/ios/polkadot-appTests/Products/ProductPermissionRepositoryTests.swift index c3c17b9a34..b678c60747 100644 --- a/hosts/ios/polkadot-appTests/Products/ProductPermissionRepositoryTests.swift +++ b/hosts/ios/polkadot-appTests/Products/ProductPermissionRepositoryTests.swift @@ -670,6 +670,7 @@ extension ProductPermissionRepositoryTests { private static var featureRequests: [PermissionAuthorizationRequest] { [ .chatAuthority, + .profileDisclosure, .statementStoreAllowance(derivationIndex: nil), .statementStoreAllowance(derivationIndex: .index(0)), .statementStoreAllowance(derivationIndex: .index(UInt32.max)), @@ -678,10 +679,12 @@ extension ProductPermissionRepositoryTests { ] } - @Test("Chat and every allowance selector round-trip without changing canonical authority") + @Test("Chat, profile disclosure and every allowance selector round-trip without changing canonical authority") func featurePermissionRoundTrips() throws { #expect(ProductPermission.chatAuthority.typeName == "chat_authority") #expect(ProductPermission.chatAuthority.key == "") + #expect(ProductPermission.profileDisclosure.typeName == "profile_disclosure") + #expect(ProductPermission.profileDisclosure.key == "") #expect(ProductPermission.statementStoreAllowance(derivationIndex: nil).typeName == "statement_store_allowance") #expect(ProductPermission.statementStoreAllowance(derivationIndex: nil).key == "legacy") #expect(ProductPermission.statementStoreAllowance(derivationIndex: .index(0)).key == "index:0") @@ -828,4 +831,48 @@ extension ProductPermissionRepositoryTests { } #expect(try await repository.getAllByProduct(productId: "chat.paseo").count == permissions.count) } + + @Test("Profile prompt decisions remain separate from Chat and other products", + arguments: [Products.PermissionDecision.allowAlways, .allowOnce, .deny]) + func profilePromptDecisions(decision: Products.PermissionDecision) async throws { + let authority = PermissionAuthorityFixture() + let repository = ProductPermissionRepository(storageFacade: UserDataStorageTestFacade(), authority: { authority }) + try await repository.grant(productId: "profile.paseo", permission: .chatAuthority) + #expect(try await repository.getPermissionState(productId: "profile.paseo", permission: .profileDisclosure) == .notDetermined) + let requester = PermissionPromptFixture(decision: decision, whilePrompting: {}) + #expect(try await repository.promptPermission( + productId: "profile.paseo", permission: .profileDisclosure, requester: requester + ) == (decision != .deny)) + let entries = try await authority.permissionAuthorizations(productId: "profile.paseo") + let status = entries.first { $0.request == .profileDisclosure }?.status ?? .notDetermined + switch decision { + case .allowAlways: + #expect(status == .authorized) + case .allowOnce: + #expect(status == .notDetermined) + #expect(repository.consumeOneTimeGrant(productId: "profile.paseo", permission: .profileDisclosure)) + #expect(!repository.consumeOneTimeGrant(productId: "profile.paseo", permission: .profileDisclosure)) + case .deny: + #expect(status == .denied) + } + #expect(try await repository.getPermissionState(productId: "profile.paseo", permission: .chatAuthority) == .allowedAlways) + #expect(try await repository.getPermissionState(productId: "other.paseo", permission: .profileDisclosure) == .notDetermined) + } + + @Test("Profile revocation fences pending consent", + arguments: [Products.PermissionDecision.allowAlways, .allowOnce]) + func pendingProfilePromptCannotResurrect(decision: Products.PermissionDecision) async throws { + let authority = PermissionAuthorityFixture() + let storage = UserDataStorageTestFacade() + let reader = ProductPermissionRepository(storageFacade: storage, authority: { authority }) + let settings = ProductPermissionRepository(storageFacade: storage, authority: { authority }) + let requester = PermissionPromptFixture(decision: decision) { + try await settings.revoke(productId: "profile.paseo", permission: .profileDisclosure) + } + #expect(try await reader.promptPermission( + productId: "profile.paseo", permission: .profileDisclosure, requester: requester + ) == false) + #expect(try await reader.getPermissionState(productId: "profile.paseo", permission: .profileDisclosure) == .notDetermined) + #expect(!reader.consumeOneTimeGrant(productId: "profile.paseo", permission: .profileDisclosure)) + } } diff --git a/hosts/ios/polkadot-appTests/TrUAPI/RustHostRuntimeBridgeTests.swift b/hosts/ios/polkadot-appTests/TrUAPI/RustHostRuntimeBridgeTests.swift index 75f62c108c..a85a3679b9 100644 --- a/hosts/ios/polkadot-appTests/TrUAPI/RustHostRuntimeBridgeTests.swift +++ b/hosts/ios/polkadot-appTests/TrUAPI/RustHostRuntimeBridgeTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import ChainRegistry +import Products import SubstrateSdk import TrUAPIHost @testable import polkadot_app @@ -15,7 +16,7 @@ private func makeHostDefaults() -> UserDefaults { private func makeHostBridge( chainRegistry: ChainRegistryProtocol = MockChainRegistry(), - confirmationPresenter: MockConfirmationPresenter = MockConfirmationPresenter() + confirmationPresenter: any TrUAPIConfirmationPresenting = MockConfirmationPresenter() ) -> RustHostRuntimeBridge { let chainConnections = TrUAPIChainConnectionPool( engineResolver: { genesisHash in @@ -114,6 +115,18 @@ struct RustHostRuntimeBridgeTests { #expect(presenter.receivedRequesterName == "host") } + @MainActor + @Test func profileDisclosureWithoutPresentationPropagatesWithoutDenial() async throws { + let presenter = TrUAPIConfirmationPresenter(routerFacade: ProductRoutersFacade.worker()) + let bridge = makeHostBridge(confirmationPresenter: presenter) + let review = UserConfirmationReview.profileDisclosure(ProfileDisclosureReview(productId: "caller.dot")) + + await #expect(throws: HostRejection.self) { + try await bridge.confirmPermission(review: review) + } + #expect(try await bridge.confirmUserAction(review: review) == false) + } + /// Core storage is the real host-global backend: writes round-trip. @Test func coreStorageRoundTrips() throws { let bridge = makeHostBridge() diff --git a/hosts/ios/polkadot-appTests/TrUAPI/RustRuntimeBridgeTests.swift b/hosts/ios/polkadot-appTests/TrUAPI/RustRuntimeBridgeTests.swift index 13c31aaa47..8d4b90f121 100644 --- a/hosts/ios/polkadot-appTests/TrUAPI/RustRuntimeBridgeTests.swift +++ b/hosts/ios/polkadot-appTests/TrUAPI/RustRuntimeBridgeTests.swift @@ -83,7 +83,7 @@ private func makeBridge( gameReminders: MockGameReminderScheduler? = nil, reminderPermissionAsker: MockReminderPermissionAsker = MockReminderPermissionAsker(), chainRegistry: MockChainRegistry = MockChainRegistry(), - confirmationPresenter: MockConfirmationPresenter = MockConfirmationPresenter(), + confirmationPresenter: any TrUAPIConfirmationPresenting = MockConfirmationPresenter(), preimageCache: TrUAPIPreimageCache = TrUAPIPreimageCache { _ in nil }, productStorageFails: Bool = false, hostProvider: ProductHostProviding = StubHostProvider(), @@ -458,6 +458,29 @@ struct RustRuntimeBridgeTests { #expect(presenter.receivedRequesterName == "caller.dot") } + @Test func profileDisclosureWithoutPresentationPropagatesWithoutDenial() async throws { + let presenter = TrUAPIConfirmationPresenter(routerFacade: ProductRoutersFacade.worker()) + let bridge = makeBridge(confirmationPresenter: presenter) + let review = UserConfirmationReview.profileDisclosure(ProfileDisclosureReview(productId: "caller.dot")) + + await #expect(throws: HostRejection.self) { + try await bridge.confirmPermission(review: review) + } + #expect(try await bridge.confirmUserAction(review: review) == false) + } + + @Test func supportedPermissionWithoutPresentationThrowsWithoutDenial() async throws { + let presenter = TrUAPIConfirmationPresenter(routerFacade: ProductRoutersFacade.worker()) + let bridge = makeBridge(confirmationPresenter: presenter) + let review = UserConfirmationReview.accountAccess( + AccountAccessReview(requestingProductId: "caller.dot", targetProductId: "target.dot") + ) + + await #expect(throws: HostRejection.self) { + try await bridge.confirmPermission(review: review) + } + } + // MARK: lookupPreimage @Test func lookupPreimageAwaitsFetchOnColdMiss() async throws { diff --git a/hosts/ios/polkadot-appTests/TrUAPI/TrUAPIReviewPromptMapperTests.swift b/hosts/ios/polkadot-appTests/TrUAPI/TrUAPIReviewPromptMapperTests.swift index fa4d8c83ab..fb0f06f837 100644 --- a/hosts/ios/polkadot-appTests/TrUAPI/TrUAPIReviewPromptMapperTests.swift +++ b/hosts/ios/polkadot-appTests/TrUAPI/TrUAPIReviewPromptMapperTests.swift @@ -4,11 +4,44 @@ import KeyDerivation import Products import SubstrateSdk import TrUAPIHost +import UIKit +import UIKitExt +@testable import PolkadotUI @testable import polkadot_app struct TrUAPIReviewPromptMapperTests { let mapper = TrUAPIReviewPromptMapper() + @MainActor + @Test(arguments: [TrUAPIPermissionDecision.allowOnce, .allowAlways, .deny]) + func profileDisclosureRoutesToExplicitNativeConsent(decision: TrUAPIPermissionDecision) async throws { + let facade = ProductRoutersFacade.worker() + let anchor = ProfilePermissionPresentationAnchor() + facade.setPresentationView(anchor) + let presenter = TrUAPIConfirmationPresenter(routerFacade: facade) + var pending: Task? + let controller = await withCheckedContinuation { continuation in + anchor.onPresent = { continuation.resume(returning: $0) } + pending = Task { + try await presenter.confirmPermission( + review: .profileDisclosure(ProfileDisclosureReview(productId: "profile.dot")), + from: "Profile" + ) + } + } + let task = try #require(pending) + defer { task.cancel() } + let sheet = try #require(controller as? TitleDetailsSheetViewController) + let action: MessageSheetAction? + switch decision { + case .allowAlways: action = sheet.viewModel.mainAction + case .allowOnce: action = sheet.viewModel.secondaryAction + case .deny: action = sheet.viewModel.tertiaryAction + } + try #require(action).handler() + #expect(try await task.value == decision) + } + @Test func mapsIdentityDisclosureToUserIdentityPermission() { let request = mapper.makePermissionRequest( @@ -33,6 +66,17 @@ struct TrUAPIReviewPromptMapperTests { )) } + @Test + func mapsProfileDisclosureToDedicatedPermission() { + let request = mapper.makePermissionRequest( + from: ProfileDisclosureReview(productId: "profile.dot") + ) + #expect(request == TrUAPIPermissionRequest( + productId: "profile.dot", + permissions: [.profileDisclosure] + )) + } + @Test func mapsPreimageSubmitToActionWithRequesterAndSize() { let request = mapper.makeActionRequest( @@ -186,3 +230,18 @@ private extension TrUAPIReviewPromptMapperTests { TrUAPIHostRingLocation(chainId: Data(repeating: 0, count: 32), junctions: []) } } + +@MainActor +private final class ProfilePermissionPresentationAnchor: UIViewController, ControllerBackedProtocol { + var controller: UIViewController { self } + var onPresent: ((UIViewController) -> Void)? + + override func present( + _ viewControllerToPresent: UIViewController, + animated _: Bool, + completion: (() -> Void)? = nil + ) { + onPresent?(viewControllerToPresent) + completion?() + } +} diff --git a/ios/truapi-host/Sources/TrUAPIHost/TrUAPIHost.swift b/ios/truapi-host/Sources/TrUAPIHost/TrUAPIHost.swift index dc7fc945fe..c81274385c 100644 --- a/ios/truapi-host/Sources/TrUAPIHost/TrUAPIHost.swift +++ b/ios/truapi-host/Sources/TrUAPIHost/TrUAPIHost.swift @@ -397,6 +397,22 @@ public protocol ContactsHostBridge: AnyObject, Sendable { /// did. With no contacts, answer `.noContacts` instead of drawing an empty /// overlay. func pickContact(productId: String) async throws -> HostContactPick + + /// Edit the complete selected audience; cancelling does not confirm empty. + func pickContacts(productId: String, selection: ContactSelection) async throws -> HostContactsPick + + /// Replace host-owned contact labels, independent of shared profile photos. + func placeContactLabels(productId: String, placed: PlacedContactLabels) async throws +} + +public extension ContactsHostBridge { + func pickContacts(productId: String, selection: ContactSelection) async throws -> HostContactsPick { + .unsupported + } + + func placeContactLabels(productId: String, placed: PlacedContactLabels) async throws { + throw HostContactsPlaceLabelsError.Unsupported + } } /// Draws the viewfinder for `scanner.scan`, following the rules on the core's @@ -636,6 +652,20 @@ private final class ContactsCallbackAdapter: NativeContactsCallbacks, @unchecked func pickContact(productId: String) async throws -> HostContactPick { try await withHostRejection { try await bridge.pickContact(productId: productId) } } + + func pickContacts(productId: String, selection: ContactSelection) async throws -> HostContactsPick { + try await withHostRejection { try await bridge.pickContacts(productId: productId, selection: selection) } + } + + func placeContactLabels(productId: String, placed: PlacedContactLabels) async throws { + do { + try await bridge.placeContactLabels(productId: productId, placed: placed) + } catch let error as HostContactsPlaceLabelsError { + throw error + } catch { + throw HostContactsPlaceLabelsError.Unknown(reason: "contact label callback failed") + } + } } /// Adapter that bridges the public `ScannerHostBridge` to the generated UniFFI diff --git a/js/container/package-lock.json b/js/container/package-lock.json index 755a9bd788..45240b42b3 100644 --- a/js/container/package-lock.json +++ b/js/container/package-lock.json @@ -18,7 +18,7 @@ }, "../packages/truapi": { "name": "@parity/truapi", - "version": "0.23.0", + "version": "0.25.0", "license": "MIT", "dependencies": { "@noble/hashes": "^2.2.0", diff --git a/js/packages/truapi-host/README.md b/js/packages/truapi-host/README.md index 8739dd73fd..bbe2728065 100644 --- a/js/packages/truapi-host/README.md +++ b/js/packages/truapi-host/README.md @@ -21,8 +21,6 @@ The package exposes tree-shakeable subpath exports — import only what your env | `@parity/truapi-host/testing/host-page` | The browser half the fixture drives, for a suite that boots its own page. | | `@parity/truapi-host/wasm/testing` | The raw glue for the signing-enabled bundle the test host runs on. | -The shipped WASM includes `WasmSigningHostRuntime`. Its configuration requires `runtimeConfig.networkSuffix`: the bare -TLD (`dot`, `paseo`, or `testnet`) matching the People chain and the wallet's onboarding configuration. `scripts/build-wasm.mjs` builds two WASM bundles, both `--no-default-features`. `wasm/web` is the production browser host and excludes `WasmSigningHostRuntime`; `wasm/testing` adds the Rust `wasm-signing-host` and `test-host` features, which is what lets the test host hold keys and answer resource allocation as granted without allocating anything. A real @@ -194,6 +192,7 @@ const callbacks: HostCallbacks = { chat, // optional: leave it out and chat products get `Unsupported` permissionStatus, // optional: reports live OS permission state pocket, // optional: serves the host's Pocket card collection + profile, // optional: shows profiles and draws contact avatars in host UI game, // optional: holds the host's game reminders contacts, // optional: leave it out and contacts calls get `Unsupported` scanner, // optional: draws the host's QR and barcode viewfinder @@ -208,6 +207,52 @@ reading as usable. Omit it and a stored grant answers on its own. replacement, and `removePocketCard` takes one out. The host owns the collection: removing an absent card succeeds, and a card the host pins is refused with `Privileged`. +`profile.presentProfile` shows the profile a product references in host-owned UI and resolves once it is shown, not +when the user dismisses it. The reference is a bearer capability: the host fetches, decrypts and renders it, and the +profile's bytes never return to the product. The core forwards only references that are non-empty, at most 2048 bytes +and printable ASCII without whitespace; parsing the format is the host's. + +`profile.presentContactProfile(product, presented)` opens host-owned contact profile UI when a product calls +`profile.presentContact`. `presented` carries the `peerIdentity`, an optional `shared` record containing the bearer +`reference` and `sharedAt` freshness timestamp (`bigint`), and the contact's optional verified `username`. +An absent `shared` requests friendly empty-profile feedback, not a fetch or an error. The username is the one the core's +Chat roster verified for that contact, else the contact's verified dotNS name, looked up for at most 2 seconds; never a +name from the product. Without one, name the contact generically, never by address. It names who sent the reference, +not whose profile it is: the record is not signed by its owner, and a contact can forward someone else's. Same contract +as `presentProfile` otherwise. The default adapter can present a shared reference through `presentProfile`; +hosts implement `presentContactProfile` to show empty-profile feedback. V2 never reports availability or rendering +failures to the product. A failed reference lookup is not represented as an empty profile. + +`profile.placeContactAvatars(product, placed)` draws contacts' avatars over a chat product. `placed` carries the +product's surface size and, per avatar, the product's `slot` id, a square `rect`, the `clip` region it is cut to, all in +surface units (framebuffer pixels for a PolkaVM product, CSS pixels of the viewport for a web product), and the +`reference` that contact disclosed, so the host can draw their photo and mood ring, with a `sharedAt` freshness token +(`bigint`). Contact tokens use Unix ms, advanced monotonically for personal revisions across relay actors; the own +avatar uses the disclosure revision, not a date. A changed token invalidates cached contents. Each call replaces what was +drawn for the product; an empty `avatars` clears it. The core calls it again with the same geometry when a contact +shares, re-shares or withdraws a profile, and with no avatars when the product's connection goes away. Draw on a layer +the product cannot +read that lets pointer input through, and never tell the product what was drawn. The host runtimes take +`RequiredHostCallbacks`, so a `profile` group implements it and `presentContactProfile` alongside `presentProfile`. +For older JavaScript embeddings missing either callback, the adapter independently normalizes both: +missing `presentContactProfile` presents a shared reference through `presentProfile` and rejects empty-profile +feedback; missing `placeContactAvatars` draws nothing and resolves, matching the Rust platform default. +Resolution does not guarantee that avatars were rendered. Omitting the entire `profile` group leaves Profile +unsupported; an absent placement callback alone is not an `Unsupported` signal. + +`profile.disclose` needs no `profile` group, but the first call from a product asks the user through +`userConfirmation.confirmPermission` with a `ProfileDisclosure` review naming that product. V1 shares app-scoped +references with every ready Chat contact; V2 can select apps or opaque Contacts handles. Personal grants are +host-renderable across recipient apps. The answer is kept like any other permission, as `ProfileDisclosure`. +Audience mutations currently reuse that product-level consent. A host that cannot render the +review should reject the call rather than answer `Deny`: the product is refused, but no refusal is remembered. + +`presentContact` V2 accepts peer or Contacts-handle selectors and hides sharing availability; V1 remains app-only. +`placeContactAvatars` V3 accepts those selectors alongside the V2 own slot. V1/V2 placement bytes remain compatible. +Hosts must call `notifyContactsChanged()` after directory changes so stale handle resolution and overlays clear. +These APIs do not create a Chat channel or a group editor. See the +[Profile RFC](../../../docs/rfcs/profile-disclosure.md) for audience, transport and withdrawal semantics. + `game` holds the host's game reminder. `scheduleGameReminder` replaces the product's held reminder, and `cancelGameReminder` drops it. The core asks for no per-product consent, so the host asks the platform for what the reminder @@ -327,16 +372,32 @@ A running fixture answers the same address through `testHost.getProductAccountAddress(productId?, index?)`, which reads the session the host actually holds and so returns `undefined` while it is signed out. -`contacts` needs both callbacks, or the group counts as absent. `pickContact` -draws the picker and returns the chosen account, or `NoContacts` when there is -nobody to show. `contacts({ handleKey, handles })` resolves the handles a -transaction names: one entry per handle, in order, the account or `undefined`. +The optional `contacts` group resolves handles through `contacts({ handleKey, handles })`: +one entry per handle, in order, the account or `undefined`. `pickContact` draws a single +picker and returns the chosen account. `pickContacts(product, { selected })` edits a +complete selection of at most 256 resolved accounts, returning `Picked { accounts }`, +`Dismissed`, or `NoContacts`. A confirmed empty array is `Picked`, not dismissal. +Missing picker callbacks answer `Unsupported`. A contact's handle is BLAKE2b-256 keyed with `handleKey` over its 32-byte account (`blake2b(account, { key: handleKey, dkLen: 32 })` in `@noble/hashes`). The core re-checks every account returned. It caches what it resolves, so call `notifyContactsChanged()` whenever a contact is removed or blocked. Omit blocked contacts from both. See the contacts RFC (`docs/rfcs/contacts-api.md`). +`placeContactLabels(product, placed)` receives surface dimensions and +`labels: [{ slot, account, rect, clip }]`. Draw names from the host's contact directory, +using an account fallback when no username exists. Profile-photo absence must not +hide a name. Keep this UI host-owned: return no label or per-slot availability. +Return `true` when the host supports label placement, even when no contact resolves. +Return `false` when that UI is unsupported; the adapter supplies this answer when +the callback is omitted. This capability acknowledgment never reports individual +contact availability. Background Workers are denied label placement. +Empty placements clear the previous names and cancel queued refreshes. Clear names +and cancel pending work on frame load, navigation or disconnect. On same-wallet +directory invalidation, clear stale names and refresh the latest live placement +without waiting for the product to resend it. The core serializes placements per +connection and rejects selections from changed sessions. + Browser signing hosts can back this UI with `runtime.getNativeChatContacts()`. It returns `{ walletPublicKey, genesisHash, contacts: [{ peerIdentity, username? }] }` to trusted host code only. The directory restores encrypted native Chat actors, checks their current authorization, includes only authenticated diff --git a/js/packages/truapi-host/src/adapter-support.ts b/js/packages/truapi-host/src/adapter-support.ts index bea241656c..e537b38246 100644 --- a/js/packages/truapi-host/src/adapter-support.ts +++ b/js/packages/truapi-host/src/adapter-support.ts @@ -12,11 +12,30 @@ import type { ChainConnect, ChainConnection, HopConnect } from "./runtime.js"; import type { ChainProvider, CoinageWalletHost, + ContactsPlatform, HopProvider, JsonRpcConnection, NativeChatFilesHost, + ProfilePlatform, } from "./generated/host-callbacks.js"; +/** Optional Contacts UI stays unsupported rather than confirming an empty selection. */ +export function contactsHostAdapter( + host: ContactsPlatform | undefined, +): Required | undefined { + if (host === undefined) return undefined; + return { + contacts: (lookup) => host.contacts(lookup), + pickContact: (product) => + host.pickContact?.(product) ?? Promise.resolve({ tag: "Unsupported" }), + pickContacts: (product, selection) => + host.pickContacts?.(product, selection) ?? + Promise.resolve({ tag: "Unsupported" }), + placeContactLabels: (product, placed) => + host.placeContactLabels?.(product, placed) ?? Promise.resolve(false), + }; +} + type WireResult = | { success: true; value: T } | { success: false; value: E }; @@ -171,6 +190,42 @@ export function coinageWalletHostAdapter( }; } +/** + * A profile host built before `presentContactProfile` still shows a contact's + * profile: without it, the contact's reference is presented as + * `presentProfile` would. Empty-profile feedback requires the contact callback. + * Missing avatar placement draws nothing, matching the Rust platform default; + * resolving does not promise that any avatar was rendered. + */ +export function profileHostAdapter( + host: ProfilePlatform | undefined, +): Required | undefined { + if (host === undefined) return undefined; + if ( + typeof host.presentContactProfile === "function" && + typeof host.placeContactAvatars === "function" + ) + return host as Required; + return { + presentProfile: (product, request) => host.presentProfile(product, request), + presentContactProfile: (product, presented) => { + if (typeof host.presentContactProfile === "function") + return host.presentContactProfile(product, presented); + if (presented.shared === undefined) + return Promise.reject( + new Error("Contact profile feedback is unavailable"), + ); + return host.presentProfile(product, { + reference: presented.shared.reference, + }); + }, + placeContactAvatars: (product, placed) => + typeof host.placeContactAvatars === "function" + ? host.placeContactAvatars(product, placed) + : Promise.resolve(), + }; +} + /** Optional SDK embeddings must fail closed, never invent successful file handles. */ export const unavailableNativeChatFilesHost: Required = { async pickChatFiles() { diff --git a/js/packages/truapi-host/src/host-callbacks-adapter.test.ts b/js/packages/truapi-host/src/host-callbacks-adapter.test.ts index 4ef95f464e..71bb20abdd 100644 --- a/js/packages/truapi-host/src/host-callbacks-adapter.test.ts +++ b/js/packages/truapi-host/src/host-callbacks-adapter.test.ts @@ -21,6 +21,7 @@ import type { } from "@parity/truapi"; import { createWasmRawCallbacks } from "./generated/host-callbacks-adapter.js"; +import { profileHostAdapter } from "./adapter-support.js"; import { AuthState, CoreStorageKey, @@ -30,6 +31,8 @@ import { NativeCoinageRequest, NativeCoinageResponse, PermissionDecision, + PlacedAvatars, + PresentedContactProfile, ProductContext, ProductExecutionKind, UserConfirmationReview, @@ -908,6 +911,141 @@ describe("createWasmRawCallbacks", () => { expect(closes).toBe(1); expect(returns).toBe(1); }); + + describe("contact profile presentation", () => { + const product = ProductContext.enc({ + productId: "egui-chat.dot", + executionKind: "App", + }); + const presented = { + shared: { + reference: "seity-contacts:v1:ab", + sharedAt: 1_700_000_000_500n, + }, + peerIdentity: new Uint8Array(32).fill(0xa1), + username: "alice.01", + }; + + const placed = { surfaceWidth: 640, surfaceHeight: 480, avatars: [] }; + + it("keeps an absent profile group absent", () => { + expect(profileHostAdapter(undefined)).toBeUndefined(); + const raw = createWasmRawCallbacks({ + ...makeHostCallbacks(), + profile: undefined, + }); + expect(raw.presentProfile).toBeUndefined(); + expect(raw.presentContactProfile).toBeUndefined(); + expect(raw.placeContactAvatars).toBeUndefined(); + }); + + it("normalizes missing placement without replacing contact presentation or its receiver", async () => { + const host = { + presentations: [] as PresentedContactProfile[], + async presentProfile() { + throw new Error("Contact presentation must not use the fallback"); + }, + async presentContactProfile( + presentationProduct: ProductContext, + contact: PresentedContactProfile, + ) { + expect(presentationProduct).toEqual(ProductContext.dec(product)); + this.presentations.push(contact); + }, + }; + const raw = createWasmRawCallbacks({ + ...makeHostCallbacks(), + profile: host as never, + }); + await raw.presentContactProfile!( + product, + PresentedContactProfile.enc(presented), + ); + await raw.presentContactProfile!( + product, + PresentedContactProfile.enc({ ...presented, shared: undefined }), + ); + await expect( + raw.placeContactAvatars!(product, PlacedAvatars.enc(placed)), + ).resolves.toBeUndefined(); + expect(host.presentations).toEqual([ + presented, + { ...presented, shared: undefined }, + ]); + }); + + it("preserves placement and its receiver when only contact presentation is missing", async () => { + const host = { + placements: [] as PlacedAvatars[], + async presentProfile() {}, + async placeContactAvatars( + placementProduct: ProductContext, + placement: PlacedAvatars, + ) { + expect(placementProduct).toEqual(ProductContext.dec(product)); + this.placements.push(placement); + }, + }; + const raw = createWasmRawCallbacks({ + ...makeHostCallbacks(), + profile: host as never, + }); + await raw.placeContactAvatars!(product, PlacedAvatars.enc(placed)); + expect(host.placements).toEqual([placed]); + }); + + it("returns complete adapters unchanged and preserves callback failures", async () => { + const failure = new Error("Overlay unavailable"); + const host = { + failure, + async presentProfile() {}, + async presentContactProfile() {}, + async placeContactAvatars() { + throw this.failure; + }, + }; + expect(profileHostAdapter(host)).toBe(host); + const raw = createWasmRawCallbacks({ + ...makeHostCallbacks(), + profile: host, + }); + await expect( + raw.placeContactAvatars!(product, PlacedAvatars.enc(placed)), + ).rejects.toBe(failure); + }); + + it("preserves shared profiles without fabricating a reference for empty feedback on older hosts", async () => { + const references: string[] = []; + const legacy = { + references, + async presentProfile( + _product: unknown, + request: { reference: string }, + ) { + this.references.push(request.reference); + }, + }; + const raw = createWasmRawCallbacks({ + ...makeHostCallbacks(), + profile: legacy as never, + }); + + await raw.presentContactProfile!( + product, + PresentedContactProfile.enc(presented), + ); + await expect( + raw.presentContactProfile!( + product, + PresentedContactProfile.enc({ ...presented, shared: undefined }), + ), + ).rejects.toThrow("Contact profile feedback is unavailable"); + expect(references).toEqual([presented.shared.reference]); + await expect( + raw.placeContactAvatars!(product, PlacedAvatars.enc(placed)), + ).resolves.toBeUndefined(); + }); + }); }); describe("ProductContext codec", () => { diff --git a/js/packages/truapi-host/src/locale.test.ts b/js/packages/truapi-host/src/locale.test.ts index 14396dbb8a..e97bb8631e 100644 --- a/js/packages/truapi-host/src/locale.test.ts +++ b/js/packages/truapi-host/src/locale.test.ts @@ -36,10 +36,20 @@ describe("timestamp localization", () => { it("groups by local midnight, not UTC midnight, independently of locale calendars", async () => { const instants = ["2024-01-01T14:59:00Z", "2024-01-01T15:00:00Z"]; - const tokyo = await localized(instants, "Asia/Tokyo", "ar-SA-u-ca-islamic-nu-arab"); + const tokyo = await localized( + instants, + "Asia/Tokyo", + "ar-SA-u-ca-islamic-nu-arab", + ); const newYork = await localized(instants); - expect(tokyo.map((value) => value.localDate)).toEqual(["2024-01-01", "2024-01-02"]); - expect(newYork.map((value) => value.localDate)).toEqual(["2024-01-01", "2024-01-01"]); + expect(tokyo.map((value) => value.localDate)).toEqual([ + "2024-01-01", + "2024-01-02", + ]); + expect(newYork.map((value) => value.localDate)).toEqual([ + "2024-01-01", + "2024-01-01", + ]); expect(tokyo[0]!.time).toMatch(/[\u0660-\u0669]/); expect(tokyo[0]!.date).toMatch(/[\u0660-\u0669]/); }); @@ -81,9 +91,15 @@ describe("timestamp localization", () => { { ...valid, timestampsMs: [-1n] }, { ...valid, timestampsMs: [253402300800000n] }, { ...valid, timestampsMs: Array(129).fill(0n) }, - { ...valid, timestampsMs: [253402300799999n], timeZone: "Pacific/Kiritimati" }, + { + ...valid, + timestampsMs: [253402300799999n], + timeZone: "Pacific/Kiritimati", + }, ]) { - await expect(localizeTimestamps(request)).rejects.toBeInstanceOf(RangeError); + await expect(localizeTimestamps(request)).rejects.toBeInstanceOf( + RangeError, + ); } }); }); diff --git a/js/packages/truapi-host/src/locale.ts b/js/packages/truapi-host/src/locale.ts index 75576468ee..3e2e286e6c 100644 --- a/js/packages/truapi-host/src/locale.ts +++ b/js/packages/truapi-host/src/locale.ts @@ -1,9 +1,9 @@ import type { LocaleHost } from "./generated/host-callbacks.js"; /** Localize each instant using the requested zone's historical offset and DST. */ -export const localizeTimestamps: NonNullable = async ( - request, -) => { +export const localizeTimestamps: NonNullable< + LocaleHost["localizeTimestamps"] +> = async (request) => { if (!request.languageTag.trim() || !request.timeZone.trim()) { throw new RangeError("A language tag and time zone are required"); } diff --git a/js/packages/truapi-host/src/test-support.ts b/js/packages/truapi-host/src/test-support.ts index 37fe1a8b3e..fa209cd12b 100644 --- a/js/packages/truapi-host/src/test-support.ts +++ b/js/packages/truapi-host/src/test-support.ts @@ -151,6 +151,18 @@ export function makeHostCallbacks( }, } : {}), + // And for profiles: the default fixture is a host that renders none, so + // Profile calls are answered `Unsupported`. + ...(overrides.profile + ? { + profile: { + presentProfile: async () => {}, + presentContactProfile: async () => {}, + placeContactAvatars: async () => {}, + ...overrides.profile, + }, + } + : {}), // An unavailable authenticated search must not look like an empty result. ...(overrides.identityBackend ? { diff --git a/js/packages/truapi-host/src/web/create-worker-host-runtime.ts b/js/packages/truapi-host/src/web/create-worker-host-runtime.ts index 4b01188eb4..c276a93c10 100644 --- a/js/packages/truapi-host/src/web/create-worker-host-runtime.ts +++ b/js/packages/truapi-host/src/web/create-worker-host-runtime.ts @@ -1761,6 +1761,7 @@ function createWebWorkerHostRuntime( chat: host.chat !== undefined, permissionStatus: host.permissionStatus !== undefined, pocket: host.pocket !== undefined, + profile: host.profile !== undefined, identityBackend: host.identityBackend !== undefined, coinageWallet: callbacks.nativeCoinage !== undefined, game: host.game !== undefined, @@ -1902,6 +1903,7 @@ function buildRuntime( contacts: callbacks.contacts !== undefined, permissionStatus: callbacks.permissionStatus !== undefined, pocket: callbacks.pocket !== undefined, + profile: callbacks.profile !== undefined, identityBackend: callbacks.identityBackend !== undefined, coinageWallet: state.rawCallbacks.nativeCoinage !== undefined, diff --git a/js/packages/truapi-host/src/web/worker-provider.test.ts b/js/packages/truapi-host/src/web/worker-provider.test.ts index 9049485581..715a91c66d 100644 --- a/js/packages/truapi-host/src/web/worker-provider.test.ts +++ b/js/packages/truapi-host/src/web/worker-provider.test.ts @@ -278,6 +278,7 @@ describe("createWebWorkerPairingHostRuntime", () => { chat: false, permissionStatus: false, pocket: false, + profile: false, identityBackend: false, coinageWallet: false, game: false, @@ -457,6 +458,7 @@ describe("createWebWorkerPairingHostRuntime", () => { chat: true, permissionStatus: false, pocket: false, + profile: false, identityBackend: false, coinageWallet: false, game: false, @@ -483,6 +485,7 @@ describe("createWebWorkerPairingHostRuntime", () => { chat: false, permissionStatus: false, pocket: true, + profile: false, identityBackend: false, coinageWallet: false, game: false, @@ -766,6 +769,7 @@ describe("createWebWorkerPairingHostRuntime", () => { chat: false, permissionStatus: false, pocket: false, + profile: false, game: true, identityBackend: false, coinageWallet: false, @@ -791,6 +795,7 @@ describe("createWebWorkerPairingHostRuntime", () => { contacts: false, permissionStatus: false, pocket: false, + profile: false, game: true, identityBackend: false, coinageWallet: false, diff --git a/rust/crates/truapi-chat-v2/src/call_payload.rs b/rust/crates/truapi-chat-v2/src/call_payload.rs index d44801acb4..ae38669659 100644 --- a/rust/crates/truapi-chat-v2/src/call_payload.rs +++ b/rust/crates/truapi-chat-v2/src/call_payload.rs @@ -7,82 +7,82 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use crate::{ - ChatError, Cursor, V2DataChannelPurpose, decode_compact_u32, encode_bytes, encode_compact_u32, - encode_compact_u128, encode_string, + ChatError, Cursor, V2DataChannelPurpose, decode_compact_u32, encode_bytes, encode_compact_u32, + encode_compact_u128, encode_string, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum V2CallSdpType { - Offer, - Answer, + Offer, + Answer, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum V2CallTransportType { - Tcp, - Udp, + Tcp, + Udp, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum V2CallCandidateType { - Host, - Srflx, - Relay, - Prflx, + Host, + Srflx, + Relay, + Prflx, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2CallIpAddress { - Ipv4([u8; 4]), - Ipv6([u16; 8]), + Ipv4([u8; 4]), + Ipv6([u16; 8]), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2CallMinimalCandidate { - pub foundation: String, - pub priority: u32, - pub transport_type: V2CallTransportType, - pub address: V2CallIpAddress, - pub port: u16, - pub candidate_type: V2CallCandidateType, + pub foundation: String, + pub priority: u32, + pub transport_type: V2CallTransportType, + pub address: V2CallIpAddress, + pub port: u16, + pub candidate_type: V2CallCandidateType, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2CallSetup { - pub sdp_type: V2CallSdpType, - pub session_id: u128, - pub session_version: u128, - pub ice_ufrag: String, - pub ice_pwd: String, - pub fingerprint: Vec, - pub candidates: Vec, + pub sdp_type: V2CallSdpType, + pub session_id: u128, + pub session_version: u128, + pub ice_ufrag: String, + pub ice_pwd: String, + pub fingerprint: Vec, + pub candidates: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2CallIceCandidate { - pub sdp: String, - pub sdp_m_line_index: u32, - pub sdp_mid: Option, + pub sdp: String, + pub sdp_m_line_index: u32, + pub sdp_mid: Option, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2CallDataChannelMessage { - pub id: String, - pub data: Vec, + pub id: String, + pub data: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2CallPeerConnectionSignal { - Offer(String), - Answer(String), - Candidates(Vec), - Closed, + Offer(String), + Answer(String), + Candidates(Vec), + Closed, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2CallDecodedSetup { - pub setup_sdp: String, - pub candidates: Vec, + pub setup_sdp: String, + pub candidates: Vec, } /// Use-case id used by the iOS and Android v2 apps for media renegotiation @@ -91,358 +91,345 @@ pub const V2_CALL_RENEGOTIATION_USE_CASE_ID: &str = "webrtc_renegotiation_intern /// Encode a native v2 data-channel setup payload. pub fn encode_v2_call_setup_payload(setup: &V2CallSetup) -> Result, ChatError> { - let mut out = Vec::new(); - out.push(sdp_type_index(setup.sdp_type)); - out.extend_from_slice(&encode_compact_u128(setup.session_id)); - out.extend_from_slice(&encode_compact_u128(setup.session_version)); - encode_string(&mut out, &setup.ice_ufrag)?; - encode_string(&mut out, &setup.ice_pwd)?; - encode_bytes(&mut out, &setup.fingerprint)?; - encode_v2_call_minimal_candidates(&mut out, &setup.candidates)?; - Ok(out) + let mut out = Vec::new(); + out.push(sdp_type_index(setup.sdp_type)); + out.extend_from_slice(&encode_compact_u128(setup.session_id)); + out.extend_from_slice(&encode_compact_u128(setup.session_version)); + encode_string(&mut out, &setup.ice_ufrag)?; + encode_string(&mut out, &setup.ice_pwd)?; + encode_bytes(&mut out, &setup.fingerprint)?; + encode_v2_call_minimal_candidates(&mut out, &setup.candidates)?; + Ok(out) } /// Decode a native v2 data-channel setup payload. pub fn decode_v2_call_setup_payload(data: &[u8]) -> Result { - let mut cursor = Cursor::new(data); - let setup = V2CallSetup { - sdp_type: decode_sdp_type(cursor.read_u8("call_setup.sdp_type")?)?, - session_id: cursor.read_compact_u128("call_setup.session_id")?, - session_version: cursor.read_compact_u128("call_setup.session_version")?, - ice_ufrag: cursor.read_string("call_setup.ice_ufrag")?, - ice_pwd: cursor.read_string("call_setup.ice_pwd")?, - fingerprint: cursor.read_bytes("call_setup.fingerprint")?, - candidates: decode_v2_call_minimal_candidates(&mut cursor, "call_setup.candidates")?, - }; - cursor.finish()?; - Ok(setup) + let mut cursor = Cursor::new(data); + let setup = V2CallSetup { + sdp_type: decode_sdp_type(cursor.read_u8("call_setup.sdp_type")?)?, + session_id: cursor.read_compact_u128("call_setup.session_id")?, + session_version: cursor.read_compact_u128("call_setup.session_version")?, + ice_ufrag: cursor.read_string("call_setup.ice_ufrag")?, + ice_pwd: cursor.read_string("call_setup.ice_pwd")?, + fingerprint: cursor.read_bytes("call_setup.fingerprint")?, + candidates: decode_v2_call_minimal_candidates(&mut cursor, "call_setup.candidates")?, + }; + cursor.finish()?; + Ok(setup) } /// Parse full SDP plus WebRTC candidates and encode the native v2 setup bytes. pub fn encode_v2_call_setup_from_sdp( - setup_sdp: &str, - candidates: &[V2CallIceCandidate], + setup_sdp: &str, + candidates: &[V2CallIceCandidate], ) -> Result, ChatError> { - let mut setup = parse_v2_call_setup_sdp(setup_sdp)?; - setup.candidates = candidates - .iter() - .map(parse_v2_call_ice_candidate) - .collect::, _>>()?; - encode_v2_call_setup_payload(&setup) + let mut setup = parse_v2_call_setup_sdp(setup_sdp)?; + setup.candidates = candidates + .iter() + .map(parse_v2_call_ice_candidate) + .collect::, _>>()?; + encode_v2_call_setup_payload(&setup) } /// Decode native v2 setup bytes back into the SDP shape accepted by WebRTC. pub fn decode_v2_call_setup_to_sdp(data: &[u8]) -> Result { - let setup = decode_v2_call_setup_payload(data)?; - Ok(V2CallDecodedSetup { - setup_sdp: reconstruct_v2_call_setup_sdp(&setup), - candidates: setup - .candidates - .iter() - .map(reconstruct_v2_call_ice_candidate) - .collect(), - }) + let setup = decode_v2_call_setup_payload(data)?; + Ok(V2CallDecodedSetup { + setup_sdp: reconstruct_v2_call_setup_sdp(&setup), + candidates: setup.candidates.iter().map(reconstruct_v2_call_ice_candidate).collect(), + }) } /// Encode native v2 trickled ICE candidate payload bytes. pub fn encode_v2_call_candidates_payload( - candidates: &[V2CallMinimalCandidate], + candidates: &[V2CallMinimalCandidate], ) -> Result, ChatError> { - let mut out = Vec::new(); - encode_v2_call_minimal_candidates(&mut out, candidates)?; - Ok(out) + let mut out = Vec::new(); + encode_v2_call_minimal_candidates(&mut out, candidates)?; + Ok(out) } /// Decode native v2 trickled ICE candidate payload bytes. pub fn decode_v2_call_candidates_payload( - data: &[u8], + data: &[u8], ) -> Result, ChatError> { - let mut cursor = Cursor::new(data); - let candidates = decode_v2_call_minimal_candidates(&mut cursor, "call_candidates")?; - cursor.finish()?; - Ok(candidates) + let mut cursor = Cursor::new(data); + let candidates = decode_v2_call_minimal_candidates(&mut cursor, "call_candidates")?; + cursor.finish()?; + Ok(candidates) } /// Parse WebRTC candidates and encode native v2 trickled ICE candidate bytes. pub fn encode_v2_call_candidates_from_sdp( - candidates: &[V2CallIceCandidate], + candidates: &[V2CallIceCandidate], ) -> Result, ChatError> { - let candidates = candidates - .iter() - .map(parse_v2_call_ice_candidate) - .collect::, _>>()?; - encode_v2_call_candidates_payload(&candidates) + let candidates = candidates + .iter() + .map(parse_v2_call_ice_candidate) + .collect::, _>>()?; + encode_v2_call_candidates_payload(&candidates) } /// Decode native v2 trickled ICE candidate bytes back into WebRTC candidates. pub fn decode_v2_call_candidates_to_sdp(data: &[u8]) -> Result, ChatError> { - Ok(decode_v2_call_candidates_payload(data)? - .iter() - .map(reconstruct_v2_call_ice_candidate) - .collect()) + Ok(decode_v2_call_candidates_payload(data)? + .iter() + .map(reconstruct_v2_call_ice_candidate) + .collect()) } /// Encode the v2 apps' generic WebRTC data-channel message wrapper. pub fn encode_v2_call_data_channel_message( - message: &V2CallDataChannelMessage, + message: &V2CallDataChannelMessage, ) -> Result, ChatError> { - let mut out = Vec::new(); - encode_string(&mut out, &message.id)?; - encode_bytes(&mut out, &message.data)?; - Ok(out) + let mut out = Vec::new(); + encode_string(&mut out, &message.id)?; + encode_bytes(&mut out, &message.data)?; + Ok(out) } /// Decode the v2 apps' generic WebRTC data-channel message wrapper. pub fn decode_v2_call_data_channel_message( - data: &[u8], + data: &[u8], ) -> Result { - let mut cursor = Cursor::new(data); - let message = V2CallDataChannelMessage { - id: cursor.read_string("call_data_channel_message.id")?, - data: cursor.read_bytes("call_data_channel_message.data")?, - }; - cursor.finish()?; - Ok(message) + let mut cursor = Cursor::new(data); + let message = V2CallDataChannelMessage { + id: cursor.read_string("call_data_channel_message.id")?, + data: cursor.read_bytes("call_data_channel_message.data")?, + }; + cursor.finish()?; + Ok(message) } /// Encode the v2 apps' media renegotiation signal carried inside /// `V2_CALL_RENEGOTIATION_USE_CASE_ID` data-channel messages. pub fn encode_v2_call_peer_connection_signal( - signal: &V2CallPeerConnectionSignal, + signal: &V2CallPeerConnectionSignal, ) -> Result, ChatError> { - let mut out = Vec::new(); - match signal { - V2CallPeerConnectionSignal::Offer(sdp) => { - out.push(0); - encode_string(&mut out, sdp)?; - } - V2CallPeerConnectionSignal::Answer(sdp) => { - out.push(1); - encode_string(&mut out, sdp)?; - } - V2CallPeerConnectionSignal::Candidates(candidates) => { - out.push(2); - let len = u32::try_from(candidates.len()).map_err(|_| { - ChatError::InvalidEncoding("call peer candidate vector is too large".into()) - })?; - out.extend_from_slice(&encode_compact_u32(len)); - for candidate in candidates { - encode_string(&mut out, &candidate.sdp)?; - out.extend_from_slice(&candidate.sdp_m_line_index.to_le_bytes()); - match &candidate.sdp_mid { - Some(sdp_mid) => { - out.push(1); - encode_string(&mut out, sdp_mid)?; - } - None => out.push(0), - } - } - } - V2CallPeerConnectionSignal::Closed => out.push(3), - } - Ok(out) + let mut out = Vec::new(); + match signal { + V2CallPeerConnectionSignal::Offer(sdp) => { + out.push(0); + encode_string(&mut out, sdp)?; + }, + V2CallPeerConnectionSignal::Answer(sdp) => { + out.push(1); + encode_string(&mut out, sdp)?; + }, + V2CallPeerConnectionSignal::Candidates(candidates) => { + out.push(2); + let len = u32::try_from(candidates.len()).map_err(|_| { + ChatError::InvalidEncoding("call peer candidate vector is too large".into()) + })?; + out.extend_from_slice(&encode_compact_u32(len)); + for candidate in candidates { + encode_string(&mut out, &candidate.sdp)?; + out.extend_from_slice(&candidate.sdp_m_line_index.to_le_bytes()); + match &candidate.sdp_mid { + Some(sdp_mid) => { + out.push(1); + encode_string(&mut out, sdp_mid)?; + }, + None => out.push(0), + } + } + }, + V2CallPeerConnectionSignal::Closed => out.push(3), + } + Ok(out) } /// Decode the v2 apps' media renegotiation signal carried inside a data channel. pub fn decode_v2_call_peer_connection_signal( - data: &[u8], + data: &[u8], ) -> Result { - let mut cursor = Cursor::new(data); - let signal = match cursor.read_u8("call_peer_connection_signal.index")? { - 0 => V2CallPeerConnectionSignal::Offer( - cursor.read_string("call_peer_connection_signal.offer")?, - ), - 1 => V2CallPeerConnectionSignal::Answer( - cursor.read_string("call_peer_connection_signal.answer")?, - ), - 2 => { - let (len, consumed) = - decode_compact_u32(&cursor.data[cursor.offset..]).map_err(|e| { - ChatError::InvalidEncoding(format!( - "call_peer_connection_signal.candidates: {e}" - )) - })?; - cursor.offset += consumed; - let len = len as usize; - if len > cursor.data.len().saturating_sub(cursor.offset) / 6 { - return Err(ChatError::InvalidEncoding( - "call_peer_connection_signal.candidates: item count exceeds remaining input" - .into(), - )); - } - let mut candidates = Vec::with_capacity(len); - for index in 0..len { - let field = format!("call_peer_connection_signal.candidates[{index}]"); - candidates.push(V2CallIceCandidate { - sdp: cursor.read_string(&format!("{field}.sdp"))?, - sdp_m_line_index: cursor.read_u32(&format!("{field}.sdp_m_line_index"))?, - sdp_mid: match cursor.read_u8(&format!("{field}.sdp_mid"))? { - 0 => None, - 1 => Some(cursor.read_string(&format!("{field}.sdp_mid.value"))?), - value => { - return Err(ChatError::InvalidEncoding(format!( - "{field}.sdp_mid has invalid option index {value}" - ))); - } - }, - }); - } - V2CallPeerConnectionSignal::Candidates(candidates) - } - 3 => V2CallPeerConnectionSignal::Closed, - value => { - return Err(ChatError::InvalidEncoding(format!( - "unsupported call peer connection signal index {value}" - ))); - } - }; - cursor.finish()?; - Ok(signal) + let mut cursor = Cursor::new(data); + let signal = match cursor.read_u8("call_peer_connection_signal.index")? { + 0 => V2CallPeerConnectionSignal::Offer( + cursor.read_string("call_peer_connection_signal.offer")?, + ), + 1 => V2CallPeerConnectionSignal::Answer( + cursor.read_string("call_peer_connection_signal.answer")?, + ), + 2 => { + let (len, consumed) = + decode_compact_u32(&cursor.data[cursor.offset..]).map_err(|e| { + ChatError::InvalidEncoding(format!( + "call_peer_connection_signal.candidates: {e}" + )) + })?; + cursor.offset += consumed; + let len = len as usize; + if len > cursor.data.len().saturating_sub(cursor.offset) / 6 { + return Err(ChatError::InvalidEncoding( + "call_peer_connection_signal.candidates: item count exceeds remaining input" + .into(), + )); + } + let mut candidates = Vec::with_capacity(len); + for index in 0..len { + let field = format!("call_peer_connection_signal.candidates[{index}]"); + candidates.push(V2CallIceCandidate { + sdp: cursor.read_string(&format!("{field}.sdp"))?, + sdp_m_line_index: cursor.read_u32(&format!("{field}.sdp_m_line_index"))?, + sdp_mid: match cursor.read_u8(&format!("{field}.sdp_mid"))? { + 0 => None, + 1 => Some(cursor.read_string(&format!("{field}.sdp_mid.value"))?), + value => { + return Err(ChatError::InvalidEncoding(format!( + "{field}.sdp_mid has invalid option index {value}" + ))); + }, + }, + }); + } + V2CallPeerConnectionSignal::Candidates(candidates) + }, + 3 => V2CallPeerConnectionSignal::Closed, + value => { + return Err(ChatError::InvalidEncoding(format!( + "unsupported call peer connection signal index {value}" + ))); + }, + }; + cursor.finish()?; + Ok(signal) } /// Encode a media renegotiation signal in the data-channel envelope expected by /// iOS v2 and Android v2. pub fn encode_v2_call_renegotiation_message( - signal: &V2CallPeerConnectionSignal, + signal: &V2CallPeerConnectionSignal, ) -> Result, ChatError> { - encode_v2_call_data_channel_message(&V2CallDataChannelMessage { - id: V2_CALL_RENEGOTIATION_USE_CASE_ID.into(), - data: encode_v2_call_peer_connection_signal(signal)?, - }) + encode_v2_call_data_channel_message(&V2CallDataChannelMessage { + id: V2_CALL_RENEGOTIATION_USE_CASE_ID.into(), + data: encode_v2_call_peer_connection_signal(signal)?, + }) } /// Decode a media renegotiation signal from the data-channel envelope expected /// by iOS v2 and Android v2. pub fn decode_v2_call_renegotiation_message( - data: &[u8], + data: &[u8], ) -> Result { - let message = decode_v2_call_data_channel_message(data)?; - if message.id != V2_CALL_RENEGOTIATION_USE_CASE_ID { - return Err(ChatError::InvalidEncoding(format!( - "unexpected call data-channel message id {}", - message.id - ))); - } - decode_v2_call_peer_connection_signal(&message.data) + let message = decode_v2_call_data_channel_message(data)?; + if message.id != V2_CALL_RENEGOTIATION_USE_CASE_ID { + return Err(ChatError::InvalidEncoding(format!( + "unexpected call data-channel message id {}", + message.id + ))); + } + decode_v2_call_peer_connection_signal(&message.data) } pub fn v2_call_purpose_from_video(with_video: bool) -> V2DataChannelPurpose { - if with_video { - V2DataChannelPurpose::Video - } else { - V2DataChannelPurpose::Audio - } + if with_video { V2DataChannelPurpose::Video } else { V2DataChannelPurpose::Audio } } fn parse_v2_call_setup_sdp(setup_sdp: &str) -> Result { - let mut ice_ufrag = None; - let mut ice_pwd = None; - let mut fingerprint = None; - let mut sdp_type = V2CallSdpType::Offer; - let mut session_id = None; - let mut session_version = None; - - for line in setup_sdp.lines() { - let trimmed = line.trim(); - if let Some(value) = trimmed.strip_prefix("a=ice-ufrag:") { - ice_ufrag = Some(value.to_string()); - } else if let Some(value) = trimmed.strip_prefix("a=ice-pwd:") { - ice_pwd = Some(value.to_string()); - } else if let Some(value) = trimmed.strip_prefix("a=fingerprint:") { - fingerprint = Some(parse_fingerprint(value)?); - } else if let Some(value) = trimmed.strip_prefix("a=setup:") { - sdp_type = if value == "actpass" { - V2CallSdpType::Offer - } else { - V2CallSdpType::Answer - }; - } else if let Some(value) = trimmed.strip_prefix("o=") { - let parts = value.split_whitespace().collect::>(); - if parts.len() < 3 { - return Err(ChatError::InvalidEncoding( - "call setup SDP has invalid o= session line".into(), - )); - } - session_id = Some(parts[1].parse::().map_err(|_| { - ChatError::InvalidEncoding("call setup SDP has invalid session id".into()) - })?); - session_version = Some(parts[2].parse::().map_err(|_| { - ChatError::InvalidEncoding("call setup SDP has invalid session version".into()) - })?); - } - } - - Ok(V2CallSetup { - sdp_type, - session_id: session_id.ok_or_else(|| { - ChatError::InvalidEncoding("call setup SDP missing o= session line".into()) - })?, - session_version: session_version.ok_or_else(|| { - ChatError::InvalidEncoding("call setup SDP missing o= session line".into()) - })?, - ice_ufrag: ice_ufrag.ok_or_else(|| { - ChatError::InvalidEncoding("call setup SDP missing a=ice-ufrag".into()) - })?, - ice_pwd: ice_pwd - .ok_or_else(|| ChatError::InvalidEncoding("call setup SDP missing a=ice-pwd".into()))?, - fingerprint: fingerprint.ok_or_else(|| { - ChatError::InvalidEncoding("call setup SDP missing a=fingerprint".into()) - })?, - candidates: Vec::new(), - }) + let mut ice_ufrag = None; + let mut ice_pwd = None; + let mut fingerprint = None; + let mut sdp_type = V2CallSdpType::Offer; + let mut session_id = None; + let mut session_version = None; + + for line in setup_sdp.lines() { + let trimmed = line.trim(); + if let Some(value) = trimmed.strip_prefix("a=ice-ufrag:") { + ice_ufrag = Some(value.to_string()); + } else if let Some(value) = trimmed.strip_prefix("a=ice-pwd:") { + ice_pwd = Some(value.to_string()); + } else if let Some(value) = trimmed.strip_prefix("a=fingerprint:") { + fingerprint = Some(parse_fingerprint(value)?); + } else if let Some(value) = trimmed.strip_prefix("a=setup:") { + sdp_type = + if value == "actpass" { V2CallSdpType::Offer } else { V2CallSdpType::Answer }; + } else if let Some(value) = trimmed.strip_prefix("o=") { + let parts = value.split_whitespace().collect::>(); + if parts.len() < 3 { + return Err(ChatError::InvalidEncoding( + "call setup SDP has invalid o= session line".into(), + )); + } + session_id = Some(parts[1].parse::().map_err(|_| { + ChatError::InvalidEncoding("call setup SDP has invalid session id".into()) + })?); + session_version = Some(parts[2].parse::().map_err(|_| { + ChatError::InvalidEncoding("call setup SDP has invalid session version".into()) + })?); + } + } + + Ok(V2CallSetup { + sdp_type, + session_id: session_id.ok_or_else(|| { + ChatError::InvalidEncoding("call setup SDP missing o= session line".into()) + })?, + session_version: session_version.ok_or_else(|| { + ChatError::InvalidEncoding("call setup SDP missing o= session line".into()) + })?, + ice_ufrag: ice_ufrag.ok_or_else(|| { + ChatError::InvalidEncoding("call setup SDP missing a=ice-ufrag".into()) + })?, + ice_pwd: ice_pwd + .ok_or_else(|| ChatError::InvalidEncoding("call setup SDP missing a=ice-pwd".into()))?, + fingerprint: fingerprint.ok_or_else(|| { + ChatError::InvalidEncoding("call setup SDP missing a=fingerprint".into()) + })?, + candidates: Vec::new(), + }) } fn parse_v2_call_ice_candidate( - candidate: &V2CallIceCandidate, + candidate: &V2CallIceCandidate, ) -> Result { - if candidate.sdp_m_line_index != 0 { - return Err(ChatError::InvalidEncoding(format!( - "call ICE candidate has unsupported sdpMLineIndex {}", - candidate.sdp_m_line_index - ))); - } - if !matches!(candidate.sdp_mid.as_deref(), None | Some("0")) { - return Err(ChatError::InvalidEncoding(format!( - "call ICE candidate has unsupported sdpMid {:?}", - candidate.sdp_mid - ))); - } - - let trimmed = candidate.sdp.trim(); - let content = trimmed.strip_prefix("candidate:").ok_or_else(|| { - ChatError::InvalidEncoding("call ICE candidate missing candidate: prefix".into()) - })?; - let parts = content.split_whitespace().collect::>(); - if parts.len() < 8 || parts[6] != "typ" { - return Err(ChatError::InvalidEncoding( - "call ICE candidate has invalid format".into(), - )); - } - - let component_id = parts[1].parse::().map_err(|_| { - ChatError::InvalidEncoding("call ICE candidate has invalid component id".into()) - })?; - if component_id != 1 { - return Err(ChatError::InvalidEncoding(format!( - "call ICE candidate has unsupported component id {component_id}" - ))); - } - - let priority = parts[3].parse::().map_err(|_| { - ChatError::InvalidEncoding("call ICE candidate has invalid priority".into()) - })?; - validate_call_priority(priority)?; - - Ok(V2CallMinimalCandidate { - foundation: parts[0].to_string(), - priority, - transport_type: parse_transport_type(parts[2])?, - address: parse_ip_address(parts[4])?, - port: parts[5].parse::().map_err(|_| { - ChatError::InvalidEncoding("call ICE candidate has invalid port".into()) - })?, - candidate_type: parse_candidate_type(parts[7])?, - }) + if candidate.sdp_m_line_index != 0 { + return Err(ChatError::InvalidEncoding(format!( + "call ICE candidate has unsupported sdpMLineIndex {}", + candidate.sdp_m_line_index + ))); + } + if !matches!(candidate.sdp_mid.as_deref(), None | Some("0")) { + return Err(ChatError::InvalidEncoding(format!( + "call ICE candidate has unsupported sdpMid {:?}", + candidate.sdp_mid + ))); + } + + let trimmed = candidate.sdp.trim(); + let content = trimmed.strip_prefix("candidate:").ok_or_else(|| { + ChatError::InvalidEncoding("call ICE candidate missing candidate: prefix".into()) + })?; + let parts = content.split_whitespace().collect::>(); + if parts.len() < 8 || parts[6] != "typ" { + return Err(ChatError::InvalidEncoding("call ICE candidate has invalid format".into())); + } + + let component_id = parts[1].parse::().map_err(|_| { + ChatError::InvalidEncoding("call ICE candidate has invalid component id".into()) + })?; + if component_id != 1 { + return Err(ChatError::InvalidEncoding(format!( + "call ICE candidate has unsupported component id {component_id}" + ))); + } + + let priority = parts[3].parse::().map_err(|_| { + ChatError::InvalidEncoding("call ICE candidate has invalid priority".into()) + })?; + validate_call_priority(priority)?; + + Ok(V2CallMinimalCandidate { + foundation: parts[0].to_string(), + priority, + transport_type: parse_transport_type(parts[2])?, + address: parse_ip_address(parts[4])?, + port: parts[5].parse::().map_err(|_| { + ChatError::InvalidEncoding("call ICE candidate has invalid port".into()) + })?, + candidate_type: parse_candidate_type(parts[7])?, + }) } /// ICE candidate priority must fit in a signed 32-bit integer to round-trip @@ -450,21 +437,21 @@ fn parse_v2_call_ice_candidate( /// produces or consumes the binary candidate form so the SDP parser, the /// binary encoder, and the binary decoder agree on the legal range. fn validate_call_priority(priority: u32) -> Result<(), ChatError> { - if priority > i32::MAX as u32 { - return Err(ChatError::InvalidEncoding(format!( - "call ICE candidate priority {priority} exceeds Android v2 Int range" - ))); - } - Ok(()) + if priority > i32::MAX as u32 { + return Err(ChatError::InvalidEncoding(format!( + "call ICE candidate priority {priority} exceeds Android v2 Int range" + ))); + } + Ok(()) } fn reconstruct_v2_call_setup_sdp(setup: &V2CallSetup) -> String { - let setup_value = match setup.sdp_type { - V2CallSdpType::Offer => "actpass", - V2CallSdpType::Answer => "active", - }; - format!( - "v=0\n\ + let setup_value = match setup.sdp_type { + V2CallSdpType::Offer => "actpass", + V2CallSdpType::Answer => "active", + }; + format!( + "v=0\n\ o=- {} {} IN IP4 0.0.0.0\n\ s=-\n\ t=0 0\n\ @@ -476,297 +463,289 @@ fn reconstruct_v2_call_setup_sdp(setup: &V2CallSetup) -> String { a=setup:{}\n\ a=mid:0\n\ a=sctp-port:5000\n", - setup.session_id, - setup.session_version, - setup.ice_ufrag, - setup.ice_pwd, - format_fingerprint(&setup.fingerprint), - setup_value - ) + setup.session_id, + setup.session_version, + setup.ice_ufrag, + setup.ice_pwd, + format_fingerprint(&setup.fingerprint), + setup_value + ) } fn reconstruct_v2_call_ice_candidate(candidate: &V2CallMinimalCandidate) -> V2CallIceCandidate { - V2CallIceCandidate { - sdp: format!( - "candidate:{} 1 {} {} {} {} typ {}", - candidate.foundation, - transport_type_string(candidate.transport_type), - candidate.priority, - ip_address_string(&candidate.address), - candidate.port, - candidate_type_string(candidate.candidate_type) - ), - sdp_m_line_index: 0, - sdp_mid: Some("0".into()), - } + V2CallIceCandidate { + sdp: format!( + "candidate:{} 1 {} {} {} {} typ {}", + candidate.foundation, + transport_type_string(candidate.transport_type), + candidate.priority, + ip_address_string(&candidate.address), + candidate.port, + candidate_type_string(candidate.candidate_type) + ), + sdp_m_line_index: 0, + sdp_mid: Some("0".into()), + } } fn encode_v2_call_minimal_candidates( - out: &mut Vec, - candidates: &[V2CallMinimalCandidate], + out: &mut Vec, + candidates: &[V2CallMinimalCandidate], ) -> Result<(), ChatError> { - let len = u32::try_from(candidates.len()) - .map_err(|_| ChatError::InvalidEncoding("call ICE candidate vector is too large".into()))?; - out.extend_from_slice(&encode_compact_u32(len)); - for candidate in candidates { - validate_call_priority(candidate.priority)?; - encode_string(out, &candidate.foundation)?; - out.extend_from_slice(&candidate.priority.to_le_bytes()); - out.push(transport_type_index(candidate.transport_type)); - encode_ip_address(out, &candidate.address); - out.extend_from_slice(&candidate.port.to_le_bytes()); - out.push(candidate_type_index(candidate.candidate_type)); - } - Ok(()) + let len = u32::try_from(candidates.len()) + .map_err(|_| ChatError::InvalidEncoding("call ICE candidate vector is too large".into()))?; + out.extend_from_slice(&encode_compact_u32(len)); + for candidate in candidates { + validate_call_priority(candidate.priority)?; + encode_string(out, &candidate.foundation)?; + out.extend_from_slice(&candidate.priority.to_le_bytes()); + out.push(transport_type_index(candidate.transport_type)); + encode_ip_address(out, &candidate.address); + out.extend_from_slice(&candidate.port.to_le_bytes()); + out.push(candidate_type_index(candidate.candidate_type)); + } + Ok(()) } fn decode_v2_call_minimal_candidates( - cursor: &mut Cursor<'_>, - field: &str, + cursor: &mut Cursor<'_>, + field: &str, ) -> Result, ChatError> { - let (len, consumed) = decode_compact_u32(&cursor.data[cursor.offset..]) - .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; - cursor.offset += consumed; - - // Cap the pre-allocation to the bytes that actually remain (each candidate - // needs at least one byte) so a malformed length prefix can't trigger a - // multi-gigabyte reservation and abort the process. - let remaining = cursor.data.len().saturating_sub(cursor.offset); - let mut out = Vec::with_capacity((len as usize).min(remaining)); - for index in 0..len { - let item_field = format!("{field}[{index}]"); - let foundation = cursor.read_string(&format!("{item_field}.foundation"))?; - let priority = cursor.read_u32(&format!("{item_field}.priority"))?; - validate_call_priority(priority)?; - let transport_type = - decode_transport_type(cursor.read_u8(&format!("{item_field}.transport_type"))?)?; - let address = decode_ip_address(cursor, &format!("{item_field}.address"))?; - let port = cursor.read_u16(&format!("{item_field}.port"))?; - let candidate_type = - decode_candidate_type(cursor.read_u8(&format!("{item_field}.candidate_type"))?)?; - out.push(V2CallMinimalCandidate { - foundation, - priority, - transport_type, - address, - port, - candidate_type, - }); - } - Ok(out) + let (len, consumed) = decode_compact_u32(&cursor.data[cursor.offset..]) + .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; + cursor.offset += consumed; + + // Cap the pre-allocation to the bytes that actually remain (each candidate + // needs at least one byte) so a malformed length prefix can't trigger a + // multi-gigabyte reservation and abort the process. + let remaining = cursor.data.len().saturating_sub(cursor.offset); + let mut out = Vec::with_capacity((len as usize).min(remaining)); + for index in 0..len { + let item_field = format!("{field}[{index}]"); + let foundation = cursor.read_string(&format!("{item_field}.foundation"))?; + let priority = cursor.read_u32(&format!("{item_field}.priority"))?; + validate_call_priority(priority)?; + let transport_type = + decode_transport_type(cursor.read_u8(&format!("{item_field}.transport_type"))?)?; + let address = decode_ip_address(cursor, &format!("{item_field}.address"))?; + let port = cursor.read_u16(&format!("{item_field}.port"))?; + let candidate_type = + decode_candidate_type(cursor.read_u8(&format!("{item_field}.candidate_type"))?)?; + out.push(V2CallMinimalCandidate { + foundation, + priority, + transport_type, + address, + port, + candidate_type, + }); + } + Ok(out) } fn encode_ip_address(out: &mut Vec, address: &V2CallIpAddress) { - match address { - V2CallIpAddress::Ipv4(bytes) => { - out.push(0); - out.extend_from_slice(bytes); - } - V2CallIpAddress::Ipv6(segments) => { - out.push(1); - for segment in segments { - out.extend_from_slice(&segment.to_le_bytes()); - } - } - } + match address { + V2CallIpAddress::Ipv4(bytes) => { + out.push(0); + out.extend_from_slice(bytes); + }, + V2CallIpAddress::Ipv6(segments) => { + out.push(1); + for segment in segments { + out.extend_from_slice(&segment.to_le_bytes()); + } + }, + } } fn decode_ip_address(cursor: &mut Cursor<'_>, field: &str) -> Result { - match cursor.read_u8(field)? { - 0 => Ok(V2CallIpAddress::Ipv4( - cursor - .read_exact(4, field)? - .try_into() - .map_err(|_| ChatError::InvalidEncoding(format!("{field}: invalid IPv4")))?, - )), - 1 => { - let mut segments = [0_u16; 8]; - for segment in &mut segments { - *segment = cursor.read_u16(field)?; - } - Ok(V2CallIpAddress::Ipv6(segments)) - } - value => Err(ChatError::InvalidEncoding(format!( - "{field}: unsupported IP address type {value}" - ))), - } + match cursor.read_u8(field)? { + 0 => Ok(V2CallIpAddress::Ipv4( + cursor + .read_exact(4, field)? + .try_into() + .map_err(|_| ChatError::InvalidEncoding(format!("{field}: invalid IPv4")))?, + )), + 1 => { + let mut segments = [0_u16; 8]; + for segment in &mut segments { + *segment = cursor.read_u16(field)?; + } + Ok(V2CallIpAddress::Ipv6(segments)) + }, + value => { + Err(ChatError::InvalidEncoding(format!("{field}: unsupported IP address type {value}"))) + }, + } } fn parse_fingerprint(value: &str) -> Result, ChatError> { - // The wire format carries only the raw digest bytes with no algorithm tag, - // and reconstruction always emits `sha-256`. Reject any other algorithm at - // parse time rather than silently relabelling a non-sha-256 fingerprint. - let trimmed = value.trim(); - let hex = match trimmed.split_once(' ') { - Some((algorithm, rest)) => { - if !algorithm.eq_ignore_ascii_case("sha-256") { - return Err(ChatError::InvalidEncoding(format!( - "call SDP fingerprint uses unsupported algorithm {algorithm}; only sha-256 is supported" - ))); - } - rest - } - None => trimmed, - } - .replace(':', ""); - // `is_multiple_of` and the slicing below are byte-oriented, so a non-ASCII - // value could otherwise slice across a UTF-8 char boundary and panic. - if !hex.is_ascii() { - return Err(ChatError::InvalidEncoding( - "call SDP fingerprint is not hex".into(), - )); - } - if !hex.len().is_multiple_of(2) { - return Err(ChatError::InvalidEncoding( - "call SDP fingerprint hex has odd length".into(), - )); - } - (0..hex.len()) - .step_by(2) - .map(|index| { - u8::from_str_radix(&hex[index..index + 2], 16) - .map_err(|_| ChatError::InvalidEncoding("call SDP fingerprint is not hex".into())) - }) - .collect() + // The wire format carries only the raw digest bytes with no algorithm tag, + // and reconstruction always emits `sha-256`. Reject any other algorithm at + // parse time rather than silently relabelling a non-sha-256 fingerprint. + let trimmed = value.trim(); + let hex = match trimmed.split_once(' ') { + Some((algorithm, rest)) => { + if !algorithm.eq_ignore_ascii_case("sha-256") { + return Err(ChatError::InvalidEncoding(format!( + "call SDP fingerprint uses unsupported algorithm {algorithm}; only sha-256 is supported" + ))); + } + rest + }, + None => trimmed, + } + .replace(':', ""); + // `is_multiple_of` and the slicing below are byte-oriented, so a non-ASCII + // value could otherwise slice across a UTF-8 char boundary and panic. + if !hex.is_ascii() { + return Err(ChatError::InvalidEncoding("call SDP fingerprint is not hex".into())); + } + if !hex.len().is_multiple_of(2) { + return Err(ChatError::InvalidEncoding("call SDP fingerprint hex has odd length".into())); + } + (0..hex.len()) + .step_by(2) + .map(|index| { + u8::from_str_radix(&hex[index..index + 2], 16) + .map_err(|_| ChatError::InvalidEncoding("call SDP fingerprint is not hex".into())) + }) + .collect() } fn format_fingerprint(data: &[u8]) -> String { - let mut out = String::from("sha-256 "); - for (index, byte) in data.iter().enumerate() { - if index > 0 { - out.push(':'); - } - out.push_str(&format!("{byte:02X}")); - } - out + let mut out = String::from("sha-256 "); + for (index, byte) in data.iter().enumerate() { + if index > 0 { + out.push(':'); + } + out.push_str(&format!("{byte:02X}")); + } + out } fn parse_ip_address(value: &str) -> Result { - match value.parse::().map_err(|_| { - ChatError::InvalidEncoding(format!("call ICE candidate has invalid IP address {value}")) - })? { - IpAddr::V4(address) => Ok(V2CallIpAddress::Ipv4(address.octets())), - IpAddr::V6(address) => Ok(V2CallIpAddress::Ipv6(address.segments())), - } + match value.parse::().map_err(|_| { + ChatError::InvalidEncoding(format!("call ICE candidate has invalid IP address {value}")) + })? { + IpAddr::V4(address) => Ok(V2CallIpAddress::Ipv4(address.octets())), + IpAddr::V6(address) => Ok(V2CallIpAddress::Ipv6(address.segments())), + } } fn ip_address_string(address: &V2CallIpAddress) -> String { - match address { - V2CallIpAddress::Ipv4(bytes) => { - Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]).to_string() - } - V2CallIpAddress::Ipv6(segments) => Ipv6Addr::new( - segments[0], - segments[1], - segments[2], - segments[3], - segments[4], - segments[5], - segments[6], - segments[7], - ) - .to_string(), - } + match address { + V2CallIpAddress::Ipv4(bytes) => { + Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]).to_string() + }, + V2CallIpAddress::Ipv6(segments) => Ipv6Addr::new( + segments[0], + segments[1], + segments[2], + segments[3], + segments[4], + segments[5], + segments[6], + segments[7], + ) + .to_string(), + } } fn sdp_type_index(value: V2CallSdpType) -> u8 { - match value { - V2CallSdpType::Offer => 0, - V2CallSdpType::Answer => 1, - } + match value { + V2CallSdpType::Offer => 0, + V2CallSdpType::Answer => 1, + } } fn decode_sdp_type(value: u8) -> Result { - match value { - 0 => Ok(V2CallSdpType::Offer), - 1 => Ok(V2CallSdpType::Answer), - value => Err(ChatError::InvalidEncoding(format!( - "unsupported call SDP type {value}" - ))), - } + match value { + 0 => Ok(V2CallSdpType::Offer), + 1 => Ok(V2CallSdpType::Answer), + value => Err(ChatError::InvalidEncoding(format!("unsupported call SDP type {value}"))), + } } fn parse_transport_type(value: &str) -> Result { - match value.to_ascii_lowercase().as_str() { - "tcp" => Ok(V2CallTransportType::Tcp), - "udp" => Ok(V2CallTransportType::Udp), - _ => Err(ChatError::InvalidEncoding(format!( - "unsupported call ICE transport {value}" - ))), - } + match value.to_ascii_lowercase().as_str() { + "tcp" => Ok(V2CallTransportType::Tcp), + "udp" => Ok(V2CallTransportType::Udp), + _ => Err(ChatError::InvalidEncoding(format!("unsupported call ICE transport {value}"))), + } } fn transport_type_index(value: V2CallTransportType) -> u8 { - match value { - V2CallTransportType::Tcp => 0, - V2CallTransportType::Udp => 1, - } + match value { + V2CallTransportType::Tcp => 0, + V2CallTransportType::Udp => 1, + } } fn decode_transport_type(value: u8) -> Result { - match value { - 0 => Ok(V2CallTransportType::Tcp), - 1 => Ok(V2CallTransportType::Udp), - value => Err(ChatError::InvalidEncoding(format!( - "unsupported call ICE transport type {value}" - ))), - } + match value { + 0 => Ok(V2CallTransportType::Tcp), + 1 => Ok(V2CallTransportType::Udp), + value => { + Err(ChatError::InvalidEncoding(format!("unsupported call ICE transport type {value}"))) + }, + } } fn transport_type_string(value: V2CallTransportType) -> &'static str { - match value { - V2CallTransportType::Tcp => "TCP", - V2CallTransportType::Udp => "UDP", - } + match value { + V2CallTransportType::Tcp => "TCP", + V2CallTransportType::Udp => "UDP", + } } fn parse_candidate_type(value: &str) -> Result { - match value.to_ascii_lowercase().as_str() { - "host" => Ok(V2CallCandidateType::Host), - "srflx" => Ok(V2CallCandidateType::Srflx), - "relay" => Ok(V2CallCandidateType::Relay), - "prflx" => Ok(V2CallCandidateType::Prflx), - _ => Err(ChatError::InvalidEncoding(format!( - "unsupported call ICE candidate type {value}" - ))), - } + match value.to_ascii_lowercase().as_str() { + "host" => Ok(V2CallCandidateType::Host), + "srflx" => Ok(V2CallCandidateType::Srflx), + "relay" => Ok(V2CallCandidateType::Relay), + "prflx" => Ok(V2CallCandidateType::Prflx), + _ => { + Err(ChatError::InvalidEncoding(format!("unsupported call ICE candidate type {value}"))) + }, + } } fn candidate_type_index(value: V2CallCandidateType) -> u8 { - match value { - V2CallCandidateType::Host => 0, - V2CallCandidateType::Srflx => 1, - V2CallCandidateType::Relay => 2, - V2CallCandidateType::Prflx => 3, - } + match value { + V2CallCandidateType::Host => 0, + V2CallCandidateType::Srflx => 1, + V2CallCandidateType::Relay => 2, + V2CallCandidateType::Prflx => 3, + } } fn candidate_type_string(value: V2CallCandidateType) -> &'static str { - match value { - V2CallCandidateType::Host => "host", - V2CallCandidateType::Srflx => "srflx", - V2CallCandidateType::Relay => "relay", - V2CallCandidateType::Prflx => "prflx", - } + match value { + V2CallCandidateType::Host => "host", + V2CallCandidateType::Srflx => "srflx", + V2CallCandidateType::Relay => "relay", + V2CallCandidateType::Prflx => "prflx", + } } fn decode_candidate_type(value: u8) -> Result { - match value { - 0 => Ok(V2CallCandidateType::Host), - 1 => Ok(V2CallCandidateType::Srflx), - 2 => Ok(V2CallCandidateType::Relay), - 3 => Ok(V2CallCandidateType::Prflx), - value => Err(ChatError::InvalidEncoding(format!( - "unsupported call ICE candidate type {value}" - ))), - } + match value { + 0 => Ok(V2CallCandidateType::Host), + 1 => Ok(V2CallCandidateType::Srflx), + 2 => Ok(V2CallCandidateType::Relay), + 3 => Ok(V2CallCandidateType::Prflx), + value => { + Err(ChatError::InvalidEncoding(format!("unsupported call ICE candidate type {value}"))) + }, + } } #[cfg(test)] mod tests { - use super::*; + use super::*; - const OFFER_SDP: &str = "v=0\n\ + const OFFER_SDP: &str = "v=0\n\ o=- 12345 67890 IN IP4 0.0.0.0\n\ s=-\nt=0 0\n\ a=ice-ufrag:ufrag123\n\ @@ -774,120 +753,108 @@ mod tests { a=fingerprint:sha-256 A1:B2:C3:D4\n\ a=setup:actpass\n"; - fn ice(sdp: &str) -> V2CallIceCandidate { - V2CallIceCandidate { - sdp: sdp.into(), - sdp_m_line_index: 0, - sdp_mid: Some("0".into()), - } - } - - // Fix 1: a malformed length prefix must not trigger a huge allocation; it - // should fail cleanly as truncated input. - #[test] - fn decode_candidates_rejects_oversized_length_without_oom() { - let mut data = encode_compact_u32(u32::MAX).to_vec(); - data.extend_from_slice(&[0x04, 0x31]); // one tiny partial candidate, then EOF - let err = decode_v2_call_candidates_payload(&data).unwrap_err(); - assert!(matches!(err, ChatError::InvalidEncoding(_))); - } - - #[test] - fn decode_peer_signal_rejects_oversized_length_without_oom() { - let data = [2, 3, 0xff, 0xff, 0xff, 0xff]; - let err = decode_v2_call_peer_connection_signal(&data).unwrap_err(); - assert!(matches!(err, ChatError::InvalidEncoding(_))); - } - - // Fix 2: a non-ASCII fingerprint must error, not panic on a char boundary. - #[test] - fn parse_fingerprint_rejects_non_ascii_without_panic() { - let err = parse_fingerprint("sha-256 A£B").unwrap_err(); - assert!(matches!(err, ChatError::InvalidEncoding(_))); - } - - // Fix 3: the wire format is sha-256 only; other algorithms must be rejected - // rather than silently relabelled on reconstruction. - #[test] - fn parse_fingerprint_rejects_non_sha256_algorithm() { - let err = parse_fingerprint("sha-1 A1:B2:C3:D4").unwrap_err(); - match err { - ChatError::InvalidEncoding(msg) => assert!(msg.contains("unsupported algorithm")), - other => panic!("unexpected error: {other:?}"), - } - // bare hex (no algorithm token) is still accepted as sha-256. - assert_eq!( - parse_fingerprint("A1:B2:C3:D4").unwrap(), - vec![0xA1, 0xB2, 0xC3, 0xD4] - ); - } - - // Fix 4: priority > i32::MAX is rejected on both the binary encode path and - // the binary decode path, matching the SDP parser — so the codec can never - // emit a value it would refuse to read back. - #[test] - fn priority_bound_enforced_on_encode_and_decode() { - let candidate = V2CallMinimalCandidate { - foundation: "1".into(), - priority: i32::MAX as u32 + 1, - transport_type: V2CallTransportType::Udp, - address: V2CallIpAddress::Ipv4([192, 168, 1, 1]), - port: 1234, - candidate_type: V2CallCandidateType::Host, - }; - assert!(encode_v2_call_candidates_payload(std::slice::from_ref(&candidate)).is_err()); - - // Hand-assemble a one-candidate payload with an out-of-range priority. - let mut data = encode_compact_u32(1).to_vec(); - data.extend_from_slice(&[0x04, 0x31]); // foundation "1" - data.extend_from_slice(&u32::MAX.to_le_bytes()); // priority - data.push(transport_type_index(V2CallTransportType::Udp)); - encode_ip_address(&mut data, &V2CallIpAddress::Ipv4([192, 168, 1, 1])); - data.extend_from_slice(&1234_u16.to_le_bytes()); - data.push(candidate_type_index(V2CallCandidateType::Host)); - assert!(decode_v2_call_candidates_payload(&data).is_err()); - } - - // Fix 5: a non-canonical (zero-padded big-mode) compact session id must be - // rejected so the wire format stays a 1:1 mapping. - #[test] - fn decode_setup_rejects_non_canonical_compact_session_id() { - // sdp_type=offer, then session_id encoded in big mode as value 5 with a - // trailing zero byte — a value that canonically fits in single-byte mode. - let data = [0x00, 0x03, 0x05, 0x00, 0x00, 0x00]; - assert!(decode_v2_call_setup_payload(&data).is_err()); - } - - // The candidate batch with an IPv6 (relay) entry must round-trip, covering - // the previously untested 16-byte address path. - #[test] - fn ipv6_candidate_round_trips() { - let bytes = encode_v2_call_candidates_from_sdp(&[ice( - "candidate:relay1 1 udp 123456 2001:db8::1 9999 typ relay", - )]) - .unwrap(); - let decoded = decode_v2_call_candidates_payload(&bytes).unwrap(); - assert_eq!(decoded.len(), 1); - assert_eq!( - decoded[0].address, - V2CallIpAddress::Ipv6([0x2001, 0x0db8, 0, 0, 0, 0, 0, 1]) - ); - assert_eq!(decoded[0].candidate_type, V2CallCandidateType::Relay); - } - - // A well-formed offer SDP still parses end-to-end after the fixes. - #[test] - fn offer_sdp_still_encodes() { - let bytes = encode_v2_call_setup_from_sdp( - OFFER_SDP, - std::slice::from_ref(&ice( - "candidate:1 1 udp 2122260223 192.168.1.1 1234 typ host", - )), - ) - .unwrap(); - let decoded = decode_v2_call_setup_payload(&bytes).unwrap(); - assert_eq!(decoded.sdp_type, V2CallSdpType::Offer); - assert_eq!(decoded.session_id, 12_345); - assert_eq!(decoded.candidates.len(), 1); - } + fn ice(sdp: &str) -> V2CallIceCandidate { + V2CallIceCandidate { sdp: sdp.into(), sdp_m_line_index: 0, sdp_mid: Some("0".into()) } + } + + // Fix 1: a malformed length prefix must not trigger a huge allocation; it + // should fail cleanly as truncated input. + #[test] + fn decode_candidates_rejects_oversized_length_without_oom() { + let mut data = encode_compact_u32(u32::MAX).to_vec(); + data.extend_from_slice(&[0x04, 0x31]); // one tiny partial candidate, then EOF + let err = decode_v2_call_candidates_payload(&data).unwrap_err(); + assert!(matches!(err, ChatError::InvalidEncoding(_))); + } + + #[test] + fn decode_peer_signal_rejects_oversized_length_without_oom() { + let data = [2, 3, 0xff, 0xff, 0xff, 0xff]; + let err = decode_v2_call_peer_connection_signal(&data).unwrap_err(); + assert!(matches!(err, ChatError::InvalidEncoding(_))); + } + + // Fix 2: a non-ASCII fingerprint must error, not panic on a char boundary. + #[test] + fn parse_fingerprint_rejects_non_ascii_without_panic() { + let err = parse_fingerprint("sha-256 A£B").unwrap_err(); + assert!(matches!(err, ChatError::InvalidEncoding(_))); + } + + // Fix 3: the wire format is sha-256 only; other algorithms must be rejected + // rather than silently relabelled on reconstruction. + #[test] + fn parse_fingerprint_rejects_non_sha256_algorithm() { + let err = parse_fingerprint("sha-1 A1:B2:C3:D4").unwrap_err(); + match err { + ChatError::InvalidEncoding(msg) => assert!(msg.contains("unsupported algorithm")), + other => panic!("unexpected error: {other:?}"), + } + // bare hex (no algorithm token) is still accepted as sha-256. + assert_eq!(parse_fingerprint("A1:B2:C3:D4").unwrap(), vec![0xA1, 0xB2, 0xC3, 0xD4]); + } + + // Fix 4: priority > i32::MAX is rejected on both the binary encode path and + // the binary decode path, matching the SDP parser — so the codec can never + // emit a value it would refuse to read back. + #[test] + fn priority_bound_enforced_on_encode_and_decode() { + let candidate = V2CallMinimalCandidate { + foundation: "1".into(), + priority: i32::MAX as u32 + 1, + transport_type: V2CallTransportType::Udp, + address: V2CallIpAddress::Ipv4([192, 168, 1, 1]), + port: 1234, + candidate_type: V2CallCandidateType::Host, + }; + assert!(encode_v2_call_candidates_payload(std::slice::from_ref(&candidate)).is_err()); + + // Hand-assemble a one-candidate payload with an out-of-range priority. + let mut data = encode_compact_u32(1).to_vec(); + data.extend_from_slice(&[0x04, 0x31]); // foundation "1" + data.extend_from_slice(&u32::MAX.to_le_bytes()); // priority + data.push(transport_type_index(V2CallTransportType::Udp)); + encode_ip_address(&mut data, &V2CallIpAddress::Ipv4([192, 168, 1, 1])); + data.extend_from_slice(&1234_u16.to_le_bytes()); + data.push(candidate_type_index(V2CallCandidateType::Host)); + assert!(decode_v2_call_candidates_payload(&data).is_err()); + } + + // Fix 5: a non-canonical (zero-padded big-mode) compact session id must be + // rejected so the wire format stays a 1:1 mapping. + #[test] + fn decode_setup_rejects_non_canonical_compact_session_id() { + // sdp_type=offer, then session_id encoded in big mode as value 5 with a + // trailing zero byte — a value that canonically fits in single-byte mode. + let data = [0x00, 0x03, 0x05, 0x00, 0x00, 0x00]; + assert!(decode_v2_call_setup_payload(&data).is_err()); + } + + // The candidate batch with an IPv6 (relay) entry must round-trip, covering + // the previously untested 16-byte address path. + #[test] + fn ipv6_candidate_round_trips() { + let bytes = encode_v2_call_candidates_from_sdp(&[ice( + "candidate:relay1 1 udp 123456 2001:db8::1 9999 typ relay", + )]) + .unwrap(); + let decoded = decode_v2_call_candidates_payload(&bytes).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].address, V2CallIpAddress::Ipv6([0x2001, 0x0db8, 0, 0, 0, 0, 0, 1])); + assert_eq!(decoded[0].candidate_type, V2CallCandidateType::Relay); + } + + // A well-formed offer SDP still parses end-to-end after the fixes. + #[test] + fn offer_sdp_still_encodes() { + let bytes = encode_v2_call_setup_from_sdp( + OFFER_SDP, + std::slice::from_ref(&ice("candidate:1 1 udp 2122260223 192.168.1.1 1234 typ host")), + ) + .unwrap(); + let decoded = decode_v2_call_setup_payload(&bytes).unwrap(); + assert_eq!(decoded.sdp_type, V2CallSdpType::Offer); + assert_eq!(decoded.session_id, 12_345); + assert_eq!(decoded.candidates.len(), 1); + } } diff --git a/rust/crates/truapi-chat-v2/src/lib.rs b/rust/crates/truapi-chat-v2/src/lib.rs index 72317d31a6..2a60d368af 100644 --- a/rust/crates/truapi-chat-v2/src/lib.rs +++ b/rust/crates/truapi-chat-v2/src/lib.rs @@ -10,15 +10,20 @@ //! request/response transport payloads. extern crate alloc; -use alloc::format; -use alloc::string::{String, ToString}; -use alloc::vec; -use alloc::vec::Vec; -use blake2::digest::consts::U32; -use blake2::digest::{Digest, KeyInit as BlakeKeyInit, Mac}; -use blake2::{Blake2b, Blake2bMac}; -use chacha20poly1305::aead::{Aead, Payload}; -use chacha20poly1305::{ChaCha20Poly1305, Nonce}; +use alloc::{ + format, + string::{String, ToString}, + vec, + vec::Vec, +}; +use blake2::{ + Blake2b, Blake2bMac, + digest::{Digest, KeyInit as BlakeKeyInit, Mac, consts::U32}, +}; +use chacha20poly1305::{ + ChaCha20Poly1305, Nonce, + aead::{Aead, Payload}, +}; use hkdf::Hkdf; use sha2::Sha256; use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret}; @@ -31,96 +36,94 @@ pub use call_payload::*; /// Statement Store topic digest. pub type Topic = [u8; 32]; fn encode_compact_u32(value: u32) -> Vec { - if value < 1 << 6 { - vec![(value as u8) << 2] - } else if value < 1 << 14 { - (((value as u16) << 2) | 0b01).to_le_bytes().to_vec() - } else if value < 1 << 30 { - ((value << 2) | 0b10).to_le_bytes().to_vec() - } else { - let mut out = Vec::with_capacity(5); - out.push(0b11); - out.extend_from_slice(&value.to_le_bytes()); - out - } + if value < 1 << 6 { + vec![(value as u8) << 2] + } else if value < 1 << 14 { + (((value as u16) << 2) | 0b01).to_le_bytes().to_vec() + } else if value < 1 << 30 { + ((value << 2) | 0b10).to_le_bytes().to_vec() + } else { + let mut out = Vec::with_capacity(5); + out.push(0b11); + out.extend_from_slice(&value.to_le_bytes()); + out + } } fn decode_compact_u32(data: &[u8]) -> Result<(u32, usize), String> { - let first = *data.first().ok_or_else(|| "compact: empty".to_string())?; - match first & 0b11 { - 0 => Ok((u32::from(first >> 2), 1)), - 1 => { - let bytes: [u8; 2] = data - .get(..2) - .ok_or_else(|| "compact: truncated 2-byte".to_string())? - .try_into() - .map_err(|_| "compact: truncated 2-byte".to_string())?; - let value = u32::from(u16::from_le_bytes(bytes) >> 2); - if value < 1 << 6 { - return Err("compact: non-canonical 2-byte".into()); - } - Ok((value, 2)) - } - 2 => { - let bytes: [u8; 4] = data - .get(..4) - .ok_or_else(|| "compact: truncated 4-byte".to_string())? - .try_into() - .map_err(|_| "compact: truncated 4-byte".to_string())?; - let value = u32::from_le_bytes(bytes) >> 2; - if value < 1 << 14 { - return Err("compact: non-canonical 4-byte".into()); - } - Ok((value, 4)) - } - 3 => { - if first >> 2 != 0 { - return Err("compact: value exceeds u32".into()); - } - let bytes: [u8; 4] = data - .get(1..5) - .ok_or_else(|| "compact: truncated big".to_string())? - .try_into() - .map_err(|_| "compact: truncated big".to_string())?; - let value = u32::from_le_bytes(bytes); - if value < 1 << 30 { - return Err("compact: non-canonical big".into()); - } - Ok((value, 5)) - } - _ => unreachable!(), - } + let first = *data.first().ok_or_else(|| "compact: empty".to_string())?; + match first & 0b11 { + 0 => Ok((u32::from(first >> 2), 1)), + 1 => { + let bytes: [u8; 2] = data + .get(..2) + .ok_or_else(|| "compact: truncated 2-byte".to_string())? + .try_into() + .map_err(|_| "compact: truncated 2-byte".to_string())?; + let value = u32::from(u16::from_le_bytes(bytes) >> 2); + if value < 1 << 6 { + return Err("compact: non-canonical 2-byte".into()); + } + Ok((value, 2)) + }, + 2 => { + let bytes: [u8; 4] = data + .get(..4) + .ok_or_else(|| "compact: truncated 4-byte".to_string())? + .try_into() + .map_err(|_| "compact: truncated 4-byte".to_string())?; + let value = u32::from_le_bytes(bytes) >> 2; + if value < 1 << 14 { + return Err("compact: non-canonical 4-byte".into()); + } + Ok((value, 4)) + }, + 3 => { + if first >> 2 != 0 { + return Err("compact: value exceeds u32".into()); + } + let bytes: [u8; 4] = data + .get(1..5) + .ok_or_else(|| "compact: truncated big".to_string())? + .try_into() + .map_err(|_| "compact: truncated big".to_string())?; + let value = u32::from_le_bytes(bytes); + if value < 1 << 30 { + return Err("compact: non-canonical big".into()); + } + Ok((value, 5)) + }, + _ => unreachable!(), + } } fn blake2b_256(data: &[u8]) -> [u8; 32] { - let mut hasher = Blake2b::::new(); - Digest::update(&mut hasher, data); - hasher.finalize().into() + let mut hasher = Blake2b::::new(); + Digest::update(&mut hasher, data); + hasher.finalize().into() } fn blake2b_256_keyed(key: &[u8], data: &[u8]) -> Result<[u8; 32], ChatError> { - if key.is_empty() { - return Err(ChatError::KeyDerivationFailed( - "BLAKE2b key must not be empty".into(), - )); - } - let mut mac = as BlakeKeyInit>::new_from_slice(key).map_err(|_| { - ChatError::KeyDerivationFailed(format!( - "BLAKE2b key length must be 1..=64, got {}", - key.len() - )) - })?; - Mac::update(&mut mac, data); - Ok(mac.finalize().into_bytes().into()) + if key.is_empty() { + return Err(ChatError::KeyDerivationFailed("BLAKE2b key must not be empty".into())); + } + let mut mac = as BlakeKeyInit>::new_from_slice(key).map_err(|_| { + ChatError::KeyDerivationFailed(format!( + "BLAKE2b key length must be 1..=64, got {}", + key.len() + )) + })?; + Mac::update(&mut mac, data); + Ok(mac.finalize().into_bytes().into()) } #[derive(Debug, thiserror::Error)] pub enum ChatError { - #[error("invalid chat v2 encoding: {0}")] - InvalidEncoding(String), + #[error("invalid chat v2 encoding: {0}")] + InvalidEncoding(String), - #[error("chat v2 key derivation failed: {0}")] - KeyDerivationFailed(String), + #[error("chat v2 key derivation failed: {0}")] + KeyDerivationFailed(String), } /// Statement-store context used by the v2 first-contact chat-request protocol. @@ -139,149 +142,149 @@ const CONTEXT_BOUND_INVITE_MAGIC: &[u8; 8] = b"DCHAT\x03\0\0"; /// Derive an X25519 public key without platform services. pub fn x25519_public_key(private_key: &[u8; 32]) -> [u8; 32] { - X25519PublicKey::from(&StaticSecret::from(*private_key)).to_bytes() + X25519PublicKey::from(&StaticSecret::from(*private_key)).to_bytes() } /// Perform X25519 agreement, rejecting non-contributory peer keys. pub fn x25519_shared_secret( - private_key: &[u8; 32], - peer_public_key: &[u8; 32], + private_key: &[u8; 32], + peer_public_key: &[u8; 32], ) -> Result<[u8; 32], ChatError> { - let shared = StaticSecret::from(*private_key) - .diffie_hellman(&X25519PublicKey::from(*peer_public_key)) - .to_bytes(); - if shared == [0; 32] { - return Err(ChatError::KeyDerivationFailed( - "X25519 peer public key is non-contributory".into(), - )); - } - Ok(shared) + let shared = StaticSecret::from(*private_key) + .diffie_hellman(&X25519PublicKey::from(*peer_public_key)) + .to_bytes(); + if shared == [0; 32] { + return Err(ChatError::KeyDerivationFailed( + "X25519 peer public key is non-contributory".into(), + )); + } + Ok(shared) } /// Expand key material exactly as CryptoKit's /// `hkdfDerivedSymmetricKey(SHA256, salt: empty, sharedInfo: empty, 32)`. pub fn hkdf_sha256_32(input_key_material: &[u8]) -> Result<[u8; 32], ChatError> { - let mut output = [0; 32]; - Hkdf::::new(Some(&[]), input_key_material) - .expand(&[], &mut output) - .map_err(|_| ChatError::KeyDerivationFailed("HKDF-SHA256 expansion failed".into()))?; - Ok(output) + let mut output = [0; 32]; + Hkdf::::new(Some(&[]), input_key_material) + .expand(&[], &mut output) + .map_err(|_| ChatError::KeyDerivationFailed("HKDF-SHA256 expansion failed".into()))?; + Ok(output) } /// Derive the Chat v2 AEAD key shared with a peer X25519 public key. pub fn x25519_hkdf_sha256_key( - private_key: &[u8; 32], - peer_public_key: &[u8; 32], + private_key: &[u8; 32], + peer_public_key: &[u8; 32], ) -> Result<[u8; 32], ChatError> { - hkdf_sha256_32(&x25519_shared_secret(private_key, peer_public_key)?) + hkdf_sha256_32(&x25519_shared_secret(private_key, peer_public_key)?) } /// Encrypt with the opt-in context-bound suite. /// /// The authenticated context binds the product/network identifier, sender, /// recipient, route, and direction. The output remains nonce-prefixed. pub fn context_bound_encrypt_with_nonce( - input_key_material: &[u8], - product_id: &str, - sender_account_id: &[u8; 32], - recipient_account_id: &[u8; 32], - channel_id: &[u8; 32], - plaintext: &[u8], - nonce: [u8; 12], + input_key_material: &[u8], + product_id: &str, + sender_account_id: &[u8; 32], + recipient_account_id: &[u8; 32], + channel_id: &[u8; 32], + plaintext: &[u8], + nonce: [u8; 12], ) -> Result, ChatError> { - let (key, aad) = context_bound_aead_material( - input_key_material, - product_id, - sender_account_id, - recipient_account_id, - channel_id, - )?; - chacha20poly1305_encrypt_with_nonce_and_aad(&key, plaintext, nonce, &aad) + let (key, aad) = context_bound_aead_material( + input_key_material, + product_id, + sender_account_id, + recipient_account_id, + channel_id, + )?; + chacha20poly1305_encrypt_with_nonce_and_aad(&key, plaintext, nonce, &aad) } /// Decrypt with the exact context selected by the sender. pub fn context_bound_decrypt( - input_key_material: &[u8], - product_id: &str, - sender_account_id: &[u8; 32], - recipient_account_id: &[u8; 32], - channel_id: &[u8; 32], - ciphertext: &[u8], + input_key_material: &[u8], + product_id: &str, + sender_account_id: &[u8; 32], + recipient_account_id: &[u8; 32], + channel_id: &[u8; 32], + ciphertext: &[u8], ) -> Result, ChatError> { - let (key, aad) = context_bound_aead_material( - input_key_material, - product_id, - sender_account_id, - recipient_account_id, - channel_id, - )?; - chacha20poly1305_decrypt_with_aad(&key, ciphertext, &aad) + let (key, aad) = context_bound_aead_material( + input_key_material, + product_id, + sender_account_id, + recipient_account_id, + channel_id, + )?; + chacha20poly1305_decrypt_with_aad(&key, ciphertext, &aad) } /// X25519 agreement followed by context-bound encryption. #[allow(clippy::too_many_arguments)] pub fn x25519_context_bound_encrypt_with_nonce( - private_key: &[u8; 32], - peer_public_key: &[u8; 32], - product_id: &str, - sender_account_id: &[u8; 32], - recipient_account_id: &[u8; 32], - channel_id: &[u8; 32], - plaintext: &[u8], - nonce: [u8; 12], + private_key: &[u8; 32], + peer_public_key: &[u8; 32], + product_id: &str, + sender_account_id: &[u8; 32], + recipient_account_id: &[u8; 32], + channel_id: &[u8; 32], + plaintext: &[u8], + nonce: [u8; 12], ) -> Result, ChatError> { - context_bound_encrypt_with_nonce( - &x25519_shared_secret(private_key, peer_public_key)?, - product_id, - sender_account_id, - recipient_account_id, - channel_id, - plaintext, - nonce, - ) + context_bound_encrypt_with_nonce( + &x25519_shared_secret(private_key, peer_public_key)?, + product_id, + sender_account_id, + recipient_account_id, + channel_id, + plaintext, + nonce, + ) } /// X25519 agreement followed by context-bound decryption. pub fn x25519_context_bound_decrypt( - private_key: &[u8; 32], - peer_public_key: &[u8; 32], - product_id: &str, - sender_account_id: &[u8; 32], - recipient_account_id: &[u8; 32], - channel_id: &[u8; 32], - ciphertext: &[u8], + private_key: &[u8; 32], + peer_public_key: &[u8; 32], + product_id: &str, + sender_account_id: &[u8; 32], + recipient_account_id: &[u8; 32], + channel_id: &[u8; 32], + ciphertext: &[u8], ) -> Result, ChatError> { - context_bound_decrypt( - &x25519_shared_secret(private_key, peer_public_key)?, - product_id, - sender_account_id, - recipient_account_id, - channel_id, - ciphertext, - ) + context_bound_decrypt( + &x25519_shared_secret(private_key, peer_public_key)?, + product_id, + sender_account_id, + recipient_account_id, + channel_id, + ciphertext, + ) } fn context_bound_aead_material( - input_key_material: &[u8], - product_id: &str, - sender_account_id: &[u8; 32], - recipient_account_id: &[u8; 32], - channel_id: &[u8; 32], + input_key_material: &[u8], + product_id: &str, + sender_account_id: &[u8; 32], + recipient_account_id: &[u8; 32], + channel_id: &[u8; 32], ) -> Result<([u8; 32], Vec), ChatError> { - let product_id_len = u32::try_from(product_id.len()) - .map_err(|_| ChatError::InvalidEncoding("product identifier is too long".into()))?; - let mut aad = - Vec::with_capacity(CONTEXT_BOUND_CIPHER_DOMAIN.len() + 4 + product_id.len() + 32 + 32 + 32); - aad.extend_from_slice(CONTEXT_BOUND_CIPHER_DOMAIN); - aad.extend_from_slice(&product_id_len.to_le_bytes()); - aad.extend_from_slice(product_id.as_bytes()); - aad.extend_from_slice(sender_account_id); - aad.extend_from_slice(recipient_account_id); - aad.extend_from_slice(channel_id); - let mut key = [0; 32]; - Hkdf::::new(Some(CONTEXT_BOUND_CIPHER_DOMAIN), input_key_material) - .expand(&aad, &mut key) - .map_err(|_| ChatError::KeyDerivationFailed("context-bound HKDF-SHA256 failed".into()))?; - Ok((key, aad)) + let product_id_len = u32::try_from(product_id.len()) + .map_err(|_| ChatError::InvalidEncoding("product identifier is too long".into()))?; + let mut aad = + Vec::with_capacity(CONTEXT_BOUND_CIPHER_DOMAIN.len() + 4 + product_id.len() + 32 + 32 + 32); + aad.extend_from_slice(CONTEXT_BOUND_CIPHER_DOMAIN); + aad.extend_from_slice(&product_id_len.to_le_bytes()); + aad.extend_from_slice(product_id.as_bytes()); + aad.extend_from_slice(sender_account_id); + aad.extend_from_slice(recipient_account_id); + aad.extend_from_slice(channel_id); + let mut key = [0; 32]; + Hkdf::::new(Some(CONTEXT_BOUND_CIPHER_DOMAIN), input_key_material) + .expand(&aad, &mut key) + .map_err(|_| ChatError::KeyDerivationFailed("context-bound HKDF-SHA256 failed".into()))?; + Ok((key, aad)) } /// Build the keyed proof binding an identity account to a product device. @@ -289,372 +292,341 @@ fn context_bound_aead_material( /// The keyed BLAKE2b-256 input is the raw identity account, raw device account, /// then the SCALE string `mds-chat-request`. pub fn v2_identity_proof( - identity_account_id: &[u8; 32], - device_account_id: &[u8; 32], - shared_secret: &[u8; 32], + identity_account_id: &[u8; 32], + device_account_id: &[u8; 32], + shared_secret: &[u8; 32], ) -> Result<[u8; 32], ChatError> { - let mut payload = Vec::with_capacity(64 + 1 + MULTI_DEVICE_CHAT_REQUEST_CONTEXT.len()); - payload.extend_from_slice(identity_account_id); - payload.extend_from_slice(device_account_id); - encode_string(&mut payload, MULTI_DEVICE_CHAT_REQUEST_CONTEXT)?; - blake2b_256_keyed(shared_secret, &payload) + let mut payload = Vec::with_capacity(64 + 1 + MULTI_DEVICE_CHAT_REQUEST_CONTEXT.len()); + payload.extend_from_slice(identity_account_id); + payload.extend_from_slice(device_account_id); + encode_string(&mut payload, MULTI_DEVICE_CHAT_REQUEST_CONTEXT)?; + blake2b_256_keyed(shared_secret, &payload) } /// Supported subset of the v2 remote chat message content enum. #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2ChatMessageContent { - /// Plain text content. V2 enum index 0. - Text(String), - /// Token content. V2 enum index 1. - Token { - token: Vec, - platform: V2PushPlatform, - }, - /// Legacy send payload for iOS v2 compatibility. V2 enum index 2. - SendLegacy { - amount: String, - block_hash: Vec, - extrinsic_hash: Vec, - }, - /// Contact added notification (deprecated). V2 enum index 3. - ContactAdded, - /// Emoji reaction to a message. V2 enum index 4. - Reacted { message_id: String, emoji: String }, - /// Emoji reaction removal. V2 enum index 5. - ReactionRemoved { message_id: String, emoji: String }, - /// Reply to a message with own content. V2 enum index 7. - Reply { - message_id: String, - text: Option, - attachments: Option>, - }, - /// WebRTC/data-channel offer signaling. V2 enum index 8. - DataChannelOffer { - sdp: Vec, - purpose: V2DataChannelPurpose, - }, - /// WebRTC/data-channel answer signaling. V2 enum index 9. - DataChannelAnswer { offer_id: String, sdp: Vec }, - /// WebRTC/data-channel ICE candidates signaling. V2 enum index 10. - DataChannelCandidates { offer_id: String, sdp: Vec }, - /// WebRTC/data-channel closed signaling. V2 enum index 11. - DataChannelClosed { offer_id: String }, - /// Edited message content. V2 enum index 12. - Edited { - message_id: String, - new_text: Option, - attachments: Option>, - }, - /// User left the chat. V2 enum index 13. - LeftChat, - /// Chat request acceptance content. V2 enum index 14. - ChatAccepted { request_id: String }, - /// Rich text message. V2 enum index 15. - RichText { - text: Option, - attachments: Option>, - }, - /// Coinage payment. V2 enum index 16. - CoinageSend { - total_value: String, - coin_keys: Vec>, - }, - /// A device was added to the identity. V2 enum index 17. - DeviceAdded { - statement_account_id: Vec, - encryption_public_key: Vec, - }, - /// A device was removed from the identity. V2 enum index 18. - DeviceRemoved { statement_account_id: Vec }, - /// Reference to a compacted message batch. V2 enum index 19. - CompactedMessages { - claim_identifier: Vec, - claim_ticket: Vec, - node: V2NodeEndpoint, - }, - /// Multi-device chat acceptance. V2 wire enum index 20. - MultiChatAccepted { - request_id: String, - device: V2PeerDevice, - }, - /// The envelope was valid enough to recover id/timestamp, but the versioned - /// content wrapper is not yet represented by this SDK surface. - UnsupportedVersion { version_index: u8 }, - /// The V1 envelope was valid enough to recover id/timestamp, but its - /// content enum is not yet represented by this SDK surface. - UnsupportedContent { content_index: u8 }, + /// Plain text content. V2 enum index 0. + Text(String), + /// Token content. V2 enum index 1. + Token { token: Vec, platform: V2PushPlatform }, + /// Legacy send payload for iOS v2 compatibility. V2 enum index 2. + SendLegacy { amount: String, block_hash: Vec, extrinsic_hash: Vec }, + /// Contact added notification (deprecated). V2 enum index 3. + ContactAdded, + /// Emoji reaction to a message. V2 enum index 4. + Reacted { message_id: String, emoji: String }, + /// Emoji reaction removal. V2 enum index 5. + ReactionRemoved { message_id: String, emoji: String }, + /// Reply to a message with own content. V2 enum index 7. + Reply { message_id: String, text: Option, attachments: Option> }, + /// WebRTC/data-channel offer signaling. V2 enum index 8. + DataChannelOffer { sdp: Vec, purpose: V2DataChannelPurpose }, + /// WebRTC/data-channel answer signaling. V2 enum index 9. + DataChannelAnswer { offer_id: String, sdp: Vec }, + /// WebRTC/data-channel ICE candidates signaling. V2 enum index 10. + DataChannelCandidates { offer_id: String, sdp: Vec }, + /// WebRTC/data-channel closed signaling. V2 enum index 11. + DataChannelClosed { offer_id: String }, + /// Edited message content. V2 enum index 12. + Edited { message_id: String, new_text: Option, attachments: Option> }, + /// User left the chat. V2 enum index 13. + LeftChat, + /// Chat request acceptance content. V2 enum index 14. + ChatAccepted { request_id: String }, + /// Rich text message. V2 enum index 15. + RichText { text: Option, attachments: Option> }, + /// Coinage payment. V2 enum index 16. + CoinageSend { total_value: String, coin_keys: Vec> }, + /// A device was added to the identity. V2 enum index 17. + DeviceAdded { statement_account_id: Vec, encryption_public_key: Vec }, + /// A device was removed from the identity. V2 enum index 18. + DeviceRemoved { statement_account_id: Vec }, + /// Reference to a compacted message batch. V2 enum index 19. + CompactedMessages { claim_identifier: Vec, claim_ticket: Vec, node: V2NodeEndpoint }, + /// Multi-device chat acceptance. V2 wire enum index 20. + MultiChatAccepted { request_id: String, device: V2PeerDevice }, + /// A profile reference the sender's host discloses to this contact, or + /// `None` to withdraw it. Host-originated and host-consumed: products + /// never send or see it. V2 wire enum index 21. + /// + /// Known gap (docs/rfcs/profile-disclosure.md): index 21 is not yet agreed with native Chat. + ProfileReference { discloser_product_id: String, reference: Option }, + /// Wallet-wide personal grant, explicitly distinguished from app-scoped + /// index 21. Content index 22 carries a validated scope byte of 1. + PersonalProfileReference { + discloser_product_id: String, + reference: Option, + revision: u64, + }, + /// The sender's host hands this contact's host the public half of its + /// pairwise host-channel key, so the two hosts can derive a channel of + /// their own and stop relaying through Chat. Host-originated and + /// host-consumed: products never send or see it. Sent once per contact; + /// a later frame replaces the earlier one. V2 wire enum index 23. + /// + /// Prototype (seity doc/HOST_CHANNEL_PLAN.md): the frame is the host + /// section of a Contacts connect, carried on Chat until Contacts exists. + HostChannelBootstrap { + /// Frame version; only `1` is defined. + version: u8, + /// X25519 public key, pairwise for this contact. + channel_public_key: [u8; 32], + }, + /// The envelope was valid enough to recover id/timestamp, but the versioned + /// content wrapper is not yet represented by this SDK surface. + UnsupportedVersion { version_index: u8 }, + /// The V1 envelope was valid enough to recover id/timestamp, but its + /// content enum is not yet represented by this SDK surface. + UnsupportedContent { content_index: u8 }, } /// V2 chat message statement payload. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatMessage { - pub message_id: String, - pub timestamp: u64, - pub content: V2ChatMessageContent, + pub message_id: String, + pub timestamp: u64, + pub content: V2ChatMessageContent, } /// Fixed-width device record carried by multi-device Chat v2 messages. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2PeerDevice { - pub statement_account_id: [u8; 32], - pub encryption_public_key: [u8; 32], + pub statement_account_id: [u8; 32], + pub encryption_public_key: [u8; 32], } /// Endpoint for a Chat v2 attachment or compacted message batch. #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2NodeEndpoint { - /// Secure WebSocket URL. Endpoint enum index 0. - WssUrl(String), + /// Secure WebSocket URL. Endpoint enum index 0. + WssUrl(String), } /// Attachment transport. Native SCALE enum index 0. #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2FileVariant { - P2pMixnet(V2P2pMixnetFile), + P2pMixnet(V2P2pMixnetFile), } /// Private HOP reference; identifiers and claim tickets are exactly 32 bytes. #[derive(Clone, PartialEq, Eq)] pub struct V2P2pMixnetFile { - pub identifier: Vec, - pub claim_ticket: Vec, - pub node: V2NodeEndpoint, - pub meta: V2FileMeta, + pub identifier: Vec, + pub claim_ticket: Vec, + pub node: V2NodeEndpoint, + pub meta: V2FileMeta, } impl core::fmt::Debug for V2P2pMixnetFile { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("V2P2pMixnetFile") - .field("meta", &self.meta) - .finish_non_exhaustive() - } + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("V2P2pMixnetFile") + .field("meta", &self.meta) + .finish_non_exhaustive() + } } impl Drop for V2P2pMixnetFile { - fn drop(&mut self) { - zeroize::Zeroize::zeroize(&mut self.claim_ticket); - } + fn drop(&mut self) { + zeroize::Zeroize::zeroize(&mut self.claim_ticket); + } } /// Native SCALE metadata indices: General = 0, Image = 1, Video = 2. #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2FileMeta { - General(V2GeneralFileMeta), - Image(V2ImageFileMeta), - Video(V2VideoFileMeta), + General(V2GeneralFileMeta), + Image(V2ImageFileMeta), + Video(V2VideoFileMeta), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2GeneralFileMeta { - pub mime_type: String, - pub file_size: u32, + pub mime_type: String, + pub file_size: u32, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ImageFileMeta { - pub general: V2GeneralFileMeta, - pub width: u32, - pub height: u32, - /// Native UTF-8 BlurHash bytes, not an encoded image. - pub thumbnail: Option>, + pub general: V2GeneralFileMeta, + pub width: u32, + pub height: u32, + /// Native UTF-8 BlurHash bytes, not an encoded image. + pub thumbnail: Option>, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2VideoFileMeta { - pub general: V2GeneralFileMeta, - pub duration: u32, - /// Native UTF-8 BlurHash bytes, not an encoded image. - pub thumbnail: Option>, + pub general: V2GeneralFileMeta, + pub duration: u32, + /// Native UTF-8 BlurHash bytes, not an encoded image. + pub thumbnail: Option>, } /// Shared data-channel purpose enum used by the v2 apps. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum V2DataChannelPurpose { - Audio, - Video, + Audio, + Video, } /// Transport-neutral call signaling model shared across v2 chat and host extensions. #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2CallSignal { - Offer { - offer_id: String, - sdp: Vec, - purpose: V2DataChannelPurpose, - }, - Answer { - offer_id: String, - sdp: Vec, - }, - Candidates { - offer_id: String, - sdp: Vec, - }, - Closed { - offer_id: String, - }, + Offer { offer_id: String, sdp: Vec, purpose: V2DataChannelPurpose }, + Answer { offer_id: String, sdp: Vec }, + Candidates { offer_id: String, sdp: Vec }, + Closed { offer_id: String }, } impl V2ChatMessage { - /// Lift supported v2 data-channel chat content into the shared call-signal model. - pub fn as_call_signal(&self) -> Option { - match &self.content { - V2ChatMessageContent::DataChannelOffer { sdp, purpose } => Some(V2CallSignal::Offer { - offer_id: self.message_id.clone(), - sdp: sdp.clone(), - purpose: *purpose, - }), - V2ChatMessageContent::DataChannelAnswer { offer_id, sdp } => { - Some(V2CallSignal::Answer { - offer_id: offer_id.clone(), - sdp: sdp.clone(), - }) - } - V2ChatMessageContent::DataChannelCandidates { offer_id, sdp } => { - Some(V2CallSignal::Candidates { - offer_id: offer_id.clone(), - sdp: sdp.clone(), - }) - } - V2ChatMessageContent::DataChannelClosed { offer_id } => Some(V2CallSignal::Closed { - offer_id: offer_id.clone(), - }), - _ => None, - } - } + /// Lift supported v2 data-channel chat content into the shared call-signal model. + pub fn as_call_signal(&self) -> Option { + match &self.content { + V2ChatMessageContent::DataChannelOffer { sdp, purpose } => Some(V2CallSignal::Offer { + offer_id: self.message_id.clone(), + sdp: sdp.clone(), + purpose: *purpose, + }), + V2ChatMessageContent::DataChannelAnswer { offer_id, sdp } => { + Some(V2CallSignal::Answer { offer_id: offer_id.clone(), sdp: sdp.clone() }) + }, + V2ChatMessageContent::DataChannelCandidates { offer_id, sdp } => { + Some(V2CallSignal::Candidates { offer_id: offer_id.clone(), sdp: sdp.clone() }) + }, + V2ChatMessageContent::DataChannelClosed { offer_id } => { + Some(V2CallSignal::Closed { offer_id: offer_id.clone() }) + }, + _ => None, + } + } } /// Push platform enum used inside first-contact chat requests. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum V2PushPlatform { - Android, - Ios, - IosVoip, + Android, + Ios, + IosVoip, } /// Optional push token bundled with a first-contact chat request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2PushToken { - pub token: Vec, - pub platform: V2PushPlatform, + pub token: Vec, + pub platform: V2PushPlatform, } /// Supported subset of the v2 first-contact request content. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatRequestMessage { - pub message_id: String, - pub timestamp: u64, - pub push_token: Option, - pub welcome_text: Option, + pub message_id: String, + pub timestamp: u64, + pub push_token: Option, + pub welcome_text: Option, } /// Raw fixed-width keyed proof carried by request content V2. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatRequestIdentityProof { - pub identity_account_id: [u8; 32], - pub proof: [u8; 32], + pub identity_account_id: [u8; 32], + pub proof: [u8; 32], } /// Current iOS multi-device first-contact request content (version index 1). #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatRequestContentV2 { - pub identity_proof: V2ChatRequestIdentityProof, - pub device_enc_pub_key: [u8; 32], - pub push_token: Option, - pub welcome_text: Option, + pub identity_proof: V2ChatRequestIdentityProof, + pub device_enc_pub_key: [u8; 32], + pub push_token: Option, + pub welcome_text: Option, } /// First-contact request message carrying request content V2. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatRequestMessageV2 { - pub message_id: String, - pub timestamp: u64, - pub content: V2ChatRequestContentV2, + pub message_id: String, + pub timestamp: u64, + pub content: V2ChatRequestContentV2, } /// Inner sr25519 proof carried by a first-contact chat request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatRequestProof { - pub signature: Vec, - pub signer: Vec, + pub signature: Vec, + pub signer: Vec, } /// Decrypted first-contact chat request payload. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatRequest { - pub message: V2ChatRequestMessage, - pub proof: V2ChatRequestProof, + pub message: V2ChatRequestMessage, + pub proof: V2ChatRequestProof, } /// Decrypted first-contact payload carrying current request content V2. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2ChatRequestV2 { - pub message: V2ChatRequestMessageV2, - pub proof: V2ChatRequestProof, + pub message: V2ChatRequestMessageV2, + pub proof: V2ChatRequestProof, } /// Encrypted transport wrapper for first-contact chat requests. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2EncryptedChatRequest { - pub encryption_pubkey: Vec, - pub encrypted_request: Vec, + pub encryption_pubkey: Vec, + pub encrypted_request: Vec, } /// Per-recipient wrapped one-shot key in a multi-device transport. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2RequestDeviceInfo { - pub statement_account_id: [u8; 32], - pub encrypted_key: Vec, + pub statement_account_id: [u8; 32], + pub encrypted_key: Vec, } /// Multi-device request envelope, StatementData index 2. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2MultiDeviceRequest { - pub encrypted_request: Vec, - pub devices_info: Vec, + pub encrypted_request: Vec, + pub devices_info: Vec, } /// Multi-device response envelope, StatementData index 3. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2MultiDeviceResponse { - pub encrypted_response: Vec, - pub devices_info: Vec, + pub encrypted_response: Vec, + pub devices_info: Vec, } /// Bare MessageExchange request encrypted inside a multi-device request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2MessageExchangeRequest { - pub request_id: String, - pub messages: Vec>, + pub request_id: String, + pub messages: Vec>, } /// Bare MessageExchange response encrypted inside a multi-device response. #[derive(Debug, Clone, PartialEq, Eq)] pub struct V2MessageExchangeResponse { - pub request_id: String, - pub response_code: u8, + pub request_id: String, + pub response_code: u8, } /// Ongoing v2 statement-store transport payload. #[derive(Debug, Clone, PartialEq, Eq)] pub enum V2StatementTransportData { - Request { - request_id: String, - messages: Vec>, - }, - Response { - request_id: String, - response_code: u8, - }, - MultiRequest(V2MultiDeviceRequest), - MultiResponse(V2MultiDeviceResponse), + Request { request_id: String, messages: Vec> }, + Response { request_id: String, response_code: u8 }, + MultiRequest(V2MultiDeviceRequest), + MultiResponse(V2MultiDeviceResponse), } /// Calculate the v2 day number from a Unix timestamp in seconds. /// /// Returns `None` for timestamps before the v2 protocol epoch. pub fn chat_request_day_from_unix(unix_timestamp_seconds: u64) -> Option { - unix_timestamp_seconds - .checked_sub(PROTOCOL_EPOCH_SECONDS) - .map(|relative| relative / SECONDS_IN_DAY) + unix_timestamp_seconds + .checked_sub(PROTOCOL_EPOCH_SECONDS) + .map(|relative| relative / SECONDS_IN_DAY) } /// Derive the full-history first-contact request topic for an acceptor account. @@ -662,68 +634,69 @@ pub fn chat_request_day_from_unix(unix_timestamp_seconds: u64) -> Option { /// Matches v2 iOS/Android: /// `blake2b256(scale(Data("chat-request")) || scale(Data(acceptor_account_id)))`. pub fn chat_request_full_topic(acceptor_account_id: &[u8; 32]) -> Topic { - derive_chat_request_topic(CHAT_REQUEST_CONTEXT, acceptor_account_id, &[]) + derive_chat_request_topic(CHAT_REQUEST_CONTEXT, acceptor_account_id, &[]) } /// Derive the day-partitioned first-contact request topic for an acceptor account. /// /// Matches v2 iOS/Android: -/// `blake2b256(scale(Data("chat-request")) || scale(Data(acceptor_account_id)) || scale(UInt64(day)))`. +/// `blake2b256(scale(Data("chat-request")) || scale(Data(acceptor_account_id)) || +/// scale(UInt64(day)))`. pub fn chat_request_day_topic(acceptor_account_id: &[u8; 32], day: u64) -> Topic { - chat_request_day_topic_with_context(CHAT_REQUEST_CONTEXT, acceptor_account_id, day) + chat_request_day_topic_with_context(CHAT_REQUEST_CONTEXT, acceptor_account_id, day) } fn chat_request_day_topic_with_context( - context: &[u8], - acceptor_account_id: &[u8; 32], - day: u64, + context: &[u8], + acceptor_account_id: &[u8; 32], + day: u64, ) -> Topic { - let day_bytes = day.to_le_bytes(); - derive_chat_request_topic(context, acceptor_account_id, &day_bytes) + let day_bytes = day.to_le_bytes(); + derive_chat_request_topic(context, acceptor_account_id, &day_bytes) } fn derive_chat_request_topic( - context: &[u8], - acceptor_account_id: &[u8; 32], - suffix: &[u8], + context: &[u8], + acceptor_account_id: &[u8; 32], + suffix: &[u8], ) -> Topic { - let mut input = Vec::with_capacity( - compact_len_size(context.len() as u32) - + context.len() - + compact_len_size(acceptor_account_id.len() as u32) - + acceptor_account_id.len() - + suffix.len(), - ); - input.extend_from_slice(&encode_compact_u32(context.len() as u32)); - input.extend_from_slice(context); - input.extend_from_slice(&encode_compact_u32(acceptor_account_id.len() as u32)); - input.extend_from_slice(acceptor_account_id); - input.extend_from_slice(suffix); - blake2b_256(&input) + let mut input = Vec::with_capacity( + compact_len_size(context.len() as u32) + + context.len() + + compact_len_size(acceptor_account_id.len() as u32) + + acceptor_account_id.len() + + suffix.len(), + ); + input.extend_from_slice(&encode_compact_u32(context.len() as u32)); + input.extend_from_slice(context); + input.extend_from_slice(&encode_compact_u32(acceptor_account_id.len() as u32)); + input.extend_from_slice(acceptor_account_id); + input.extend_from_slice(suffix); + blake2b_256(&input) } fn compact_len_size(value: u32) -> usize { - encode_compact_u32(value).len() + encode_compact_u32(value).len() } /// Build v2 session id parameters: /// `requester_account_id || acceptor_account_id || "/" || requester_pin || "/" || acceptor_pin`. pub fn chat_request_session_id_params( - requester_account_id: &[u8; 32], - requester_pin: Option<&str>, - acceptor_account_id: &[u8; 32], - acceptor_pin: Option<&str>, + requester_account_id: &[u8; 32], + requester_pin: Option<&str>, + acceptor_account_id: &[u8; 32], + acceptor_pin: Option<&str>, ) -> Vec { - let requester_pin = requester_pin.unwrap_or("").as_bytes(); - let acceptor_pin = acceptor_pin.unwrap_or("").as_bytes(); - let mut out = Vec::with_capacity(32 + 32 + 1 + requester_pin.len() + 1 + acceptor_pin.len()); - out.extend_from_slice(requester_account_id); - out.extend_from_slice(acceptor_account_id); - out.push(b'/'); - out.extend_from_slice(requester_pin); - out.push(b'/'); - out.extend_from_slice(acceptor_pin); - out + let requester_pin = requester_pin.unwrap_or("").as_bytes(); + let acceptor_pin = acceptor_pin.unwrap_or("").as_bytes(); + let mut out = Vec::with_capacity(32 + 32 + 1 + requester_pin.len() + 1 + acceptor_pin.len()); + out.extend_from_slice(requester_account_id); + out.extend_from_slice(acceptor_account_id); + out.push(b'/'); + out.extend_from_slice(requester_pin); + out.push(b'/'); + out.extend_from_slice(acceptor_pin); + out } /// Derive the session fallback first-contact request topic. @@ -731,367 +704,437 @@ pub fn chat_request_session_id_params( /// Matches v2 Android: /// `keyed_blake2b256(shared_secret, "chat-request" || session_id_params)`. pub fn chat_request_session_topic( - shared_secret: &[u8], - requester_account_id: &[u8; 32], - requester_pin: Option<&str>, - acceptor_account_id: &[u8; 32], - acceptor_pin: Option<&str>, + shared_secret: &[u8], + requester_account_id: &[u8; 32], + requester_pin: Option<&str>, + acceptor_account_id: &[u8; 32], + acceptor_pin: Option<&str>, ) -> Result { - if shared_secret.len() != 32 { - return Err(ChatError::KeyDerivationFailed(format!( - "shared_secret must be 32 bytes, got {}", - shared_secret.len() - ))); - } - - let session_id_params = chat_request_session_id_params( - requester_account_id, - requester_pin, - acceptor_account_id, - acceptor_pin, - ); - let mut input = Vec::with_capacity(CHAT_REQUEST_CONTEXT.len() + session_id_params.len()); - input.extend_from_slice(CHAT_REQUEST_CONTEXT); - input.extend_from_slice(&session_id_params); - blake2b_256_keyed(shared_secret, &input) + if shared_secret.len() != 32 { + return Err(ChatError::KeyDerivationFailed(format!( + "shared_secret must be 32 bytes, got {}", + shared_secret.len() + ))); + } + + let session_id_params = chat_request_session_id_params( + requester_account_id, + requester_pin, + acceptor_account_id, + acceptor_pin, + ); + let mut input = Vec::with_capacity(CHAT_REQUEST_CONTEXT.len() + session_id_params.len()); + input.extend_from_slice(CHAT_REQUEST_CONTEXT); + input.extend_from_slice(&session_id_params); + blake2b_256_keyed(shared_secret, &input) } /// Derive an ongoing identity session id in one account direction. pub fn chat_identity_session_id( - shared_secret: &[u8; 32], - first_account_id: &[u8; 32], - first_pin: Option<&str>, - second_account_id: &[u8; 32], - second_pin: Option<&str>, + shared_secret: &[u8; 32], + first_account_id: &[u8; 32], + first_pin: Option<&str>, + second_account_id: &[u8; 32], + second_pin: Option<&str>, ) -> Result<[u8; 32], ChatError> { - let params = - chat_request_session_id_params(first_account_id, first_pin, second_account_id, second_pin); - let mut input = Vec::with_capacity(7 + params.len()); - input.extend_from_slice(b"session"); - input.extend_from_slice(¶ms); - blake2b_256_keyed(shared_secret, &input) + let params = + chat_request_session_id_params(first_account_id, first_pin, second_account_id, second_pin); + let mut input = Vec::with_capacity(7 + params.len()); + input.extend_from_slice(b"session"); + input.extend_from_slice(¶ms); + blake2b_256_keyed(shared_secret, &input) } /// Derive the request topic for an ongoing identity session. pub fn chat_identity_request_topic(session_id: &[u8; 32]) -> Result { - blake2b_256_keyed(session_id, b"request") + blake2b_256_keyed(session_id, b"request") } /// Derive the response topic for an ongoing identity session. pub fn chat_identity_response_topic(session_id: &[u8; 32]) -> Result { - blake2b_256_keyed(session_id, b"response") + blake2b_256_keyed(session_id, b"response") } /// Encode a v2 text message statement payload. pub fn encode_text_message( - message_id: &str, - timestamp: u64, - text: &str, + message_id: &str, + timestamp: u64, + text: &str, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(0); - encode_string(out, text) - }) + encode_message(message_id, timestamp, |out| { + out.push(0); + encode_string(out, text) + }) } /// Encode a v2 chat-accepted message statement payload. pub fn encode_chat_accepted_message( - message_id: &str, - timestamp: u64, - request_id: &str, + message_id: &str, + timestamp: u64, + request_id: &str, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(14); - encode_string(out, request_id) - }) + encode_message(message_id, timestamp, |out| { + out.push(14); + encode_string(out, request_id) + }) } /// Encode a v2 token message statement payload. pub fn encode_token_message( - message_id: &str, - timestamp: u64, - token: &[u8], - platform: V2PushPlatform, + message_id: &str, + timestamp: u64, + token: &[u8], + platform: V2PushPlatform, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(1); - encode_bytes(out, token)?; - out.push(push_platform_index(platform)); - Ok(()) - }) + encode_message(message_id, timestamp, |out| { + out.push(1); + encode_bytes(out, token)?; + out.push(push_platform_index(platform)); + Ok(()) + }) } /// Encode a v2 legacy send message statement payload. pub fn encode_send_legacy_message( - message_id: &str, - timestamp: u64, - amount: &str, - block_hash: &[u8], - extrinsic_hash: &[u8], + message_id: &str, + timestamp: u64, + amount: &str, + block_hash: &[u8], + extrinsic_hash: &[u8], ) -> Result, ChatError> { - if block_hash.len() != 32 { - return Err(ChatError::InvalidEncoding(format!( - "legacy send block_hash must be 32 bytes, got {}", - block_hash.len() - ))); - } - if extrinsic_hash.len() != 32 { - return Err(ChatError::InvalidEncoding(format!( - "legacy send extrinsic_hash must be 32 bytes, got {}", - extrinsic_hash.len() - ))); - } - encode_message(message_id, timestamp, |out| { - out.push(2); - encode_balance(out, amount)?; - out.extend_from_slice(block_hash); - out.extend_from_slice(extrinsic_hash); - Ok(()) - }) + if block_hash.len() != 32 { + return Err(ChatError::InvalidEncoding(format!( + "legacy send block_hash must be 32 bytes, got {}", + block_hash.len() + ))); + } + if extrinsic_hash.len() != 32 { + return Err(ChatError::InvalidEncoding(format!( + "legacy send extrinsic_hash must be 32 bytes, got {}", + extrinsic_hash.len() + ))); + } + encode_message(message_id, timestamp, |out| { + out.push(2); + encode_balance(out, amount)?; + out.extend_from_slice(block_hash); + out.extend_from_slice(extrinsic_hash); + Ok(()) + }) } /// Encode a v2 contact-added message statement payload. pub fn encode_contact_added_message( - message_id: &str, - timestamp: u64, + message_id: &str, + timestamp: u64, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(3); - Ok(()) - }) + encode_message(message_id, timestamp, |out| { + out.push(3); + Ok(()) + }) } /// Encode a v2 reacted message statement payload. pub fn encode_reacted_message( - message_id: &str, - timestamp: u64, - referenced_message_id: &str, - emoji: &str, + message_id: &str, + timestamp: u64, + referenced_message_id: &str, + emoji: &str, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(4); - encode_string(out, referenced_message_id)?; - encode_string(out, emoji) - }) + encode_message(message_id, timestamp, |out| { + out.push(4); + encode_string(out, referenced_message_id)?; + encode_string(out, emoji) + }) } /// Encode a v2 reaction-removed message statement payload. pub fn encode_reaction_removed_message( - message_id: &str, - timestamp: u64, - referenced_message_id: &str, - emoji: &str, + message_id: &str, + timestamp: u64, + referenced_message_id: &str, + emoji: &str, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(5); - encode_string(out, referenced_message_id)?; - encode_string(out, emoji) - }) + encode_message(message_id, timestamp, |out| { + out.push(5); + encode_string(out, referenced_message_id)?; + encode_string(out, emoji) + }) } /// Encode a v2 reply message statement payload. pub fn encode_reply_message( - message_id: &str, - timestamp: u64, - referenced_message_id: &str, - text: Option<&str>, + message_id: &str, + timestamp: u64, + referenced_message_id: &str, + text: Option<&str>, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(7); - encode_string(out, referenced_message_id)?; - encode_rich_text(out, text, None) - }) + encode_message(message_id, timestamp, |out| { + out.push(7); + encode_string(out, referenced_message_id)?; + encode_rich_text(out, text, None) + }) } /// Encode a v2 edited message statement payload. pub fn encode_edited_message( - message_id: &str, - timestamp: u64, - referenced_message_id: &str, - new_text: Option<&str>, + message_id: &str, + timestamp: u64, + referenced_message_id: &str, + new_text: Option<&str>, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(12); - encode_string(out, referenced_message_id)?; - encode_rich_text(out, new_text, None) - }) + encode_message(message_id, timestamp, |out| { + out.push(12); + encode_string(out, referenced_message_id)?; + encode_rich_text(out, new_text, None) + }) } /// Encode a v2 left-chat message statement payload. pub fn encode_left_chat_message(message_id: &str, timestamp: u64) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(13); - Ok(()) - }) + encode_message(message_id, timestamp, |out| { + out.push(13); + Ok(()) + }) } /// Encode a v2 rich-text message statement payload. pub fn encode_rich_text_message( - message_id: &str, - timestamp: u64, - text: Option<&str>, - attachments: Option<&[V2FileVariant]>, + message_id: &str, + timestamp: u64, + text: Option<&str>, + attachments: Option<&[V2FileVariant]>, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(15); - encode_rich_text(out, text, attachments) - }) + encode_message(message_id, timestamp, |out| { + out.push(15); + encode_rich_text(out, text, attachments) + }) } /// Encode a v2 coinage-send message statement payload. pub fn encode_coinage_send_message( - message_id: &str, - timestamp: u64, - total_value: &str, - coin_keys: &[Vec], + message_id: &str, + timestamp: u64, + total_value: &str, + coin_keys: &[Vec], ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(16); - encode_balance(out, total_value)?; - encode_vec_of_bytes(out, coin_keys) - }) + encode_message(message_id, timestamp, |out| { + out.push(16); + encode_balance(out, total_value)?; + encode_vec_of_bytes(out, coin_keys) + }) } /// Encode a v2 device-added message (content index 17). pub fn encode_device_added_message( - message_id: &str, - timestamp: u64, - statement_account_id: &[u8], - encryption_public_key: &[u8], + message_id: &str, + timestamp: u64, + statement_account_id: &[u8], + encryption_public_key: &[u8], ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(17); - encode_bytes(out, statement_account_id)?; - encode_bytes(out, encryption_public_key) - }) + encode_message(message_id, timestamp, |out| { + out.push(17); + encode_bytes(out, statement_account_id)?; + encode_bytes(out, encryption_public_key) + }) } /// Encode a v2 device-removed message (content index 18). pub fn encode_device_removed_message( - message_id: &str, - timestamp: u64, - statement_account_id: &[u8], + message_id: &str, + timestamp: u64, + statement_account_id: &[u8], ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(18); - encode_bytes(out, statement_account_id) - }) + encode_message(message_id, timestamp, |out| { + out.push(18); + encode_bytes(out, statement_account_id) + }) +} + +/// Encode a v2 profile-reference message (content index 21). +pub fn encode_profile_reference_message( + message_id: &str, + timestamp: u64, + discloser_product_id: &str, + reference: Option<&str>, +) -> Result, ChatError> { + encode_message(message_id, timestamp, |out| { + out.push(21); + encode_string(out, discloser_product_id)?; + match reference { + Some(reference) => { + out.push(1); + encode_string(out, reference) + }, + None => { + out.push(0); + Ok(()) + }, + } + }) +} + +/// Encode a wallet-wide personal profile grant (content 22, personal scope 1). +/// Hosts must never fall back to the app-scoped content type for this grant. +pub fn encode_personal_profile_reference_message( + message_id: &str, + timestamp: u64, + revision: u64, + discloser_product_id: &str, + reference: Option<&str>, +) -> Result, ChatError> { + if revision == 0 { + return Err(ChatError::InvalidEncoding("invalid personal profile revision".into())); + } + encode_message(message_id, timestamp, |out| { + out.push(22); + out.push(1); + out.extend_from_slice(&revision.to_le_bytes()); + encode_string(out, discloser_product_id)?; + match reference { + Some(reference) => { + out.push(1); + encode_string(out, reference) + }, + None => { + out.push(0); + Ok(()) + }, + } + }) +} + +/// Encode a host-channel bootstrap (content index 23, version 1). +pub fn encode_host_channel_bootstrap_message( + message_id: &str, + timestamp: u64, + channel_public_key: &[u8; 32], +) -> Result, ChatError> { + encode_message(message_id, timestamp, |out| { + out.push(23); + out.push(HOST_CHANNEL_BOOTSTRAP_VERSION); + out.extend_from_slice(channel_public_key); + Ok(()) + }) } +/// The one host-channel bootstrap frame version this crate writes and reads. +pub const HOST_CHANNEL_BOOTSTRAP_VERSION: u8 = 1; + /// Encode a v2 compacted-messages reference (content index 19). pub fn encode_compacted_messages_message( - message_id: &str, - timestamp: u64, - claim_identifier: &[u8], - claim_ticket: &[u8], - node: &V2NodeEndpoint, + message_id: &str, + timestamp: u64, + claim_identifier: &[u8], + claim_ticket: &[u8], + node: &V2NodeEndpoint, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(19); - encode_bytes(out, claim_identifier)?; - encode_bytes(out, claim_ticket)?; - match node { - V2NodeEndpoint::WssUrl(url) => { - out.push(0); - encode_string(out, url) - } - } - }) + encode_message(message_id, timestamp, |out| { + out.push(19); + encode_bytes(out, claim_identifier)?; + encode_bytes(out, claim_ticket)?; + match node { + V2NodeEndpoint::WssUrl(url) => { + out.push(0); + encode_string(out, url) + }, + } + }) } /// Encode a v2 multi-device chat acceptance (wire content index 20). pub fn encode_multi_chat_accepted_message( - message_id: &str, - timestamp: u64, - request_id: &str, - device: &V2PeerDevice, + message_id: &str, + timestamp: u64, + request_id: &str, + device: &V2PeerDevice, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(20); - encode_string(out, request_id)?; - out.extend_from_slice(&device.statement_account_id); - out.extend_from_slice(&device.encryption_public_key); - Ok(()) - }) + encode_message(message_id, timestamp, |out| { + out.push(20); + encode_string(out, request_id)?; + out.extend_from_slice(&device.statement_account_id); + out.extend_from_slice(&device.encryption_public_key); + Ok(()) + }) } /// Encode a transport-neutral call signal into the v2 chat message wire format. pub fn encode_call_signal_message( - message_id: &str, - timestamp: u64, - signal: &V2CallSignal, + message_id: &str, + timestamp: u64, + signal: &V2CallSignal, ) -> Result, ChatError> { - match signal { - V2CallSignal::Offer { sdp, purpose, .. } => { - encode_data_channel_offer_message(message_id, timestamp, sdp, *purpose) - } - V2CallSignal::Answer { offer_id, sdp } => { - encode_data_channel_answer_message(message_id, timestamp, offer_id, sdp) - } - V2CallSignal::Candidates { offer_id, sdp } => { - encode_data_channel_candidates_message(message_id, timestamp, offer_id, sdp) - } - V2CallSignal::Closed { offer_id } => { - encode_data_channel_closed_message(message_id, timestamp, offer_id) - } - } + match signal { + V2CallSignal::Offer { sdp, purpose, .. } => { + encode_data_channel_offer_message(message_id, timestamp, sdp, *purpose) + }, + V2CallSignal::Answer { offer_id, sdp } => { + encode_data_channel_answer_message(message_id, timestamp, offer_id, sdp) + }, + V2CallSignal::Candidates { offer_id, sdp } => { + encode_data_channel_candidates_message(message_id, timestamp, offer_id, sdp) + }, + V2CallSignal::Closed { offer_id } => { + encode_data_channel_closed_message(message_id, timestamp, offer_id) + }, + } } /// Encode a v2 data-channel-offer message statement payload. pub fn encode_data_channel_offer_message( - message_id: &str, - timestamp: u64, - sdp: &[u8], - purpose: V2DataChannelPurpose, + message_id: &str, + timestamp: u64, + sdp: &[u8], + purpose: V2DataChannelPurpose, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(8); - encode_bytes(out, sdp)?; - out.push(match purpose { - V2DataChannelPurpose::Audio => 0, - V2DataChannelPurpose::Video => 1, - }); - Ok(()) - }) + encode_message(message_id, timestamp, |out| { + out.push(8); + encode_bytes(out, sdp)?; + out.push(match purpose { + V2DataChannelPurpose::Audio => 0, + V2DataChannelPurpose::Video => 1, + }); + Ok(()) + }) } /// Encode a v2 data-channel-answer message statement payload. pub fn encode_data_channel_answer_message( - message_id: &str, - timestamp: u64, - offer_id: &str, - sdp: &[u8], + message_id: &str, + timestamp: u64, + offer_id: &str, + sdp: &[u8], ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(9); - encode_string(out, offer_id)?; - encode_bytes(out, sdp) - }) + encode_message(message_id, timestamp, |out| { + out.push(9); + encode_string(out, offer_id)?; + encode_bytes(out, sdp) + }) } /// Encode a v2 data-channel-candidates message statement payload. pub fn encode_data_channel_candidates_message( - message_id: &str, - timestamp: u64, - offer_id: &str, - sdp: &[u8], + message_id: &str, + timestamp: u64, + offer_id: &str, + sdp: &[u8], ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(10); - encode_string(out, offer_id)?; - encode_bytes(out, sdp) - }) + encode_message(message_id, timestamp, |out| { + out.push(10); + encode_string(out, offer_id)?; + encode_bytes(out, sdp) + }) } /// Encode a v2 data-channel-closed message statement payload. pub fn encode_data_channel_closed_message( - message_id: &str, - timestamp: u64, - offer_id: &str, + message_id: &str, + timestamp: u64, + offer_id: &str, ) -> Result, ChatError> { - encode_message(message_id, timestamp, |out| { - out.push(11); - encode_string(out, offer_id) - }) + encode_message(message_id, timestamp, |out| { + out.push(11); + encode_string(out, offer_id) + }) } /// Decode a v2 chat message statement payload. @@ -1099,367 +1142,370 @@ pub fn encode_data_channel_closed_message( /// The decoder preserves `message_id` and `timestamp` for unsupported content /// variants so host apps can store/display an unsupported placeholder. pub fn decode_message(data: &[u8]) -> Result { - let mut cursor = Cursor::new(data); - let message_id = cursor.read_string("message_id")?; - let timestamp = cursor.read_u64("timestamp")?; - let version_index = cursor.read_u8("version_index")?; - if version_index != 0 { - return Ok(V2ChatMessage { - message_id, - timestamp, - content: V2ChatMessageContent::UnsupportedVersion { version_index }, - }); - } - - let content_index = cursor.read_u8("content_index")?; - let content = match content_index { - 0 => { - let text = cursor.read_string("text")?; - cursor.finish()?; - V2ChatMessageContent::Text(text) - } - 1 => { - let token = cursor.read_bytes("push_token")?; - let platform = decode_push_platform(cursor.read_u8("push_platform")?)?; - cursor.finish()?; - V2ChatMessageContent::Token { token, platform } - } - 2 => { - let amount = cursor.read_balance("amount")?; - let block_hash = cursor.read_exact(32, "block_hash")?.to_vec(); - let extrinsic_hash = cursor.read_exact(32, "extrinsic_hash")?.to_vec(); - cursor.finish()?; - V2ChatMessageContent::SendLegacy { - amount, - block_hash, - extrinsic_hash, - } - } - 3 => { - cursor.finish()?; - V2ChatMessageContent::ContactAdded - } - 4 => { - let message_id = cursor.read_string("referenced_message_id")?; - let emoji = cursor.read_string("emoji")?; - cursor.finish()?; - V2ChatMessageContent::Reacted { message_id, emoji } - } - 5 => { - let message_id = cursor.read_string("referenced_message_id")?; - let emoji = cursor.read_string("emoji")?; - cursor.finish()?; - V2ChatMessageContent::ReactionRemoved { message_id, emoji } - } - 7 => { - let message_id = cursor.read_string("referenced_message_id")?; - let (text, attachments) = decode_rich_text(&mut cursor)?; - cursor.finish()?; - V2ChatMessageContent::Reply { - message_id, - text, - attachments, - } - } - 8 => { - let sdp = cursor.read_bytes("sdp")?; - let purpose = match cursor.read_u8("purpose")? { - 0 => V2DataChannelPurpose::Audio, - 1 => V2DataChannelPurpose::Video, - value => { - return Err(ChatError::InvalidEncoding(format!( - "unsupported data channel purpose {value}" - ))); - } - }; - cursor.finish()?; - V2ChatMessageContent::DataChannelOffer { sdp, purpose } - } - 9 => { - let offer_id = cursor.read_string("offer_id")?; - let sdp = cursor.read_bytes("sdp")?; - cursor.finish()?; - V2ChatMessageContent::DataChannelAnswer { offer_id, sdp } - } - 10 => { - let offer_id = cursor.read_string("offer_id")?; - let sdp = cursor.read_bytes("sdp")?; - cursor.finish()?; - V2ChatMessageContent::DataChannelCandidates { offer_id, sdp } - } - 11 => { - let offer_id = cursor.read_string("offer_id")?; - cursor.finish()?; - V2ChatMessageContent::DataChannelClosed { offer_id } - } - 12 => { - let message_id = cursor.read_string("referenced_message_id")?; - let (new_text, attachments) = decode_rich_text(&mut cursor)?; - cursor.finish()?; - V2ChatMessageContent::Edited { - message_id, - new_text, - attachments, - } - } - 13 => { - cursor.finish()?; - V2ChatMessageContent::LeftChat - } - 14 => { - let request_id = cursor.read_string("request_id")?; - cursor.finish()?; - V2ChatMessageContent::ChatAccepted { request_id } - } - 15 => { - let (text, attachments) = decode_rich_text(&mut cursor)?; - cursor.finish()?; - V2ChatMessageContent::RichText { text, attachments } - } - 16 => { - let total_value = cursor.read_balance("total_value")?; - let coin_keys = cursor.read_vec_of_bytes("coin_keys")?; - cursor.finish()?; - V2ChatMessageContent::CoinageSend { - total_value, - coin_keys, - } - } - 17 => { - let statement_account_id = cursor.read_bytes("statement_account_id")?; - let encryption_public_key = cursor.read_bytes("encryption_public_key")?; - cursor.finish()?; - V2ChatMessageContent::DeviceAdded { - statement_account_id, - encryption_public_key, - } - } - 18 => { - let statement_account_id = cursor.read_bytes("statement_account_id")?; - cursor.finish()?; - V2ChatMessageContent::DeviceRemoved { - statement_account_id, - } - } - 19 => { - let claim_identifier = cursor.read_bytes("claim_identifier")?; - let claim_ticket = cursor.read_bytes("claim_ticket")?; - let node = match cursor.read_u8("node_endpoint")? { - 0 => V2NodeEndpoint::WssUrl(cursor.read_string("wss_url")?), - value => { - return Err(ChatError::InvalidEncoding(format!( - "unsupported node endpoint {value}" - ))); - } - }; - cursor.finish()?; - V2ChatMessageContent::CompactedMessages { - claim_identifier, - claim_ticket, - node, - } - } - 20 => { - let request_id = cursor.read_string("request_id")?; - let statement_account_id = cursor.read_array_32("device_statement_account_id")?; - let encryption_public_key = cursor.read_array_32("device_encryption_public_key")?; - cursor.finish()?; - V2ChatMessageContent::MultiChatAccepted { - request_id, - device: V2PeerDevice { - statement_account_id, - encryption_public_key, - }, - } - } - index => V2ChatMessageContent::UnsupportedContent { - content_index: index, - }, - }; - - Ok(V2ChatMessage { - message_id, - timestamp, - content, - }) + let mut cursor = Cursor::new(data); + let message_id = cursor.read_string("message_id")?; + let timestamp = cursor.read_u64("timestamp")?; + let version_index = cursor.read_u8("version_index")?; + if version_index != 0 { + return Ok(V2ChatMessage { + message_id, + timestamp, + content: V2ChatMessageContent::UnsupportedVersion { version_index }, + }); + } + + let content_index = cursor.read_u8("content_index")?; + let content = match content_index { + 0 => { + let text = cursor.read_string("text")?; + cursor.finish()?; + V2ChatMessageContent::Text(text) + }, + 1 => { + let token = cursor.read_bytes("push_token")?; + let platform = decode_push_platform(cursor.read_u8("push_platform")?)?; + cursor.finish()?; + V2ChatMessageContent::Token { token, platform } + }, + 2 => { + let amount = cursor.read_balance("amount")?; + let block_hash = cursor.read_exact(32, "block_hash")?.to_vec(); + let extrinsic_hash = cursor.read_exact(32, "extrinsic_hash")?.to_vec(); + cursor.finish()?; + V2ChatMessageContent::SendLegacy { amount, block_hash, extrinsic_hash } + }, + 3 => { + cursor.finish()?; + V2ChatMessageContent::ContactAdded + }, + 4 => { + let message_id = cursor.read_string("referenced_message_id")?; + let emoji = cursor.read_string("emoji")?; + cursor.finish()?; + V2ChatMessageContent::Reacted { message_id, emoji } + }, + 5 => { + let message_id = cursor.read_string("referenced_message_id")?; + let emoji = cursor.read_string("emoji")?; + cursor.finish()?; + V2ChatMessageContent::ReactionRemoved { message_id, emoji } + }, + 7 => { + let message_id = cursor.read_string("referenced_message_id")?; + let (text, attachments) = decode_rich_text(&mut cursor)?; + cursor.finish()?; + V2ChatMessageContent::Reply { message_id, text, attachments } + }, + 8 => { + let sdp = cursor.read_bytes("sdp")?; + let purpose = match cursor.read_u8("purpose")? { + 0 => V2DataChannelPurpose::Audio, + 1 => V2DataChannelPurpose::Video, + value => { + return Err(ChatError::InvalidEncoding(format!( + "unsupported data channel purpose {value}" + ))); + }, + }; + cursor.finish()?; + V2ChatMessageContent::DataChannelOffer { sdp, purpose } + }, + 9 => { + let offer_id = cursor.read_string("offer_id")?; + let sdp = cursor.read_bytes("sdp")?; + cursor.finish()?; + V2ChatMessageContent::DataChannelAnswer { offer_id, sdp } + }, + 10 => { + let offer_id = cursor.read_string("offer_id")?; + let sdp = cursor.read_bytes("sdp")?; + cursor.finish()?; + V2ChatMessageContent::DataChannelCandidates { offer_id, sdp } + }, + 11 => { + let offer_id = cursor.read_string("offer_id")?; + cursor.finish()?; + V2ChatMessageContent::DataChannelClosed { offer_id } + }, + 12 => { + let message_id = cursor.read_string("referenced_message_id")?; + let (new_text, attachments) = decode_rich_text(&mut cursor)?; + cursor.finish()?; + V2ChatMessageContent::Edited { message_id, new_text, attachments } + }, + 13 => { + cursor.finish()?; + V2ChatMessageContent::LeftChat + }, + 14 => { + let request_id = cursor.read_string("request_id")?; + cursor.finish()?; + V2ChatMessageContent::ChatAccepted { request_id } + }, + 15 => { + let (text, attachments) = decode_rich_text(&mut cursor)?; + cursor.finish()?; + V2ChatMessageContent::RichText { text, attachments } + }, + 16 => { + let total_value = cursor.read_balance("total_value")?; + let coin_keys = cursor.read_vec_of_bytes("coin_keys")?; + cursor.finish()?; + V2ChatMessageContent::CoinageSend { total_value, coin_keys } + }, + 17 => { + let statement_account_id = cursor.read_bytes("statement_account_id")?; + let encryption_public_key = cursor.read_bytes("encryption_public_key")?; + cursor.finish()?; + V2ChatMessageContent::DeviceAdded { statement_account_id, encryption_public_key } + }, + 18 => { + let statement_account_id = cursor.read_bytes("statement_account_id")?; + cursor.finish()?; + V2ChatMessageContent::DeviceRemoved { statement_account_id } + }, + 19 => { + let claim_identifier = cursor.read_bytes("claim_identifier")?; + let claim_ticket = cursor.read_bytes("claim_ticket")?; + let node = match cursor.read_u8("node_endpoint")? { + 0 => V2NodeEndpoint::WssUrl(cursor.read_string("wss_url")?), + value => { + return Err(ChatError::InvalidEncoding(format!( + "unsupported node endpoint {value}" + ))); + }, + }; + cursor.finish()?; + V2ChatMessageContent::CompactedMessages { claim_identifier, claim_ticket, node } + }, + 20 => { + let request_id = cursor.read_string("request_id")?; + let statement_account_id = cursor.read_array_32("device_statement_account_id")?; + let encryption_public_key = cursor.read_array_32("device_encryption_public_key")?; + cursor.finish()?; + V2ChatMessageContent::MultiChatAccepted { + request_id, + device: V2PeerDevice { statement_account_id, encryption_public_key }, + } + }, + 23 => { + let version = cursor.read_u8("host_channel_version")?; + if version != HOST_CHANNEL_BOOTSTRAP_VERSION { + return Err(ChatError::InvalidEncoding(format!( + "unsupported host channel bootstrap version {version}" + ))); + } + let channel_public_key = cursor.read_array_32("host_channel_public_key")?; + cursor.finish()?; + V2ChatMessageContent::HostChannelBootstrap { version, channel_public_key } + }, + 21 | 22 => { + if content_index == 22 && cursor.read_u8("profile_scope")? != 1 { + return Err(ChatError::InvalidEncoding("invalid personal profile scope".into())); + } + let revision = if content_index == 22 { + let revision = cursor.read_u64("profile_revision")?; + if revision == 0 { + return Err(ChatError::InvalidEncoding( + "invalid personal profile revision".into(), + )); + } + revision + } else { + 0 + }; + let discloser_product_id = cursor.read_string("discloser_product_id")?; + let reference = match cursor.read_u8("reference_option")? { + 0 => None, + 1 => Some(cursor.read_string("reference")?), + value => { + return Err(ChatError::InvalidEncoding(format!( + "invalid profile reference option {value}" + ))); + }, + }; + cursor.finish()?; + if content_index == 22 { + V2ChatMessageContent::PersonalProfileReference { + discloser_product_id, + reference, + revision, + } + } else { + V2ChatMessageContent::ProfileReference { discloser_product_id, reference } + } + }, + index => V2ChatMessageContent::UnsupportedContent { content_index: index }, + }; + + Ok(V2ChatMessage { message_id, timestamp, content }) } /// Encode a first-contact chat request message. pub fn encode_chat_request_message( - message_id: &str, - timestamp: u64, - push_token: Option<&V2PushToken>, - welcome_text: Option<&str>, + message_id: &str, + timestamp: u64, + push_token: Option<&V2PushToken>, + welcome_text: Option<&str>, ) -> Result, ChatError> { - let mut out = Vec::new(); - encode_string(&mut out, message_id)?; - out.extend_from_slice(×tamp.to_le_bytes()); - out.push(0); // VersionedRequestContent::V1 + let mut out = Vec::new(); + encode_string(&mut out, message_id)?; + out.extend_from_slice(×tamp.to_le_bytes()); + out.push(0); // VersionedRequestContent::V1 - encode_optional_push_token(&mut out, push_token)?; - encode_optional_rich_text(&mut out, welcome_text)?; + encode_optional_push_token(&mut out, push_token)?; + encode_optional_rich_text(&mut out, welcome_text)?; - Ok(out) + Ok(out) } /// Decode a first-contact chat request message. pub fn decode_chat_request_message(data: &[u8]) -> Result { - let mut cursor = Cursor::new(data); - let message_id = cursor.read_string("message_id")?; - let timestamp = cursor.read_u64("timestamp")?; - let version_index = cursor.read_u8("version_index")?; - if version_index != 0 { - return Err(ChatError::InvalidEncoding(format!( - "unsupported v2 chat request version index {version_index}" - ))); - } - - let push_token = decode_optional_push_token(&mut cursor)?; - let welcome_text = decode_optional_rich_text(&mut cursor)?; - cursor.finish()?; - - Ok(V2ChatRequestMessage { - message_id, - timestamp, - push_token, - welcome_text, - }) + let mut cursor = Cursor::new(data); + let message_id = cursor.read_string("message_id")?; + let timestamp = cursor.read_u64("timestamp")?; + let version_index = cursor.read_u8("version_index")?; + if version_index != 0 { + return Err(ChatError::InvalidEncoding(format!( + "unsupported v2 chat request version index {version_index}" + ))); + } + + let push_token = decode_optional_push_token(&mut cursor)?; + let welcome_text = decode_optional_rich_text(&mut cursor)?; + cursor.finish()?; + + Ok(V2ChatRequestMessage { message_id, timestamp, push_token, welcome_text }) } /// Encode the proof payload that the requester signs for a first-contact chat request. pub fn encode_chat_request_proof_payload( - message: &V2ChatRequestMessage, - acceptor_account_id: &[u8; 32], + message: &V2ChatRequestMessage, + acceptor_account_id: &[u8; 32], ) -> Result, ChatError> { - let mut out = encode_chat_request_message( - &message.message_id, - message.timestamp, - message.push_token.as_ref(), - message.welcome_text.as_deref(), - )?; - encode_bytes(&mut out, acceptor_account_id)?; - Ok(out) + let mut out = encode_chat_request_message( + &message.message_id, + message.timestamp, + message.push_token.as_ref(), + message.welcome_text.as_deref(), + )?; + encode_bytes(&mut out, acceptor_account_id)?; + Ok(out) } /// Encode a decrypted first-contact chat request payload. pub fn encode_chat_request(request: &V2ChatRequest) -> Result, ChatError> { - if request.proof.signature.len() != 64 { - return Err(ChatError::InvalidEncoding(format!( - "chat request proof signature must be 64 bytes, got {}", - request.proof.signature.len() - ))); - } - if request.proof.signer.len() != 32 { - return Err(ChatError::InvalidEncoding(format!( - "chat request proof signer must be 32 bytes, got {}", - request.proof.signer.len() - ))); - } - - let mut out = encode_chat_request_message( - &request.message.message_id, - request.message.timestamp, - request.message.push_token.as_ref(), - request.message.welcome_text.as_deref(), - )?; - out.push(0); // StatementProof::sr25519 - out.extend_from_slice(&request.proof.signature); - out.extend_from_slice(&request.proof.signer); - Ok(out) + if request.proof.signature.len() != 64 { + return Err(ChatError::InvalidEncoding(format!( + "chat request proof signature must be 64 bytes, got {}", + request.proof.signature.len() + ))); + } + if request.proof.signer.len() != 32 { + return Err(ChatError::InvalidEncoding(format!( + "chat request proof signer must be 32 bytes, got {}", + request.proof.signer.len() + ))); + } + + let mut out = encode_chat_request_message( + &request.message.message_id, + request.message.timestamp, + request.message.push_token.as_ref(), + request.message.welcome_text.as_deref(), + )?; + out.push(0); // StatementProof::sr25519 + out.extend_from_slice(&request.proof.signature); + out.extend_from_slice(&request.proof.signer); + Ok(out) } /// Encode a first-contact request carrying current multi-device content V2. pub fn encode_chat_request_message_v2( - message: &V2ChatRequestMessageV2, + message: &V2ChatRequestMessageV2, ) -> Result, ChatError> { - let mut out = Vec::new(); - encode_string(&mut out, &message.message_id)?; - out.extend_from_slice(&message.timestamp.to_le_bytes()); - out.push(1); - out.extend_from_slice(&message.content.identity_proof.identity_account_id); - out.extend_from_slice(&message.content.identity_proof.proof); - out.extend_from_slice(&message.content.device_enc_pub_key); - encode_optional_push_token(&mut out, message.content.push_token.as_ref())?; - encode_optional_rich_text(&mut out, message.content.welcome_text.as_deref())?; - Ok(out) + let mut out = Vec::new(); + encode_string(&mut out, &message.message_id)?; + out.extend_from_slice(&message.timestamp.to_le_bytes()); + out.push(1); + out.extend_from_slice(&message.content.identity_proof.identity_account_id); + out.extend_from_slice(&message.content.identity_proof.proof); + out.extend_from_slice(&message.content.device_enc_pub_key); + encode_optional_push_token(&mut out, message.content.push_token.as_ref())?; + encode_optional_rich_text(&mut out, message.content.welcome_text.as_deref())?; + Ok(out) } /// Decode a first-contact request carrying current multi-device content V2. pub fn decode_chat_request_message_v2(data: &[u8]) -> Result { - let mut cursor = Cursor::new(data); - let message = decode_chat_request_message_v2_cursor(&mut cursor)?; - cursor.finish()?; - Ok(message) + let mut cursor = Cursor::new(data); + let message = decode_chat_request_message_v2_cursor(&mut cursor)?; + cursor.finish()?; + Ok(message) } /// Encode the sr25519 proof payload for request content V2. pub fn encode_chat_request_v2_proof_payload( - message: &V2ChatRequestMessageV2, - acceptor_account_id: &[u8; 32], + message: &V2ChatRequestMessageV2, + acceptor_account_id: &[u8; 32], ) -> Result, ChatError> { - let mut out = encode_chat_request_message_v2(message)?; - encode_bytes(&mut out, acceptor_account_id)?; - Ok(out) + let mut out = encode_chat_request_message_v2(message)?; + encode_bytes(&mut out, acceptor_account_id)?; + Ok(out) } /// Encode a decrypted first-contact request carrying request content V2. pub fn encode_chat_request_v2(request: &V2ChatRequestV2) -> Result, ChatError> { - validate_chat_request_proof(&request.proof)?; - let mut out = encode_chat_request_message_v2(&request.message)?; - out.push(0); // StatementProof::sr25519 - out.extend_from_slice(&request.proof.signature); - out.extend_from_slice(&request.proof.signer); - Ok(out) + validate_chat_request_proof(&request.proof)?; + let mut out = encode_chat_request_message_v2(&request.message)?; + out.push(0); // StatementProof::sr25519 + out.extend_from_slice(&request.proof.signature); + out.extend_from_slice(&request.proof.signer); + Ok(out) } /// Decode a decrypted first-contact request carrying request content V2. pub fn decode_chat_request_v2(data: &[u8]) -> Result { - let mut cursor = Cursor::new(data); - let message = decode_chat_request_message_v2_cursor(&mut cursor)?; - let proof = decode_chat_request_proof(&mut cursor)?; - cursor.finish()?; - Ok(V2ChatRequestV2 { message, proof }) + let mut cursor = Cursor::new(data); + let message = decode_chat_request_message_v2_cursor(&mut cursor)?; + let proof = decode_chat_request_proof(&mut cursor)?; + cursor.finish()?; + Ok(V2ChatRequestV2 { message, proof }) } /// Decode a decrypted first-contact chat request payload. pub fn decode_chat_request(data: &[u8]) -> Result { - let mut cursor = Cursor::new(data); - let message = decode_chat_request_message_cursor(&mut cursor)?; - let proof_index = cursor.read_u8("proof_index")?; - if proof_index != 0 { - return Err(ChatError::InvalidEncoding(format!( - "unsupported chat request proof index {proof_index}" - ))); - } - let signature = cursor.read_exact(64, "proof_signature")?.to_vec(); - let signer = cursor.read_exact(32, "proof_signer")?.to_vec(); - cursor.finish()?; - - Ok(V2ChatRequest { - message, - proof: V2ChatRequestProof { signature, signer }, - }) + let mut cursor = Cursor::new(data); + let message = decode_chat_request_message_cursor(&mut cursor)?; + let proof_index = cursor.read_u8("proof_index")?; + if proof_index != 0 { + return Err(ChatError::InvalidEncoding(format!( + "unsupported chat request proof index {proof_index}" + ))); + } + let signature = cursor.read_exact(64, "proof_signature")?.to_vec(); + let signer = cursor.read_exact(32, "proof_signer")?.to_vec(); + cursor.finish()?; + + Ok(V2ChatRequest { message, proof: V2ChatRequestProof { signature, signer } }) } /// Encode the encrypted outer wrapper for a first-contact chat request. pub fn encode_encrypted_chat_request( - request: &V2EncryptedChatRequest, + request: &V2EncryptedChatRequest, ) -> Result, ChatError> { - let mut out = Vec::new(); - encode_bytes(&mut out, &request.encryption_pubkey)?; - encode_bytes(&mut out, &request.encrypted_request)?; - Ok(out) + let mut out = Vec::new(); + encode_bytes(&mut out, &request.encryption_pubkey)?; + encode_bytes(&mut out, &request.encrypted_request)?; + Ok(out) } /// Decode the encrypted outer wrapper for a first-contact chat request. pub fn decode_encrypted_chat_request(data: &[u8]) -> Result { - let mut cursor = Cursor::new(data); - let encryption_pubkey = cursor.read_bytes("encryption_pubkey")?; - let encrypted_request = cursor.read_bytes("encrypted_request")?; - cursor.finish()?; - Ok(V2EncryptedChatRequest { - encryption_pubkey, - encrypted_request, - }) + let mut cursor = Cursor::new(data); + let encryption_pubkey = cursor.read_bytes("encryption_pubkey")?; + let encrypted_request = cursor.read_bytes("encrypted_request")?; + cursor.finish()?; + Ok(V2EncryptedChatRequest { encryption_pubkey, encrypted_request }) } /// Encode and seal request content V2 with a caller-provided fresh ephemeral @@ -1468,2332 +1514,2304 @@ pub fn decode_encrypted_chat_request(data: &[u8]) -> Result Result, ChatError> { - let plaintext = encode_chat_request_v2(request)?; - let key = x25519_hkdf_sha256_key(ephemeral_private_key, peer_public_key)?; - let encrypted_request = chacha20poly1305_encrypt_with_nonce(&key, &plaintext, nonce)?; - encode_encrypted_chat_request(&V2EncryptedChatRequest { - encryption_pubkey: x25519_public_key(ephemeral_private_key).to_vec(), - encrypted_request, - }) + let plaintext = encode_chat_request_v2(request)?; + let key = x25519_hkdf_sha256_key(ephemeral_private_key, peer_public_key)?; + let encrypted_request = chacha20poly1305_encrypt_with_nonce(&key, &plaintext, nonce)?; + encode_encrypted_chat_request(&V2EncryptedChatRequest { + encryption_pubkey: x25519_public_key(ephemeral_private_key).to_vec(), + encrypted_request, + }) } /// Encode and seal request content V2 with OS-generated ephemeral key material /// and nonce. #[cfg(feature = "std")] pub fn seal_chat_request_v2( - peer_public_key: &[u8; 32], - request: &V2ChatRequestV2, + peer_public_key: &[u8; 32], + request: &V2ChatRequestV2, ) -> Result, ChatError> { - let ephemeral_private_key = random_bytes_32()?; - seal_chat_request_v2_with_nonce( - &ephemeral_private_key, - peer_public_key, - request, - random_nonce()?, - ) + let ephemeral_private_key = random_bytes_32()?; + seal_chat_request_v2_with_nonce( + &ephemeral_private_key, + peer_public_key, + request, + random_nonce()?, + ) } /// Open and decode a request-content-V2 first-contact wrapper. pub fn open_chat_request_v2( - static_private_key: &[u8; 32], - encoded_wrapper: &[u8], + static_private_key: &[u8; 32], + encoded_wrapper: &[u8], ) -> Result { - let wrapper = decode_encrypted_chat_request(encoded_wrapper)?; - let ephemeral_public_key: [u8; 32] = - wrapper - .encryption_pubkey - .try_into() - .map_err(|key: Vec| { - ChatError::InvalidEncoding(format!( - "first-contact ephemeral public key must be 32 bytes, got {}", - key.len() - )) - })?; - let key = x25519_hkdf_sha256_key(static_private_key, &ephemeral_public_key)?; - let plaintext = chacha20poly1305_decrypt(&key, &wrapper.encrypted_request)?; - decode_chat_request_v2(&plaintext) + let wrapper = decode_encrypted_chat_request(encoded_wrapper)?; + let ephemeral_public_key: [u8; 32] = + wrapper.encryption_pubkey.try_into().map_err(|key: Vec| { + ChatError::InvalidEncoding(format!( + "first-contact ephemeral public key must be 32 bytes, got {}", + key.len() + )) + })?; + let key = x25519_hkdf_sha256_key(static_private_key, &ephemeral_public_key)?; + let plaintext = chacha20poly1305_decrypt(&key, &wrapper.encrypted_request)?; + decode_chat_request_v2(&plaintext) } /// Seal a first-contact request with explicit product, account, route, and /// direction binding. The clear header is authenticated as AEAD context. #[allow(clippy::too_many_arguments)] pub fn seal_context_bound_chat_request_v2_with_nonce( - ephemeral_private_key: &[u8; 32], - peer_public_key: &[u8; 32], - product_id: &str, - sender_account_id: &[u8; 32], - recipient_account_id: &[u8; 32], - channel_id: &[u8; 32], - request: &V2ChatRequestV2, - nonce: [u8; 12], + ephemeral_private_key: &[u8; 32], + peer_public_key: &[u8; 32], + product_id: &str, + sender_account_id: &[u8; 32], + recipient_account_id: &[u8; 32], + channel_id: &[u8; 32], + request: &V2ChatRequestV2, + nonce: [u8; 12], ) -> Result, ChatError> { - if request.message.content.identity_proof.identity_account_id != *sender_account_id { - return Err(ChatError::InvalidEncoding( - "context-bound invite sender does not match its identity proof".into(), - )); - } - let ephemeral_public_key = x25519_public_key(ephemeral_private_key); - let encrypted = x25519_context_bound_encrypt_with_nonce( - ephemeral_private_key, - peer_public_key, - product_id, - sender_account_id, - recipient_account_id, - channel_id, - &encode_chat_request_v2(request)?, - nonce, - )?; - let mut out = Vec::with_capacity(CONTEXT_BOUND_INVITE_MAGIC.len() + 128 + encrypted.len()); - out.extend_from_slice(CONTEXT_BOUND_INVITE_MAGIC); - out.extend_from_slice(sender_account_id); - out.extend_from_slice(recipient_account_id); - out.extend_from_slice(channel_id); - out.extend_from_slice(&ephemeral_public_key); - out.extend_from_slice(&encrypted); - Ok(out) + if request.message.content.identity_proof.identity_account_id != *sender_account_id { + return Err(ChatError::InvalidEncoding( + "context-bound invite sender does not match its identity proof".into(), + )); + } + let ephemeral_public_key = x25519_public_key(ephemeral_private_key); + let encrypted = x25519_context_bound_encrypt_with_nonce( + ephemeral_private_key, + peer_public_key, + product_id, + sender_account_id, + recipient_account_id, + channel_id, + &encode_chat_request_v2(request)?, + nonce, + )?; + let mut out = Vec::with_capacity(CONTEXT_BOUND_INVITE_MAGIC.len() + 128 + encrypted.len()); + out.extend_from_slice(CONTEXT_BOUND_INVITE_MAGIC); + out.extend_from_slice(sender_account_id); + out.extend_from_slice(recipient_account_id); + out.extend_from_slice(channel_id); + out.extend_from_slice(&ephemeral_public_key); + out.extend_from_slice(&encrypted); + Ok(out) } /// Clear first-contact header. Fields remain untrusted until AEAD opening and /// verification of the decrypted request identity and proof. pub struct V2ContextBoundChatRequest<'a> { - pub sender_account_id: [u8; 32], - pub recipient_account_id: [u8; 32], - pub channel_id: [u8; 32], - pub ephemeral_public_key: [u8; 32], - pub encrypted_request: &'a [u8], + pub sender_account_id: [u8; 32], + pub recipient_account_id: [u8; 32], + pub channel_id: [u8; 32], + pub ephemeral_public_key: [u8; 32], + pub encrypted_request: &'a [u8], } /// Recognize the context-bound format family, including unsupported versions. /// Invalid members of this family must never be retried as legacy invites. pub fn is_context_bound_chat_request_v2(encoded_wrapper: &[u8]) -> bool { - encoded_wrapper.starts_with(&CONTEXT_BOUND_INVITE_MAGIC[..5]) + encoded_wrapper.starts_with(&CONTEXT_BOUND_INVITE_MAGIC[..5]) } /// Decode and check the clear header without accessing identity secrets. /// The caller must authenticate ciphertext and verify the decrypted sender. pub fn decode_context_bound_chat_request_v2<'a>( - expected_recipient_account_id: &[u8; 32], - expected_channel_id: &[u8; 32], - encoded_wrapper: &'a [u8], + expected_recipient_account_id: &[u8; 32], + expected_channel_id: &[u8; 32], + encoded_wrapper: &'a [u8], ) -> Result, ChatError> { - const HEADER_LEN: usize = 8 + 32 + 32 + 32 + 32; - if encoded_wrapper.len() < HEADER_LEN + 28 - || &encoded_wrapper[..CONTEXT_BOUND_INVITE_MAGIC.len()] != CONTEXT_BOUND_INVITE_MAGIC - { - return Err(ChatError::InvalidEncoding( - "invalid context-bound invite header".into(), - )); - } - let sender_account_id: [u8; 32] = encoded_wrapper[8..40] - .try_into() - .map_err(|_| ChatError::InvalidEncoding("invalid context-bound invite sender".into()))?; - let recipient_account_id: [u8; 32] = encoded_wrapper[40..72] - .try_into() - .map_err(|_| ChatError::InvalidEncoding("invalid context-bound invite recipient".into()))?; - let channel_id: [u8; 32] = encoded_wrapper[72..104] - .try_into() - .map_err(|_| ChatError::InvalidEncoding("invalid context-bound invite route".into()))?; - let ephemeral_public_key: [u8; 32] = - encoded_wrapper[104..HEADER_LEN].try_into().map_err(|_| { - ChatError::InvalidEncoding("invalid context-bound invite ephemeral key".into()) - })?; - if recipient_account_id != *expected_recipient_account_id || channel_id != *expected_channel_id - { - return Err(ChatError::InvalidEncoding( - "context-bound invite recipient or route mismatch".into(), - )); - } - Ok(V2ContextBoundChatRequest { - sender_account_id, - recipient_account_id, - channel_id, - ephemeral_public_key, - encrypted_request: &encoded_wrapper[HEADER_LEN..], - }) + const HEADER_LEN: usize = 8 + 32 + 32 + 32 + 32; + if encoded_wrapper.len() < HEADER_LEN + 28 || + &encoded_wrapper[..CONTEXT_BOUND_INVITE_MAGIC.len()] != CONTEXT_BOUND_INVITE_MAGIC + { + return Err(ChatError::InvalidEncoding("invalid context-bound invite header".into())); + } + let sender_account_id: [u8; 32] = encoded_wrapper[8..40] + .try_into() + .map_err(|_| ChatError::InvalidEncoding("invalid context-bound invite sender".into()))?; + let recipient_account_id: [u8; 32] = encoded_wrapper[40..72] + .try_into() + .map_err(|_| ChatError::InvalidEncoding("invalid context-bound invite recipient".into()))?; + let channel_id: [u8; 32] = encoded_wrapper[72..104] + .try_into() + .map_err(|_| ChatError::InvalidEncoding("invalid context-bound invite route".into()))?; + let ephemeral_public_key: [u8; 32] = + encoded_wrapper[104..HEADER_LEN].try_into().map_err(|_| { + ChatError::InvalidEncoding("invalid context-bound invite ephemeral key".into()) + })?; + if recipient_account_id != *expected_recipient_account_id || channel_id != *expected_channel_id + { + return Err(ChatError::InvalidEncoding( + "context-bound invite recipient or route mismatch".into(), + )); + } + Ok(V2ContextBoundChatRequest { + sender_account_id, + recipient_account_id, + channel_id, + ephemeral_public_key, + encrypted_request: &encoded_wrapper[HEADER_LEN..], + }) } /// Open a context-bound first-contact request without legacy fallback. pub fn open_context_bound_chat_request_v2( - static_private_key: &[u8; 32], - product_id: &str, - expected_recipient_account_id: &[u8; 32], - expected_channel_id: &[u8; 32], - encoded_wrapper: &[u8], + static_private_key: &[u8; 32], + product_id: &str, + expected_recipient_account_id: &[u8; 32], + expected_channel_id: &[u8; 32], + encoded_wrapper: &[u8], ) -> Result { - let V2ContextBoundChatRequest { - sender_account_id, - recipient_account_id, - channel_id, - ephemeral_public_key, - encrypted_request, - } = decode_context_bound_chat_request_v2( - expected_recipient_account_id, - expected_channel_id, - encoded_wrapper, - )?; - let plaintext = x25519_context_bound_decrypt( - static_private_key, - &ephemeral_public_key, - product_id, - &sender_account_id, - &recipient_account_id, - &channel_id, - encrypted_request, - )?; - let request = decode_chat_request_v2(&plaintext)?; - if request.message.content.identity_proof.identity_account_id != sender_account_id { - return Err(ChatError::InvalidEncoding( - "context-bound invite identity proof does not match sender".into(), - )); - } - Ok(request) + let V2ContextBoundChatRequest { + sender_account_id, + recipient_account_id, + channel_id, + ephemeral_public_key, + encrypted_request, + } = decode_context_bound_chat_request_v2( + expected_recipient_account_id, + expected_channel_id, + encoded_wrapper, + )?; + let plaintext = x25519_context_bound_decrypt( + static_private_key, + &ephemeral_public_key, + product_id, + &sender_account_id, + &recipient_account_id, + &channel_id, + encrypted_request, + )?; + let request = decode_chat_request_v2(&plaintext)?; + if request.message.content.identity_proof.identity_account_id != sender_account_id { + return Err(ChatError::InvalidEncoding( + "context-bound invite identity proof does not match sender".into(), + )); + } + Ok(request) } /// Encode the plaintext StatementData::request payload without applying AEAD. pub fn encode_transport_request_plaintext( - request_id: &str, - messages: &[Vec], + request_id: &str, + messages: &[Vec], ) -> Result, ChatError> { - let mut plaintext = Vec::new(); - plaintext.push(0); - encode_string(&mut plaintext, request_id)?; - encode_vec_of_bytes(&mut plaintext, messages)?; - Ok(plaintext) + let mut plaintext = Vec::new(); + plaintext.push(0); + encode_string(&mut plaintext, request_id)?; + encode_vec_of_bytes(&mut plaintext, messages)?; + Ok(plaintext) } /// Encode the plaintext StatementData::response payload without applying AEAD. pub fn encode_transport_response_plaintext( - request_id: &str, - response_code: u8, + request_id: &str, + response_code: u8, ) -> Result, ChatError> { - let mut plaintext = Vec::new(); - plaintext.push(1); - encode_string(&mut plaintext, request_id)?; - plaintext.push(response_code); - Ok(plaintext) + let mut plaintext = Vec::new(); + plaintext.push(1); + encode_string(&mut plaintext, request_id)?; + plaintext.push(response_code); + Ok(plaintext) } /// Encode bare MessageExchange::Request plaintext for the encryptedRequest /// field of StatementData::MultiRequest. pub fn encode_message_exchange_request_plaintext( - request_id: &str, - messages: &[Vec], + request_id: &str, + messages: &[Vec], ) -> Result, ChatError> { - let mut plaintext = Vec::new(); - encode_string(&mut plaintext, request_id)?; - encode_vec_of_bytes(&mut plaintext, messages)?; - Ok(plaintext) + let mut plaintext = Vec::new(); + encode_string(&mut plaintext, request_id)?; + encode_vec_of_bytes(&mut plaintext, messages)?; + Ok(plaintext) } /// Decode bare MessageExchange::Request plaintext. pub fn decode_message_exchange_request_plaintext( - plaintext: &[u8], + plaintext: &[u8], ) -> Result { - let mut cursor = Cursor::new(plaintext); - let request_id = cursor.read_string("request_id")?; - let messages = cursor.read_vec_of_bytes("messages")?; - cursor.finish()?; - Ok(V2MessageExchangeRequest { - request_id, - messages, - }) + let mut cursor = Cursor::new(plaintext); + let request_id = cursor.read_string("request_id")?; + let messages = cursor.read_vec_of_bytes("messages")?; + cursor.finish()?; + Ok(V2MessageExchangeRequest { request_id, messages }) } /// Encode bare MessageExchange::Response plaintext for the encryptedResponse /// field of StatementData::MultiResponse. pub fn encode_message_exchange_response_plaintext( - request_id: &str, - response_code: u8, + request_id: &str, + response_code: u8, ) -> Result, ChatError> { - let mut plaintext = Vec::new(); - encode_string(&mut plaintext, request_id)?; - plaintext.push(response_code); - Ok(plaintext) + let mut plaintext = Vec::new(); + encode_string(&mut plaintext, request_id)?; + plaintext.push(response_code); + Ok(plaintext) } /// Decode bare MessageExchange::Response plaintext. pub fn decode_message_exchange_response_plaintext( - plaintext: &[u8], + plaintext: &[u8], ) -> Result { - let mut cursor = Cursor::new(plaintext); - let request_id = cursor.read_string("request_id")?; - let response_code = cursor.read_u8("response_code")?; - cursor.finish()?; - Ok(V2MessageExchangeResponse { - request_id, - response_code, - }) + let mut cursor = Cursor::new(plaintext); + let request_id = cursor.read_string("request_id")?; + let response_code = cursor.read_u8("response_code")?; + cursor.finish()?; + Ok(V2MessageExchangeResponse { request_id, response_code }) } /// Encode the plaintext StatementData::multirequest payload without applying AEAD. pub fn encode_transport_multi_request_plaintext( - request: &V2MultiDeviceRequest, + request: &V2MultiDeviceRequest, ) -> Result, ChatError> { - let mut plaintext = Vec::new(); - plaintext.push(2); - encode_bytes(&mut plaintext, &request.encrypted_request)?; - encode_request_device_infos(&mut plaintext, &request.devices_info)?; - Ok(plaintext) + let mut plaintext = Vec::new(); + plaintext.push(2); + encode_bytes(&mut plaintext, &request.encrypted_request)?; + encode_request_device_infos(&mut plaintext, &request.devices_info)?; + Ok(plaintext) } /// Encode the plaintext StatementData::multiresponse payload without applying AEAD. pub fn encode_transport_multi_response_plaintext( - response: &V2MultiDeviceResponse, + response: &V2MultiDeviceResponse, ) -> Result, ChatError> { - let mut plaintext = Vec::new(); - plaintext.push(3); - encode_bytes(&mut plaintext, &response.encrypted_response)?; - encode_request_device_infos(&mut plaintext, &response.devices_info)?; - Ok(plaintext) + let mut plaintext = Vec::new(); + plaintext.push(3); + encode_bytes(&mut plaintext, &response.encrypted_response)?; + encode_request_device_infos(&mut plaintext, &response.devices_info)?; + Ok(plaintext) } /// Encode and encrypt an ongoing v2 statement-store request payload with OS /// randomness. Guests must use [`encode_transport_request_with_nonce`]. #[cfg(feature = "std")] pub fn encode_transport_request( - aead_key: &[u8; 32], - request_id: &str, - messages: &[Vec], + aead_key: &[u8; 32], + request_id: &str, + messages: &[Vec], ) -> Result, ChatError> { - encode_transport_request_with_nonce(aead_key, request_id, messages, random_nonce()?) + encode_transport_request_with_nonce(aead_key, request_id, messages, random_nonce()?) } /// Encode and encrypt a request with a caller-supplied unique nonce. pub fn encode_transport_request_with_nonce( - aead_key: &[u8; 32], - request_id: &str, - messages: &[Vec], - nonce: [u8; 12], + aead_key: &[u8; 32], + request_id: &str, + messages: &[Vec], + nonce: [u8; 12], ) -> Result, ChatError> { - let plaintext = encode_transport_request_plaintext(request_id, messages)?; - chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) + let plaintext = encode_transport_request_plaintext(request_id, messages)?; + chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) } /// Encode and encrypt an ongoing v2 response with OS randomness. Guests must /// use [`encode_transport_response_with_nonce`]. #[cfg(feature = "std")] pub fn encode_transport_response( - aead_key: &[u8; 32], - request_id: &str, - response_code: u8, + aead_key: &[u8; 32], + request_id: &str, + response_code: u8, ) -> Result, ChatError> { - encode_transport_response_with_nonce(aead_key, request_id, response_code, random_nonce()?) + encode_transport_response_with_nonce(aead_key, request_id, response_code, random_nonce()?) } /// Encode and encrypt a response with a caller-supplied unique nonce. pub fn encode_transport_response_with_nonce( - aead_key: &[u8; 32], - request_id: &str, - response_code: u8, - nonce: [u8; 12], + aead_key: &[u8; 32], + request_id: &str, + response_code: u8, + nonce: [u8; 12], ) -> Result, ChatError> { - let plaintext = encode_transport_response_plaintext(request_id, response_code)?; - chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) + let plaintext = encode_transport_response_plaintext(request_id, response_code)?; + chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) } /// Encode and encrypt StatementData::multirequest with OS randomness. #[cfg(feature = "std")] pub fn encode_transport_multi_request( - aead_key: &[u8; 32], - request: &V2MultiDeviceRequest, + aead_key: &[u8; 32], + request: &V2MultiDeviceRequest, ) -> Result, ChatError> { - encode_transport_multi_request_with_nonce(aead_key, request, random_nonce()?) + encode_transport_multi_request_with_nonce(aead_key, request, random_nonce()?) } /// Encode and encrypt StatementData::multiresponse with OS randomness. #[cfg(feature = "std")] pub fn encode_transport_multi_response( - aead_key: &[u8; 32], - response: &V2MultiDeviceResponse, + aead_key: &[u8; 32], + response: &V2MultiDeviceResponse, ) -> Result, ChatError> { - encode_transport_multi_response_with_nonce(aead_key, response, random_nonce()?) + encode_transport_multi_response_with_nonce(aead_key, response, random_nonce()?) } /// Wrap a one-shot key with an OS-random nonce. #[cfg(feature = "std")] pub fn wrap_multi_device_key( - own_private_key: &[u8; 32], - peer_public_key: &[u8; 32], - one_shot_key: &[u8; 32], + own_private_key: &[u8; 32], + peer_public_key: &[u8; 32], + one_shot_key: &[u8; 32], ) -> Result, ChatError> { - wrap_multi_device_key_with_nonce( - own_private_key, - peer_public_key, - one_shot_key, - random_nonce()?, - ) + wrap_multi_device_key_with_nonce( + own_private_key, + peer_public_key, + one_shot_key, + random_nonce()?, + ) } /// Encrypt an inner multi-device payload with an OS-random nonce. #[cfg(feature = "std")] pub fn encrypt_multi_device_payload( - one_shot_key: &[u8; 32], - plaintext: &[u8], + one_shot_key: &[u8; 32], + plaintext: &[u8], ) -> Result, ChatError> { - encrypt_multi_device_payload_with_nonce(one_shot_key, plaintext, random_nonce()?) + encrypt_multi_device_payload_with_nonce(one_shot_key, plaintext, random_nonce()?) } /// Encode and encrypt StatementData::multirequest with a caller-supplied nonce. pub fn encode_transport_multi_request_with_nonce( - aead_key: &[u8; 32], - request: &V2MultiDeviceRequest, - nonce: [u8; 12], + aead_key: &[u8; 32], + request: &V2MultiDeviceRequest, + nonce: [u8; 12], ) -> Result, ChatError> { - let plaintext = encode_transport_multi_request_plaintext(request)?; - chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) + let plaintext = encode_transport_multi_request_plaintext(request)?; + chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) } /// Encode and encrypt StatementData::multiresponse with a caller-supplied nonce. pub fn encode_transport_multi_response_with_nonce( - aead_key: &[u8; 32], - response: &V2MultiDeviceResponse, - nonce: [u8; 12], + aead_key: &[u8; 32], + response: &V2MultiDeviceResponse, + nonce: [u8; 12], ) -> Result, ChatError> { - let plaintext = encode_transport_multi_response_plaintext(response)?; - chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) + let plaintext = encode_transport_multi_response_plaintext(response)?; + chacha20poly1305_encrypt_with_nonce(aead_key, &plaintext, nonce) } /// Encrypt a one-shot key for one recipient device using the X25519-derived /// CryptoKit-compatible key and a caller-supplied unique nonce. pub fn wrap_multi_device_key_with_nonce( - own_private_key: &[u8; 32], - peer_public_key: &[u8; 32], - one_shot_key: &[u8; 32], - nonce: [u8; 12], + own_private_key: &[u8; 32], + peer_public_key: &[u8; 32], + one_shot_key: &[u8; 32], + nonce: [u8; 12], ) -> Result, ChatError> { - let wrapping_key = x25519_hkdf_sha256_key(own_private_key, peer_public_key)?; - chacha20poly1305_encrypt_with_nonce(&wrapping_key, one_shot_key, nonce) + let wrapping_key = x25519_hkdf_sha256_key(own_private_key, peer_public_key)?; + chacha20poly1305_encrypt_with_nonce(&wrapping_key, one_shot_key, nonce) } /// Unwrap a one-shot key received from a peer device. pub fn unwrap_multi_device_key( - own_private_key: &[u8; 32], - peer_public_key: &[u8; 32], - encrypted_key: &[u8], + own_private_key: &[u8; 32], + peer_public_key: &[u8; 32], + encrypted_key: &[u8], ) -> Result<[u8; 32], ChatError> { - let wrapping_key = x25519_hkdf_sha256_key(own_private_key, peer_public_key)?; - let plaintext = chacha20poly1305_decrypt(&wrapping_key, encrypted_key)?; - plaintext.try_into().map_err(|plaintext: Vec| { - ChatError::InvalidEncoding(format!( - "unwrapped multi-device key must be 32 bytes, got {}", - plaintext.len() - )) - }) + let wrapping_key = x25519_hkdf_sha256_key(own_private_key, peer_public_key)?; + let plaintext = chacha20poly1305_decrypt(&wrapping_key, encrypted_key)?; + plaintext.try_into().map_err(|plaintext: Vec| { + ChatError::InvalidEncoding(format!( + "unwrapped multi-device key must be 32 bytes, got {}", + plaintext.len() + )) + }) } /// Encrypt an inner multi-device request/response using its one-shot key and a /// caller-supplied unique nonce. pub fn encrypt_multi_device_payload_with_nonce( - one_shot_key: &[u8; 32], - plaintext: &[u8], - nonce: [u8; 12], + one_shot_key: &[u8; 32], + plaintext: &[u8], + nonce: [u8; 12], ) -> Result, ChatError> { - chacha20poly1305_encrypt_with_nonce(one_shot_key, plaintext, nonce) + chacha20poly1305_encrypt_with_nonce(one_shot_key, plaintext, nonce) } /// Decrypt an inner multi-device request/response. pub fn decrypt_multi_device_payload( - one_shot_key: &[u8; 32], - ciphertext: &[u8], + one_shot_key: &[u8; 32], + ciphertext: &[u8], ) -> Result, ChatError> { - chacha20poly1305_decrypt(one_shot_key, ciphertext) + chacha20poly1305_decrypt(one_shot_key, ciphertext) } /// Decode and decrypt an ongoing v2 statement-store transport payload. pub fn decode_transport( - data: &[u8], - aead_key: &[u8; 32], + data: &[u8], + aead_key: &[u8; 32], ) -> Result { - let plaintext = match chacha20poly1305_decrypt(aead_key, data) { - Ok(plaintext) => plaintext, - Err(raw_error) => { - let mut outer = Cursor::new(data); - let encrypted = outer.read_bytes("encrypted_transport")?; - outer.finish()?; - chacha20poly1305_decrypt(aead_key, &encrypted).map_err(|_| raw_error)? - } - }; - decode_transport_plaintext(&plaintext) + let plaintext = match chacha20poly1305_decrypt(aead_key, data) { + Ok(plaintext) => plaintext, + Err(raw_error) => { + let mut outer = Cursor::new(data); + let encrypted = outer.read_bytes("encrypted_transport")?; + outer.finish()?; + chacha20poly1305_decrypt(aead_key, &encrypted).map_err(|_| raw_error)? + }, + }; + decode_transport_plaintext(&plaintext) } /// Decode plaintext StatementData after a Host has opened the identity route. pub fn decode_transport_plaintext(plaintext: &[u8]) -> Result { - let mut cursor = Cursor::new(plaintext); - let kind = cursor.read_u8("transport_kind")?; - let decoded = match kind { - 0 => { - let request_id = cursor.read_string("request_id")?; - let messages = cursor.read_vec_of_bytes("messages")?; - cursor.finish()?; - V2StatementTransportData::Request { - request_id, - messages, - } - } - 1 => { - let request_id = cursor.read_string("request_id")?; - let response_code = cursor.read_u8("response_code")?; - cursor.finish()?; - V2StatementTransportData::Response { - request_id, - response_code, - } - } - 2 => { - let encrypted_request = cursor.read_bytes("encrypted_request")?; - let devices_info = cursor.read_request_device_infos("devices_info")?; - cursor.finish()?; - V2StatementTransportData::MultiRequest(V2MultiDeviceRequest { - encrypted_request, - devices_info, - }) - } - 3 => { - let encrypted_response = cursor.read_bytes("encrypted_response")?; - let devices_info = cursor.read_request_device_infos("devices_info")?; - cursor.finish()?; - V2StatementTransportData::MultiResponse(V2MultiDeviceResponse { - encrypted_response, - devices_info, - }) - } - value => { - return Err(ChatError::InvalidEncoding(format!( - "unsupported v2 transport kind {value}" - ))); - } - }; - Ok(decoded) + let mut cursor = Cursor::new(plaintext); + let kind = cursor.read_u8("transport_kind")?; + let decoded = match kind { + 0 => { + let request_id = cursor.read_string("request_id")?; + let messages = cursor.read_vec_of_bytes("messages")?; + cursor.finish()?; + V2StatementTransportData::Request { request_id, messages } + }, + 1 => { + let request_id = cursor.read_string("request_id")?; + let response_code = cursor.read_u8("response_code")?; + cursor.finish()?; + V2StatementTransportData::Response { request_id, response_code } + }, + 2 => { + let encrypted_request = cursor.read_bytes("encrypted_request")?; + let devices_info = cursor.read_request_device_infos("devices_info")?; + cursor.finish()?; + V2StatementTransportData::MultiRequest(V2MultiDeviceRequest { + encrypted_request, + devices_info, + }) + }, + 3 => { + let encrypted_response = cursor.read_bytes("encrypted_response")?; + let devices_info = cursor.read_request_device_infos("devices_info")?; + cursor.finish()?; + V2StatementTransportData::MultiResponse(V2MultiDeviceResponse { + encrypted_response, + devices_info, + }) + }, + value => { + return Err(ChatError::InvalidEncoding(format!( + "unsupported v2 transport kind {value}" + ))); + }, + }; + Ok(decoded) } fn encode_message( - message_id: &str, - timestamp: u64, - encode_content: impl FnOnce(&mut Vec) -> Result<(), ChatError>, + message_id: &str, + timestamp: u64, + encode_content: impl FnOnce(&mut Vec) -> Result<(), ChatError>, ) -> Result, ChatError> { - let mut out = Vec::new(); - encode_string(&mut out, message_id)?; - out.extend_from_slice(×tamp.to_le_bytes()); - out.push(0); // VersionedChatMessage.V1 - encode_content(&mut out)?; - Ok(out) + let mut out = Vec::new(); + encode_string(&mut out, message_id)?; + out.extend_from_slice(×tamp.to_le_bytes()); + out.push(0); // VersionedChatMessage.V1 + encode_content(&mut out)?; + Ok(out) } fn encode_string(out: &mut Vec, value: &str) -> Result<(), ChatError> { - let len = u32::try_from(value.len()).map_err(|_| { - ChatError::InvalidEncoding("string is too large for SCALE Compact".into()) - })?; - out.extend_from_slice(&encode_compact_u32(len)); - out.extend_from_slice(value.as_bytes()); - Ok(()) + let len = u32::try_from(value.len()).map_err(|_| { + ChatError::InvalidEncoding("string is too large for SCALE Compact".into()) + })?; + out.extend_from_slice(&encode_compact_u32(len)); + out.extend_from_slice(value.as_bytes()); + Ok(()) } fn encode_bytes(out: &mut Vec, value: &[u8]) -> Result<(), ChatError> { - let len = u32::try_from(value.len()).map_err(|_| { - ChatError::InvalidEncoding("byte array is too large for SCALE Compact".into()) - })?; - out.extend_from_slice(&encode_compact_u32(len)); - out.extend_from_slice(value); - Ok(()) + let len = u32::try_from(value.len()).map_err(|_| { + ChatError::InvalidEncoding("byte array is too large for SCALE Compact".into()) + })?; + out.extend_from_slice(&encode_compact_u32(len)); + out.extend_from_slice(value); + Ok(()) } fn encode_balance(out: &mut Vec, value: &str) -> Result<(), ChatError> { - let value = value - .parse::() - .map_err(|_| ChatError::InvalidEncoding(format!("invalid balance value: {value}")))?; - out.extend_from_slice(&encode_compact_u128(value)); - Ok(()) + let value = value + .parse::() + .map_err(|_| ChatError::InvalidEncoding(format!("invalid balance value: {value}")))?; + out.extend_from_slice(&encode_compact_u128(value)); + Ok(()) } fn encode_compact_u128(value: u128) -> Vec { - if value < 1 << 6 { - vec![(value as u8) << 2] - } else if value < 1 << 14 { - (((value as u16) << 2) | 0b01).to_le_bytes().to_vec() - } else if value < 1 << 30 { - (((value as u32) << 2) | 0b10).to_le_bytes().to_vec() - } else { - let mut bytes = value.to_le_bytes().to_vec(); - while bytes.last() == Some(&0) { - bytes.pop(); - } - let header = (((bytes.len() - 4) as u8) << 2) | 0b11; - let mut out = Vec::with_capacity(1 + bytes.len()); - out.push(header); - out.extend_from_slice(&bytes); - out - } + if value < 1 << 6 { + vec![(value as u8) << 2] + } else if value < 1 << 14 { + (((value as u16) << 2) | 0b01).to_le_bytes().to_vec() + } else if value < 1 << 30 { + (((value as u32) << 2) | 0b10).to_le_bytes().to_vec() + } else { + let mut bytes = value.to_le_bytes().to_vec(); + while bytes.last() == Some(&0) { + bytes.pop(); + } + let header = (((bytes.len() - 4) as u8) << 2) | 0b11; + let mut out = Vec::with_capacity(1 + bytes.len()); + out.push(header); + out.extend_from_slice(&bytes); + out + } } fn push_platform_index(platform: V2PushPlatform) -> u8 { - match platform { - V2PushPlatform::Android => 0, - V2PushPlatform::Ios => 1, - V2PushPlatform::IosVoip => 2, - } + match platform { + V2PushPlatform::Android => 0, + V2PushPlatform::Ios => 1, + V2PushPlatform::IosVoip => 2, + } } fn decode_push_platform(value: u8) -> Result { - match value { - 0 => Ok(V2PushPlatform::Android), - 1 => Ok(V2PushPlatform::Ios), - 2 => Ok(V2PushPlatform::IosVoip), - value => Err(ChatError::InvalidEncoding(format!( - "unsupported push platform {value}" - ))), - } + match value { + 0 => Ok(V2PushPlatform::Android), + 1 => Ok(V2PushPlatform::Ios), + 2 => Ok(V2PushPlatform::IosVoip), + value => Err(ChatError::InvalidEncoding(format!("unsupported push platform {value}"))), + } } fn encode_rich_text( - out: &mut Vec, - text: Option<&str>, - attachments: Option<&[V2FileVariant]>, + out: &mut Vec, + text: Option<&str>, + attachments: Option<&[V2FileVariant]>, ) -> Result<(), ChatError> { - match text { - Some(t) => { - out.push(1); // text = Some - encode_string(out, t)?; - } - None => out.push(0), // text = None - } - match attachments { - None => out.push(0), - Some(files) => { - let count = u32::try_from(files.len()) - .map_err(|_| ChatError::InvalidEncoding("too many attachments".into()))?; - out.push(1); - out.extend_from_slice(&encode_compact_u32(count)); - for file in files { - encode_file(out, file)?; - } - } - } - Ok(()) + match text { + Some(t) => { + out.push(1); // text = Some + encode_string(out, t)?; + }, + None => out.push(0), // text = None + } + match attachments { + None => out.push(0), + Some(files) => { + let count = u32::try_from(files.len()) + .map_err(|_| ChatError::InvalidEncoding("too many attachments".into()))?; + out.push(1); + out.extend_from_slice(&encode_compact_u32(count)); + for file in files { + encode_file(out, file)?; + } + }, + } + Ok(()) } fn validate_file_node(node: &V2NodeEndpoint) -> Result<(), ChatError> { - let V2NodeEndpoint::WssUrl(url) = node; - let invalid = || ChatError::InvalidEncoding("invalid attachment WSS endpoint".into()); - let (scheme, rest) = url.split_once("://").ok_or_else(invalid)?; - if !scheme.eq_ignore_ascii_case("wss") - || url - .bytes() - .any(|byte| byte <= b' ' || byte == 0x7f || byte == b'\\') - || rest.contains('#') - { - return Err(invalid()); - } - let authority = rest.split(['/', '?']).next().ok_or_else(invalid)?; - if authority.is_empty() || authority.contains('@') { - return Err(invalid()); - } - let port = if let Some(ipv6) = authority.strip_prefix('[') { - let (address, suffix) = ipv6.split_once(']').ok_or_else(invalid)?; - address - .parse::() - .map_err(|_| invalid())?; - if suffix.is_empty() { - None - } else { - Some(suffix.strip_prefix(':').ok_or_else(invalid)?) - } - } else { - let (host, port) = match authority.split_once(':') { - Some((host, port)) => (host, Some(port)), - None => (authority, None), - }; - let host = host.strip_suffix('.').unwrap_or(host); - if host.is_empty() - || host.len() > 253 - || !host.split('.').all(|label| { - !label.is_empty() - && label.len() <= 63 - && !label.starts_with('-') - && !label.ends_with('-') - && label - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') - }) - { - return Err(invalid()); - } - if host - .bytes() - .all(|byte| byte.is_ascii_digit() || byte == b'.') - { - host.parse::().map_err(|_| invalid())?; - } - port - }; - if let Some(port) = port - && (port.is_empty() - || !port.bytes().all(|byte| byte.is_ascii_digit()) - || port.parse::().is_err()) - { - return Err(invalid()); - } - Ok(()) + let V2NodeEndpoint::WssUrl(url) = node; + let invalid = || ChatError::InvalidEncoding("invalid attachment WSS endpoint".into()); + let (scheme, rest) = url.split_once("://").ok_or_else(invalid)?; + if !scheme.eq_ignore_ascii_case("wss") || + url.bytes().any(|byte| byte <= b' ' || byte == 0x7f || byte == b'\\') || + rest.contains('#') + { + return Err(invalid()); + } + let authority = rest.split(['/', '?']).next().ok_or_else(invalid)?; + if authority.is_empty() || authority.contains('@') { + return Err(invalid()); + } + let port = if let Some(ipv6) = authority.strip_prefix('[') { + let (address, suffix) = ipv6.split_once(']').ok_or_else(invalid)?; + address.parse::().map_err(|_| invalid())?; + if suffix.is_empty() { None } else { Some(suffix.strip_prefix(':').ok_or_else(invalid)?) } + } else { + let (host, port) = match authority.split_once(':') { + Some((host, port)) => (host, Some(port)), + None => (authority, None), + }; + let host = host.strip_suffix('.').unwrap_or(host); + if host.is_empty() || + host.len() > 253 || + !host.split('.').all(|label| { + !label.is_empty() && + label.len() <= 63 && + !label.starts_with('-') && + !label.ends_with('-') && + label.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + }) { + return Err(invalid()); + } + if host.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.') { + host.parse::().map_err(|_| invalid())?; + } + port + }; + if let Some(port) = port && + (port.is_empty() || + !port.bytes().all(|byte| byte.is_ascii_digit()) || + port.parse::().is_err()) + { + return Err(invalid()); + } + Ok(()) } fn encode_file(out: &mut Vec, file: &V2FileVariant) -> Result<(), ChatError> { - let V2FileVariant::P2pMixnet(file) = file; - if file.identifier.len() != 32 || file.claim_ticket.len() != 32 { - return Err(ChatError::InvalidEncoding( - "attachment identifier and claim ticket must be exactly 32 bytes".into(), - )); - } - validate_file_node(&file.node)?; - out.push(0); // FileVariant::P2pMixnet - encode_bytes(out, &file.identifier)?; - encode_bytes(out, &file.claim_ticket)?; - let V2NodeEndpoint::WssUrl(url) = &file.node; - out.push(0); // NodeEndpoint::WssUrl - encode_string(out, url)?; - match &file.meta { - V2FileMeta::General(general) => { - out.push(0); - encode_general_file_meta(out, general)?; - } - V2FileMeta::Image(image) => { - out.push(1); - encode_general_file_meta(out, &image.general)?; - out.extend_from_slice(&image.width.to_le_bytes()); - out.extend_from_slice(&image.height.to_le_bytes()); - encode_thumbnail(out, image.thumbnail.as_deref())?; - } - V2FileMeta::Video(video) => { - out.push(2); - encode_general_file_meta(out, &video.general)?; - out.extend_from_slice(&video.duration.to_le_bytes()); - encode_thumbnail(out, video.thumbnail.as_deref())?; - } - } - Ok(()) + let V2FileVariant::P2pMixnet(file) = file; + if file.identifier.len() != 32 || file.claim_ticket.len() != 32 { + return Err(ChatError::InvalidEncoding( + "attachment identifier and claim ticket must be exactly 32 bytes".into(), + )); + } + validate_file_node(&file.node)?; + out.push(0); // FileVariant::P2pMixnet + encode_bytes(out, &file.identifier)?; + encode_bytes(out, &file.claim_ticket)?; + let V2NodeEndpoint::WssUrl(url) = &file.node; + out.push(0); // NodeEndpoint::WssUrl + encode_string(out, url)?; + match &file.meta { + V2FileMeta::General(general) => { + out.push(0); + encode_general_file_meta(out, general)?; + }, + V2FileMeta::Image(image) => { + out.push(1); + encode_general_file_meta(out, &image.general)?; + out.extend_from_slice(&image.width.to_le_bytes()); + out.extend_from_slice(&image.height.to_le_bytes()); + encode_thumbnail(out, image.thumbnail.as_deref())?; + }, + V2FileMeta::Video(video) => { + out.push(2); + encode_general_file_meta(out, &video.general)?; + out.extend_from_slice(&video.duration.to_le_bytes()); + encode_thumbnail(out, video.thumbnail.as_deref())?; + }, + } + Ok(()) } fn encode_general_file_meta( - out: &mut Vec, - general: &V2GeneralFileMeta, + out: &mut Vec, + general: &V2GeneralFileMeta, ) -> Result<(), ChatError> { - encode_string(out, &general.mime_type)?; - out.extend_from_slice(&general.file_size.to_le_bytes()); - Ok(()) + encode_string(out, &general.mime_type)?; + out.extend_from_slice(&general.file_size.to_le_bytes()); + Ok(()) } fn encode_thumbnail(out: &mut Vec, thumbnail: Option<&[u8]>) -> Result<(), ChatError> { - match thumbnail { - None => out.push(0), - Some(bytes) => { - out.push(1); - encode_bytes(out, bytes)?; - } - } - Ok(()) + match thumbnail { + None => out.push(0), + Some(bytes) => { + out.push(1); + encode_bytes(out, bytes)?; + }, + } + Ok(()) } fn decode_file(cursor: &mut Cursor<'_>) -> Result { - let variant = cursor.read_u8("file_variant")?; - if variant != 0 { - return Err(ChatError::InvalidEncoding(format!( - "unsupported file variant {variant}" - ))); - } - let identifier = decode_file_key(cursor, "file_identifier")?; - let mut claim_ticket = zeroize::Zeroizing::new(decode_file_key(cursor, "file_claim_ticket")?); - let node = match cursor.read_u8("file_node_endpoint")? { - 0 => V2NodeEndpoint::WssUrl(cursor.read_string("file_wss_url")?), - value => { - return Err(ChatError::InvalidEncoding(format!( - "unsupported attachment node endpoint {value}" - ))); - } - }; - validate_file_node(&node)?; - let meta_index = cursor.read_u8("file_meta")?; - if meta_index > 2 { - return Err(ChatError::InvalidEncoding(format!( - "unsupported file metadata {meta_index}" - ))); - } - let general = V2GeneralFileMeta { - mime_type: cursor.read_string("file_mime_type")?, - file_size: cursor.read_u32("file_size")?, - }; - let meta = match meta_index { - 0 => V2FileMeta::General(general), - 1 => V2FileMeta::Image(V2ImageFileMeta { - general, - width: cursor.read_u32("image_width")?, - height: cursor.read_u32("image_height")?, - thumbnail: decode_thumbnail(cursor)?, - }), - 2 => V2FileMeta::Video(V2VideoFileMeta { - general, - duration: cursor.read_u32("video_duration")?, - thumbnail: decode_thumbnail(cursor)?, - }), - _ => unreachable!(), - }; - Ok(V2FileVariant::P2pMixnet(V2P2pMixnetFile { - identifier, - claim_ticket: core::mem::take(&mut *claim_ticket), - node, - meta, - })) + let variant = cursor.read_u8("file_variant")?; + if variant != 0 { + return Err(ChatError::InvalidEncoding(format!("unsupported file variant {variant}"))); + } + let identifier = decode_file_key(cursor, "file_identifier")?; + let mut claim_ticket = zeroize::Zeroizing::new(decode_file_key(cursor, "file_claim_ticket")?); + let node = match cursor.read_u8("file_node_endpoint")? { + 0 => V2NodeEndpoint::WssUrl(cursor.read_string("file_wss_url")?), + value => { + return Err(ChatError::InvalidEncoding(format!( + "unsupported attachment node endpoint {value}" + ))); + }, + }; + validate_file_node(&node)?; + let meta_index = cursor.read_u8("file_meta")?; + if meta_index > 2 { + return Err(ChatError::InvalidEncoding(format!("unsupported file metadata {meta_index}"))); + } + let general = V2GeneralFileMeta { + mime_type: cursor.read_string("file_mime_type")?, + file_size: cursor.read_u32("file_size")?, + }; + let meta = match meta_index { + 0 => V2FileMeta::General(general), + 1 => V2FileMeta::Image(V2ImageFileMeta { + general, + width: cursor.read_u32("image_width")?, + height: cursor.read_u32("image_height")?, + thumbnail: decode_thumbnail(cursor)?, + }), + 2 => V2FileMeta::Video(V2VideoFileMeta { + general, + duration: cursor.read_u32("video_duration")?, + thumbnail: decode_thumbnail(cursor)?, + }), + _ => unreachable!(), + }; + Ok(V2FileVariant::P2pMixnet(V2P2pMixnetFile { + identifier, + claim_ticket: core::mem::take(&mut *claim_ticket), + node, + meta, + })) } fn decode_file_key(cursor: &mut Cursor<'_>, field: &str) -> Result, ChatError> { - let (len, consumed) = - decode_compact_u32(&cursor.data[cursor.offset..]).map_err(ChatError::InvalidEncoding)?; - cursor.offset += consumed; - if len != 32 { - return Err(ChatError::InvalidEncoding(format!( - "{field} must be exactly 32 bytes" - ))); - } - Ok(cursor.read_exact(32, field)?.to_vec()) + let (len, consumed) = + decode_compact_u32(&cursor.data[cursor.offset..]).map_err(ChatError::InvalidEncoding)?; + cursor.offset += consumed; + if len != 32 { + return Err(ChatError::InvalidEncoding(format!("{field} must be exactly 32 bytes"))); + } + Ok(cursor.read_exact(32, field)?.to_vec()) } fn decode_thumbnail(cursor: &mut Cursor<'_>) -> Result>, ChatError> { - match cursor.read_u8("thumbnail_option")? { - 0 => Ok(None), - 1 => Ok(Some(cursor.read_bytes("thumbnail")?)), - value => Err(ChatError::InvalidEncoding(format!( - "invalid SCALE option for thumbnail: {value}" - ))), - } + match cursor.read_u8("thumbnail_option")? { + 0 => Ok(None), + 1 => Ok(Some(cursor.read_bytes("thumbnail")?)), + value => { + Err(ChatError::InvalidEncoding(format!("invalid SCALE option for thumbnail: {value}"))) + }, + } } fn encode_optional_push_token( - out: &mut Vec, - push_token: Option<&V2PushToken>, + out: &mut Vec, + push_token: Option<&V2PushToken>, ) -> Result<(), ChatError> { - match push_token { - Some(push_token) => { - out.push(1); - encode_bytes(out, &push_token.token)?; - out.push(match push_token.platform { - V2PushPlatform::Android => 0, - V2PushPlatform::Ios => 1, - V2PushPlatform::IosVoip => 2, - }); - } - None => out.push(0), - } - Ok(()) + match push_token { + Some(push_token) => { + out.push(1); + encode_bytes(out, &push_token.token)?; + out.push(match push_token.platform { + V2PushPlatform::Android => 0, + V2PushPlatform::Ios => 1, + V2PushPlatform::IosVoip => 2, + }); + }, + None => out.push(0), + } + Ok(()) } fn encode_optional_rich_text( - out: &mut Vec, - welcome_text: Option<&str>, + out: &mut Vec, + welcome_text: Option<&str>, ) -> Result<(), ChatError> { - match welcome_text { - Some(text) => { - out.push(1); // Some(RichText) - out.push(1); // RichText.text = Some - encode_string(out, text)?; - out.push(0); // RichText.attachments = None - } - None => out.push(0), - } - Ok(()) + match welcome_text { + Some(text) => { + out.push(1); // Some(RichText) + out.push(1); // RichText.text = Some + encode_string(out, text)?; + out.push(0); // RichText.attachments = None + }, + None => out.push(0), + } + Ok(()) } fn encode_vec_of_bytes(out: &mut Vec, items: &[Vec]) -> Result<(), ChatError> { - let len = u32::try_from(items.len()).map_err(|_| { - ChatError::InvalidEncoding("messages vector is too large for SCALE Compact".into()) - })?; - out.extend_from_slice(&encode_compact_u32(len)); - for item in items { - encode_bytes(out, item)?; - } - Ok(()) + let len = u32::try_from(items.len()).map_err(|_| { + ChatError::InvalidEncoding("messages vector is too large for SCALE Compact".into()) + })?; + out.extend_from_slice(&encode_compact_u32(len)); + for item in items { + encode_bytes(out, item)?; + } + Ok(()) } fn encode_request_device_infos( - out: &mut Vec, - devices: &[V2RequestDeviceInfo], + out: &mut Vec, + devices: &[V2RequestDeviceInfo], ) -> Result<(), ChatError> { - let len = u32::try_from(devices.len()).map_err(|_| { - ChatError::InvalidEncoding("devices vector is too large for SCALE Compact".into()) - })?; - out.extend_from_slice(&encode_compact_u32(len)); - for device in devices { - out.extend_from_slice(&device.statement_account_id); - encode_bytes(out, &device.encrypted_key)?; - } - Ok(()) + let len = u32::try_from(devices.len()).map_err(|_| { + ChatError::InvalidEncoding("devices vector is too large for SCALE Compact".into()) + })?; + out.extend_from_slice(&encode_compact_u32(len)); + for device in devices { + out.extend_from_slice(&device.statement_account_id); + encode_bytes(out, &device.encrypted_key)?; + } + Ok(()) } fn decode_chat_request_message_cursor( - cursor: &mut Cursor<'_>, + cursor: &mut Cursor<'_>, ) -> Result { - let message_id = cursor.read_string("message_id")?; - let timestamp = cursor.read_u64("timestamp")?; - let version_index = cursor.read_u8("version_index")?; - if version_index != 0 { - return Err(ChatError::InvalidEncoding(format!( - "unsupported v2 chat request version index {version_index}" - ))); - } - - let push_token = decode_optional_push_token(cursor)?; - let welcome_text = decode_optional_rich_text(cursor)?; - - Ok(V2ChatRequestMessage { - message_id, - timestamp, - push_token, - welcome_text, - }) + let message_id = cursor.read_string("message_id")?; + let timestamp = cursor.read_u64("timestamp")?; + let version_index = cursor.read_u8("version_index")?; + if version_index != 0 { + return Err(ChatError::InvalidEncoding(format!( + "unsupported v2 chat request version index {version_index}" + ))); + } + + let push_token = decode_optional_push_token(cursor)?; + let welcome_text = decode_optional_rich_text(cursor)?; + + Ok(V2ChatRequestMessage { message_id, timestamp, push_token, welcome_text }) } fn decode_chat_request_message_v2_cursor( - cursor: &mut Cursor<'_>, + cursor: &mut Cursor<'_>, ) -> Result { - let message_id = cursor.read_string("message_id")?; - let timestamp = cursor.read_u64("timestamp")?; - let version_index = cursor.read_u8("version_index")?; - if version_index != 1 { - return Err(ChatError::InvalidEncoding(format!( - "expected chat request content version index 1, got {version_index}" - ))); - } - let identity_account_id = cursor.read_array_32("identity_account_id")?; - let proof = cursor.read_array_32("identity_proof")?; - let device_enc_pub_key = cursor.read_array_32("device_enc_pub_key")?; - let push_token = decode_optional_push_token(cursor)?; - let welcome_text = decode_optional_rich_text(cursor)?; - Ok(V2ChatRequestMessageV2 { - message_id, - timestamp, - content: V2ChatRequestContentV2 { - identity_proof: V2ChatRequestIdentityProof { - identity_account_id, - proof, - }, - device_enc_pub_key, - push_token, - welcome_text, - }, - }) + let message_id = cursor.read_string("message_id")?; + let timestamp = cursor.read_u64("timestamp")?; + let version_index = cursor.read_u8("version_index")?; + if version_index != 1 { + return Err(ChatError::InvalidEncoding(format!( + "expected chat request content version index 1, got {version_index}" + ))); + } + let identity_account_id = cursor.read_array_32("identity_account_id")?; + let proof = cursor.read_array_32("identity_proof")?; + let device_enc_pub_key = cursor.read_array_32("device_enc_pub_key")?; + let push_token = decode_optional_push_token(cursor)?; + let welcome_text = decode_optional_rich_text(cursor)?; + Ok(V2ChatRequestMessageV2 { + message_id, + timestamp, + content: V2ChatRequestContentV2 { + identity_proof: V2ChatRequestIdentityProof { identity_account_id, proof }, + device_enc_pub_key, + push_token, + welcome_text, + }, + }) } fn validate_chat_request_proof(proof: &V2ChatRequestProof) -> Result<(), ChatError> { - if proof.signature.len() != 64 { - return Err(ChatError::InvalidEncoding(format!( - "chat request proof signature must be 64 bytes, got {}", - proof.signature.len() - ))); - } - if proof.signer.len() != 32 { - return Err(ChatError::InvalidEncoding(format!( - "chat request proof signer must be 32 bytes, got {}", - proof.signer.len() - ))); - } - Ok(()) + if proof.signature.len() != 64 { + return Err(ChatError::InvalidEncoding(format!( + "chat request proof signature must be 64 bytes, got {}", + proof.signature.len() + ))); + } + if proof.signer.len() != 32 { + return Err(ChatError::InvalidEncoding(format!( + "chat request proof signer must be 32 bytes, got {}", + proof.signer.len() + ))); + } + Ok(()) } fn decode_chat_request_proof(cursor: &mut Cursor<'_>) -> Result { - let proof_index = cursor.read_u8("proof_index")?; - if proof_index != 0 { - return Err(ChatError::InvalidEncoding(format!( - "unsupported chat request proof index {proof_index}" - ))); - } - let signature = cursor.read_exact(64, "proof_signature")?.to_vec(); - let signer = cursor.read_exact(32, "proof_signer")?.to_vec(); - Ok(V2ChatRequestProof { signature, signer }) + let proof_index = cursor.read_u8("proof_index")?; + if proof_index != 0 { + return Err(ChatError::InvalidEncoding(format!( + "unsupported chat request proof index {proof_index}" + ))); + } + let signature = cursor.read_exact(64, "proof_signature")?.to_vec(); + let signer = cursor.read_exact(32, "proof_signer")?.to_vec(); + Ok(V2ChatRequestProof { signature, signer }) } fn decode_optional_push_token(cursor: &mut Cursor<'_>) -> Result, ChatError> { - match cursor.read_u8("push_token_option")? { - 0 => Ok(None), - 1 => { - let token = cursor.read_bytes("push_token")?; - let platform = match cursor.read_u8("push_platform")? { - 0 => V2PushPlatform::Android, - 1 => V2PushPlatform::Ios, - 2 => V2PushPlatform::IosVoip, - value => { - return Err(ChatError::InvalidEncoding(format!( - "unsupported push platform {value}" - ))); - } - }; - Ok(Some(V2PushToken { token, platform })) - } - value => Err(ChatError::InvalidEncoding(format!( - "invalid SCALE option for push token: {value}" - ))), - } + match cursor.read_u8("push_token_option")? { + 0 => Ok(None), + 1 => { + let token = cursor.read_bytes("push_token")?; + let platform = match cursor.read_u8("push_platform")? { + 0 => V2PushPlatform::Android, + 1 => V2PushPlatform::Ios, + 2 => V2PushPlatform::IosVoip, + value => { + return Err(ChatError::InvalidEncoding(format!( + "unsupported push platform {value}" + ))); + }, + }; + Ok(Some(V2PushToken { token, platform })) + }, + value => { + Err(ChatError::InvalidEncoding(format!("invalid SCALE option for push token: {value}"))) + }, + } } /// Decode a RichText value from the cursor (non-optional outer wrapper). /// /// RichText = Option text + Option attachments. fn decode_rich_text( - cursor: &mut Cursor<'_>, + cursor: &mut Cursor<'_>, ) -> Result<(Option, Option>), ChatError> { - let text = match cursor.read_u8("rich_text_text_option")? { - 0 => None, - 1 => Some(cursor.read_string("rich_text_text")?), - value => { - return Err(ChatError::InvalidEncoding(format!( - "invalid SCALE option for rich text: {value}" - ))); - } - }; - - let attachments = match cursor.read_u8("rich_text_attachments_option")? { - 0 => None, - 1 => { - let (count, consumed) = decode_compact_u32(&cursor.data[cursor.offset..]) - .map_err(ChatError::InvalidEncoding)?; - cursor.offset += consumed; - let count = count as usize; - // Even with empty URL/MIME strings, a native file needs 75 bytes. - // Bound the collection before reserving from an untrusted count. - if count > cursor.data.len().saturating_sub(cursor.offset) / 75 { - return Err(ChatError::InvalidEncoding( - "attachment count exceeds remaining input".into(), - )); - } - let mut files = Vec::with_capacity(count); - for _ in 0..count { - files.push(decode_file(cursor)?); - } - Some(files) - } - value => { - return Err(ChatError::InvalidEncoding(format!( - "invalid SCALE option for rich text attachments: {value}" - ))); - } - }; - Ok((text, attachments)) + let text = match cursor.read_u8("rich_text_text_option")? { + 0 => None, + 1 => Some(cursor.read_string("rich_text_text")?), + value => { + return Err(ChatError::InvalidEncoding(format!( + "invalid SCALE option for rich text: {value}" + ))); + }, + }; + + let attachments = match cursor.read_u8("rich_text_attachments_option")? { + 0 => None, + 1 => { + let (count, consumed) = decode_compact_u32(&cursor.data[cursor.offset..]) + .map_err(ChatError::InvalidEncoding)?; + cursor.offset += consumed; + let count = count as usize; + // Even with empty URL/MIME strings, a native file needs 75 bytes. + // Bound the collection before reserving from an untrusted count. + if count > cursor.data.len().saturating_sub(cursor.offset) / 75 { + return Err(ChatError::InvalidEncoding( + "attachment count exceeds remaining input".into(), + )); + } + let mut files = Vec::with_capacity(count); + for _ in 0..count { + files.push(decode_file(cursor)?); + } + Some(files) + }, + value => { + return Err(ChatError::InvalidEncoding(format!( + "invalid SCALE option for rich text attachments: {value}" + ))); + }, + }; + Ok((text, attachments)) } fn decode_optional_rich_text(cursor: &mut Cursor<'_>) -> Result, ChatError> { - match cursor.read_u8("welcome_option")? { - 0 => Ok(None), - 1 => { - let text = match cursor.read_u8("welcome_text_option")? { - 0 => None, - 1 => Some(cursor.read_string("welcome_text")?), - value => { - return Err(ChatError::InvalidEncoding(format!( - "invalid SCALE option for rich text text: {value}" - ))); - } - }; - - match cursor.read_u8("welcome_attachments_option")? { - 0 => Ok(text), - 1 => Err(ChatError::InvalidEncoding( - "welcome message attachments cannot be represented".into(), - )), - value => Err(ChatError::InvalidEncoding(format!( - "invalid SCALE option for rich text attachments: {value}" - ))), - } - } - value => Err(ChatError::InvalidEncoding(format!( - "invalid SCALE option for welcome message: {value}" - ))), - } + match cursor.read_u8("welcome_option")? { + 0 => Ok(None), + 1 => { + let text = match cursor.read_u8("welcome_text_option")? { + 0 => None, + 1 => Some(cursor.read_string("welcome_text")?), + value => { + return Err(ChatError::InvalidEncoding(format!( + "invalid SCALE option for rich text text: {value}" + ))); + }, + }; + + match cursor.read_u8("welcome_attachments_option")? { + 0 => Ok(text), + 1 => Err(ChatError::InvalidEncoding( + "welcome message attachments cannot be represented".into(), + )), + value => Err(ChatError::InvalidEncoding(format!( + "invalid SCALE option for rich text attachments: {value}" + ))), + } + }, + value => Err(ChatError::InvalidEncoding(format!( + "invalid SCALE option for welcome message: {value}" + ))), + } } #[cfg(feature = "std")] fn random_bytes_32() -> Result<[u8; 32], ChatError> { - let mut bytes = [0; 32]; - getrandom::getrandom(&mut bytes) - .map_err(|_| ChatError::KeyDerivationFailed("OS key generation failed".into()))?; - Ok(bytes) + let mut bytes = [0; 32]; + getrandom::getrandom(&mut bytes) + .map_err(|_| ChatError::KeyDerivationFailed("OS key generation failed".into()))?; + Ok(bytes) } #[cfg(feature = "std")] fn random_nonce() -> Result<[u8; 12], ChatError> { - let mut nonce = [0; 12]; - getrandom::getrandom(&mut nonce) - .map_err(|_| ChatError::KeyDerivationFailed("OS nonce generation failed".into()))?; - Ok(nonce) + let mut nonce = [0; 12]; + getrandom::getrandom(&mut nonce) + .map_err(|_| ChatError::KeyDerivationFailed("OS nonce generation failed".into()))?; + Ok(nonce) } fn chacha20poly1305_encrypt_with_nonce( - key: &[u8; 32], - plaintext: &[u8], - nonce_bytes: [u8; 12], + key: &[u8; 32], + plaintext: &[u8], + nonce_bytes: [u8; 12], ) -> Result, ChatError> { - chacha20poly1305_encrypt_with_nonce_and_aad(key, plaintext, nonce_bytes, &[]) + chacha20poly1305_encrypt_with_nonce_and_aad(key, plaintext, nonce_bytes, &[]) } fn chacha20poly1305_encrypt_with_nonce_and_aad( - key: &[u8; 32], - plaintext: &[u8], - nonce_bytes: [u8; 12], - aad: &[u8], + key: &[u8; 32], + plaintext: &[u8], + nonce_bytes: [u8; 12], + aad: &[u8], ) -> Result, ChatError> { - let cipher = ChaCha20Poly1305::new(key.into()); - let ciphertext = cipher - .encrypt( - Nonce::from_slice(&nonce_bytes), - Payload { - msg: plaintext, - aad, - }, - ) - .map_err(|_| ChatError::InvalidEncoding("ChaCha20-Poly1305 encryption failed".into()))?; - - let mut out = Vec::with_capacity(12 + ciphertext.len()); - out.extend_from_slice(&nonce_bytes); - out.extend_from_slice(&ciphertext); - Ok(out) + let cipher = ChaCha20Poly1305::new(key.into()); + let ciphertext = cipher + .encrypt(Nonce::from_slice(&nonce_bytes), Payload { msg: plaintext, aad }) + .map_err(|_| ChatError::InvalidEncoding("ChaCha20-Poly1305 encryption failed".into()))?; + + let mut out = Vec::with_capacity(12 + ciphertext.len()); + out.extend_from_slice(&nonce_bytes); + out.extend_from_slice(&ciphertext); + Ok(out) } fn chacha20poly1305_decrypt(key: &[u8; 32], ciphertext: &[u8]) -> Result, ChatError> { - chacha20poly1305_decrypt_with_aad(key, ciphertext, &[]) + chacha20poly1305_decrypt_with_aad(key, ciphertext, &[]) } fn chacha20poly1305_decrypt_with_aad( - key: &[u8; 32], - ciphertext: &[u8], - aad: &[u8], + key: &[u8; 32], + ciphertext: &[u8], + aad: &[u8], ) -> Result, ChatError> { - if ciphertext.len() < 28 { - return Err(ChatError::InvalidEncoding(format!( - "ciphertext too short: {} bytes", - ciphertext.len() - ))); - } - - let cipher = ChaCha20Poly1305::new(key.into()); - let nonce = Nonce::from_slice(&ciphertext[..12]); - cipher - .decrypt( - nonce, - Payload { - msg: &ciphertext[12..], - aad, - }, - ) - .map_err(|_| ChatError::InvalidEncoding("ChaCha20-Poly1305 decryption failed".into())) + if ciphertext.len() < 28 { + return Err(ChatError::InvalidEncoding(format!( + "ciphertext too short: {} bytes", + ciphertext.len() + ))); + } + + let cipher = ChaCha20Poly1305::new(key.into()); + let nonce = Nonce::from_slice(&ciphertext[..12]); + cipher + .decrypt(nonce, Payload { msg: &ciphertext[12..], aad }) + .map_err(|_| ChatError::InvalidEncoding("ChaCha20-Poly1305 decryption failed".into())) } struct Cursor<'a> { - data: &'a [u8], - offset: usize, + data: &'a [u8], + offset: usize, } impl<'a> Cursor<'a> { - fn new(data: &'a [u8]) -> Self { - Self { data, offset: 0 } - } - - fn read_u8(&mut self, field: &str) -> Result { - let value = *self.data.get(self.offset).ok_or_else(|| { - ChatError::InvalidEncoding(format!("v2 chat message truncated at {field}")) - })?; - self.offset += 1; - Ok(value) - } - - #[cfg(feature = "std")] - fn read_u16(&mut self, field: &str) -> Result { - let bytes = self.read_exact(2, field)?; - Ok(u16::from_le_bytes(bytes.try_into().map_err(|_| { - ChatError::InvalidEncoding(format!("v2 chat message invalid u16 for {field}")) - })?)) - } - - fn read_u32(&mut self, field: &str) -> Result { - let bytes = self.read_exact(4, field)?; - Ok(u32::from_le_bytes(bytes.try_into().map_err(|_| { - ChatError::InvalidEncoding(format!("v2 chat message invalid u32 for {field}")) - })?)) - } - - fn read_compact_u128(&mut self, field: &str) -> Result { - let first = self.read_u8(field)?; - let mode = first & 0b11; - let non_canonical = - || ChatError::InvalidEncoding(format!("{field}: non-canonical compact integer")); - let value = match mode { - 0b00 => u128::from(first >> 2), - 0b01 => { - let next = self.read_exact(1, field)?[0]; - let value = u128::from(u16::from_le_bytes([first, next]) >> 2); - if value < 1 << 6 { - return Err(non_canonical()); - } - value - } - 0b10 => { - let rest = self.read_exact(3, field)?; - let value = u128::from(u32::from_le_bytes([first, rest[0], rest[1], rest[2]]) >> 2); - if value < 1 << 14 { - return Err(non_canonical()); - } - value - } - 0b11 => { - let len = usize::from(first >> 2) + 4; - if len > 16 { - return Err(ChatError::InvalidEncoding(format!( - "{field}: compact integer exceeds u128" - ))); - } - let bytes = self.read_exact(len, field)?; - if bytes[len - 1] == 0 { - return Err(non_canonical()); - } - let mut padded = [0_u8; 16]; - padded[..len].copy_from_slice(bytes); - let value = u128::from_le_bytes(padded); - if value < 1 << 30 { - return Err(non_canonical()); - } - value - } - _ => unreachable!(), - }; - Ok(value) - } - - fn read_u64(&mut self, field: &str) -> Result { - let bytes = self.read_exact(8, field)?; - Ok(u64::from_le_bytes(bytes.try_into().map_err(|_| { - ChatError::InvalidEncoding(format!("v2 chat message invalid u64 for {field}")) - })?)) - } - - fn read_array_32(&mut self, field: &str) -> Result<[u8; 32], ChatError> { - self.read_exact(32, field)? - .try_into() - .map_err(|_| ChatError::InvalidEncoding(format!("invalid 32-byte field {field}"))) - } - - fn read_balance(&mut self, field: &str) -> Result { - self.read_compact_u128(field).map(|value| value.to_string()) - } - - fn read_string(&mut self, field: &str) -> Result { - let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) - .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; - self.offset += consumed; - let bytes = self.read_exact(len as usize, field)?; - String::from_utf8(bytes.to_vec()) - .map_err(|e| ChatError::InvalidEncoding(format!("{field}: invalid utf-8: {e}"))) - } - - fn read_exact(&mut self, len: usize, field: &str) -> Result<&'a [u8], ChatError> { - let end = self.offset.checked_add(len).ok_or_else(|| { - ChatError::InvalidEncoding(format!("v2 chat message length overflow at {field}")) - })?; - if end > self.data.len() { - return Err(ChatError::InvalidEncoding(format!( - "v2 chat message truncated at {field}" - ))); - } - let bytes = &self.data[self.offset..end]; - self.offset = end; - Ok(bytes) - } - - fn read_bytes(&mut self, field: &str) -> Result, ChatError> { - let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) - .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; - self.offset += consumed; - Ok(self.read_exact(len as usize, field)?.to_vec()) - } - - fn read_vec_of_bytes(&mut self, field: &str) -> Result>, ChatError> { - let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) - .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; - self.offset += consumed; - let len = len as usize; - if len > self.data.len().saturating_sub(self.offset) { - return Err(ChatError::InvalidEncoding(format!( - "{field}: item count exceeds remaining input" - ))); - } - let mut out = Vec::with_capacity(len); - for index in 0..len { - out.push(self.read_bytes(&format!("{field}[{index}]"))?); - } - Ok(out) - } - - fn read_request_device_infos( - &mut self, - field: &str, - ) -> Result, ChatError> { - let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) - .map_err(|error| ChatError::InvalidEncoding(format!("{field}: {error}")))?; - self.offset += consumed; - let len = len as usize; - if len > self.data.len().saturating_sub(self.offset) / 33 { - return Err(ChatError::InvalidEncoding(format!( - "{field}: device count exceeds remaining input" - ))); - } - let mut devices = Vec::with_capacity(len); - for index in 0..len { - devices.push(V2RequestDeviceInfo { - statement_account_id: self - .read_array_32(&format!("{field}[{index}].statement_account_id"))?, - encrypted_key: self.read_bytes(&format!("{field}[{index}].encrypted_key"))?, - }); - } - Ok(devices) - } - - fn finish(&self) -> Result<(), ChatError> { - if self.offset != self.data.len() { - return Err(ChatError::InvalidEncoding(format!( - "v2 chat message has {} trailing bytes", - self.data.len() - self.offset - ))); - } - Ok(()) - } + fn new(data: &'a [u8]) -> Self { + Self { data, offset: 0 } + } + + fn read_u8(&mut self, field: &str) -> Result { + let value = *self.data.get(self.offset).ok_or_else(|| { + ChatError::InvalidEncoding(format!("v2 chat message truncated at {field}")) + })?; + self.offset += 1; + Ok(value) + } + + #[cfg(feature = "std")] + fn read_u16(&mut self, field: &str) -> Result { + let bytes = self.read_exact(2, field)?; + Ok(u16::from_le_bytes(bytes.try_into().map_err(|_| { + ChatError::InvalidEncoding(format!("v2 chat message invalid u16 for {field}")) + })?)) + } + + fn read_u32(&mut self, field: &str) -> Result { + let bytes = self.read_exact(4, field)?; + Ok(u32::from_le_bytes(bytes.try_into().map_err(|_| { + ChatError::InvalidEncoding(format!("v2 chat message invalid u32 for {field}")) + })?)) + } + + fn read_compact_u128(&mut self, field: &str) -> Result { + let first = self.read_u8(field)?; + let mode = first & 0b11; + let non_canonical = + || ChatError::InvalidEncoding(format!("{field}: non-canonical compact integer")); + let value = match mode { + 0b00 => u128::from(first >> 2), + 0b01 => { + let next = self.read_exact(1, field)?[0]; + let value = u128::from(u16::from_le_bytes([first, next]) >> 2); + if value < 1 << 6 { + return Err(non_canonical()); + } + value + }, + 0b10 => { + let rest = self.read_exact(3, field)?; + let value = u128::from(u32::from_le_bytes([first, rest[0], rest[1], rest[2]]) >> 2); + if value < 1 << 14 { + return Err(non_canonical()); + } + value + }, + 0b11 => { + let len = usize::from(first >> 2) + 4; + if len > 16 { + return Err(ChatError::InvalidEncoding(format!( + "{field}: compact integer exceeds u128" + ))); + } + let bytes = self.read_exact(len, field)?; + if bytes[len - 1] == 0 { + return Err(non_canonical()); + } + let mut padded = [0_u8; 16]; + padded[..len].copy_from_slice(bytes); + let value = u128::from_le_bytes(padded); + if value < 1 << 30 { + return Err(non_canonical()); + } + value + }, + _ => unreachable!(), + }; + Ok(value) + } + + fn read_u64(&mut self, field: &str) -> Result { + let bytes = self.read_exact(8, field)?; + Ok(u64::from_le_bytes(bytes.try_into().map_err(|_| { + ChatError::InvalidEncoding(format!("v2 chat message invalid u64 for {field}")) + })?)) + } + + fn read_array_32(&mut self, field: &str) -> Result<[u8; 32], ChatError> { + self.read_exact(32, field)? + .try_into() + .map_err(|_| ChatError::InvalidEncoding(format!("invalid 32-byte field {field}"))) + } + + fn read_balance(&mut self, field: &str) -> Result { + self.read_compact_u128(field).map(|value| value.to_string()) + } + + fn read_string(&mut self, field: &str) -> Result { + let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) + .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; + self.offset += consumed; + let bytes = self.read_exact(len as usize, field)?; + String::from_utf8(bytes.to_vec()) + .map_err(|e| ChatError::InvalidEncoding(format!("{field}: invalid utf-8: {e}"))) + } + + fn read_exact(&mut self, len: usize, field: &str) -> Result<&'a [u8], ChatError> { + let end = self.offset.checked_add(len).ok_or_else(|| { + ChatError::InvalidEncoding(format!("v2 chat message length overflow at {field}")) + })?; + if end > self.data.len() { + return Err(ChatError::InvalidEncoding(format!( + "v2 chat message truncated at {field}" + ))); + } + let bytes = &self.data[self.offset..end]; + self.offset = end; + Ok(bytes) + } + + fn read_bytes(&mut self, field: &str) -> Result, ChatError> { + let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) + .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; + self.offset += consumed; + Ok(self.read_exact(len as usize, field)?.to_vec()) + } + + fn read_vec_of_bytes(&mut self, field: &str) -> Result>, ChatError> { + let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) + .map_err(|e| ChatError::InvalidEncoding(format!("{field}: {e}")))?; + self.offset += consumed; + let len = len as usize; + if len > self.data.len().saturating_sub(self.offset) { + return Err(ChatError::InvalidEncoding(format!( + "{field}: item count exceeds remaining input" + ))); + } + let mut out = Vec::with_capacity(len); + for index in 0..len { + out.push(self.read_bytes(&format!("{field}[{index}]"))?); + } + Ok(out) + } + + fn read_request_device_infos( + &mut self, + field: &str, + ) -> Result, ChatError> { + let (len, consumed) = decode_compact_u32(&self.data[self.offset..]) + .map_err(|error| ChatError::InvalidEncoding(format!("{field}: {error}")))?; + self.offset += consumed; + let len = len as usize; + if len > self.data.len().saturating_sub(self.offset) / 33 { + return Err(ChatError::InvalidEncoding(format!( + "{field}: device count exceeds remaining input" + ))); + } + let mut devices = Vec::with_capacity(len); + for index in 0..len { + devices.push(V2RequestDeviceInfo { + statement_account_id: self + .read_array_32(&format!("{field}[{index}].statement_account_id"))?, + encrypted_key: self.read_bytes(&format!("{field}[{index}].encrypted_key"))?, + }); + } + Ok(devices) + } + + fn finish(&self) -> Result<(), ChatError> { + if self.offset != self.data.len() { + return Err(ChatError::InvalidEncoding(format!( + "v2 chat message has {} trailing bytes", + self.data.len() - self.offset + ))); + } + Ok(()) + } } #[cfg(test)] mod tests { - use super::*; - - fn hex_array_32(hex: &str) -> [u8; 32] { - assert_eq!(hex.len(), 64); - let mut out = [0_u8; 32]; - for (index, byte) in out.iter_mut().enumerate() { - let offset = index * 2; - *byte = u8::from_str_radix(&hex[offset..offset + 2], 16).unwrap(); - } - out - } - - #[test] - fn chacha20poly1305_matches_rfc_8439_vector() { - let key = hex_array_32("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"); - let nonce: [u8; 12] = hex::decode("070000004041424344454647") - .unwrap() - .try_into() - .unwrap(); - let plaintext = hex::decode(concat!( - "4c616469657320616e642047656e746c656d656e206f662074686520636c617373", - "206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c", - "79206f6e652074697020666f7220746865206675747572652c2073756e7363726565", - "6e20776f756c642062652069742e" - )) - .unwrap(); - let aad = hex::decode("50515253c0c1c2c3c4c5c6c7").unwrap(); - let expected = hex::decode(concat!( - "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63", - "dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692d", - "dbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4d", - "ef08e4b7a9de576d26586cec64b6116", - "1ae10b594f09e26a7e902ecbd0600691" - )) - .unwrap(); - - use chacha20poly1305::aead::Payload; - let cipher = ChaCha20Poly1305::new((&key).into()); - let encrypted = cipher - .encrypt( - Nonce::from_slice(&nonce), - Payload { - msg: &plaintext, - aad: &aad, - }, - ) - .unwrap(); - assert_eq!(encrypted, expected); - assert_eq!( - cipher - .decrypt( - Nonce::from_slice(&nonce), - Payload { - msg: &encrypted, - aad: &aad, - }, - ) - .unwrap(), - plaintext - ); - } - - #[test] - fn day_from_unix_uses_v2_protocol_epoch() { - assert_eq!(chat_request_day_from_unix(PROTOCOL_EPOCH_SECONDS - 1), None); - assert_eq!(chat_request_day_from_unix(PROTOCOL_EPOCH_SECONDS), Some(0)); - assert_eq!( - chat_request_day_from_unix(PROTOCOL_EPOCH_SECONDS + SECONDS_IN_DAY * 7 + 12), - Some(7) - ); - } - - #[test] - fn full_topic_matches_ios_v2_data_layout() { - let account = [0x11; 32]; - let mut expected_input = Vec::new(); - expected_input.extend_from_slice(&encode_compact_u32(CHAT_REQUEST_CONTEXT.len() as u32)); - expected_input.extend_from_slice(CHAT_REQUEST_CONTEXT); - expected_input.extend_from_slice(&encode_compact_u32(account.len() as u32)); - expected_input.extend_from_slice(&account); - assert_eq!( - chat_request_full_topic(&account), - blake2b_256(&expected_input) - ); - } - - #[test] - fn day_topic_appends_little_endian_u64_day() { - let account = [0x22; 32]; - let day = 42_u64; - let mut expected_input = Vec::new(); - expected_input.extend_from_slice(&encode_compact_u32(CHAT_REQUEST_CONTEXT.len() as u32)); - expected_input.extend_from_slice(CHAT_REQUEST_CONTEXT); - expected_input.extend_from_slice(&encode_compact_u32(account.len() as u32)); - expected_input.extend_from_slice(&account); - expected_input.extend_from_slice(&day.to_le_bytes()); - assert_eq!( - chat_request_day_topic(&account, day), - blake2b_256(&expected_input) - ); - } - - #[test] - fn full_topic_matches_ios_v2_observed_topic() { - let account = - hex_array_32("e6f8b1d6f1c8fde666469b9662d3d0925b21085f876722e428b1226d78ae1301"); - assert_eq!( - chat_request_full_topic(&account), - hex_array_32("463725e892e8c663bb531e8ed8ecf4b4e7e4a198ddfbce76a646d515dab1c5b2") - ); - } - - #[test] - fn session_id_params_match_v2_ordering() { - let requester = [0xAA; 32]; - let acceptor = [0xBB; 32]; - let params = chat_request_session_id_params(&requester, Some("1234"), &acceptor, None); - let mut expected = Vec::new(); - expected.extend_from_slice(&requester); - expected.extend_from_slice(&acceptor); - expected.extend_from_slice(b"/1234/"); - assert_eq!(params, expected); - } - - #[test] - fn session_topic_is_keyed_hash_of_context_and_params() { - let secret = [0x44; 32]; - let requester = [0x55; 32]; - let acceptor = [0x66; 32]; - let params = chat_request_session_id_params(&requester, None, &acceptor, Some("9999")); - let mut input = Vec::new(); - input.extend_from_slice(CHAT_REQUEST_CONTEXT); - input.extend_from_slice(¶ms); - let expected = blake2b_256_keyed(&secret, &input).unwrap(); - assert_eq!( - chat_request_session_topic(&secret, &requester, None, &acceptor, Some("9999")).unwrap(), - expected - ); - } - - #[test] - fn session_topic_rejects_non_32_byte_secret() { - let requester = [0x55; 32]; - let acceptor = [0x66; 32]; - let err = - chat_request_session_topic(&[0x44; 31], &requester, None, &acceptor, None).unwrap_err(); - assert!(err.to_string().contains("shared_secret must be 32 bytes")); - } - - #[test] - fn text_message_round_trips() { - let encoded = encode_text_message("msg-1", 123, "hello").unwrap(); - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-1".into(), - timestamp: 123, - content: V2ChatMessageContent::Text("hello".into()) - } - ); - } - - #[test] - fn chat_accepted_message_round_trips() { - let encoded = encode_chat_accepted_message("msg-2", 456, "request-1").unwrap(); - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-2".into(), - timestamp: 456, - content: V2ChatMessageContent::ChatAccepted { - request_id: "request-1".into() - } - } - ); - } - - #[test] - fn data_channel_offer_round_trips() { - let encoded = encode_data_channel_offer_message( - "msg-offer", - 457, - b"offer-sdp", - V2DataChannelPurpose::Video, - ) - .unwrap(); - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-offer".into(), - timestamp: 457, - content: V2ChatMessageContent::DataChannelOffer { - sdp: b"offer-sdp".to_vec(), - purpose: V2DataChannelPurpose::Video, - } - } - ); - } - - #[test] - fn data_channel_offer_lifts_to_transport_neutral_call_signal() { - let decoded = decode_message( - &encode_data_channel_offer_message( - "msg-offer", - 457, - b"offer-sdp", - V2DataChannelPurpose::Video, - ) - .unwrap(), - ) - .unwrap(); - - assert_eq!( - decoded.as_call_signal(), - Some(V2CallSignal::Offer { - offer_id: "msg-offer".into(), - sdp: b"offer-sdp".to_vec(), - purpose: V2DataChannelPurpose::Video, - }) - ); - } - - #[test] - fn data_channel_answer_round_trips() { - let encoded = - encode_data_channel_answer_message("msg-answer", 458, "offer-1", b"answer-sdp") - .unwrap(); - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-answer".into(), - timestamp: 458, - content: V2ChatMessageContent::DataChannelAnswer { - offer_id: "offer-1".into(), - sdp: b"answer-sdp".to_vec(), - } - } - ); - } - - #[test] - fn data_channel_candidates_round_trips() { - let encoded = encode_data_channel_candidates_message( - "msg-candidates", - 459, - "offer-2", - b"candidate-batch", - ) - .unwrap(); - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-candidates".into(), - timestamp: 459, - content: V2ChatMessageContent::DataChannelCandidates { - offer_id: "offer-2".into(), - sdp: b"candidate-batch".to_vec(), - } - } - ); - } - - #[test] - fn data_channel_closed_round_trips() { - let encoded = encode_data_channel_closed_message("msg-closed", 460, "offer-3").unwrap(); - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-closed".into(), - timestamp: 460, - content: V2ChatMessageContent::DataChannelClosed { - offer_id: "offer-3".into(), - } - } - ); - } - - #[test] - fn transport_neutral_call_signal_encodes_to_v2_message() { - let encoded = encode_call_signal_message( - "msg-call", - 461, - &V2CallSignal::Candidates { - offer_id: "offer-4".into(), - sdp: b"candidate-batch".to_vec(), - }, - ) - .unwrap(); - - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-call".into(), - timestamp: 461, - content: V2ChatMessageContent::DataChannelCandidates { - offer_id: "offer-4".into(), - sdp: b"candidate-batch".to_vec(), - } - } - ); - } - - #[test] - fn unsupported_content_preserves_header() { - let mut encoded = Vec::new(); - encode_string(&mut encoded, "msg-3").unwrap(); - encoded.extend_from_slice(&789_u64.to_le_bytes()); - encoded.push(0); - encoded.push(99); // 99 is not a known content index - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-3".into(), - timestamp: 789, - content: V2ChatMessageContent::UnsupportedContent { content_index: 99 } - } - ); - } - - #[test] - fn unsupported_version_preserves_header() { - let mut encoded = Vec::new(); - encode_string(&mut encoded, "msg-4").unwrap(); - encoded.extend_from_slice(&890_u64.to_le_bytes()); - encoded.push(1); - encoded.extend_from_slice(b"future payload"); - assert_eq!( - decode_message(&encoded).unwrap(), - V2ChatMessage { - message_id: "msg-4".into(), - timestamp: 890, - content: V2ChatMessageContent::UnsupportedVersion { version_index: 1 } - } - ); - } - - #[test] - fn supported_content_rejects_trailing_bytes() { - let mut encoded = encode_text_message("msg-5", 901, "hello").unwrap(); - encoded.push(0); - let err = decode_message(&encoded).unwrap_err(); - assert!(err.to_string().contains("trailing bytes")); - } - - #[test] - fn invalid_data_channel_purpose_rejects_decode() { - let mut encoded = Vec::new(); - encode_string(&mut encoded, "msg-invalid").unwrap(); - encoded.extend_from_slice(&902_u64.to_le_bytes()); - encoded.push(0); - encoded.push(8); - encode_bytes(&mut encoded, b"sdp").unwrap(); - encoded.push(9); - - let err = decode_message(&encoded).unwrap_err(); - assert!(err.to_string().contains("unsupported data channel purpose")); - } - - #[test] - fn test_token_message_roundtrip() { - let encoded = - encode_token_message("msg-1", 1000, &[0xAA, 0xBB], V2PushPlatform::Ios).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!(decoded.message_id, "msg-1"); - assert_eq!(decoded.timestamp, 1000); - assert_eq!( - decoded.content, - V2ChatMessageContent::Token { - token: vec![0xAA, 0xBB], - platform: V2PushPlatform::Ios - } - ); - } - - #[test] - fn token_message_decodes_v2_push_token_shape() { - let mut encoded = Vec::new(); - encode_string(&mut encoded, "msg-token-push").unwrap(); - encoded.extend_from_slice(&1001_u64.to_le_bytes()); - encoded.push(0); - encoded.push(1); - encode_bytes(&mut encoded, &[0xAA, 0xBB, 0xCC]).unwrap(); - encoded.push(2); - - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::Token { - token: vec![0xAA, 0xBB, 0xCC], - platform: V2PushPlatform::IosVoip - } - ); - } - - #[test] - fn test_send_legacy_message_roundtrip() { - let block_hash = vec![0x11; 32]; - let extrinsic_hash = vec![0x22; 32]; - let encoded = - encode_send_legacy_message("msg-2", 2000, "100", &block_hash, &extrinsic_hash).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::SendLegacy { - amount: "100".into(), - block_hash, - extrinsic_hash - } - ); - } - - #[test] - fn send_legacy_rejects_truncated_ios_payload_shape() { - let mut encoded = Vec::new(); - encode_string(&mut encoded, "msg-send-legacy-real").unwrap(); - encoded.extend_from_slice(&2001_u64.to_le_bytes()); - encoded.push(0); - encoded.push(2); - encode_balance(&mut encoded, "100").unwrap(); - encoded.extend_from_slice(&[0x11; 31]); - - let err = decode_message(&encoded).unwrap_err(); - assert!(err.to_string().contains("truncated at block_hash")); - } - - #[test] - fn send_legacy_rejects_non_canonical_amount() { - let encode = |amount: &[u8]| { - let mut encoded = Vec::new(); - encode_string(&mut encoded, "msg-send-legacy").unwrap(); - encoded.extend_from_slice(&2001_u64.to_le_bytes()); - encoded.push(0); - encoded.push(2); - encoded.extend_from_slice(amount); - encoded.extend_from_slice(&[0x11; 32]); - encoded.extend_from_slice(&[0x22; 32]); - encoded - }; - - assert!(decode_message(&encode(&[10 << 2])).is_ok()); - for amount in [ - &[(10 << 2) | 0b01, 0][..], - &[(10 << 2) | 0b10, 0, 0, 0][..], - &[0b11, 10, 0, 0, 0][..], - &[(1 << 2) | 0b11, 0, 0, 0, 0x40, 0][..], - ] { - let err = decode_message(&encode(amount)).unwrap_err(); - assert!( - err.to_string().contains("non-canonical"), - "{amount:?}: {err}" - ); - } - } - - #[test] - fn test_contact_added_message_roundtrip() { - let encoded = encode_contact_added_message("msg-3", 3000).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!(decoded.content, V2ChatMessageContent::ContactAdded); - } - - #[test] - fn test_reacted_message_roundtrip() { - let encoded = encode_reacted_message("msg-4", 4000, "ref-1", "\u{1F44D}").unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::Reacted { - message_id: "ref-1".into(), - emoji: "\u{1F44D}".into() - } - ); - } - - #[test] - fn test_reaction_removed_message_roundtrip() { - let encoded = - encode_reaction_removed_message("msg-5", 5000, "ref-2", "\u{2764}\u{FE0F}").unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::ReactionRemoved { - message_id: "ref-2".into(), - emoji: "\u{2764}\u{FE0F}".into() - } - ); - } - - #[test] - fn test_reply_message_roundtrip() { - let encoded = encode_reply_message("msg-6", 6000, "ref-3", Some("reply text")).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::Reply { - message_id: "ref-3".into(), - text: Some("reply text".into()), - attachments: None, - } - ); - } - - #[test] - fn test_reply_message_without_text_roundtrip() { - let encoded = encode_reply_message("msg-6b", 6001, "ref-3b", None).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::Reply { - message_id: "ref-3b".into(), - text: None, - attachments: None, - } - ); - } - - #[test] - fn test_edited_message_roundtrip() { - let encoded = encode_edited_message("msg-7", 7000, "ref-4", Some("new content")).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::Edited { - message_id: "ref-4".into(), - new_text: Some("new content".into()), - attachments: None, - } - ); - } - - #[test] - fn test_left_chat_message_roundtrip() { - let encoded = encode_left_chat_message("msg-8", 8000).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!(decoded.content, V2ChatMessageContent::LeftChat); - } - - #[test] - fn test_rich_text_message_roundtrip() { - let encoded = encode_rich_text_message("msg-9", 9000, Some("hello rich"), None).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::RichText { - text: Some("hello rich".into()), - attachments: None, - } - ); - } - - #[test] - fn egui_rich_text_matches_native_chat_v2_vector() { - let encoded = encode_rich_text_message( - "egui-message", - 1_700_000_000_123, - Some("hello from egui"), - None, - ) - .unwrap(); - assert_eq!( - hex::encode(&encoded), - "30656775692d6d6573736167657b68e5cf8b010000000f013c68656c6c6f2066726f6d206567756900" - ); - - let decoded = decode_message(&encoded).unwrap(); - assert_eq!(decoded.message_id, "egui-message"); - assert_eq!(decoded.timestamp, 1_700_000_000_123); - assert_eq!( - decoded.content, - V2ChatMessageContent::RichText { - text: Some("hello from egui".into()), - attachments: None, - } - ); - } - - #[test] - fn test_rich_text_message_without_text_roundtrip() { - let encoded = encode_rich_text_message("msg-9b", 9001, None, None).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::RichText { - text: None, - attachments: None - } - ); - } - - // Native brevity-chat wire.rs field order/indices and fixed-u32 numeric - // fixture, with real 32-byte HOP entry hashes and FileTicket keys. - fn native_attachment_fixture(content_index: u8, meta_index: u8) -> Vec { - let mut bytes = vec![4, b'm', 1, 0, 0, 0, 0, 0, 0, 0, 0, content_index]; - if content_index == 7 || content_index == 12 { - bytes.extend_from_slice(&[4, b'r']); - } - bytes.extend_from_slice(&[0, 1, 4, 0, 0x80]); // None text, Some(one file), hash length - bytes.extend_from_slice(&[0xa1; 32]); - bytes.push(0x80); // ticket length - bytes.extend_from_slice(&[0xb1; 32]); - bytes.extend_from_slice(&[0, 0x1c]); // WssUrl, length 7 - bytes.extend_from_slice(b"wss://n"); - bytes.push(meta_index); - match meta_index { - 0 => { - bytes.push(0x28); - bytes.extend_from_slice(b"text/plain"); - bytes.extend_from_slice(&[0xff; 4]); // file_size = u32::MAX - } - 1 => { - bytes.push(0x28); - bytes.extend_from_slice(b"image/jpeg"); - bytes.extend_from_slice(&[0x40, 0xe2, 1, 0]); // file_size = 123456 - bytes.extend_from_slice(&[0x20, 3, 0, 0]); // width = 800 - bytes.extend_from_slice(&[0x58, 2, 0, 0]); // height = 600 - bytes.extend_from_slice(&[1, 0x10, b'L', b'K', b'O', b'2']); - } - 2 => { - bytes.push(0x24); - bytes.extend_from_slice(b"video/mp4"); - bytes.extend_from_slice(&[7, 0, 0, 0]); // file_size = 7 - bytes.extend_from_slice(&[90, 0, 0, 0, 0]); // duration = 90, no thumbnail - } - _ => unreachable!(), - } - bytes - } - - fn native_attachment(meta: V2FileMeta) -> V2FileVariant { - V2FileVariant::P2pMixnet(V2P2pMixnetFile { - identifier: vec![0xa1; 32], - claim_ticket: vec![0xb1; 32], - node: V2NodeEndpoint::WssUrl("wss://n".into()), - meta, - }) - } - - #[test] - fn native_ordinary_reply_and_edit_attachment_fixtures() { - let cases = [ - ( - 7, - 0, - V2FileMeta::General(V2GeneralFileMeta { - mime_type: "text/plain".into(), - file_size: u32::MAX, - }), - ), - ( - 15, - 1, - V2FileMeta::Image(V2ImageFileMeta { - general: V2GeneralFileMeta { - mime_type: "image/jpeg".into(), - file_size: 123_456, - }, - width: 800, - height: 600, - thumbnail: Some(b"LKO2".to_vec()), - }), - ), - ( - 12, - 2, - V2FileMeta::Video(V2VideoFileMeta { - general: V2GeneralFileMeta { - mime_type: "video/mp4".into(), - file_size: 7, - }, - duration: 90, - thumbnail: None, - }), - ), - ]; - for (content_index, meta_index, meta) in cases { - let attachments = vec![native_attachment(meta)]; - let expected = match content_index { - 7 => V2ChatMessageContent::Reply { - message_id: "r".into(), - text: None, - attachments: Some(attachments.clone()), - }, - 12 => V2ChatMessageContent::Edited { - message_id: "r".into(), - new_text: None, - attachments: Some(attachments.clone()), - }, - _ => V2ChatMessageContent::RichText { - text: None, - attachments: Some(attachments.clone()), - }, - }; - assert_eq!( - decode_message(&native_attachment_fixture(content_index, meta_index)).unwrap(), - V2ChatMessage { - message_id: "m".into(), - timestamp: 1, - content: expected - }, - ); - assert_eq!( - encode_rich_text_message("m", 1, None, Some(&attachments)).unwrap(), - native_attachment_fixture(15, meta_index), - ); - } - } - - #[test] - fn rich_attachment_options_preserve_empty_and_multiple_files() { - let file = native_attachment(V2FileMeta::General(V2GeneralFileMeta { - mime_type: "text/plain".into(), - file_size: 0, - })); - for attachments in [Some(vec![]), Some(vec![file.clone(), file]), None] { - let encoded = - encode_rich_text_message("m", 1, Some("caption"), attachments.as_deref()).unwrap(); - assert_eq!( - decode_message(&encoded).unwrap().content, - V2ChatMessageContent::RichText { - text: Some("caption".into()), - attachments - } - ); - } - } - - #[test] - fn attachment_decoder_rejects_malformed_boundaries() { - let valid = native_attachment_fixture(15, 1); - // Each offset is a different SCALE discriminant in the native image fixture. - for (offset, value) in [(12, 2), (13, 2), (15, 1), (82, 1), (91, 3), (115, 2)] { - let mut malformed = valid.clone(); - malformed[offset] = value; - assert!( - decode_message(&malformed).is_err(), - "discriminant at {offset}" - ); - } - // The hash and ticket are Vec on wire but must be exact native keys. - for offset in [16, 49] { - let mut short = valid.clone(); - short[offset] = 31 << 2; - short.remove(offset + 1); - assert!(decode_message(&short).is_err()); - let mut long = valid.clone(); - long[offset] = 33 << 2; - long.insert(offset + 1, 0); - assert!(decode_message(&long).is_err()); - } - // Counts and variable lengths must be checked before allocation. - for offset in [14, 83, 92, 116] { - let mut oversized = valid[..offset].to_vec(); - oversized.extend_from_slice(&[3, 255, 255, 255, 255]); // compact u32::MAX - oversized.extend_from_slice(&valid[offset + 1..]); - assert!(decode_message(&oversized).is_err(), "length at {offset}"); - } - let mut noncanonical = valid[..14].to_vec(); - noncanonical.extend_from_slice(&[5, 0]); // noncanonical compact count 1 - noncanonical.extend_from_slice(&valid[15..]); - assert!(decode_message(&noncanonical).is_err()); - for end in 0..valid.len() { - assert!(decode_message(&valid[..end]).is_err(), "truncated at {end}"); - } - let mut trailing = valid; - trailing.push(0); - assert!(decode_message(&trailing).is_err()); - } - - #[test] - fn attachment_encoder_rejects_wrong_key_widths_and_unsafe_nodes() { - let V2FileVariant::P2pMixnet(file) = - native_attachment(V2FileMeta::General(V2GeneralFileMeta { - mime_type: "text/plain".into(), - file_size: 0, - })); - let mut short_hash = file.clone(); - short_hash.identifier.pop(); - let mut long_ticket = file.clone(); - long_ticket.claim_ticket.push(0); - for invalid in [short_hash, long_ticket] { - assert!( - encode_rich_text_message("m", 1, None, Some(&[V2FileVariant::P2pMixnet(invalid),])) - .is_err() - ); - } - for url in [ - "ws://n", - "wss://", - "wss://user@n", - "wss://n#fragment", - "wss://n:65536", - "wss://[bad]", - "wss://n\n/path", - ] { - let mut invalid = file.clone(); - invalid.node = V2NodeEndpoint::WssUrl(url.into()); - assert!( - encode_rich_text_message("m", 1, None, Some(&[V2FileVariant::P2pMixnet(invalid),])) - .is_err() - ); - } - let mut invalid_wire = native_attachment_fixture(15, 0); - invalid_wire[84] = b'x'; // xss://n is not a secure WebSocket endpoint. - assert!(decode_message(&invalid_wire).is_err()); - } - - #[test] - fn invitation_decoders_do_not_drop_attachments() { - let rich = native_attachment_fixture(15, 1); - let mut legacy = vec![4, b'm', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; - legacy.extend_from_slice(&rich[12..]); - assert!(decode_chat_request_message(&legacy).is_err()); - let mut current = vec![4, b'm', 1, 0, 0, 0, 0, 0, 0, 0, 1]; - current.extend_from_slice(&[1; 96]); // identity, proof, device encryption key - current.extend_from_slice(&[0, 1]); // no push token, Some welcome - current.extend_from_slice(&rich[12..]); - assert!(decode_chat_request_message_v2(¤t).is_err()); - } - - #[test] - fn test_coinage_send_message_roundtrip() { - let coin_keys = vec![vec![0xAAu8; 32], vec![0xBBu8; 32]]; - let encoded = encode_coinage_send_message("msg-10", 10000, "1000", &coin_keys).unwrap(); - let decoded = decode_message(&encoded).unwrap(); - assert_eq!( - decoded.content, - V2ChatMessageContent::CoinageSend { - total_value: "1000".into(), - coin_keys: coin_keys.clone() - } - ); - } - #[test] - fn current_multi_device_wire_roundtrips() { - let added = encode_device_added_message("add", 1, &[1; 32], &[2; 32]).unwrap(); - assert!(matches!( - decode_message(&added).unwrap().content, - V2ChatMessageContent::DeviceAdded { .. } - )); - let removed = encode_device_removed_message("remove", 2, &[1; 32]).unwrap(); - assert!(matches!( - decode_message(&removed).unwrap().content, - V2ChatMessageContent::DeviceRemoved { .. } - )); - let compacted = encode_compacted_messages_message( - "compact", - 3, - &[3; 4], - &[4; 5], - &V2NodeEndpoint::WssUrl("wss://chat.example".into()), - ) - .unwrap(); - assert!(matches!( - decode_message(&compacted).unwrap().content, - V2ChatMessageContent::CompactedMessages { .. } - )); - let accepted = encode_multi_chat_accepted_message( - "accept", - 4, - "request", - &V2PeerDevice { - statement_account_id: [5; 32], - encryption_public_key: [6; 32], - }, - ) - .unwrap(); - assert_eq!(accepted[16], 20, "Android DeviceChatAccepted wire index"); - assert!(matches!( - decode_message(&accepted).unwrap().content, - V2ChatMessageContent::MultiChatAccepted { .. } - )); - } - - #[test] - fn request_content_v2_seals_and_opens_with_fixed_nonce() { - let request = V2ChatRequestV2 { - message: V2ChatRequestMessageV2 { - message_id: "request-v2".into(), - timestamp: 42, - content: V2ChatRequestContentV2 { - identity_proof: V2ChatRequestIdentityProof { - identity_account_id: [7; 32], - proof: [8; 32], - }, - device_enc_pub_key: [9; 32], - push_token: None, - welcome_text: Some("hello".into()), - }, - }, - proof: V2ChatRequestProof { - signature: vec![10; 64], - signer: vec![11; 32], - }, - }; - let recipient_private = [12; 32]; - let wrapper = seal_chat_request_v2_with_nonce( - &[13; 32], - &x25519_public_key(&recipient_private), - &request, - [14; 12], - ) - .unwrap(); - assert_eq!( - open_chat_request_v2(&recipient_private, &wrapper).unwrap(), - request - ); - } - #[test] - fn context_bound_invite_authenticates_product_accounts_and_route() { - let sender_account_id = [7; 32]; - let recipient_account_id = [12; 32]; - let channel_id = [15; 32]; - let request = V2ChatRequestV2 { - message: V2ChatRequestMessageV2 { - message_id: "context-bound".into(), - timestamp: 42, - content: V2ChatRequestContentV2 { - identity_proof: V2ChatRequestIdentityProof { - identity_account_id: sender_account_id, - proof: [8; 32], - }, - device_enc_pub_key: [9; 32], - push_token: None, - welcome_text: Some("secure hello".into()), - }, - }, - proof: V2ChatRequestProof { - signature: vec![10; 64], - signer: vec![11; 32], - }, - }; - let recipient_private = [12; 32]; - let wrapper = seal_context_bound_chat_request_v2_with_nonce( - &[13; 32], - &x25519_public_key(&recipient_private), - "egui-chat.paseo", - &sender_account_id, - &recipient_account_id, - &channel_id, - &request, - [14; 12], - ) - .unwrap(); - assert_eq!( - open_context_bound_chat_request_v2( - &recipient_private, - "egui-chat.paseo", - &recipient_account_id, - &channel_id, - &wrapper, - ) - .unwrap(), - request - ); - assert!( - open_context_bound_chat_request_v2( - &recipient_private, - "egui-chat.westend", - &recipient_account_id, - &channel_id, - &wrapper, - ) - .is_err() - ); - assert!( - open_context_bound_chat_request_v2( - &recipient_private, - "egui-chat.paseo", - &recipient_account_id, - &[16; 32], - &wrapper, - ) - .is_err() - ); - assert!(open_chat_request_v2(&recipient_private, &wrapper).is_err()); - assert!(decode_context_bound_chat_request_v2(&[99; 32], &channel_id, &wrapper).is_err()); - assert!( - decode_context_bound_chat_request_v2( - &recipient_account_id, - &channel_id, - &wrapper[..163] - ) - .is_err() - ); - let mut unsupported_version = wrapper.clone(); - unsupported_version[5] = 4; - assert!(is_context_bound_chat_request_v2(&unsupported_version)); - assert!( - decode_context_bound_chat_request_v2( - &recipient_account_id, - &channel_id, - &unsupported_version, - ) - .is_err() - ); - } - - #[test] - fn bare_message_exchange_has_no_statement_data_index() { - let request = - encode_message_exchange_request_plaintext("inner", &[vec![0xaa, 0xbb]]).unwrap(); - assert_eq!( - request, - [vec![0x14], b"inner".to_vec(), vec![0x04, 0x08, 0xaa, 0xbb],].concat() - ); - assert_eq!( - decode_message_exchange_request_plaintext(&request).unwrap(), - V2MessageExchangeRequest { - request_id: "inner".into(), - messages: vec![vec![0xaa, 0xbb]], - } - ); - let response = encode_message_exchange_response_plaintext("inner", 0).unwrap(); - assert_eq!(response, [vec![0x14], b"inner".to_vec(), vec![0]].concat()); - assert_eq!( - decode_message_exchange_response_plaintext(&response).unwrap(), - V2MessageExchangeResponse { - request_id: "inner".into(), - response_code: 0, - } - ); - } - - #[test] - fn oversized_collection_counts_are_rejected_before_allocation() { - assert!(decode_transport_plaintext(&[2, 0, 3, 0xff, 0xff, 0xff, 0xff]).is_err()); - assert!( - decode_message_exchange_request_plaintext(&[0, 3, 0xff, 0xff, 0xff, 0xff]).is_err() - ); - } + use super::*; + + fn hex_array_32(hex: &str) -> [u8; 32] { + assert_eq!(hex.len(), 64); + let mut out = [0_u8; 32]; + for (index, byte) in out.iter_mut().enumerate() { + let offset = index * 2; + *byte = u8::from_str_radix(&hex[offset..offset + 2], 16).unwrap(); + } + out + } + + #[test] + fn chacha20poly1305_matches_rfc_8439_vector() { + let key = hex_array_32("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"); + let nonce: [u8; 12] = hex::decode("070000004041424344454647").unwrap().try_into().unwrap(); + let plaintext = hex::decode(concat!( + "4c616469657320616e642047656e746c656d656e206f662074686520636c617373", + "206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c", + "79206f6e652074697020666f7220746865206675747572652c2073756e7363726565", + "6e20776f756c642062652069742e" + )) + .unwrap(); + let aad = hex::decode("50515253c0c1c2c3c4c5c6c7").unwrap(); + let expected = hex::decode(concat!( + "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63", + "dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692d", + "dbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4d", + "ef08e4b7a9de576d26586cec64b6116", + "1ae10b594f09e26a7e902ecbd0600691" + )) + .unwrap(); + + use chacha20poly1305::aead::Payload; + let cipher = ChaCha20Poly1305::new((&key).into()); + let encrypted = cipher + .encrypt(Nonce::from_slice(&nonce), Payload { msg: &plaintext, aad: &aad }) + .unwrap(); + assert_eq!(encrypted, expected); + assert_eq!( + cipher + .decrypt(Nonce::from_slice(&nonce), Payload { msg: &encrypted, aad: &aad },) + .unwrap(), + plaintext + ); + } + + #[test] + fn day_from_unix_uses_v2_protocol_epoch() { + assert_eq!(chat_request_day_from_unix(PROTOCOL_EPOCH_SECONDS - 1), None); + assert_eq!(chat_request_day_from_unix(PROTOCOL_EPOCH_SECONDS), Some(0)); + assert_eq!( + chat_request_day_from_unix(PROTOCOL_EPOCH_SECONDS + SECONDS_IN_DAY * 7 + 12), + Some(7) + ); + } + + #[test] + fn full_topic_matches_ios_v2_data_layout() { + let account = [0x11; 32]; + let mut expected_input = Vec::new(); + expected_input.extend_from_slice(&encode_compact_u32(CHAT_REQUEST_CONTEXT.len() as u32)); + expected_input.extend_from_slice(CHAT_REQUEST_CONTEXT); + expected_input.extend_from_slice(&encode_compact_u32(account.len() as u32)); + expected_input.extend_from_slice(&account); + assert_eq!(chat_request_full_topic(&account), blake2b_256(&expected_input)); + } + + #[test] + fn day_topic_appends_little_endian_u64_day() { + let account = [0x22; 32]; + let day = 42_u64; + let mut expected_input = Vec::new(); + expected_input.extend_from_slice(&encode_compact_u32(CHAT_REQUEST_CONTEXT.len() as u32)); + expected_input.extend_from_slice(CHAT_REQUEST_CONTEXT); + expected_input.extend_from_slice(&encode_compact_u32(account.len() as u32)); + expected_input.extend_from_slice(&account); + expected_input.extend_from_slice(&day.to_le_bytes()); + assert_eq!(chat_request_day_topic(&account, day), blake2b_256(&expected_input)); + } + + #[test] + fn full_topic_matches_ios_v2_observed_topic() { + let account = + hex_array_32("e6f8b1d6f1c8fde666469b9662d3d0925b21085f876722e428b1226d78ae1301"); + assert_eq!( + chat_request_full_topic(&account), + hex_array_32("463725e892e8c663bb531e8ed8ecf4b4e7e4a198ddfbce76a646d515dab1c5b2") + ); + } + + #[test] + fn session_id_params_match_v2_ordering() { + let requester = [0xAA; 32]; + let acceptor = [0xBB; 32]; + let params = chat_request_session_id_params(&requester, Some("1234"), &acceptor, None); + let mut expected = Vec::new(); + expected.extend_from_slice(&requester); + expected.extend_from_slice(&acceptor); + expected.extend_from_slice(b"/1234/"); + assert_eq!(params, expected); + } + + #[test] + fn session_topic_is_keyed_hash_of_context_and_params() { + let secret = [0x44; 32]; + let requester = [0x55; 32]; + let acceptor = [0x66; 32]; + let params = chat_request_session_id_params(&requester, None, &acceptor, Some("9999")); + let mut input = Vec::new(); + input.extend_from_slice(CHAT_REQUEST_CONTEXT); + input.extend_from_slice(¶ms); + let expected = blake2b_256_keyed(&secret, &input).unwrap(); + assert_eq!( + chat_request_session_topic(&secret, &requester, None, &acceptor, Some("9999")).unwrap(), + expected + ); + } + + #[test] + fn session_topic_rejects_non_32_byte_secret() { + let requester = [0x55; 32]; + let acceptor = [0x66; 32]; + let err = + chat_request_session_topic(&[0x44; 31], &requester, None, &acceptor, None).unwrap_err(); + assert!(err.to_string().contains("shared_secret must be 32 bytes")); + } + + #[test] + fn text_message_round_trips() { + let encoded = encode_text_message("msg-1", 123, "hello").unwrap(); + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-1".into(), + timestamp: 123, + content: V2ChatMessageContent::Text("hello".into()) + } + ); + } + + #[test] + fn chat_accepted_message_round_trips() { + let encoded = encode_chat_accepted_message("msg-2", 456, "request-1").unwrap(); + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-2".into(), + timestamp: 456, + content: V2ChatMessageContent::ChatAccepted { request_id: "request-1".into() } + } + ); + } + + #[test] + fn data_channel_offer_round_trips() { + let encoded = encode_data_channel_offer_message( + "msg-offer", + 457, + b"offer-sdp", + V2DataChannelPurpose::Video, + ) + .unwrap(); + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-offer".into(), + timestamp: 457, + content: V2ChatMessageContent::DataChannelOffer { + sdp: b"offer-sdp".to_vec(), + purpose: V2DataChannelPurpose::Video, + } + } + ); + } + + #[test] + fn data_channel_offer_lifts_to_transport_neutral_call_signal() { + let decoded = decode_message( + &encode_data_channel_offer_message( + "msg-offer", + 457, + b"offer-sdp", + V2DataChannelPurpose::Video, + ) + .unwrap(), + ) + .unwrap(); + + assert_eq!( + decoded.as_call_signal(), + Some(V2CallSignal::Offer { + offer_id: "msg-offer".into(), + sdp: b"offer-sdp".to_vec(), + purpose: V2DataChannelPurpose::Video, + }) + ); + } + + #[test] + fn data_channel_answer_round_trips() { + let encoded = + encode_data_channel_answer_message("msg-answer", 458, "offer-1", b"answer-sdp") + .unwrap(); + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-answer".into(), + timestamp: 458, + content: V2ChatMessageContent::DataChannelAnswer { + offer_id: "offer-1".into(), + sdp: b"answer-sdp".to_vec(), + } + } + ); + } + + #[test] + fn data_channel_candidates_round_trips() { + let encoded = encode_data_channel_candidates_message( + "msg-candidates", + 459, + "offer-2", + b"candidate-batch", + ) + .unwrap(); + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-candidates".into(), + timestamp: 459, + content: V2ChatMessageContent::DataChannelCandidates { + offer_id: "offer-2".into(), + sdp: b"candidate-batch".to_vec(), + } + } + ); + } + + #[test] + fn data_channel_closed_round_trips() { + let encoded = encode_data_channel_closed_message("msg-closed", 460, "offer-3").unwrap(); + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-closed".into(), + timestamp: 460, + content: V2ChatMessageContent::DataChannelClosed { offer_id: "offer-3".into() } + } + ); + } + + #[test] + fn transport_neutral_call_signal_encodes_to_v2_message() { + let encoded = encode_call_signal_message( + "msg-call", + 461, + &V2CallSignal::Candidates { + offer_id: "offer-4".into(), + sdp: b"candidate-batch".to_vec(), + }, + ) + .unwrap(); + + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-call".into(), + timestamp: 461, + content: V2ChatMessageContent::DataChannelCandidates { + offer_id: "offer-4".into(), + sdp: b"candidate-batch".to_vec(), + } + } + ); + } + + #[test] + fn unsupported_content_preserves_header() { + let mut encoded = Vec::new(); + encode_string(&mut encoded, "msg-3").unwrap(); + encoded.extend_from_slice(&789_u64.to_le_bytes()); + encoded.push(0); + encoded.push(99); // 99 is not a known content index + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-3".into(), + timestamp: 789, + content: V2ChatMessageContent::UnsupportedContent { content_index: 99 } + } + ); + } + + #[test] + fn unsupported_version_preserves_header() { + let mut encoded = Vec::new(); + encode_string(&mut encoded, "msg-4").unwrap(); + encoded.extend_from_slice(&890_u64.to_le_bytes()); + encoded.push(1); + encoded.extend_from_slice(b"future payload"); + assert_eq!( + decode_message(&encoded).unwrap(), + V2ChatMessage { + message_id: "msg-4".into(), + timestamp: 890, + content: V2ChatMessageContent::UnsupportedVersion { version_index: 1 } + } + ); + } + + #[test] + fn supported_content_rejects_trailing_bytes() { + let mut encoded = encode_text_message("msg-5", 901, "hello").unwrap(); + encoded.push(0); + let err = decode_message(&encoded).unwrap_err(); + assert!(err.to_string().contains("trailing bytes")); + } + + #[test] + fn invalid_data_channel_purpose_rejects_decode() { + let mut encoded = Vec::new(); + encode_string(&mut encoded, "msg-invalid").unwrap(); + encoded.extend_from_slice(&902_u64.to_le_bytes()); + encoded.push(0); + encoded.push(8); + encode_bytes(&mut encoded, b"sdp").unwrap(); + encoded.push(9); + + let err = decode_message(&encoded).unwrap_err(); + assert!(err.to_string().contains("unsupported data channel purpose")); + } + + #[test] + fn test_token_message_roundtrip() { + let encoded = + encode_token_message("msg-1", 1000, &[0xAA, 0xBB], V2PushPlatform::Ios).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!(decoded.message_id, "msg-1"); + assert_eq!(decoded.timestamp, 1000); + assert_eq!( + decoded.content, + V2ChatMessageContent::Token { token: vec![0xAA, 0xBB], platform: V2PushPlatform::Ios } + ); + } + + #[test] + fn token_message_decodes_v2_push_token_shape() { + let mut encoded = Vec::new(); + encode_string(&mut encoded, "msg-token-push").unwrap(); + encoded.extend_from_slice(&1001_u64.to_le_bytes()); + encoded.push(0); + encoded.push(1); + encode_bytes(&mut encoded, &[0xAA, 0xBB, 0xCC]).unwrap(); + encoded.push(2); + + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::Token { + token: vec![0xAA, 0xBB, 0xCC], + platform: V2PushPlatform::IosVoip + } + ); + } + + #[test] + fn test_send_legacy_message_roundtrip() { + let block_hash = vec![0x11; 32]; + let extrinsic_hash = vec![0x22; 32]; + let encoded = + encode_send_legacy_message("msg-2", 2000, "100", &block_hash, &extrinsic_hash).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::SendLegacy { amount: "100".into(), block_hash, extrinsic_hash } + ); + } + + #[test] + fn send_legacy_rejects_truncated_ios_payload_shape() { + let mut encoded = Vec::new(); + encode_string(&mut encoded, "msg-send-legacy-real").unwrap(); + encoded.extend_from_slice(&2001_u64.to_le_bytes()); + encoded.push(0); + encoded.push(2); + encode_balance(&mut encoded, "100").unwrap(); + encoded.extend_from_slice(&[0x11; 31]); + + let err = decode_message(&encoded).unwrap_err(); + assert!(err.to_string().contains("truncated at block_hash")); + } + + #[test] + fn send_legacy_rejects_non_canonical_amount() { + let encode = |amount: &[u8]| { + let mut encoded = Vec::new(); + encode_string(&mut encoded, "msg-send-legacy").unwrap(); + encoded.extend_from_slice(&2001_u64.to_le_bytes()); + encoded.push(0); + encoded.push(2); + encoded.extend_from_slice(amount); + encoded.extend_from_slice(&[0x11; 32]); + encoded.extend_from_slice(&[0x22; 32]); + encoded + }; + + assert!(decode_message(&encode(&[10 << 2])).is_ok()); + for amount in [ + &[(10 << 2) | 0b01, 0][..], + &[(10 << 2) | 0b10, 0, 0, 0][..], + &[0b11, 10, 0, 0, 0][..], + &[(1 << 2) | 0b11, 0, 0, 0, 0x40, 0][..], + ] { + let err = decode_message(&encode(amount)).unwrap_err(); + assert!(err.to_string().contains("non-canonical"), "{amount:?}: {err}"); + } + } + + #[test] + fn test_contact_added_message_roundtrip() { + let encoded = encode_contact_added_message("msg-3", 3000).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!(decoded.content, V2ChatMessageContent::ContactAdded); + } + + #[test] + fn test_reacted_message_roundtrip() { + let encoded = encode_reacted_message("msg-4", 4000, "ref-1", "\u{1F44D}").unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::Reacted { message_id: "ref-1".into(), emoji: "\u{1F44D}".into() } + ); + } + + #[test] + fn test_reaction_removed_message_roundtrip() { + let encoded = + encode_reaction_removed_message("msg-5", 5000, "ref-2", "\u{2764}\u{FE0F}").unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::ReactionRemoved { + message_id: "ref-2".into(), + emoji: "\u{2764}\u{FE0F}".into() + } + ); + } + + #[test] + fn test_reply_message_roundtrip() { + let encoded = encode_reply_message("msg-6", 6000, "ref-3", Some("reply text")).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::Reply { + message_id: "ref-3".into(), + text: Some("reply text".into()), + attachments: None, + } + ); + } + + #[test] + fn test_reply_message_without_text_roundtrip() { + let encoded = encode_reply_message("msg-6b", 6001, "ref-3b", None).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::Reply { + message_id: "ref-3b".into(), + text: None, + attachments: None, + } + ); + } + + #[test] + fn test_edited_message_roundtrip() { + let encoded = encode_edited_message("msg-7", 7000, "ref-4", Some("new content")).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::Edited { + message_id: "ref-4".into(), + new_text: Some("new content".into()), + attachments: None, + } + ); + } + + #[test] + fn test_left_chat_message_roundtrip() { + let encoded = encode_left_chat_message("msg-8", 8000).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!(decoded.content, V2ChatMessageContent::LeftChat); + } + + #[test] + fn test_rich_text_message_roundtrip() { + let encoded = encode_rich_text_message("msg-9", 9000, Some("hello rich"), None).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::RichText { text: Some("hello rich".into()), attachments: None } + ); + } + + #[test] + fn egui_rich_text_matches_native_chat_v2_vector() { + let encoded = encode_rich_text_message( + "egui-message", + 1_700_000_000_123, + Some("hello from egui"), + None, + ) + .unwrap(); + assert_eq!( + hex::encode(&encoded), + "30656775692d6d6573736167657b68e5cf8b010000000f013c68656c6c6f2066726f6d206567756900" + ); + + let decoded = decode_message(&encoded).unwrap(); + assert_eq!(decoded.message_id, "egui-message"); + assert_eq!(decoded.timestamp, 1_700_000_000_123); + assert_eq!( + decoded.content, + V2ChatMessageContent::RichText { + text: Some("hello from egui".into()), + attachments: None, + } + ); + } + + #[test] + fn test_rich_text_message_without_text_roundtrip() { + let encoded = encode_rich_text_message("msg-9b", 9001, None, None).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::RichText { text: None, attachments: None } + ); + } + + // Native brevity-chat wire.rs field order/indices and fixed-u32 numeric + // fixture, with real 32-byte HOP entry hashes and FileTicket keys. + fn native_attachment_fixture(content_index: u8, meta_index: u8) -> Vec { + let mut bytes = vec![4, b'm', 1, 0, 0, 0, 0, 0, 0, 0, 0, content_index]; + if content_index == 7 || content_index == 12 { + bytes.extend_from_slice(&[4, b'r']); + } + bytes.extend_from_slice(&[0, 1, 4, 0, 0x80]); // None text, Some(one file), hash length + bytes.extend_from_slice(&[0xa1; 32]); + bytes.push(0x80); // ticket length + bytes.extend_from_slice(&[0xb1; 32]); + bytes.extend_from_slice(&[0, 0x1c]); // WssUrl, length 7 + bytes.extend_from_slice(b"wss://n"); + bytes.push(meta_index); + match meta_index { + 0 => { + bytes.push(0x28); + bytes.extend_from_slice(b"text/plain"); + bytes.extend_from_slice(&[0xff; 4]); // file_size = u32::MAX + }, + 1 => { + bytes.push(0x28); + bytes.extend_from_slice(b"image/jpeg"); + bytes.extend_from_slice(&[0x40, 0xe2, 1, 0]); // file_size = 123456 + bytes.extend_from_slice(&[0x20, 3, 0, 0]); // width = 800 + bytes.extend_from_slice(&[0x58, 2, 0, 0]); // height = 600 + bytes.extend_from_slice(&[1, 0x10, b'L', b'K', b'O', b'2']); + }, + 2 => { + bytes.push(0x24); + bytes.extend_from_slice(b"video/mp4"); + bytes.extend_from_slice(&[7, 0, 0, 0]); // file_size = 7 + bytes.extend_from_slice(&[90, 0, 0, 0, 0]); // duration = 90, no thumbnail + }, + _ => unreachable!(), + } + bytes + } + + fn native_attachment(meta: V2FileMeta) -> V2FileVariant { + V2FileVariant::P2pMixnet(V2P2pMixnetFile { + identifier: vec![0xa1; 32], + claim_ticket: vec![0xb1; 32], + node: V2NodeEndpoint::WssUrl("wss://n".into()), + meta, + }) + } + + #[test] + fn native_ordinary_reply_and_edit_attachment_fixtures() { + let cases = [ + ( + 7, + 0, + V2FileMeta::General(V2GeneralFileMeta { + mime_type: "text/plain".into(), + file_size: u32::MAX, + }), + ), + ( + 15, + 1, + V2FileMeta::Image(V2ImageFileMeta { + general: V2GeneralFileMeta { + mime_type: "image/jpeg".into(), + file_size: 123_456, + }, + width: 800, + height: 600, + thumbnail: Some(b"LKO2".to_vec()), + }), + ), + ( + 12, + 2, + V2FileMeta::Video(V2VideoFileMeta { + general: V2GeneralFileMeta { mime_type: "video/mp4".into(), file_size: 7 }, + duration: 90, + thumbnail: None, + }), + ), + ]; + for (content_index, meta_index, meta) in cases { + let attachments = vec![native_attachment(meta)]; + let expected = match content_index { + 7 => V2ChatMessageContent::Reply { + message_id: "r".into(), + text: None, + attachments: Some(attachments.clone()), + }, + 12 => V2ChatMessageContent::Edited { + message_id: "r".into(), + new_text: None, + attachments: Some(attachments.clone()), + }, + _ => V2ChatMessageContent::RichText { + text: None, + attachments: Some(attachments.clone()), + }, + }; + assert_eq!( + decode_message(&native_attachment_fixture(content_index, meta_index)).unwrap(), + V2ChatMessage { message_id: "m".into(), timestamp: 1, content: expected }, + ); + assert_eq!( + encode_rich_text_message("m", 1, None, Some(&attachments)).unwrap(), + native_attachment_fixture(15, meta_index), + ); + } + } + + #[test] + fn rich_attachment_options_preserve_empty_and_multiple_files() { + let file = native_attachment(V2FileMeta::General(V2GeneralFileMeta { + mime_type: "text/plain".into(), + file_size: 0, + })); + for attachments in [Some(vec![]), Some(vec![file.clone(), file]), None] { + let encoded = + encode_rich_text_message("m", 1, Some("caption"), attachments.as_deref()).unwrap(); + assert_eq!( + decode_message(&encoded).unwrap().content, + V2ChatMessageContent::RichText { text: Some("caption".into()), attachments } + ); + } + } + + #[test] + fn attachment_decoder_rejects_malformed_boundaries() { + let valid = native_attachment_fixture(15, 1); + // Each offset is a different SCALE discriminant in the native image fixture. + for (offset, value) in [(12, 2), (13, 2), (15, 1), (82, 1), (91, 3), (115, 2)] { + let mut malformed = valid.clone(); + malformed[offset] = value; + assert!(decode_message(&malformed).is_err(), "discriminant at {offset}"); + } + // The hash and ticket are Vec on wire but must be exact native keys. + for offset in [16, 49] { + let mut short = valid.clone(); + short[offset] = 31 << 2; + short.remove(offset + 1); + assert!(decode_message(&short).is_err()); + let mut long = valid.clone(); + long[offset] = 33 << 2; + long.insert(offset + 1, 0); + assert!(decode_message(&long).is_err()); + } + // Counts and variable lengths must be checked before allocation. + for offset in [14, 83, 92, 116] { + let mut oversized = valid[..offset].to_vec(); + oversized.extend_from_slice(&[3, 255, 255, 255, 255]); // compact u32::MAX + oversized.extend_from_slice(&valid[offset + 1..]); + assert!(decode_message(&oversized).is_err(), "length at {offset}"); + } + let mut noncanonical = valid[..14].to_vec(); + noncanonical.extend_from_slice(&[5, 0]); // noncanonical compact count 1 + noncanonical.extend_from_slice(&valid[15..]); + assert!(decode_message(&noncanonical).is_err()); + for end in 0..valid.len() { + assert!(decode_message(&valid[..end]).is_err(), "truncated at {end}"); + } + let mut trailing = valid; + trailing.push(0); + assert!(decode_message(&trailing).is_err()); + } + + #[test] + fn attachment_encoder_rejects_wrong_key_widths_and_unsafe_nodes() { + let V2FileVariant::P2pMixnet(file) = + native_attachment(V2FileMeta::General(V2GeneralFileMeta { + mime_type: "text/plain".into(), + file_size: 0, + })); + let mut short_hash = file.clone(); + short_hash.identifier.pop(); + let mut long_ticket = file.clone(); + long_ticket.claim_ticket.push(0); + for invalid in [short_hash, long_ticket] { + assert!( + encode_rich_text_message("m", 1, None, Some(&[V2FileVariant::P2pMixnet(invalid),])) + .is_err() + ); + } + for url in [ + "ws://n", + "wss://", + "wss://user@n", + "wss://n#fragment", + "wss://n:65536", + "wss://[bad]", + "wss://n\n/path", + ] { + let mut invalid = file.clone(); + invalid.node = V2NodeEndpoint::WssUrl(url.into()); + assert!( + encode_rich_text_message("m", 1, None, Some(&[V2FileVariant::P2pMixnet(invalid),])) + .is_err() + ); + } + let mut invalid_wire = native_attachment_fixture(15, 0); + invalid_wire[84] = b'x'; // xss://n is not a secure WebSocket endpoint. + assert!(decode_message(&invalid_wire).is_err()); + } + + #[test] + fn invitation_decoders_do_not_drop_attachments() { + let rich = native_attachment_fixture(15, 1); + let mut legacy = vec![4, b'm', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; + legacy.extend_from_slice(&rich[12..]); + assert!(decode_chat_request_message(&legacy).is_err()); + let mut current = vec![4, b'm', 1, 0, 0, 0, 0, 0, 0, 0, 1]; + current.extend_from_slice(&[1; 96]); // identity, proof, device encryption key + current.extend_from_slice(&[0, 1]); // no push token, Some welcome + current.extend_from_slice(&rich[12..]); + assert!(decode_chat_request_message_v2(¤t).is_err()); + } + + #[test] + fn test_coinage_send_message_roundtrip() { + let coin_keys = vec![vec![0xAAu8; 32], vec![0xBBu8; 32]]; + let encoded = encode_coinage_send_message("msg-10", 10000, "1000", &coin_keys).unwrap(); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!( + decoded.content, + V2ChatMessageContent::CoinageSend { + total_value: "1000".into(), + coin_keys: coin_keys.clone() + } + ); + } + #[test] + fn profile_reference_wire_roundtrips_disclosure_and_withdrawal() { + let disclosed = encode_profile_reference_message( + "profile", + 5, + "seity.dot", + Some("seity-contacts:v1:00"), + ) + .unwrap(); + let decoded = decode_message(&disclosed).unwrap(); + assert_eq!(decoded.message_id, "profile"); + assert_eq!( + decoded.content, + V2ChatMessageContent::ProfileReference { + discloser_product_id: "seity.dot".into(), + reference: Some("seity-contacts:v1:00".into()), + } + ); + let withdrawn = encode_profile_reference_message("profile", 6, "seity.dot", None).unwrap(); + assert_eq!( + decode_message(&withdrawn).unwrap().content, + V2ChatMessageContent::ProfileReference { + discloser_product_id: "seity.dot".into(), + reference: None, + } + ); + // A malformed option byte is refused, not guessed at. + let mut bad = withdrawn.clone(); + *bad.last_mut().unwrap() = 7; + assert!(decode_message(&bad).is_err()); + } + + #[test] + fn host_channel_bootstrap_wire_roundtrips_and_pins_its_bytes() { + let key = [0x42u8; 32]; + let encoded = encode_host_channel_bootstrap_message("hc", 9, &key).unwrap(); + // message_id "hc", timestamp 9, VersionedChatMessage.V1, index 23, version 1, key. + let mut expected = vec![8, b'h', b'c']; + expected.extend_from_slice(&9u64.to_le_bytes()); + expected.extend_from_slice(&[0, 23, 1]); + expected.extend_from_slice(&key); + assert_eq!(encoded, expected); + let decoded = decode_message(&encoded).unwrap(); + assert_eq!(decoded.message_id, "hc"); + assert_eq!(decoded.timestamp, 9); + assert_eq!( + decoded.content, + V2ChatMessageContent::HostChannelBootstrap { version: 1, channel_public_key: key } + ); + } + + #[test] + fn host_channel_bootstrap_refuses_other_versions_and_trailing_bytes() { + let key = [7u8; 32]; + let mut other_version = encode_host_channel_bootstrap_message("hc", 1, &key).unwrap(); + // compact("hc") is 3 bytes, timestamp 8, envelope version 1, index 1: the frame version is + // byte 13. + other_version[3 + 8 + 1 + 1] = 2; + assert!(decode_message(&other_version).is_err()); + let mut trailing = encode_host_channel_bootstrap_message("hc", 1, &key).unwrap(); + trailing.push(0); + assert!(decode_message(&trailing).is_err()); + let mut short = encode_host_channel_bootstrap_message("hc", 1, &key).unwrap(); + short.pop(); + assert!(decode_message(&short).is_err()); + } + + #[test] + fn personal_profile_wire_requires_explicit_scope_and_durable_revision() { + for reference in [Some("profile:secret"), None] { + let encoded = + encode_personal_profile_reference_message("p", 5, 42, "seity.dot", reference) + .unwrap(); + assert_eq!( + decode_message(&encoded).unwrap().content, + V2ChatMessageContent::PersonalProfileReference { + discloser_product_id: "seity.dot".into(), + reference: reference.map(String::from), + revision: 42, + } + ); + let mut bad_scope = encoded.clone(); + bad_scope[12] = 0; + assert!( + decode_message(&bad_scope).is_err(), + "personal cannot silently become app-scoped" + ); + let mut bad_revision = encoded.clone(); + bad_revision[13..21].fill(0); + assert!(decode_message(&bad_revision).is_err()); + let mut trailing = encoded.clone(); + trailing.push(0); + assert!(decode_message(&trailing).is_err()); + assert!(decode_message(&encoded[..20]).is_err()); + } + assert!(encode_personal_profile_reference_message("p", 5, 0, "seity.dot", None).is_err()); + assert_eq!( + encode_profile_reference_message("p", 5, "s", None).unwrap(), + vec![4, b'p', 5, 0, 0, 0, 0, 0, 0, 0, 0, 21, 4, b's', 0], + "legacy content 21 keeps its original byte layout" + ); + } + + #[test] + fn current_multi_device_wire_roundtrips() { + let added = encode_device_added_message("add", 1, &[1; 32], &[2; 32]).unwrap(); + assert!(matches!( + decode_message(&added).unwrap().content, + V2ChatMessageContent::DeviceAdded { .. } + )); + let removed = encode_device_removed_message("remove", 2, &[1; 32]).unwrap(); + assert!(matches!( + decode_message(&removed).unwrap().content, + V2ChatMessageContent::DeviceRemoved { .. } + )); + let compacted = encode_compacted_messages_message( + "compact", + 3, + &[3; 4], + &[4; 5], + &V2NodeEndpoint::WssUrl("wss://chat.example".into()), + ) + .unwrap(); + assert!(matches!( + decode_message(&compacted).unwrap().content, + V2ChatMessageContent::CompactedMessages { .. } + )); + let accepted = encode_multi_chat_accepted_message( + "accept", + 4, + "request", + &V2PeerDevice { statement_account_id: [5; 32], encryption_public_key: [6; 32] }, + ) + .unwrap(); + assert_eq!(accepted[16], 20, "Android DeviceChatAccepted wire index"); + assert!(matches!( + decode_message(&accepted).unwrap().content, + V2ChatMessageContent::MultiChatAccepted { .. } + )); + } + + #[test] + fn request_content_v2_seals_and_opens_with_fixed_nonce() { + let request = V2ChatRequestV2 { + message: V2ChatRequestMessageV2 { + message_id: "request-v2".into(), + timestamp: 42, + content: V2ChatRequestContentV2 { + identity_proof: V2ChatRequestIdentityProof { + identity_account_id: [7; 32], + proof: [8; 32], + }, + device_enc_pub_key: [9; 32], + push_token: None, + welcome_text: Some("hello".into()), + }, + }, + proof: V2ChatRequestProof { signature: vec![10; 64], signer: vec![11; 32] }, + }; + let recipient_private = [12; 32]; + let wrapper = seal_chat_request_v2_with_nonce( + &[13; 32], + &x25519_public_key(&recipient_private), + &request, + [14; 12], + ) + .unwrap(); + assert_eq!(open_chat_request_v2(&recipient_private, &wrapper).unwrap(), request); + } + #[test] + fn context_bound_invite_authenticates_product_accounts_and_route() { + let sender_account_id = [7; 32]; + let recipient_account_id = [12; 32]; + let channel_id = [15; 32]; + let request = V2ChatRequestV2 { + message: V2ChatRequestMessageV2 { + message_id: "context-bound".into(), + timestamp: 42, + content: V2ChatRequestContentV2 { + identity_proof: V2ChatRequestIdentityProof { + identity_account_id: sender_account_id, + proof: [8; 32], + }, + device_enc_pub_key: [9; 32], + push_token: None, + welcome_text: Some("secure hello".into()), + }, + }, + proof: V2ChatRequestProof { signature: vec![10; 64], signer: vec![11; 32] }, + }; + let recipient_private = [12; 32]; + let wrapper = seal_context_bound_chat_request_v2_with_nonce( + &[13; 32], + &x25519_public_key(&recipient_private), + "egui-chat.paseo", + &sender_account_id, + &recipient_account_id, + &channel_id, + &request, + [14; 12], + ) + .unwrap(); + assert_eq!( + open_context_bound_chat_request_v2( + &recipient_private, + "egui-chat.paseo", + &recipient_account_id, + &channel_id, + &wrapper, + ) + .unwrap(), + request + ); + assert!( + open_context_bound_chat_request_v2( + &recipient_private, + "egui-chat.westend", + &recipient_account_id, + &channel_id, + &wrapper, + ) + .is_err() + ); + assert!( + open_context_bound_chat_request_v2( + &recipient_private, + "egui-chat.paseo", + &recipient_account_id, + &[16; 32], + &wrapper, + ) + .is_err() + ); + assert!(open_chat_request_v2(&recipient_private, &wrapper).is_err()); + assert!(decode_context_bound_chat_request_v2(&[99; 32], &channel_id, &wrapper).is_err()); + assert!( + decode_context_bound_chat_request_v2( + &recipient_account_id, + &channel_id, + &wrapper[..163] + ) + .is_err() + ); + let mut unsupported_version = wrapper.clone(); + unsupported_version[5] = 4; + assert!(is_context_bound_chat_request_v2(&unsupported_version)); + assert!( + decode_context_bound_chat_request_v2( + &recipient_account_id, + &channel_id, + &unsupported_version, + ) + .is_err() + ); + } + + #[test] + fn bare_message_exchange_has_no_statement_data_index() { + let request = + encode_message_exchange_request_plaintext("inner", &[vec![0xaa, 0xbb]]).unwrap(); + assert_eq!( + request, + [vec![0x14], b"inner".to_vec(), vec![0x04, 0x08, 0xaa, 0xbb],].concat() + ); + assert_eq!( + decode_message_exchange_request_plaintext(&request).unwrap(), + V2MessageExchangeRequest { + request_id: "inner".into(), + messages: vec![vec![0xaa, 0xbb]], + } + ); + let response = encode_message_exchange_response_plaintext("inner", 0).unwrap(); + assert_eq!(response, [vec![0x14], b"inner".to_vec(), vec![0]].concat()); + assert_eq!( + decode_message_exchange_response_plaintext(&response).unwrap(), + V2MessageExchangeResponse { request_id: "inner".into(), response_code: 0 } + ); + } + + #[test] + fn oversized_collection_counts_are_rejected_before_allocation() { + assert!(decode_transport_plaintext(&[2, 0, 3, 0xff, 0xff, 0xff, 0xff]).is_err()); + assert!( + decode_message_exchange_request_plaintext(&[0, 3, 0xff, 0xff, 0xff, 0xff]).is_err() + ); + } } diff --git a/rust/crates/truapi-client/src/generated.rs b/rust/crates/truapi-client/src/generated.rs index 3942085969..f964056022 100644 --- a/rust/crates/truapi-client/src/generated.rs +++ b/rust/crates/truapi-client/src/generated.rs @@ -5,7 +5,7 @@ use super::*; /// Fingerprint of the generated wire contract. -pub const TRUAPI_WIRE_SCHEMA_HASH: &str = "c62f51d3168b6df1"; +pub const TRUAPI_WIRE_SCHEMA_HASH: &str = "cd75e8a5d770eb65"; /// `account_connection_status_subscribe` method marker. pub struct AccountConnectionStatusSubscribe; @@ -1015,6 +1015,54 @@ impl RequestMethod for ContactsPick { const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; } +/// `contacts_pick_many` method marker. +pub struct ContactsPickMany; +impl ContactsPickMany { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Contacts", + method: "pick_many", + wire_name: "contacts_pick_many", + request_type: "truapi::versioned::contacts::HostContactsPickManyRequest", + response_type: "truapi::versioned::contacts::HostContactsPickManyResponse", + error_type: Some("truapi::versioned::contacts::HostContactsPickManyError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 20, method_id: 1 }), + }; +} +impl RequestMethod for ContactsPickMany { + type Request = truapi::versioned::contacts::HostContactsPickManyRequest; + type Response = truapi::versioned::contacts::HostContactsPickManyResponse; + type Error = truapi::versioned::contacts::HostContactsPickManyError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + +/// `contacts_place_labels` method marker. +pub struct ContactsPlaceLabels; +impl ContactsPlaceLabels { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Contacts", + method: "place_labels", + wire_name: "contacts_place_labels", + request_type: "truapi::versioned::contacts::HostContactsPlaceLabelsRequest", + response_type: "truapi::versioned::contacts::HostContactsPlaceLabelsResponse", + error_type: Some("truapi::versioned::contacts::HostContactsPlaceLabelsError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 20, method_id: 2 }), + }; +} +impl RequestMethod for ContactsPlaceLabels { + type Request = truapi::versioned::contacts::HostContactsPlaceLabelsRequest; + type Response = truapi::versioned::contacts::HostContactsPlaceLabelsResponse; + type Error = truapi::versioned::contacts::HostContactsPlaceLabelsError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + /// `entropy_derive` method marker. pub struct EntropyDerive; impl EntropyDerive { @@ -1591,6 +1639,174 @@ impl RequestMethod for PreimageSubmit { const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; } +/// `profile_present` method marker. +pub struct ProfilePresent; +impl ProfilePresent { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Profile", + method: "present", + wire_name: "profile_present", + request_type: "truapi::versioned::profile::HostProfilePresentRequest", + response_type: "truapi::versioned::profile::HostProfilePresentResponse", + error_type: Some("truapi::versioned::profile::HostProfilePresentError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 69, method_id: 0 }), + }; +} +impl RequestMethod for ProfilePresent { + type Request = truapi::versioned::profile::HostProfilePresentRequest; + type Response = truapi::versioned::profile::HostProfilePresentResponse; + type Error = truapi::versioned::profile::HostProfilePresentError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + +/// `profile_disclose` method marker. +pub struct ProfileDisclose; +impl ProfileDisclose { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Profile", + method: "disclose", + wire_name: "profile_disclose", + request_type: "truapi::versioned::profile::HostProfileDiscloseRequest", + response_type: "truapi::versioned::profile::HostProfileDiscloseResponse", + error_type: Some("truapi::versioned::profile::HostProfileDiscloseError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 69, method_id: 1 }), + }; +} +impl RequestMethod for ProfileDisclose { + type Request = truapi::versioned::profile::HostProfileDiscloseRequest; + type Response = truapi::versioned::profile::HostProfileDiscloseResponse; + type Error = truapi::versioned::profile::HostProfileDiscloseError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + +/// `profile_retract` method marker. +pub struct ProfileRetract; +impl ProfileRetract { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Profile", + method: "retract", + wire_name: "profile_retract", + request_type: "truapi::versioned::profile::HostProfileRetractRequest", + response_type: "truapi::versioned::profile::HostProfileRetractResponse", + error_type: Some("truapi::versioned::profile::HostProfileRetractError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 69, method_id: 2 }), + }; +} +impl RequestMethod for ProfileRetract { + type Request = truapi::versioned::profile::HostProfileRetractRequest; + type Response = truapi::versioned::profile::HostProfileRetractResponse; + type Error = truapi::versioned::profile::HostProfileRetractError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + +/// `profile_present_contact` method marker. +pub struct ProfilePresentContact; +impl ProfilePresentContact { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Profile", + method: "present_contact", + wire_name: "profile_present_contact", + request_type: "truapi::versioned::profile::HostProfilePresentContactRequest", + response_type: "truapi::versioned::profile::HostProfilePresentContactResponse", + error_type: Some("truapi::versioned::profile::HostProfilePresentContactError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 69, method_id: 3 }), + }; +} +impl RequestMethod for ProfilePresentContact { + type Request = truapi::versioned::profile::HostProfilePresentContactRequest; + type Response = truapi::versioned::profile::HostProfilePresentContactResponse; + type Error = truapi::versioned::profile::HostProfilePresentContactError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + +/// `profile_place_contact_avatars` method marker. +pub struct ProfilePlaceContactAvatars; +impl ProfilePlaceContactAvatars { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Profile", + method: "place_contact_avatars", + wire_name: "profile_place_contact_avatars", + request_type: "truapi::versioned::profile::HostProfilePlaceContactAvatarsRequest", + response_type: "truapi::versioned::profile::HostProfilePlaceContactAvatarsResponse", + error_type: Some("truapi::versioned::profile::HostProfilePlaceContactAvatarsError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 69, method_id: 4 }), + }; +} +impl RequestMethod for ProfilePlaceContactAvatars { + type Request = truapi::versioned::profile::HostProfilePlaceContactAvatarsRequest; + type Response = truapi::versioned::profile::HostProfilePlaceContactAvatarsResponse; + type Error = truapi::versioned::profile::HostProfilePlaceContactAvatarsError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + +/// `profile_own_status` method marker. +pub struct ProfileOwnStatus; +impl ProfileOwnStatus { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Profile", + method: "own_status", + wire_name: "profile_own_status", + request_type: "truapi::versioned::profile::HostProfileOwnStatusRequest", + response_type: "truapi::versioned::profile::HostProfileOwnStatusResponse", + error_type: Some("truapi::versioned::profile::HostProfileOwnStatusError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 69, method_id: 5 }), + }; +} +impl RequestMethod for ProfileOwnStatus { + type Request = truapi::versioned::profile::HostProfileOwnStatusRequest; + type Response = truapi::versioned::profile::HostProfileOwnStatusResponse; + type Error = truapi::versioned::profile::HostProfileOwnStatusError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + +/// `profile_present_own` method marker. +pub struct ProfilePresentOwn; +impl ProfilePresentOwn { + /// Canonical metadata and frame ids for this method. + pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor { + service: "Profile", + method: "present_own", + wire_name: "profile_present_own", + request_type: "truapi::versioned::profile::HostProfilePresentOwnRequest", + response_type: "truapi::versioned::profile::HostProfilePresentOwnResponse", + error_type: Some("truapi::versioned::profile::HostProfilePresentOwnError"), + kind: MethodKind::Request, + direction: Direction::ProductToHost, + required_execution: None, + wire: MethodWire::Request(MethodIds { trait_id: 69, method_id: 6 }), + }; +} +impl RequestMethod for ProfilePresentOwn { + type Request = truapi::versioned::profile::HostProfilePresentOwnRequest; + type Response = truapi::versioned::profile::HostProfilePresentOwnResponse; + type Error = truapi::versioned::profile::HostProfilePresentOwnError; + const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR; +} + /// `renderer_render` method marker. pub struct RendererRender; impl RendererRender { @@ -2213,6 +2429,8 @@ pub const APP_METHODS: &[MethodDescriptor] = &[ CoinPaymentRefund::DESCRIPTOR, CoinPaymentListenForPayment::DESCRIPTOR, ContactsPick::DESCRIPTOR, + ContactsPickMany::DESCRIPTOR, + ContactsPlaceLabels::DESCRIPTOR, EntropyDerive::DESCRIPTOR, GameRemindNextGame::DESCRIPTOR, GameCancelNextGame::DESCRIPTOR, @@ -2234,6 +2452,13 @@ pub const APP_METHODS: &[MethodDescriptor] = &[ PermissionsAuthorizeDevicePermission::DESCRIPTOR, PreimageLookupSubscribe::DESCRIPTOR, PreimageSubmit::DESCRIPTOR, + ProfilePresent::DESCRIPTOR, + ProfileDisclose::DESCRIPTOR, + ProfileRetract::DESCRIPTOR, + ProfilePresentContact::DESCRIPTOR, + ProfilePlaceContactAvatars::DESCRIPTOR, + ProfileOwnStatus::DESCRIPTOR, + ProfilePresentOwn::DESCRIPTOR, ResourceAllocationRequest::DESCRIPTOR, ScannerScan::DESCRIPTOR, SigningCreateTransaction::DESCRIPTOR, @@ -2294,6 +2519,8 @@ pub const WIDGET_METHODS: &[MethodDescriptor] = &[ CoinPaymentRefund::DESCRIPTOR, CoinPaymentListenForPayment::DESCRIPTOR, ContactsPick::DESCRIPTOR, + ContactsPickMany::DESCRIPTOR, + ContactsPlaceLabels::DESCRIPTOR, EntropyDerive::DESCRIPTOR, ExpandedCardSetFaceShown::DESCRIPTOR, GameRemindNextGame::DESCRIPTOR, @@ -2316,6 +2543,13 @@ pub const WIDGET_METHODS: &[MethodDescriptor] = &[ PermissionsAuthorizeDevicePermission::DESCRIPTOR, PreimageLookupSubscribe::DESCRIPTOR, PreimageSubmit::DESCRIPTOR, + ProfilePresent::DESCRIPTOR, + ProfileDisclose::DESCRIPTOR, + ProfileRetract::DESCRIPTOR, + ProfilePresentContact::DESCRIPTOR, + ProfilePlaceContactAvatars::DESCRIPTOR, + ProfileOwnStatus::DESCRIPTOR, + ProfilePresentOwn::DESCRIPTOR, ResourceAllocationRequest::DESCRIPTOR, ScannerScan::DESCRIPTOR, SigningCreateTransaction::DESCRIPTOR, @@ -2382,6 +2616,8 @@ pub const WORKER_METHODS: &[MethodDescriptor] = &[ CoinPaymentRefund::DESCRIPTOR, CoinPaymentListenForPayment::DESCRIPTOR, ContactsPick::DESCRIPTOR, + ContactsPickMany::DESCRIPTOR, + ContactsPlaceLabels::DESCRIPTOR, EntropyDerive::DESCRIPTOR, GameRemindNextGame::DESCRIPTOR, GameCancelNextGame::DESCRIPTOR, @@ -2405,6 +2641,13 @@ pub const WORKER_METHODS: &[MethodDescriptor] = &[ PocketRemoveCard::DESCRIPTOR, PreimageLookupSubscribe::DESCRIPTOR, PreimageSubmit::DESCRIPTOR, + ProfilePresent::DESCRIPTOR, + ProfileDisclose::DESCRIPTOR, + ProfileRetract::DESCRIPTOR, + ProfilePresentContact::DESCRIPTOR, + ProfilePlaceContactAvatars::DESCRIPTOR, + ProfileOwnStatus::DESCRIPTOR, + ProfilePresentOwn::DESCRIPTOR, RendererRender::DESCRIPTOR, RendererActionSubscribe::DESCRIPTOR, ResourceAllocationRequest::DESCRIPTOR, diff --git a/rust/crates/truapi-client/src/lib.rs b/rust/crates/truapi-client/src/lib.rs index 4737cf004c..2b5909076f 100644 --- a/rust/crates/truapi-client/src/lib.rs +++ b/rust/crates/truapi-client/src/lib.rs @@ -7,8 +7,7 @@ extern crate alloc; -use alloc::string::String; -use alloc::vec::Vec; +use alloc::{string::String, vec::Vec}; use parity_scale_codec::{Decode, Encode}; use truapi::CallError; @@ -18,680 +17,602 @@ pub use generated::*; /// Product executable kinds used by TrUAPI authorization. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExecutionKind { - /// Full application surface. - App, - /// Embedded widget surface. - Widget, - /// Background product worker. - Worker, + /// Full application surface. + App, + /// Embedded widget surface. + Widget, + /// Background product worker. + Worker, } /// Direction in which a method's initial frame travels. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Direction { - /// Product starts the call and the host serves it. - ProductToHost, - /// Host starts the call and the product serves it. - HostToProduct, + /// Product starts the call and the host serves it. + ProductToHost, + /// Host starts the call and the product serves it. + HostToProduct, } /// Wire interaction shape. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MethodKind { - /// One request followed by one response. - Request, - /// Items followed by a normal or failed interruption. - Subscription, + /// One request followed by one response. + Request, + /// Items followed by a normal or failed interruption. + Subscription, } /// The address shared by every leg of one method. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MethodIds { - /// Trait discriminant. - pub trait_id: u8, - /// Method discriminant within the trait. - pub method_id: u8, + /// Trait discriminant. + pub trait_id: u8, + /// Method discriminant within the trait. + pub method_id: u8, } /// Which leg of an exchange a frame carries. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum MessageType { - /// Request, or subscription start. - Request = 0, - /// Response, or subscription item. - Response = 1, - /// Subscription completion carrying `Result<(), CallError>`. - Interrupt = 2, - /// Subscription cancellation with no payload. - Stop = 3, + /// Request, or subscription start. + Request = 0, + /// Response, or subscription item. + Response = 1, + /// Subscription completion carrying `Result<(), CallError>`. + Interrupt = 2, + /// Subscription cancellation with no payload. + Stop = 3, } /// Wire ids and interaction shape for one method. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MethodWire { - /// Request/response method. - Request(MethodIds), - /// Subscription method. - Subscription(MethodIds), + /// Request/response method. + Request(MethodIds), + /// Subscription method. + Subscription(MethodIds), } /// Generated metadata for one canonical method. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MethodDescriptor { - /// Canonical service trait name. - pub service: &'static str, - /// Rust method name. - pub method: &'static str, - /// Globally unique wire method name. - pub wire_name: &'static str, - /// Rust type of the request envelope. - pub request_type: &'static str, - /// Rust type of the success or stream-item envelope. - pub response_type: &'static str, - /// Rust type of the domain error. - pub error_type: Option<&'static str>, - /// Interaction shape. - pub kind: MethodKind, - /// Initial-frame direction. - pub direction: Direction, - /// Required executable kind, or `None` for every kind. - pub required_execution: Option, - /// Canonical address and shape. - pub wire: MethodWire, + /// Canonical service trait name. + pub service: &'static str, + /// Rust method name. + pub method: &'static str, + /// Globally unique wire method name. + pub wire_name: &'static str, + /// Rust type of the request envelope. + pub request_type: &'static str, + /// Rust type of the success or stream-item envelope. + pub response_type: &'static str, + /// Rust type of the domain error. + pub error_type: Option<&'static str>, + /// Interaction shape. + pub kind: MethodKind, + /// Initial-frame direction. + pub direction: Direction, + /// Required executable kind, or `None` for every kind. + pub required_execution: Option, + /// Canonical address and shape. + pub wire: MethodWire, } /// Generated marker for a product-initiated request method. pub trait RequestMethod { - /// Request envelope. - type Request: Encode; - /// Success envelope. - type Response: Decode; - /// Domain-error envelope. - type Error: Decode; - /// Canonical method metadata. - const DESCRIPTOR: MethodDescriptor; + /// Request envelope. + type Request: Encode; + /// Success envelope. + type Response: Decode; + /// Domain-error envelope. + type Error: Decode; + /// Canonical method metadata. + const DESCRIPTOR: MethodDescriptor; } /// Generated marker for a product-initiated subscription. pub trait SubscriptionMethod { - /// Start request, or unit for an empty payload. - type Request: Encode; - /// Stream item. - type Item: Decode; - /// Domain error carried by the interrupt leg. - type Error: Decode; - /// Canonical method metadata. - const DESCRIPTOR: MethodDescriptor; + /// Start request, or unit for an empty payload. + type Request: Encode; + /// Stream item. + type Item: Decode; + /// Domain error carried by the interrupt leg. + type Error: Decode; + /// Canonical method metadata. + const DESCRIPTOR: MethodDescriptor; } /// Generated marker for a host-initiated subscription served by a product. pub trait HostSubscriptionMethod { - /// Host request. - type Request: Decode; - /// Product stream item. - type Item: Encode; - /// Domain error carried by the interrupt leg. - type Error: Encode; - /// Canonical method metadata. - const DESCRIPTOR: MethodDescriptor; + /// Host request. + type Request: Decode; + /// Product stream item. + type Item: Encode; + /// Domain error carried by the interrupt leg. + type Error: Encode; + /// Canonical method metadata. + const DESCRIPTOR: MethodDescriptor; } /// Decoded value paired with its transport request id. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Decoded { - /// Request id from the envelope. - pub request_id: String, - /// Typed payload. - pub value: T, + /// Request id from the envelope. + pub request_id: String, + /// Typed payload. + pub value: T, } /// Typed outcome carried by a request response. pub type RequestOutcome = - Result<::Response, CallError<::Error>>; + Result<::Response, CallError<::Error>>; /// Result of decoding a request response. pub type DecodedResponse = Result>, DecodeError>; /// Typed completion carried by a subscription interruption. pub type SubscriptionOutcome = Result<(), CallError<::Error>>; /// Reserved method-independent protocol error address. -pub const PROTOCOL_ERROR_IDS: MethodIds = MethodIds { - trait_id: 255, - method_id: 255, -}; +pub const PROTOCOL_ERROR_IDS: MethodIds = MethodIds { trait_id: 255, method_id: 255 }; /// A recognized protocol failure from a peer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProtocolError { - /// The peer cannot route this method address. - UnsupportedMessage(MethodIds), + /// The peer cannot route this method address. + UnsupportedMessage(MethodIds), } /// Structural or protocol failure while decoding a frame. #[derive(Debug, Clone, PartialEq, Eq)] pub enum DecodeError { - /// Invalid SCALE or a truncated envelope. - Malformed, - /// Bytes remain after the expected payload. - TrailingBytes, - /// The frame belongs to another method. - UnexpectedMethod { - /// Expected method address. - expected: MethodIds, - /// Actual method address. - actual: MethodIds, - }, - /// The frame belongs to another leg of the exchange. - UnexpectedMessageType { - /// Expected leg. - expected: MessageType, - /// Actual message-type byte. - actual: u8, - }, - /// A descriptor has a shape incompatible with the operation. - WrongMethodKind, - /// A correlated protocol failure. An unknown future version or variant is - /// retained as `None` rather than mistaken for malformed known data. - Protocol { - /// Request id of the call that failed. - request_id: String, - /// Recognized failure, if supported by this build. - error: Option, - }, + /// Invalid SCALE or a truncated envelope. + Malformed, + /// Bytes remain after the expected payload. + TrailingBytes, + /// The frame belongs to another method. + UnexpectedMethod { + /// Expected method address. + expected: MethodIds, + /// Actual method address. + actual: MethodIds, + }, + /// The frame belongs to another leg of the exchange. + UnexpectedMessageType { + /// Expected leg. + expected: MessageType, + /// Actual message-type byte. + actual: u8, + }, + /// A descriptor has a shape incompatible with the operation. + WrongMethodKind, + /// A correlated protocol failure. An unknown future version or variant is + /// retained as `None` rather than mistaken for malformed known data. + Protocol { + /// Request id of the call that failed. + request_id: String, + /// Recognized failure, if supported by this build. + error: Option, + }, } /// Encodes a request without an intermediate payload allocation. pub fn encode_request(request_id: &str, request: &M::Request) -> Vec { - encode_value_frame( - request_id, - generated_request_ids(M::DESCRIPTOR), - MessageType::Request, - request, - ) + encode_value_frame( + request_id, + generated_request_ids(M::DESCRIPTOR), + MessageType::Request, + request, + ) } /// Decodes a response's `Result>` payload. pub fn decode_response(frame: &[u8]) -> DecodedResponse { - decode_value_frame( - frame, - generated_request_ids(M::DESCRIPTOR), - MessageType::Response, - ) + decode_value_frame(frame, generated_request_ids(M::DESCRIPTOR), MessageType::Response) } /// Encodes a subscription start. pub fn encode_subscription_start( - request_id: &str, - request: &M::Request, + request_id: &str, + request: &M::Request, ) -> Vec { - encode_value_frame( - request_id, - generated_subscription_ids(M::DESCRIPTOR), - MessageType::Request, - request, - ) + encode_value_frame( + request_id, + generated_subscription_ids(M::DESCRIPTOR), + MessageType::Request, + request, + ) } /// Encodes subscription cancellation; rejects request descriptors. pub fn encode_subscription_stop( - request_id: &str, - descriptor: MethodDescriptor, + request_id: &str, + descriptor: MethodDescriptor, ) -> Result, DecodeError> { - Ok(encode_value_frame( - request_id, - subscription_ids(descriptor)?, - MessageType::Stop, - &(), - )) + Ok(encode_value_frame(request_id, subscription_ids(descriptor)?, MessageType::Stop, &())) } /// Decodes a subscription item. pub fn decode_subscription_item( - frame: &[u8], + frame: &[u8], ) -> Result, DecodeError> { - decode_value_frame( - frame, - generated_subscription_ids(M::DESCRIPTOR), - MessageType::Response, - ) + decode_value_frame(frame, generated_subscription_ids(M::DESCRIPTOR), MessageType::Response) } /// Decodes normal completion (`Ok(())`) or a typed subscription failure. pub fn decode_subscription_interrupt( - frame: &[u8], + frame: &[u8], ) -> Result>, DecodeError> { - decode_value_frame( - frame, - generated_subscription_ids(M::DESCRIPTOR), - MessageType::Interrupt, - ) + decode_value_frame(frame, generated_subscription_ids(M::DESCRIPTOR), MessageType::Interrupt) } /// Whether a frame interrupts this subscription; rejects request descriptors. pub fn is_subscription_interrupt( - frame: &[u8], - descriptor: MethodDescriptor, + frame: &[u8], + descriptor: MethodDescriptor, ) -> Result { - let ids = subscription_ids(descriptor)?; - let frame = decode_frame(frame)?; - Ok(frame.ids == ids && frame.message_type == MessageType::Interrupt as u8) + let ids = subscription_ids(descriptor)?; + let frame = decode_frame(frame)?; + Ok(frame.ids == ids && frame.message_type == MessageType::Interrupt as u8) } /// Decodes a host-initiated start for a product worker. pub fn decode_host_subscription_start( - frame: &[u8], + frame: &[u8], ) -> Result, DecodeError> { - decode_value_frame( - frame, - generated_subscription_ids(M::DESCRIPTOR), - MessageType::Request, - ) + decode_value_frame(frame, generated_subscription_ids(M::DESCRIPTOR), MessageType::Request) } /// Encodes a product-served subscription item. pub fn encode_host_subscription_item( - request_id: &str, - item: &M::Item, + request_id: &str, + item: &M::Item, ) -> Vec { - encode_value_frame( - request_id, - generated_subscription_ids(M::DESCRIPTOR), - MessageType::Response, - item, - ) + encode_value_frame( + request_id, + generated_subscription_ids(M::DESCRIPTOR), + MessageType::Response, + item, + ) } /// Encodes normal or failed termination of a product-served subscription. pub fn encode_host_subscription_interrupt( - request_id: &str, - outcome: &Result<(), CallError>, + request_id: &str, + outcome: &Result<(), CallError>, ) -> Vec { - encode_value_frame( - request_id, - generated_subscription_ids(M::DESCRIPTOR), - MessageType::Interrupt, - outcome, - ) + encode_value_frame( + request_id, + generated_subscription_ids(M::DESCRIPTOR), + MessageType::Interrupt, + outcome, + ) } /// Whether a host frame cancels this product-served subscription. pub fn is_host_subscription_stop( - frame: &[u8], + frame: &[u8], ) -> Result { - let frame = decode_frame(frame)?; - let matches = frame.ids == generated_subscription_ids(M::DESCRIPTOR) - && frame.message_type == MessageType::Stop as u8; - if matches { - decode_exact::<()>(frame.payload)?; - } - Ok(matches) + let frame = decode_frame(frame)?; + let matches = frame.ids == generated_subscription_ids(M::DESCRIPTOR) && + frame.message_type == MessageType::Stop as u8; + if matches { + decode_exact::<()>(frame.payload)?; + } + Ok(matches) } fn generated_request_ids(descriptor: MethodDescriptor) -> MethodIds { - match descriptor.wire { - MethodWire::Request(ids) => ids, - MethodWire::Subscription(_) => { - panic!("generated request descriptor must use request wire ids") - } - } + match descriptor.wire { + MethodWire::Request(ids) => ids, + MethodWire::Subscription(_) => { + panic!("generated request descriptor must use request wire ids") + }, + } } fn subscription_ids(descriptor: MethodDescriptor) -> Result { - match descriptor.wire { - MethodWire::Subscription(ids) => Ok(ids), - MethodWire::Request(_) => Err(DecodeError::WrongMethodKind), - } + match descriptor.wire { + MethodWire::Subscription(ids) => Ok(ids), + MethodWire::Request(_) => Err(DecodeError::WrongMethodKind), + } } fn generated_subscription_ids(descriptor: MethodDescriptor) -> MethodIds { - subscription_ids(descriptor) - .expect("generated subscription descriptor must use subscription wire ids") + subscription_ids(descriptor) + .expect("generated subscription descriptor must use subscription wire ids") } fn encode_value_frame( - request_id: &str, - ids: MethodIds, - message_type: MessageType, - value: &T, + request_id: &str, + ids: MethodIds, + message_type: MessageType, + value: &T, ) -> Vec { - let mut frame = Vec::new(); - request_id.encode_to(&mut frame); - frame.extend_from_slice(&[ids.trait_id, ids.method_id, message_type as u8]); - value.encode_to(&mut frame); - frame + let mut frame = Vec::new(); + request_id.encode_to(&mut frame); + frame.extend_from_slice(&[ids.trait_id, ids.method_id, message_type as u8]); + value.encode_to(&mut frame); + frame } struct BorrowedFrame<'a> { - request_id: String, - ids: MethodIds, - message_type: u8, - payload: &'a [u8], + request_id: String, + ids: MethodIds, + message_type: u8, + payload: &'a [u8], } fn decode_frame(mut frame: &[u8]) -> Result, DecodeError> { - let request_id = String::decode(&mut frame).map_err(|_| DecodeError::Malformed)?; - let [trait_id, method_id, message_type, payload @ ..] = frame else { - return Err(DecodeError::Malformed); - }; - let ids = MethodIds { - trait_id: *trait_id, - method_id: *method_id, - }; - if ids == PROTOCOL_ERROR_IDS { - if *message_type != MessageType::Response as u8 { - return Err(DecodeError::UnexpectedMessageType { - expected: MessageType::Response, - actual: *message_type, - }); - } - let error = match (payload.first(), payload.get(1)) { - (None, _) => return Err(DecodeError::Malformed), - (Some(version), _) if *version != 0 => None, - (Some(_), Some(variant)) if *variant != 0 => None, - _ => { - let (version, variant, trait_id, method_id): (u8, u8, u8, u8) = - decode_exact(payload)?; - debug_assert_eq!((version, variant), (0, 0)); - Some(ProtocolError::UnsupportedMessage(MethodIds { - trait_id, - method_id, - })) - } - }; - return Err(DecodeError::Protocol { request_id, error }); - } - Ok(BorrowedFrame { - request_id, - ids, - message_type: *message_type, - payload, - }) + let request_id = String::decode(&mut frame).map_err(|_| DecodeError::Malformed)?; + let [trait_id, method_id, message_type, payload @ ..] = frame else { + return Err(DecodeError::Malformed); + }; + let ids = MethodIds { trait_id: *trait_id, method_id: *method_id }; + if ids == PROTOCOL_ERROR_IDS { + if *message_type != MessageType::Response as u8 { + return Err(DecodeError::UnexpectedMessageType { + expected: MessageType::Response, + actual: *message_type, + }); + } + let error = match (payload.first(), payload.get(1)) { + (None, _) => return Err(DecodeError::Malformed), + (Some(version), _) if *version != 0 => None, + (Some(_), Some(variant)) if *variant != 0 => None, + _ => { + let (version, variant, trait_id, method_id): (u8, u8, u8, u8) = + decode_exact(payload)?; + debug_assert_eq!((version, variant), (0, 0)); + Some(ProtocolError::UnsupportedMessage(MethodIds { trait_id, method_id })) + }, + }; + return Err(DecodeError::Protocol { request_id, error }); + } + Ok(BorrowedFrame { request_id, ids, message_type: *message_type, payload }) } fn decode_value_frame( - frame: &[u8], - ids: MethodIds, - message_type: MessageType, + frame: &[u8], + ids: MethodIds, + message_type: MessageType, ) -> Result, DecodeError> { - let frame = decode_frame(frame)?; - if frame.ids != ids { - return Err(DecodeError::UnexpectedMethod { - expected: ids, - actual: frame.ids, - }); - } - if frame.message_type != message_type as u8 { - return Err(DecodeError::UnexpectedMessageType { - expected: message_type, - actual: frame.message_type, - }); - } - Ok(Decoded { - request_id: frame.request_id, - value: decode_exact(frame.payload)?, - }) + let frame = decode_frame(frame)?; + if frame.ids != ids { + return Err(DecodeError::UnexpectedMethod { expected: ids, actual: frame.ids }); + } + if frame.message_type != message_type as u8 { + return Err(DecodeError::UnexpectedMessageType { + expected: message_type, + actual: frame.message_type, + }); + } + Ok(Decoded { request_id: frame.request_id, value: decode_exact(frame.payload)? }) } fn decode_exact(mut payload: &[u8]) -> Result { - let value = T::decode(&mut payload).map_err(|_| DecodeError::Malformed)?; - if payload.is_empty() { - Ok(value) - } else { - Err(DecodeError::TrailingBytes) - } + let value = T::decode(&mut payload).map_err(|_| DecodeError::Malformed)?; + if payload.is_empty() { Ok(value) } else { Err(DecodeError::TrailingBytes) } } #[cfg(test)] mod tests { - use super::*; - use alloc::vec; - use truapi::v01; - use truapi::versioned::system::{HostHandshakeRequest, HostHandshakeResponse}; - - #[test] - fn request_and_response_use_canonical_envelopes() { - let request = HostHandshakeRequest::V1(v01::HostHandshakeRequest { codec_version: 2 }); - assert_eq!( - encode_request::("p:1", &request), - [12, b'p', b':', b'1', 1, 0, 0, 0, 2] - ); - let decoded = decode_response::(&[12, b'p', b':', b'1', 1, 0, 1, 0, 0]) - .expect("response frame"); - assert_eq!(decoded.request_id, "p:1"); - assert_eq!(decoded.value, Ok(HostHandshakeResponse::V1)); - } - - #[test] - fn response_domain_error_preserves_versioned_payload() { - let error = CallError::Domain(truapi::versioned::system::HostHandshakeError::V1( - v01::HostHandshakeError::UnsupportedProtocolVersion, - )); - let mut frame = vec![12, b'p', b':', b'1', 1, 0, 1, 1]; - error.encode_to(&mut frame); - assert_eq!( - decode_response::(&frame) - .expect("error frame") - .value, - Err(error) - ); - } - - #[test] - fn native_chat_uses_method_twelve_with_v2_envelopes() { - use truapi::{latest as dto, versioned::account}; - - let request = account::HostProductDeviceChatRequest::V2( - dto::HostProductDeviceChatRequest::Initialize, - ); - assert_eq!( - encode_request::("p:1", &request), - [12, b'p', b':', b'1', 2, 12, 0, 1, 0], - ); - let denomination_request = account::HostProductDeviceChatRequest::V2( - dto::HostProductDeviceChatRequest::PaymentDenomination, - ); - assert_eq!( - encode_request::("p:1", &denomination_request), - [12, b'p', b':', b'1', 2, 12, 0, 1, 12], - ); - - let response = - account::HostProductDeviceChatResponse::V2(dto::HostProductDeviceChatResponse { - device: dto::HostNativeChatDevice { - identity_account_id: [1; 32], - identity_chat_public_key: [2; 32], - product_account: v01::ProductAccountId { - dot_ns_identifier: "chat.dot".into(), - derivation_index: v01::DerivationIndex::Index(0), - }, - account_id: [3; 32], - chat_public_key: [4; 32], - }, - peers: vec![], - binding: None, - opened: vec![], - prepared: vec![], - payments: vec![], - rich_messages: vec![], - migration: None, - migration_id: None, - open_page: None, - migration_invitations: vec![], - state_page: None, - coinage_cents_unit: None, - }); - let mut frame = vec![12, b'p', b':', b'1', 2, 12, 1, 0]; - response.encode_to(&mut frame); - assert_eq!(frame[8], 1, "response envelope is V2"); - assert_eq!( - decode_response::(&frame), - Ok(Decoded { - request_id: "p:1".into(), - value: Ok(response), - }), - ); - - frame[5] = 11; - assert_eq!( - decode_response::(&frame), - Err(DecodeError::UnexpectedMethod { - expected: MethodIds { - trait_id: 2, - method_id: 12, - }, - actual: MethodIds { - trait_id: 2, - method_id: 11, - }, - }), - ); - } - - #[test] - fn worker_serves_unified_renderer() { - use truapi::versioned::renderer::{ - ProductRendererRenderItem, ProductRendererRenderRequest, - }; - let request = ProductRendererRenderRequest::V1(v01::ProductRendererRenderRequest { - context: v01::RenderContext::PocketCard { - card_id: "loyalty".into(), - }, - payload: vec![1, 2, 3], - }); - let ids = generated_subscription_ids(RendererRender::DESCRIPTOR); - let start = encode_value_frame("host:4", ids, MessageType::Request, &request); - let decoded = - decode_host_subscription_start::(&start).expect("start frame"); - assert_eq!(decoded.request_id, "host:4"); - assert_eq!(decoded.value, request); - let item = ProductRendererRenderItem::V1(v01::RendererNode::Nil); - let rendered = encode_host_subscription_item::("host:4", &item); - assert_eq!( - decode_value_frame::(&rendered, ids, MessageType::Response) - .expect("item frame") - .value, - item - ); - let stop = encode_value_frame("host:4", ids, MessageType::Stop, &()); - assert_eq!(is_host_subscription_stop::(&stop), Ok(true)); - let interrupt = encode_host_subscription_interrupt::("host:4", &Ok(())); - assert_eq!( - decode_value_frame::>>( - &interrupt, - ids, - MessageType::Interrupt - ) - .expect("interrupt") - .value, - Ok(()) - ); - } - - #[test] - fn subscription_completion_and_failure_are_typed_and_strict() { - type Method = AccountConnectionStatusSubscribe; - let ids = generated_subscription_ids(Method::DESCRIPTOR); - let complete = encode_value_frame( - "p:1", - ids, - MessageType::Interrupt, - &Ok::<(), CallError>(()), - ); - assert_eq!( - decode_subscription_interrupt::(&complete) - .expect("completion") - .value, - Ok(()) - ); - let failed = encode_value_frame( - "p:1", - ids, - MessageType::Interrupt, - &Err::<(), _>(CallError::::Denied), - ); - assert_eq!( - decode_subscription_interrupt::(&failed) - .expect("failure") - .value, - Err(CallError::Denied) - ); - let mut trailing = complete; - trailing.push(0); - assert_eq!( - decode_subscription_interrupt::(&trailing), - Err(DecodeError::TrailingBytes) - ); - let empty = encode_value_frame("p:1", ids, MessageType::Interrupt, &()); - assert_eq!( - decode_subscription_interrupt::(&empty), - Err(DecodeError::Malformed) - ); - } - - #[test] - fn frame_address_and_leg_both_must_match() { - let ids = generated_request_ids(SystemHandshake::DESCRIPTOR); - let other = MethodIds { - trait_id: ids.trait_id + 1, - method_id: ids.method_id, - }; - let wrong_method = encode_value_frame( - "p:1", - other, - MessageType::Response, - &Ok::<_, CallError<()>>(HostHandshakeResponse::V1), - ); - assert_eq!( - decode_response::(&wrong_method), - Err(DecodeError::UnexpectedMethod { - expected: ids, - actual: other - }) - ); - let wrong_leg = encode_value_frame("p:1", ids, MessageType::Request, &()); - assert_eq!( - decode_response::(&wrong_leg), - Err(DecodeError::UnexpectedMessageType { - expected: MessageType::Response, - actual: 0 - }) - ); - assert_eq!( - encode_subscription_stop("p:1", SystemHandshake::DESCRIPTOR), - Err(DecodeError::WrongMethodKind) - ); - } - - #[test] - fn protocol_failures_keep_correlation_and_accept_future_variants() { - let known = [12, b'p', b':', b'1', 255, 255, 1, 0, 0, 4, 7]; - assert_eq!( - decode_response::(&known), - Err(DecodeError::Protocol { - request_id: "p:1".into(), - error: Some(ProtocolError::UnsupportedMessage(MethodIds { - trait_id: 4, - method_id: 7 - })) - }) - ); - let future = [12, b'p', b':', b'1', 255, 255, 1, 0, 1, 42]; - assert_eq!( - decode_response::(&future), - Err(DecodeError::Protocol { - request_id: "p:1".into(), - error: None - }) - ); - assert_eq!( - decode_response::(&known[..known.len() - 1]), - Err(DecodeError::Malformed) - ); - let mut trailing = known.to_vec(); - trailing.push(0); - assert_eq!( - decode_response::(&trailing), - Err(DecodeError::TrailingBytes) - ); - } + use super::*; + use alloc::vec; + use truapi::{ + v01, + versioned::system::{HostHandshakeRequest, HostHandshakeResponse}, + }; + + #[test] + fn request_and_response_use_canonical_envelopes() { + let request = HostHandshakeRequest::V1(v01::HostHandshakeRequest { codec_version: 2 }); + assert_eq!( + encode_request::("p:1", &request), + [12, b'p', b':', b'1', 1, 0, 0, 0, 2] + ); + let decoded = decode_response::(&[12, b'p', b':', b'1', 1, 0, 1, 0, 0]) + .expect("response frame"); + assert_eq!(decoded.request_id, "p:1"); + assert_eq!(decoded.value, Ok(HostHandshakeResponse::V1)); + } + + #[test] + fn response_domain_error_preserves_versioned_payload() { + let error = CallError::Domain(truapi::versioned::system::HostHandshakeError::V1( + v01::HostHandshakeError::UnsupportedProtocolVersion, + )); + let mut frame = vec![12, b'p', b':', b'1', 1, 0, 1, 1]; + error.encode_to(&mut frame); + assert_eq!( + decode_response::(&frame).expect("error frame").value, + Err(error) + ); + } + + #[test] + fn native_chat_uses_method_twelve_with_v2_envelopes() { + use truapi::{latest as dto, versioned::account}; + + let request = account::HostProductDeviceChatRequest::V2( + dto::HostProductDeviceChatRequest::Initialize, + ); + assert_eq!( + encode_request::("p:1", &request), + [12, b'p', b':', b'1', 2, 12, 0, 1, 0], + ); + let denomination_request = account::HostProductDeviceChatRequest::V2( + dto::HostProductDeviceChatRequest::PaymentDenomination, + ); + assert_eq!( + encode_request::("p:1", &denomination_request), + [12, b'p', b':', b'1', 2, 12, 0, 1, 12], + ); + + let response = + account::HostProductDeviceChatResponse::V2(dto::HostProductDeviceChatResponse { + device: dto::HostNativeChatDevice { + identity_account_id: [1; 32], + identity_chat_public_key: [2; 32], + product_account: v01::ProductAccountId { + dot_ns_identifier: "chat.dot".into(), + derivation_index: v01::DerivationIndex::Index(0), + }, + account_id: [3; 32], + chat_public_key: [4; 32], + }, + peers: vec![], + binding: None, + opened: vec![], + prepared: vec![], + payments: vec![], + rich_messages: vec![], + migration: None, + migration_id: None, + open_page: None, + migration_invitations: vec![], + state_page: None, + coinage_cents_unit: None, + }); + let mut frame = vec![12, b'p', b':', b'1', 2, 12, 1, 0]; + response.encode_to(&mut frame); + assert_eq!(frame[8], 1, "response envelope is V2"); + assert_eq!( + decode_response::(&frame), + Ok(Decoded { request_id: "p:1".into(), value: Ok(response) }), + ); + + frame[5] = 11; + assert_eq!( + decode_response::(&frame), + Err(DecodeError::UnexpectedMethod { + expected: MethodIds { trait_id: 2, method_id: 12 }, + actual: MethodIds { trait_id: 2, method_id: 11 }, + }), + ); + } + + #[test] + fn worker_serves_unified_renderer() { + use truapi::versioned::renderer::{ + ProductRendererRenderItem, ProductRendererRenderRequest, + }; + let request = ProductRendererRenderRequest::V1(v01::ProductRendererRenderRequest { + context: v01::RenderContext::PocketCard { card_id: "loyalty".into() }, + payload: vec![1, 2, 3], + }); + let ids = generated_subscription_ids(RendererRender::DESCRIPTOR); + let start = encode_value_frame("host:4", ids, MessageType::Request, &request); + let decoded = + decode_host_subscription_start::(&start).expect("start frame"); + assert_eq!(decoded.request_id, "host:4"); + assert_eq!(decoded.value, request); + let item = ProductRendererRenderItem::V1(v01::RendererNode::Nil); + let rendered = encode_host_subscription_item::("host:4", &item); + assert_eq!( + decode_value_frame::(&rendered, ids, MessageType::Response) + .expect("item frame") + .value, + item + ); + let stop = encode_value_frame("host:4", ids, MessageType::Stop, &()); + assert_eq!(is_host_subscription_stop::(&stop), Ok(true)); + let interrupt = encode_host_subscription_interrupt::("host:4", &Ok(())); + assert_eq!( + decode_value_frame::>>( + &interrupt, + ids, + MessageType::Interrupt + ) + .expect("interrupt") + .value, + Ok(()) + ); + } + + #[test] + fn subscription_completion_and_failure_are_typed_and_strict() { + type Method = AccountConnectionStatusSubscribe; + let ids = generated_subscription_ids(Method::DESCRIPTOR); + let complete = encode_value_frame( + "p:1", + ids, + MessageType::Interrupt, + &Ok::<(), CallError>(()), + ); + assert_eq!( + decode_subscription_interrupt::(&complete).expect("completion").value, + Ok(()) + ); + let failed = encode_value_frame( + "p:1", + ids, + MessageType::Interrupt, + &Err::<(), _>(CallError::::Denied), + ); + assert_eq!( + decode_subscription_interrupt::(&failed).expect("failure").value, + Err(CallError::Denied) + ); + let mut trailing = complete; + trailing.push(0); + assert_eq!( + decode_subscription_interrupt::(&trailing), + Err(DecodeError::TrailingBytes) + ); + let empty = encode_value_frame("p:1", ids, MessageType::Interrupt, &()); + assert_eq!(decode_subscription_interrupt::(&empty), Err(DecodeError::Malformed)); + } + + #[test] + fn frame_address_and_leg_both_must_match() { + let ids = generated_request_ids(SystemHandshake::DESCRIPTOR); + let other = MethodIds { trait_id: ids.trait_id + 1, method_id: ids.method_id }; + let wrong_method = encode_value_frame( + "p:1", + other, + MessageType::Response, + &Ok::<_, CallError<()>>(HostHandshakeResponse::V1), + ); + assert_eq!( + decode_response::(&wrong_method), + Err(DecodeError::UnexpectedMethod { expected: ids, actual: other }) + ); + let wrong_leg = encode_value_frame("p:1", ids, MessageType::Request, &()); + assert_eq!( + decode_response::(&wrong_leg), + Err(DecodeError::UnexpectedMessageType { expected: MessageType::Response, actual: 0 }) + ); + assert_eq!( + encode_subscription_stop("p:1", SystemHandshake::DESCRIPTOR), + Err(DecodeError::WrongMethodKind) + ); + } + + #[test] + fn protocol_failures_keep_correlation_and_accept_future_variants() { + let known = [12, b'p', b':', b'1', 255, 255, 1, 0, 0, 4, 7]; + assert_eq!( + decode_response::(&known), + Err(DecodeError::Protocol { + request_id: "p:1".into(), + error: Some(ProtocolError::UnsupportedMessage(MethodIds { + trait_id: 4, + method_id: 7 + })) + }) + ); + let future = [12, b'p', b':', b'1', 255, 255, 1, 0, 1, 42]; + assert_eq!( + decode_response::(&future), + Err(DecodeError::Protocol { request_id: "p:1".into(), error: None }) + ); + assert_eq!( + decode_response::(&known[..known.len() - 1]), + Err(DecodeError::Malformed) + ); + let mut trailing = known.to_vec(); + trailing.push(0); + assert_eq!(decode_response::(&trailing), Err(DecodeError::TrailingBytes)); + } } diff --git a/rust/crates/truapi-codegen/src/platform_callbacks.rs b/rust/crates/truapi-codegen/src/platform_callbacks.rs index 176d662c8d..405dbda21a 100644 --- a/rust/crates/truapi-codegen/src/platform_callbacks.rs +++ b/rust/crates/truapi-codegen/src/platform_callbacks.rs @@ -10,24 +10,24 @@ use crate::{ /// Compound callback results with inline SCALE codecs shared by both bridges. /// Byte vectors themselves remain unencoded byte payloads. pub(crate) fn is_scale_vector_result(ty: &TypeRef) -> bool { - matches!( - ty, - TypeRef::Vec(inner) - if matches!(inner.as_ref(), TypeRef::Array(element, _) - if matches!(element.as_ref(), TypeRef::Primitive(name) if name == "u8")) - || matches!(inner.as_ref(), TypeRef::Primitive(name) if name == "str") - || matches!(inner.as_ref(), TypeRef::Named { args, .. } if args.is_empty()) - ) + matches!( + ty, + TypeRef::Vec(inner) + if matches!(inner.as_ref(), TypeRef::Array(element, _) + if matches!(element.as_ref(), TypeRef::Primitive(name) if name == "u8")) + || matches!(inner.as_ref(), TypeRef::Primitive(name) if name == "str") + || matches!(inner.as_ref(), TypeRef::Named { args, .. } if args.is_empty()) + ) } /// Traits the platform surface actually composes: the super trait's /// constituents when one exists, otherwise every collected trait. pub fn composed_traits(definition: &PlatformDefinition) -> Vec<&PlatformTrait> { - let mut composed: BTreeSet = match &definition.super_trait { - Some(s) => s.composes.iter().cloned().collect(), - None => definition.traits.iter().map(|t| t.name.clone()).collect(), - }; - composed.extend(optional_trait_names(definition)); + let mut composed: BTreeSet = match &definition.super_trait { + Some(s) => s.composes.iter().cloned().collect(), + None => definition.traits.iter().map(|t| t.name.clone()).collect(), + }; + composed.extend(optional_trait_names(definition)); definition.traits.iter().filter(|t| composed.contains(&t.name)).collect() } @@ -35,80 +35,80 @@ pub fn composed_traits(definition: &PlatformDefinition) -> Vec<&PlatformTrait> { /// super-trait. A host that supplies none of a trait's callbacks is not /// broken: the core applies the capability's absence behavior. pub fn optional_trait_names(definition: &PlatformDefinition) -> BTreeSet { - definition - .optional_super_trait - .as_ref() - .map(|s| s.composes.iter().cloned().collect()) - .unwrap_or_default() + definition + .optional_super_trait + .as_ref() + .map(|s| s.composes.iter().cloned().collect()) + .unwrap_or_default() } /// JS-side callback name for a platform method (camelCase of the Rust name). pub fn raw_callback_name(method: &PlatformMethod) -> String { - to_camel_case(&method.name) + to_camel_case(&method.name) } /// Set of all platform trait names, used to recognize trait-object returns. pub fn platform_trait_names(definition: &PlatformDefinition) -> BTreeSet { - definition.traits.iter().map(|t| t.name.clone()).collect() + definition.traits.iter().map(|t| t.name.clone()).collect() } /// Name of the platform trait a method returns as a handle, if any. pub fn trait_object_return_name<'a>( - method: &'a PlatformMethod, - platform_trait_names: &BTreeSet, + method: &'a PlatformMethod, + platform_trait_names: &BTreeSet, ) -> Option<&'a str> { - match &method.return_shape.inner { - PlatformInner::TraitObject(name) => Some(name.as_str()), - PlatformInner::Result { ok, .. } | PlatformInner::Plain(ok) => { - named_platform_trait(ok, platform_trait_names) + match &method.return_shape.inner { + PlatformInner::TraitObject(name) => Some(name.as_str()), + PlatformInner::Result { ok, .. } | PlatformInner::Plain(ok) => { + named_platform_trait(ok, platform_trait_names) }, - PlatformInner::Unit | PlatformInner::Stream(_) => None, - } + PlatformInner::Unit | PlatformInner::Stream(_) => None, + } } /// Wire name of a raw callback. Handle-returning methods get a trait /// namespace prefix so equally named methods on different traits stay /// distinct. pub fn raw_callback_wire_name( - trait_def: &PlatformTrait, - method: &PlatformMethod, - platform_trait_names: &BTreeSet, + trait_def: &PlatformTrait, + method: &PlatformMethod, + platform_trait_names: &BTreeSet, ) -> String { - // The public Rust method spells out its capability; the established raw - // connection bridge uses the same namespace-first shape as chainConnect. - if trait_def.name == "HopProvider" && method.name == "connect_hop" { - return "hopConnect".to_string(); - } - let raw = raw_callback_name(method); - if trait_object_return_name(method, platform_trait_names).is_some() { + // The public Rust method spells out its capability; the established raw + // connection bridge uses the same namespace-first shape as chainConnect. + if trait_def.name == "HopProvider" && method.name == "connect_hop" { + return "hopConnect".to_string(); + } + let raw = raw_callback_name(method); + if trait_object_return_name(method, platform_trait_names).is_some() { return format!("{}{}", callback_namespace(&trait_def.name), upper_first(&raw)); - } - raw + } + raw } /// Field name holding the callback in the generated Rust bridge struct. pub fn raw_callback_field_name( - trait_def: &PlatformTrait, - method: &PlatformMethod, - platform_trait_names: &BTreeSet, + trait_def: &PlatformTrait, + method: &PlatformMethod, + platform_trait_names: &BTreeSet, ) -> String { snake_case(&raw_callback_wire_name(trait_def, method, platform_trait_names)) } /// TS type name for the raw callback in the generated host-callback bridge. pub fn raw_callback_type_name( - trait_def: &PlatformTrait, - method: &PlatformMethod, - platform_trait_names: &BTreeSet, + trait_def: &PlatformTrait, + method: &PlatformMethod, + platform_trait_names: &BTreeSet, ) -> String { upper_first(&raw_callback_wire_name(trait_def, method, platform_trait_names)) } /// Name of the TS adapter that wraps a typed host callback into its raw form. pub fn raw_callback_adapter_name( - trait_def: &PlatformTrait, - method: &PlatformMethod, - platform_trait_names: &BTreeSet, + trait_def: &PlatformTrait, + method: &PlatformMethod, + platform_trait_names: &BTreeSet, ) -> String { format!("{}Adapter", raw_callback_wire_name(trait_def, method, platform_trait_names)) } @@ -116,24 +116,24 @@ pub fn raw_callback_adapter_name( /// Callback-object namespace for a trait: its name with the role suffix /// (`Provider`, `Presenter`, `Host`) stripped, lower-cased first letter. pub fn callback_namespace(trait_name: &str) -> String { - let stem = ["Provider", "Presenter", "Host", "Platform"] - .into_iter() - .find_map(|suffix| trait_name.strip_suffix(suffix)) - .unwrap_or(trait_name); - lower_pascal_case(stem) + let stem = ["Provider", "Presenter", "Host", "Platform"] + .into_iter() + .find_map(|suffix| trait_name.strip_suffix(suffix)) + .unwrap_or(trait_name); + lower_pascal_case(stem) } fn named_platform_trait<'a>( - ty: &'a TypeRef, - platform_trait_names: &BTreeSet, + ty: &'a TypeRef, + platform_trait_names: &BTreeSet, ) -> Option<&'a str> { - let TypeRef::Named { name, args } = ty else { - return None; - }; - if args.is_empty() && platform_trait_names.contains(name) { - return Some(name.as_str()); - } - None + let TypeRef::Named { name, args } = ty else { + return None; + }; + if args.is_empty() && platform_trait_names.contains(name) { + return Some(name.as_str()); + } + None } /// Unwrap a `Result` stream item to its `T`; other item types pass @@ -143,160 +143,160 @@ pub fn stream_item(item: &TypeRef) -> &TypeRef { if let TypeRef::Named { name, args } = item && name == "Result" && let Some(ok) = args.first() - { - return ok; - } - item + { + return ok; + } + item } /// Convert a snake_case identifier to camelCase. pub fn to_camel_case(name: &str) -> String { - let mut out = String::with_capacity(name.len()); - let mut upper_next = false; - for (idx, ch) in name.chars().enumerate() { - if ch == '_' { - upper_next = idx != 0; - continue; - } - if upper_next { - out.extend(ch.to_uppercase()); - upper_next = false; - } else { - out.push(ch); - } - } - out + let mut out = String::with_capacity(name.len()); + let mut upper_next = false; + for (idx, ch) in name.chars().enumerate() { + if ch == '_' { + upper_next = idx != 0; + continue; + } + if upper_next { + out.extend(ch.to_uppercase()); + upper_next = false; + } else { + out.push(ch); + } + } + out } fn lower_pascal_case(name: &str) -> String { - let mut chars = name.chars(); - let Some(first) = chars.next() else { - return String::new(); - }; + let mut chars = name.chars(); + let Some(first) = chars.next() else { + return String::new(); + }; format!("{}{}", first.to_ascii_lowercase(), chars.collect::()) } fn upper_first(name: &str) -> String { - let mut chars = name.chars(); - let Some(first) = chars.next() else { - return String::new(); - }; + let mut chars = name.chars(); + let Some(first) = chars.next() else { + return String::new(); + }; format!("{}{}", first.to_ascii_uppercase(), chars.collect::()) } /// Convert a camelCase identifier to snake_case. pub fn snake_case(name: &str) -> String { - let mut out = String::with_capacity(name.len() + 4); - for (idx, ch) in name.chars().enumerate() { - if ch.is_ascii_uppercase() { - if idx != 0 { - out.push('_'); - } - out.push(ch.to_ascii_lowercase()); - } else { - out.push(ch); - } - } - out + let mut out = String::with_capacity(name.len() + 4); + for (idx, ch) in name.chars().enumerate() { + if ch.is_ascii_uppercase() { + if idx != 0 { + out.push('_'); + } + out.push(ch.to_ascii_lowercase()); + } else { + out.push(ch); + } + } + out } /// Collect local types reachable from callback payloads, including transitive /// field references, for the Rust WASM and TypeScript host bridges. pub fn collect_local_bridge_payload_types(definition: &PlatformDefinition) -> BTreeSet<&str> { - let local: BTreeSet<&str> = definition.types.iter().map(|ty| ty.name.as_str()).collect(); - let mut out = BTreeSet::new(); - for trait_def in &definition.traits { - for method in &trait_def.methods { - for param in &method.params { - collect_local_from_type(¶m.type_ref, &local, &mut out); - } - match &method.return_shape.inner { - PlatformInner::Result { ok, .. } | PlatformInner::Plain(ok) => { - collect_local_from_type(ok, &local, &mut out); + let local: BTreeSet<&str> = definition.types.iter().map(|ty| ty.name.as_str()).collect(); + let mut out = BTreeSet::new(); + for trait_def in &definition.traits { + for method in &trait_def.methods { + for param in &method.params { + collect_local_from_type(¶m.type_ref, &local, &mut out); + } + match &method.return_shape.inner { + PlatformInner::Result { ok, .. } | PlatformInner::Plain(ok) => { + collect_local_from_type(ok, &local, &mut out); }, - PlatformInner::Stream(item) => { - collect_local_from_type(stream_item(item), &local, &mut out) + PlatformInner::Stream(item) => { + collect_local_from_type(stream_item(item), &local, &mut out) }, PlatformInner::Unit | PlatformInner::TraitObject(_) => {}, - } - } - } - let mut changed = true; - while changed { - changed = false; - let referenced = definition - .types - .iter() - .filter(|ty| out.contains(ty.name.as_str())) - .collect::>(); - for type_def in referenced { - let before = out.len(); - collect_local_from_type_def(type_def, &local, &mut out); - changed |= out.len() != before; - } - } - out + } + } + } + let mut changed = true; + while changed { + changed = false; + let referenced = definition + .types + .iter() + .filter(|ty| out.contains(ty.name.as_str())) + .collect::>(); + for type_def in referenced { + let before = out.len(); + collect_local_from_type_def(type_def, &local, &mut out); + changed |= out.len() != before; + } + } + out } fn collect_local_from_type_def<'a>( - type_def: &'a TypeDef, - local: &BTreeSet<&'a str>, - out: &mut BTreeSet<&'a str>, + type_def: &'a TypeDef, + local: &BTreeSet<&'a str>, + out: &mut BTreeSet<&'a str>, ) { - match &type_def.kind { - TypeDefKind::Alias(type_ref) => collect_local_from_type(type_ref, local, out), - TypeDefKind::Struct(fields) => { - for field in fields { - collect_local_from_type(&field.type_ref, local, out); - } + match &type_def.kind { + TypeDefKind::Alias(type_ref) => collect_local_from_type(type_ref, local, out), + TypeDefKind::Struct(fields) => { + for field in fields { + collect_local_from_type(&field.type_ref, local, out); + } }, - TypeDefKind::TupleStruct(fields) => { - for field in fields { - collect_local_from_type(field, local, out); - } + TypeDefKind::TupleStruct(fields) => { + for field in fields { + collect_local_from_type(field, local, out); + } }, - TypeDefKind::Enum(variants) => { - for variant in variants { - match &variant.fields { + TypeDefKind::Enum(variants) => { + for variant in variants { + match &variant.fields { VariantFields::Unit => {}, - VariantFields::Unnamed(types) => { - for ty in types { - collect_local_from_type(ty, local, out); - } + VariantFields::Unnamed(types) => { + for ty in types { + collect_local_from_type(ty, local, out); + } }, - VariantFields::Named(fields) => { - for field in fields { - collect_local_from_type(&field.type_ref, local, out); - } + VariantFields::Named(fields) => { + for field in fields { + collect_local_from_type(&field.type_ref, local, out); + } }, - } - } + } + } }, - } + } } fn collect_local_from_type<'a>( - ty: &'a TypeRef, - local: &BTreeSet<&'a str>, - out: &mut BTreeSet<&'a str>, + ty: &'a TypeRef, + local: &BTreeSet<&'a str>, + out: &mut BTreeSet<&'a str>, ) { - match ty { - TypeRef::Named { name, args } => { - if local.contains(name.as_str()) { - out.insert(name); - } - for arg in args { - collect_local_from_type(arg, local, out); - } + match ty { + TypeRef::Named { name, args } => { + if local.contains(name.as_str()) { + out.insert(name); + } + for arg in args { + collect_local_from_type(arg, local, out); + } }, - TypeRef::Vec(inner) | TypeRef::Option(inner) | TypeRef::Array(inner, _) => { - collect_local_from_type(inner, local, out); + TypeRef::Vec(inner) | TypeRef::Option(inner) | TypeRef::Array(inner, _) => { + collect_local_from_type(inner, local, out); }, - TypeRef::Tuple(items) => { - for item in items { - collect_local_from_type(item, local, out); - } + TypeRef::Tuple(items) => { + for item in items { + collect_local_from_type(item, local, out); + } }, TypeRef::Primitive(_) | TypeRef::Generic(_) | TypeRef::Unit => {}, - } + } } diff --git a/rust/crates/truapi-codegen/src/rust/client.rs b/rust/crates/truapi-codegen/src/rust/client.rs index 931f11bfbc..306cb66917 100644 --- a/rust/crates/truapi-codegen/src/rust/client.rs +++ b/rust/crates/truapi-codegen/src/rust/client.rs @@ -8,262 +8,235 @@ use super::{module_for_trait, wire_method_name, wire_table}; use crate::rustdoc::{ApiDefinition, MethodDef, MethodKind, ReturnType, TraitDef, TypeRef}; pub fn generate_client(api: &ApiDefinition, schema_hash: &str) -> Result { - let mut out = String::new(); - writeln!(out, "//! Canonical TrUAPI client method catalog.")?; - writeln!(out, "//!")?; - writeln!(out, "//! Auto-generated by truapi-codegen. Do not edit.\n")?; - writeln!(out, "use super::*;\n")?; - writeln!(out, "/// Fingerprint of the generated wire contract.")?; - writeln!( - out, - "pub const TRUAPI_WIRE_SCHEMA_HASH: &str = \"{schema_hash}\";\n" - )?; + let mut out = String::new(); + writeln!(out, "//! Canonical TrUAPI client method catalog.")?; + writeln!(out, "//!")?; + writeln!(out, "//! Auto-generated by truapi-codegen. Do not edit.\n")?; + writeln!(out, "use super::*;\n")?; + writeln!(out, "/// Fingerprint of the generated wire contract.")?; + writeln!(out, "pub const TRUAPI_WIRE_SCHEMA_HASH: &str = \"{schema_hash}\";\n")?; - let mut app = Vec::new(); - let mut widget = Vec::new(); - let mut worker = Vec::new(); - let mut worker_only = Vec::new(); + let mut app = Vec::new(); + let mut widget = Vec::new(); + let mut worker = Vec::new(); + let mut worker_only = Vec::new(); - for trait_name in &api.public_trait_order { - let service = api - .traits - .iter() - .find(|candidate| candidate.name == *trait_name) - .ok_or_else(|| anyhow::anyhow!("public trait `{trait_name}` was not extracted"))?; - let requirement = execution_requirement(service)?; - for method in &service.methods { - let marker = marker_name(service, method); - emit_method(&mut out, service, method, requirement, &marker)?; - match requirement { - None => { - app.push(marker.clone()); - widget.push(marker.clone()); - worker.push(marker); - } - Some("App") => app.push(marker), - Some("Widget") => widget.push(marker), - Some("Worker") => { - worker.push(marker.clone()); - worker_only.push(marker); - } - Some(other) => bail!("unsupported execution requirement `{other}`"), - } - } - } + for trait_name in &api.public_trait_order { + let service = api + .traits + .iter() + .find(|candidate| candidate.name == *trait_name) + .ok_or_else(|| anyhow::anyhow!("public trait `{trait_name}` was not extracted"))?; + let requirement = execution_requirement(service)?; + for method in &service.methods { + let marker = marker_name(service, method); + emit_method(&mut out, service, method, requirement, &marker)?; + match requirement { + None => { + app.push(marker.clone()); + widget.push(marker.clone()); + worker.push(marker); + }, + Some("App") => app.push(marker), + Some("Widget") => widget.push(marker), + Some("Worker") => { + worker.push(marker.clone()); + worker_only.push(marker); + }, + Some(other) => bail!("unsupported execution requirement `{other}`"), + } + } + } - emit_catalog(&mut out, "APP_METHODS", &app)?; - emit_catalog(&mut out, "WIDGET_METHODS", &widget)?; - emit_catalog(&mut out, "WORKER_METHODS", &worker)?; - emit_catalog(&mut out, "WORKER_ONLY_METHODS", &worker_only)?; - Ok(out) + emit_catalog(&mut out, "APP_METHODS", &app)?; + emit_catalog(&mut out, "WIDGET_METHODS", &widget)?; + emit_catalog(&mut out, "WORKER_METHODS", &worker)?; + emit_catalog(&mut out, "WORKER_ONLY_METHODS", &worker_only)?; + Ok(out) } fn execution_requirement(service: &TraitDef) -> Result> { - let requirement = service.required_execution(); - if let Some(value) = requirement - && !matches!(value, "App" | "Widget" | "Worker") - { - bail!( - "service `{}` has unknown execution requirement `{value}`", - service.name - ); - } - Ok(requirement) + let requirement = service.required_execution(); + if let Some(value) = requirement && + !matches!(value, "App" | "Widget" | "Worker") + { + bail!("service `{}` has unknown execution requirement `{value}`", service.name); + } + Ok(requirement) } fn marker_name(service: &TraitDef, method: &MethodDef) -> String { - format!("{}_{}", service.name, method.name).to_case(Case::Pascal) + format!("{}_{}", service.name, method.name).to_case(Case::Pascal) } fn emit_method( - out: &mut String, - service: &TraitDef, - method: &MethodDef, - requirement: Option<&str>, - marker: &str, + out: &mut String, + service: &TraitDef, + method: &MethodDef, + requirement: Option<&str>, + marker: &str, ) -> Result<()> { - let module = module_for_trait(&service.name); - let wire_name = wire_method_name(&service.name, &method.name); - let execution = requirement - .map(|value| format!("Some(ExecutionKind::{value})")) - .unwrap_or_else(|| "None".to_string()); - let direction = if method.wire.host_initiated { - "Direction::HostToProduct" - } else { - "Direction::ProductToHost" - }; - let kind = match method.kind { - MethodKind::Request => "MethodKind::Request", - MethodKind::Subscription => "MethodKind::Subscription", - }; - let trait_id = wire_table::trait_wire_id(service)?; - let method_id = wire_table::method_wire_id(service, method)?; - let wire_kind = match method.kind { - MethodKind::Request => "Request", - MethodKind::Subscription => "Subscription", - }; - let wire = format!( - "MethodWire::{wire_kind}(MethodIds {{ trait_id: {trait_id}, method_id: {method_id} }})" - ); - let request_name = request_type(method, &module)?; - let (response_name, error_name) = match &method.return_type { - ReturnType::Result { ok, err } => ( - rust_type(ok, &module)?, - Some(rust_type(call_error_domain(err)?, &module)?), - ), - ReturnType::Subscription { item, interrupt } => ( - rust_type(item, &module)?, - Some(rust_type(call_error_domain(interrupt)?, &module)?), - ), - }; + let module = module_for_trait(&service.name); + let wire_name = wire_method_name(&service.name, &method.name); + let execution = requirement + .map(|value| format!("Some(ExecutionKind::{value})")) + .unwrap_or_else(|| "None".to_string()); + let direction = if method.wire.host_initiated { + "Direction::HostToProduct" + } else { + "Direction::ProductToHost" + }; + let kind = match method.kind { + MethodKind::Request => "MethodKind::Request", + MethodKind::Subscription => "MethodKind::Subscription", + }; + let trait_id = wire_table::trait_wire_id(service)?; + let method_id = wire_table::method_wire_id(service, method)?; + let wire_kind = match method.kind { + MethodKind::Request => "Request", + MethodKind::Subscription => "Subscription", + }; + let wire = format!( + "MethodWire::{wire_kind}(MethodIds {{ trait_id: {trait_id}, method_id: {method_id} }})" + ); + let request_name = request_type(method, &module)?; + let (response_name, error_name) = match &method.return_type { + ReturnType::Result { ok, err } => { + (rust_type(ok, &module)?, Some(rust_type(call_error_domain(err)?, &module)?)) + }, + ReturnType::Subscription { item, interrupt } => { + (rust_type(item, &module)?, Some(rust_type(call_error_domain(interrupt)?, &module)?)) + }, + }; - writeln!(out, "/// `{wire_name}` method marker.")?; - writeln!(out, "pub struct {marker};")?; - writeln!(out, "impl {marker} {{")?; - writeln!( - out, - " /// Canonical metadata and frame ids for this method." - )?; - writeln!( - out, - " pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor {{" - )?; - writeln!(out, " service: \"{}\",", service.name)?; - writeln!(out, " method: \"{}\",", method.name)?; - writeln!(out, " wire_name: \"{wire_name}\",")?; - writeln!(out, " request_type: \"{request_name}\",")?; - writeln!(out, " response_type: \"{response_name}\",")?; - match error_name { - Some(error) => writeln!(out, " error_type: Some(\"{error}\"),")?, - None => writeln!(out, " error_type: None,")?, - } - writeln!(out, " kind: {kind},")?; - writeln!(out, " direction: {direction},")?; - writeln!(out, " required_execution: {execution},")?; - writeln!(out, " wire: {wire},")?; - writeln!(out, " }};")?; - writeln!(out, "}}")?; + writeln!(out, "/// `{wire_name}` method marker.")?; + writeln!(out, "pub struct {marker};")?; + writeln!(out, "impl {marker} {{")?; + writeln!(out, " /// Canonical metadata and frame ids for this method.")?; + writeln!(out, " pub const DESCRIPTOR: MethodDescriptor = MethodDescriptor {{")?; + writeln!(out, " service: \"{}\",", service.name)?; + writeln!(out, " method: \"{}\",", method.name)?; + writeln!(out, " wire_name: \"{wire_name}\",")?; + writeln!(out, " request_type: \"{request_name}\",")?; + writeln!(out, " response_type: \"{response_name}\",")?; + match error_name { + Some(error) => writeln!(out, " error_type: Some(\"{error}\"),")?, + None => writeln!(out, " error_type: None,")?, + } + writeln!(out, " kind: {kind},")?; + writeln!(out, " direction: {direction},")?; + writeln!(out, " required_execution: {execution},")?; + writeln!(out, " wire: {wire},")?; + writeln!(out, " }};")?; + writeln!(out, "}}")?; - let request = request_type(method, &module)?; - match ( - &method.kind, - &method.return_type, - method.wire.host_initiated, - ) { - (MethodKind::Request, ReturnType::Result { ok, err }, false) => { - let response = rust_type(ok, &module)?; - let error = rust_type(call_error_domain(err)?, &module)?; - writeln!(out, "impl RequestMethod for {marker} {{")?; - writeln!(out, " type Request = {request};")?; - writeln!(out, " type Response = {response};")?; - writeln!(out, " type Error = {error};")?; - writeln!( - out, - " const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR;" - )?; - writeln!(out, "}}\n")?; - } - ( - MethodKind::Subscription, - ReturnType::Subscription { item, interrupt }, - host_initiated, - ) => { - let item = rust_type(item, &module)?; - let error = rust_type(call_error_domain(interrupt)?, &module)?; - let subscription_trait = if host_initiated { - "HostSubscriptionMethod" - } else { - "SubscriptionMethod" - }; - writeln!(out, "impl {subscription_trait} for {marker} {{")?; - writeln!(out, " type Request = {request};")?; - writeln!(out, " type Error = {error};")?; - writeln!(out, " type Item = {item};")?; - writeln!( - out, - " const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR;" - )?; - writeln!(out, "}}\n")?; - } - _ => bail!("method `{wire_name}` has unsupported kind/return/direction combination"), - } - Ok(()) + let request = request_type(method, &module)?; + match (&method.kind, &method.return_type, method.wire.host_initiated) { + (MethodKind::Request, ReturnType::Result { ok, err }, false) => { + let response = rust_type(ok, &module)?; + let error = rust_type(call_error_domain(err)?, &module)?; + writeln!(out, "impl RequestMethod for {marker} {{")?; + writeln!(out, " type Request = {request};")?; + writeln!(out, " type Response = {response};")?; + writeln!(out, " type Error = {error};")?; + writeln!(out, " const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR;")?; + writeln!(out, "}}\n")?; + }, + ( + MethodKind::Subscription, + ReturnType::Subscription { item, interrupt }, + host_initiated, + ) => { + let item = rust_type(item, &module)?; + let error = rust_type(call_error_domain(interrupt)?, &module)?; + let subscription_trait = + if host_initiated { "HostSubscriptionMethod" } else { "SubscriptionMethod" }; + writeln!(out, "impl {subscription_trait} for {marker} {{")?; + writeln!(out, " type Request = {request};")?; + writeln!(out, " type Error = {error};")?; + writeln!(out, " type Item = {item};")?; + writeln!(out, " const DESCRIPTOR: MethodDescriptor = Self::DESCRIPTOR;")?; + writeln!(out, "}}\n")?; + }, + _ => bail!("method `{wire_name}` has unsupported kind/return/direction combination"), + } + Ok(()) } fn request_type(method: &MethodDef, module: &str) -> Result { - match method.params.as_slice() { - [] => Ok("()".to_string()), - [param] => rust_type(¶m.type_ref, module), - params => bail!( - "method `{}` has {} wire parameters; expected at most one request wrapper", - method.name, - params.len() - ), - } + match method.params.as_slice() { + [] => Ok("()".to_string()), + [param] => rust_type(¶m.type_ref, module), + params => bail!( + "method `{}` has {} wire parameters; expected at most one request wrapper", + method.name, + params.len() + ), + } } fn call_error_domain(error: &TypeRef) -> Result<&TypeRef> { - match error { - TypeRef::Named { name, args } if name == "CallError" && args.len() == 1 => Ok(&args[0]), - _ => bail!("method error is not CallError: {error:?}"), - } + match error { + TypeRef::Named { name, args } if name == "CallError" && args.len() == 1 => Ok(&args[0]), + _ => bail!("method error is not CallError: {error:?}"), + } } fn rust_type(value: &TypeRef, module: &str) -> Result { - Ok(match value { - TypeRef::Primitive(name) if name == "String" => "alloc::string::String".to_string(), - TypeRef::Primitive(name) => name.clone(), - TypeRef::Named { name, args } if name == "String" && args.is_empty() => { - "alloc::string::String".to_string() - } - TypeRef::Named { name, args } if name == "Vec" && args.len() == 1 => { - format!("alloc::vec::Vec<{}>", rust_type(&args[0], module)?) - } - TypeRef::Named { name, args } if name == "Option" && args.len() == 1 => { - format!("Option<{}>", rust_type(&args[0], module)?) - } - TypeRef::Named { name, args } if name == "Infallible" && args.is_empty() => { - "core::convert::Infallible".to_string() - } - TypeRef::Named { name, args } if name == "GenericError" && args.is_empty() => { - "truapi::v01::GenericError".to_string() - } - TypeRef::Named { name, args } if args.is_empty() => { - format!("truapi::versioned::{module}::{name}") - } - TypeRef::Named { name, args } => { - let args = args - .iter() - .map(|arg| rust_type(arg, module)) - .collect::>>()? - .join(", "); - format!("truapi::versioned::{module}::{name}<{args}>") - } - TypeRef::Vec(inner) => format!("alloc::vec::Vec<{}>", rust_type(inner, module)?), - TypeRef::Option(inner) => format!("Option<{}>", rust_type(inner, module)?), - TypeRef::Tuple(items) => { - let mut rendered = items - .iter() - .map(|item| rust_type(item, module)) - .collect::>>()? - .join(", "); - if items.len() == 1 { - rendered.push(','); - } - format!("({rendered})") - } - TypeRef::Array(inner, len) => format!("[{}; {len}]", rust_type(inner, module)?), - TypeRef::Generic(name) => bail!("unresolved generic type `{name}` in method surface"), - TypeRef::Unit => "()".to_string(), - }) + Ok(match value { + TypeRef::Primitive(name) if name == "String" => "alloc::string::String".to_string(), + TypeRef::Primitive(name) => name.clone(), + TypeRef::Named { name, args } if name == "String" && args.is_empty() => { + "alloc::string::String".to_string() + }, + TypeRef::Named { name, args } if name == "Vec" && args.len() == 1 => { + format!("alloc::vec::Vec<{}>", rust_type(&args[0], module)?) + }, + TypeRef::Named { name, args } if name == "Option" && args.len() == 1 => { + format!("Option<{}>", rust_type(&args[0], module)?) + }, + TypeRef::Named { name, args } if name == "Infallible" && args.is_empty() => { + "core::convert::Infallible".to_string() + }, + TypeRef::Named { name, args } if name == "GenericError" && args.is_empty() => { + "truapi::v01::GenericError".to_string() + }, + TypeRef::Named { name, args } if args.is_empty() => { + format!("truapi::versioned::{module}::{name}") + }, + TypeRef::Named { name, args } => { + let args = args + .iter() + .map(|arg| rust_type(arg, module)) + .collect::>>()? + .join(", "); + format!("truapi::versioned::{module}::{name}<{args}>") + }, + TypeRef::Vec(inner) => format!("alloc::vec::Vec<{}>", rust_type(inner, module)?), + TypeRef::Option(inner) => format!("Option<{}>", rust_type(inner, module)?), + TypeRef::Tuple(items) => { + let mut rendered = items + .iter() + .map(|item| rust_type(item, module)) + .collect::>>()? + .join(", "); + if items.len() == 1 { + rendered.push(','); + } + format!("({rendered})") + }, + TypeRef::Array(inner, len) => format!("[{}; {len}]", rust_type(inner, module)?), + TypeRef::Generic(name) => bail!("unresolved generic type `{name}` in method surface"), + TypeRef::Unit => "()".to_string(), + }) } fn emit_catalog(out: &mut String, name: &str, markers: &[String]) -> Result<()> { - writeln!(out, "/// Generated `{name}` execution catalog.")?; - writeln!(out, "pub const {name}: &[MethodDescriptor] = &[")?; - for marker in markers { - writeln!(out, " {marker}::DESCRIPTOR,")?; - } - writeln!(out, "];\n")?; - Ok(()) + writeln!(out, "/// Generated `{name}` execution catalog.")?; + writeln!(out, "pub const {name}: &[MethodDescriptor] = &[")?; + for marker in markers { + writeln!(out, " {marker}::DESCRIPTOR,")?; + } + writeln!(out, "];\n")?; + Ok(()) } diff --git a/rust/crates/truapi-codegen/src/rust/wasm_bridge.rs b/rust/crates/truapi-codegen/src/rust/wasm_bridge.rs index 5363394187..97d99704eb 100644 --- a/rust/crates/truapi-codegen/src/rust/wasm_bridge.rs +++ b/rust/crates/truapi-codegen/src/rust/wasm_bridge.rs @@ -9,7 +9,7 @@ use indoc::{formatdoc, writedoc}; use crate::{ platform::{PlatformDefinition, PlatformInner, PlatformMethod, PlatformTrait}, platform_callbacks::{ - callback_namespace, collect_local_bridge_payload_types, composed_traits, + callback_namespace, collect_local_bridge_payload_types, composed_traits, is_scale_vector_result, optional_trait_names, platform_trait_names, raw_callback_field_name, raw_callback_name, raw_callback_wire_name, snake_case, stream_item, trait_object_return_name, }, @@ -650,6 +650,9 @@ fn validate_error_type(err: &TypeRef, ctx: &BridgeCtx<'_>) -> Result<()> { validate_error_name(name, ctx, &mut seen) } +/// `seen` holds the envelopes on the path from the root, not every name +/// visited: two versions of one envelope may carry the same payload, which is +/// sharing, not recursion. fn validate_error_name<'a>( name: &'a str, ctx: &BridgeCtx<'a>, @@ -661,6 +664,16 @@ fn validate_error_name<'a>( if !seen.insert(name) { bail!("platform error type `{name}` contains a recursive alias/envelope"); } + let result = validate_error_def(name, ctx, seen); + seen.remove(name); + result +} + +fn validate_error_def<'a>( + name: &'a str, + ctx: &BridgeCtx<'a>, + seen: &mut BTreeSet<&'a str>, +) -> Result<()> { let Some(type_def) = resolve_alias_type(name, ctx) else { bail!("platform error type `{name}` is not present in the API definition"); }; diff --git a/rust/crates/truapi-codegen/src/ts/host_callbacks.rs b/rust/crates/truapi-codegen/src/ts/host_callbacks.rs index 1e1c3e9c13..bd6b8ff8fc 100644 --- a/rust/crates/truapi-codegen/src/ts/host_callbacks.rs +++ b/rust/crates/truapi-codegen/src/ts/host_callbacks.rs @@ -18,10 +18,10 @@ use crate::{ PlatformTrait, }, platform_callbacks::{ - callback_namespace, collect_local_bridge_payload_types, composed_traits, + callback_namespace, collect_local_bridge_payload_types, composed_traits, is_scale_vector_result, optional_trait_names, platform_trait_names, raw_callback_adapter_name, raw_callback_name, raw_callback_type_name, raw_callback_wire_name, stream_item, to_camel_case, - trait_object_return_name, + trait_object_return_name, }, rustdoc::{FieldDef, TypeDef, TypeDefKind, TypeRef, VariantDef, VariantFields}, ts::ts_string_literal, @@ -191,11 +191,10 @@ fn emit_wasm_adapter( { support_imports.insert("unavailableNativeChatFilesHost".to_string()); } - if traits - .iter() - .any(|trait_def| trait_def.name == "CoinageWalletHost") - { - support_imports.insert("coinageWalletHostAdapter".to_string()); + for trait_def in &traits { + if let Some(adapter) = optional_host_adapter(&trait_def.name) { + support_imports.insert(adapter.to_string()); + } } for trait_def in &traits { for method in &trait_def.methods { @@ -310,14 +309,13 @@ fn emit_wasm_adapter( // narrowed reference rather than re-reading a possibly-absent member. for name in &optional_traits { let namespace = callback_namespace(name); - if name == "CoinageWalletHost" { - writeln!( + match optional_host_adapter(name) { + Some(adapter) => writeln!( out, - " const {namespace} = coinageWalletHostAdapter(callbacks.{namespace});" + " const {namespace} = {adapter}(callbacks.{namespace});" ) - .unwrap(); - } else { - writeln!(out, " const {namespace} = callbacks.{namespace};").unwrap(); + .unwrap(), + None => writeln!(out, " const {namespace} = callbacks.{namespace};").unwrap(), } } // HOP remains a required Rust capability. Older JS embeddings get its @@ -362,6 +360,21 @@ fn emit_wasm_adapter( Ok(out) } +/// The hand-written `adapter-support` wrapper an optional capability group +/// passes through before the adapter binds it, if it has one. +/// +/// `ProfilePlatform`'s wrapper applies `present_contact_profile`'s Rust default +/// for a host built before that callback, so the core never reaches a missing +/// function for it. +fn optional_host_adapter(trait_name: &str) -> Option<&'static str> { + match trait_name { + "CoinageWalletHost" => Some("coinageWalletHostAdapter"), + "ContactsPlatform" => Some("contactsHostAdapter"), + "ProfilePlatform" => Some("profileHostAdapter"), + _ => None, + } +} + /// Emit the generated callback metadata/proxy used by the Web Worker bridge. /// /// The lifecycle/transport pieces stay hand-written in `worker-runtime.ts` and @@ -1637,6 +1650,9 @@ fn emit_host_callback_composites( let required_members = composes .iter() .map(|trait_name| { + if trait_name == "ContactsPlatform" { + return format!(" {}?: ContactsPlatform;", callback_namespace(trait_name)); + } format!( " {}{}: Required<{}>;", callback_namespace(trait_name), diff --git a/rust/crates/truapi-codegen/tests/deterministic_emit.rs b/rust/crates/truapi-codegen/tests/deterministic_emit.rs index f6e0d58439..af941a18f3 100644 --- a/rust/crates/truapi-codegen/tests/deterministic_emit.rs +++ b/rust/crates/truapi-codegen/tests/deterministic_emit.rs @@ -4,72 +4,71 @@ //! runtime documentation. The nightly named in `nightly-toolchain` is required; //! `TRUAPI_NIGHTLY_TOOLCHAIN` overrides it. -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, + process::Command, +}; /// The dated nightly CI runs, unless `TRUAPI_NIGHTLY_TOOLCHAIN` names another. fn nightly_toolchain() -> String { - std::env::var("TRUAPI_NIGHTLY_TOOLCHAIN").unwrap_or_else(|_| { - include_str!("../../../../nightly-toolchain") - .trim() - .to_string() - }) + std::env::var("TRUAPI_NIGHTLY_TOOLCHAIN") + .unwrap_or_else(|_| include_str!("../../../../nightly-toolchain").trim().to_string()) } /// Build the protocol definitions with the same nightly used by codegen. fn produce_rustdoc_json(workspace_root: &Path) -> PathBuf { - let target_dir = workspace_root - .join("target/codegen-test-rustdoc/truapi_--no-default-features_--features_host-api"); - let toolchain = nightly_toolchain(); - let output = Command::new("cargo") - .arg(format!("+{toolchain}")) - .args([ - "rustdoc", - "-p", - "truapi", - "--no-default-features", - "--features", - "host-api", - "--target-dir", - ]) - .arg(&target_dir) - .args(["--", "-Z", "unstable-options", "--output-format", "json"]) - .current_dir(workspace_root) - .output() - .expect("failed to spawn rustdoc; install the pinned nightly named in nightly-toolchain"); - assert!( - output.status.success(), - "`cargo +{toolchain} rustdoc -p truapi` failed (status {}); that nightly toolchain is required.\nstdout:\n{}\nstderr:\n{}", - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr), - ); - let json = target_dir.join("doc/truapi.json"); - assert!( - json.exists(), - "rustdoc JSON not found at {} after successful rustdoc invocation", - json.display(), - ); - json + let target_dir = workspace_root + .join("target/codegen-test-rustdoc/truapi_--no-default-features_--features_host-api"); + let toolchain = nightly_toolchain(); + let output = Command::new("cargo") + .arg(format!("+{toolchain}")) + .args([ + "rustdoc", + "-p", + "truapi", + "--no-default-features", + "--features", + "host-api", + "--target-dir", + ]) + .arg(&target_dir) + .args(["--", "-Z", "unstable-options", "--output-format", "json"]) + .current_dir(workspace_root) + .output() + .expect("failed to spawn rustdoc; install the pinned nightly named in nightly-toolchain"); + assert!( + output.status.success(), + "`cargo +{toolchain} rustdoc -p truapi` failed (status {}); that nightly toolchain is required.\nstdout:\n{}\nstderr:\n{}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + let json = target_dir.join("doc/truapi.json"); + assert!( + json.exists(), + "rustdoc JSON not found at {} after successful rustdoc invocation", + json.display(), + ); + json } fn workspace_root() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .ancestors() - .nth(3) - .expect("workspace root above rust/crates/truapi-codegen") - .to_path_buf() + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .nth(3) + .expect("workspace root above rust/crates/truapi-codegen") + .to_path_buf() } fn workspace_tempdir(workspace: &Path) -> tempfile::TempDir { - let parent = workspace.join("target/codegen-test-tmp"); - fs::create_dir_all(&parent).expect("create workspace codegen temp directory"); - tempfile::Builder::new() - .prefix("golden-") - .tempdir_in(parent) - .expect("workspace tempdir") + let parent = workspace.join("target/codegen-test-tmp"); + fs::create_dir_all(&parent).expect("create workspace codegen temp directory"); + tempfile::Builder::new() + .prefix("golden-") + .tempdir_in(parent) + .expect("workspace tempdir") } /// Idempotence guard at the integration level: running the binary twice @@ -78,67 +77,56 @@ fn workspace_tempdir(workspace: &Path) -> tempfile::TempDir { /// inline unit tests might miss because they exercise smaller APIs. #[test] fn binary_emission_is_idempotent() { - let workspace = workspace_root(); - let rustdoc_json = produce_rustdoc_json(&workspace); + let workspace = workspace_root(); + let rustdoc_json = produce_rustdoc_json(&workspace); - // Every emitted file, not a hand-picked list: the nondeterminism this - // guards against has landed in the TypeScript output as readily as in the - // Rust output, and a list only covers what someone remembered to add. - let run_once = || -> BTreeMap { - let tmp = workspace_tempdir(&workspace); - let status = Command::new(env!("CARGO_BIN_EXE_truapi-codegen")) - .args([ - "--input", - rustdoc_json.to_str().unwrap(), - "--output", - tmp.path().join("ts").to_str().unwrap(), - "--rust-output", - tmp.path().join("rust").to_str().unwrap(), - ]) - .status() - .expect("run truapi-codegen"); - assert!(status.success(), "codegen run failed"); - read_tree(tmp.path()) - }; + // Every emitted file, not a hand-picked list: the nondeterminism this + // guards against has landed in the TypeScript output as readily as in the + // Rust output, and a list only covers what someone remembered to add. + let run_once = || -> BTreeMap { + let tmp = workspace_tempdir(&workspace); + let status = Command::new(env!("CARGO_BIN_EXE_truapi-codegen")) + .args([ + "--input", + rustdoc_json.to_str().unwrap(), + "--output", + tmp.path().join("ts").to_str().unwrap(), + "--rust-output", + tmp.path().join("rust").to_str().unwrap(), + ]) + .status() + .expect("run truapi-codegen"); + assert!(status.success(), "codegen run failed"); + read_tree(tmp.path()) + }; - let first = run_once(); - let second = run_once(); - assert!(!first.is_empty(), "codegen emitted nothing"); - assert_eq!( - first.keys().collect::>(), - second.keys().collect::>(), - "the two runs emitted different files" - ); - for (path, contents) in &first { - assert_eq!( - contents, - &second[path], - "{} differs between runs", - path.display() - ); - } + let first = run_once(); + let second = run_once(); + assert!(!first.is_empty(), "codegen emitted nothing"); + assert_eq!( + first.keys().collect::>(), + second.keys().collect::>(), + "the two runs emitted different files" + ); + for (path, contents) in &first { + assert_eq!(contents, &second[path], "{} differs between runs", path.display()); + } } /// Every file under `root`, keyed by its path relative to `root`. fn read_tree(root: &Path) -> BTreeMap { - let mut files = BTreeMap::new(); - let mut pending = vec![root.to_path_buf()]; - while let Some(dir) = pending.pop() { - for entry in fs::read_dir(&dir).expect("read generated directory") { - let path = entry.expect("read generated entry").path(); - if path.is_dir() { - pending.push(path); - } else { - let relative = path - .strip_prefix(root) - .expect("path under root") - .to_path_buf(); - files.insert( - relative, - fs::read_to_string(&path).expect("read generated file"), - ); - } - } - } - files + let mut files = BTreeMap::new(); + let mut pending = vec![root.to_path_buf()]; + while let Some(dir) = pending.pop() { + for entry in fs::read_dir(&dir).expect("read generated directory") { + let path = entry.expect("read generated entry").path(); + if path.is_dir() { + pending.push(path); + } else { + let relative = path.strip_prefix(root).expect("path under root").to_path_buf(); + files.insert(relative, fs::read_to_string(&path).expect("read generated file")); + } + } + } + files } diff --git a/rust/crates/truapi-coinage/src/allocator.rs b/rust/crates/truapi-coinage/src/allocator.rs index 991017688a..0a9389cd74 100644 --- a/rust/crates/truapi-coinage/src/allocator.rs +++ b/rust/crates/truapi-coinage/src/allocator.rs @@ -11,18 +11,18 @@ use std::sync::Arc; -use crate::clock::Clock; -use crate::constants::MAX_VOUCHER_WAIT_TIME; -use crate::index_store::{CoinageIndexStore, IndexKind}; -use crate::model::{ - Coin, CoinState, Voucher, VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState, +use crate::{ + clock::Clock, + constants::MAX_VOUCHER_WAIT_TIME, + index_store::{CoinageIndexStore, IndexKind}, + model::{Coin, CoinState, Voucher, VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}, }; /// The voucher readiness-delay source. Injected so tests pin it; the /// production impl draws uniform jitter. pub trait VoucherDelayProvider: Send + Sync { - /// A delay in `0..=MAX_VOUCHER_WAIT_TIME` milliseconds. - fn ready_delay_ms(&self) -> i64; + /// A delay in `0..=MAX_VOUCHER_WAIT_TIME` milliseconds. + fn ready_delay_ms(&self) -> i64; } /// Production jitter from the OS entropy-backed hasher seed. Not @@ -32,145 +32,131 @@ pub trait VoucherDelayProvider: Send + Sync { pub struct SystemJitterDelayProvider; impl VoucherDelayProvider for SystemJitterDelayProvider { - fn ready_delay_ms(&self) -> i64 { - use std::hash::{BuildHasher, Hasher, RandomState}; - let raw = RandomState::new().build_hasher().finish(); - let span = MAX_VOUCHER_WAIT_TIME.as_millis() as u64 + 1; - (raw % span) as i64 - } + fn ready_delay_ms(&self) -> i64 { + use std::hash::{BuildHasher, Hasher, RandomState}; + let raw = RandomState::new().build_hasher().finish(); + let span = MAX_VOUCHER_WAIT_TIME.as_millis() as u64 + 1; + (raw % span) as i64 + } } /// Fixed delay for tests. pub struct FixedDelayProvider(pub i64); impl VoucherDelayProvider for FixedDelayProvider { - fn ready_delay_ms(&self) -> i64 { - self.0 - } + fn ready_delay_ms(&self) -> i64 { + self.0 + } } pub struct CoinAllocator { - index_store: Arc, + index_store: Arc, } impl CoinAllocator { - pub fn new(index_store: Arc) -> Self { - Self { index_store } - } - - pub async fn allocate(&self, exponent: i16) -> Result { - let derivation_index = self.index_store.get_next_index(IndexKind::Coin).await?; - Ok(Coin { - exponent, - derivation_index, - age: None, - state: CoinState::Available, - }) - } + pub fn new(index_store: Arc) -> Self { + Self { index_store } + } + + pub async fn allocate(&self, exponent: i16) -> Result { + let derivation_index = self.index_store.get_next_index(IndexKind::Coin).await?; + Ok(Coin { exponent, derivation_index, age: None, state: CoinState::Available }) + } } /// Allocates fresh vouchers: next index, `ready_at = now + jitter`, /// `Unlocated` remote state and `Degraded` privacy until a later scan /// reconciles the voucher's on-chain position. pub struct VoucherAllocator { - index_store: Arc, - delay: Arc, - clock: Arc, + index_store: Arc, + delay: Arc, + clock: Arc, } impl VoucherAllocator { - pub fn new( - index_store: Arc, - delay: Arc, - clock: Arc, - ) -> Self { - Self { - index_store, - delay, - clock, - } - } - - pub async fn allocate(&self, exponent: i16) -> Result { - let derivation_index = self.index_store.get_next_index(IndexKind::Voucher).await?; - let allocated_at_ms = self.clock.now_ms(); - Ok(Voucher { - exponent, - derivation_index, - allocated_at_ms, - ready_at_ms: allocated_at_ms.saturating_add(self.delay.ready_delay_ms()), - remote_state: VoucherRemoteState::Unlocated, - local_state: VoucherLocalState::Available, - privacy: VoucherPrivacyLevel::Degraded, - }) - } + pub fn new( + index_store: Arc, + delay: Arc, + clock: Arc, + ) -> Self { + Self { index_store, delay, clock } + } + + pub async fn allocate(&self, exponent: i16) -> Result { + let derivation_index = self.index_store.get_next_index(IndexKind::Voucher).await?; + let allocated_at_ms = self.clock.now_ms(); + Ok(Voucher { + exponent, + derivation_index, + allocated_at_ms, + ready_at_ms: allocated_at_ms.saturating_add(self.delay.ready_delay_ms()), + remote_state: VoucherRemoteState::Unlocated, + local_state: VoucherLocalState::Available, + privacy: VoucherPrivacyLevel::Degraded, + }) + } } #[cfg(test)] mod tests { - use super::*; - use crate::clock::FixedClock; - use crate::index_store::InMemoryCoinageIndexStore; - - #[tokio::test] - async fn coin_allocation_draws_sequential_indices() { - let store = Arc::new(InMemoryCoinageIndexStore::default()); - let allocator = CoinAllocator::new(Arc::clone(&store) as Arc<_>); - let first = allocator.allocate(3).await.unwrap(); - let second = allocator.allocate(0).await.unwrap(); - assert_eq!( - (first.derivation_index, second.derivation_index), - (0, 1), - "COINB-051 sequence" - ); - assert_eq!(first.exponent, 3); - assert_eq!(first.age, None, "age unknown until first sync"); - assert_eq!(first.state, CoinState::Available); - } - - #[tokio::test] - async fn voucher_allocation_applies_the_readiness_jitter() { - let store = Arc::new(InMemoryCoinageIndexStore::default()); - let allocator = VoucherAllocator::new( - Arc::clone(&store) as Arc<_>, - Arc::new(FixedDelayProvider(5_000)), - Arc::new(FixedClock(1_000)), - ); - let voucher = allocator.allocate(2).await.unwrap(); - assert_eq!(voucher.derivation_index, 0); - assert_eq!(voucher.allocated_at_ms, 1_000); - assert_eq!(voucher.ready_at_ms, 6_000, "allocated_at + delay"); - assert_eq!(voucher.remote_state, VoucherRemoteState::Unlocated); - assert_eq!(voucher.local_state, VoucherLocalState::Available); - assert_eq!( - voucher.privacy, - VoucherPrivacyLevel::Degraded, - "degraded until the ring proves large enough" - ); - } - - /// Coin and voucher counters never share an index space. - #[tokio::test] - async fn allocators_use_independent_counters() { - let store = Arc::new(InMemoryCoinageIndexStore::default()); - let coins = CoinAllocator::new(Arc::clone(&store) as Arc<_>); - let vouchers = VoucherAllocator::new( - Arc::clone(&store) as Arc<_>, - Arc::new(FixedDelayProvider(0)), - Arc::new(FixedClock(0)), - ); - coins.allocate(0).await.unwrap(); - coins.allocate(0).await.unwrap(); - assert_eq!(vouchers.allocate(0).await.unwrap().derivation_index, 0); - } - - #[test] - fn system_jitter_stays_inside_the_wait_window() { - let provider = SystemJitterDelayProvider; - for _ in 0..64 { - let delay = provider.ready_delay_ms(); - assert!(delay >= 0); - assert!(delay <= MAX_VOUCHER_WAIT_TIME.as_millis() as i64); - } - } + use super::*; + use crate::{clock::FixedClock, index_store::InMemoryCoinageIndexStore}; + + #[tokio::test] + async fn coin_allocation_draws_sequential_indices() { + let store = Arc::new(InMemoryCoinageIndexStore::default()); + let allocator = CoinAllocator::new(Arc::clone(&store) as Arc<_>); + let first = allocator.allocate(3).await.unwrap(); + let second = allocator.allocate(0).await.unwrap(); + assert_eq!((first.derivation_index, second.derivation_index), (0, 1), "COINB-051 sequence"); + assert_eq!(first.exponent, 3); + assert_eq!(first.age, None, "age unknown until first sync"); + assert_eq!(first.state, CoinState::Available); + } + + #[tokio::test] + async fn voucher_allocation_applies_the_readiness_jitter() { + let store = Arc::new(InMemoryCoinageIndexStore::default()); + let allocator = VoucherAllocator::new( + Arc::clone(&store) as Arc<_>, + Arc::new(FixedDelayProvider(5_000)), + Arc::new(FixedClock(1_000)), + ); + let voucher = allocator.allocate(2).await.unwrap(); + assert_eq!(voucher.derivation_index, 0); + assert_eq!(voucher.allocated_at_ms, 1_000); + assert_eq!(voucher.ready_at_ms, 6_000, "allocated_at + delay"); + assert_eq!(voucher.remote_state, VoucherRemoteState::Unlocated); + assert_eq!(voucher.local_state, VoucherLocalState::Available); + assert_eq!( + voucher.privacy, + VoucherPrivacyLevel::Degraded, + "degraded until the ring proves large enough" + ); + } + + /// Coin and voucher counters never share an index space. + #[tokio::test] + async fn allocators_use_independent_counters() { + let store = Arc::new(InMemoryCoinageIndexStore::default()); + let coins = CoinAllocator::new(Arc::clone(&store) as Arc<_>); + let vouchers = VoucherAllocator::new( + Arc::clone(&store) as Arc<_>, + Arc::new(FixedDelayProvider(0)), + Arc::new(FixedClock(0)), + ); + coins.allocate(0).await.unwrap(); + coins.allocate(0).await.unwrap(); + assert_eq!(vouchers.allocate(0).await.unwrap().derivation_index, 0); + } + + #[test] + fn system_jitter_stays_inside_the_wait_window() { + let provider = SystemJitterDelayProvider; + for _ in 0..64 { + let delay = provider.ready_delay_ms(); + assert!(delay >= 0); + assert!(delay <= MAX_VOUCHER_WAIT_TIME.as_millis() as i64); + } + } } diff --git a/rust/crates/truapi-coinage/src/balance.rs b/rust/crates/truapi-coinage/src/balance.rs index b253365900..01c75608c5 100644 --- a/rust/crates/truapi-coinage/src/balance.rs +++ b/rust/crates/truapi-coinage/src/balance.rs @@ -2,248 +2,240 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use crate::denomination::DenominationBreakdownContext; -use crate::model::{ - Coin, CoinState, EffectivePrivacy, Voucher, VoucherLocalState, VoucherPrivacyLevel, +use crate::{ + denomination::DenominationBreakdownContext, + model::{Coin, CoinState, EffectivePrivacy, Voucher, VoucherLocalState, VoucherPrivacyLevel}, }; /// The three balance buckets, in planks. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct BalanceBuckets { - pub full_privacy_planks: u128, - pub degraded_planks: u128, - pub locked_planks: u128, + pub full_privacy_planks: u128, + pub degraded_planks: u128, + pub locked_planks: u128, } impl BalanceBuckets { - pub fn total_planks(&self) -> u128 { - self.full_privacy_planks - .saturating_add(self.degraded_planks) - .saturating_add(self.locked_planks) - } + pub fn total_planks(&self) -> u128 { + self.full_privacy_planks + .saturating_add(self.degraded_planks) + .saturating_add(self.locked_planks) + } } pub fn compute_balance( - coins: &[Coin], - vouchers: &[Voucher], - context: &DenominationBreakdownContext, - now_ms: i64, + coins: &[Coin], + vouchers: &[Voucher], + context: &DenominationBreakdownContext, + now_ms: i64, ) -> BalanceBuckets { - let mut buckets = BalanceBuckets::default(); - for coin in coins { - let value = context.value_in_planks(coin.exponent); - match coin.state { - CoinState::Available if coin.is_expiring_soon() => { - buckets.locked_planks = buckets.locked_planks.saturating_add(value); - } - CoinState::Available => { - buckets.full_privacy_planks = buckets.full_privacy_planks.saturating_add(value); - } - CoinState::Recycling => { - buckets.locked_planks = buckets.locked_planks.saturating_add(value); - } - CoinState::PendingTransfer | CoinState::Spent => {} - } - } - for voucher in vouchers { - if voucher.local_state != VoucherLocalState::Available { - continue; - } - let value = context.value_in_planks(voucher.exponent); - if !voucher.remote_state.is_in_recycler() { - buckets.locked_planks = buckets.locked_planks.saturating_add(value); - } else { - match voucher.effective_privacy(now_ms) { - EffectivePrivacy::Full => { - buckets.full_privacy_planks = buckets.full_privacy_planks.saturating_add(value); - } - EffectivePrivacy::Degraded => { - buckets.degraded_planks = buckets.degraded_planks.saturating_add(value); - } - } - } - } - buckets + let mut buckets = BalanceBuckets::default(); + for coin in coins { + let value = context.value_in_planks(coin.exponent); + match coin.state { + CoinState::Available if coin.is_expiring_soon() => { + buckets.locked_planks = buckets.locked_planks.saturating_add(value); + }, + CoinState::Available => { + buckets.full_privacy_planks = buckets.full_privacy_planks.saturating_add(value); + }, + CoinState::Recycling => { + buckets.locked_planks = buckets.locked_planks.saturating_add(value); + }, + CoinState::PendingTransfer | CoinState::Spent => {}, + } + } + for voucher in vouchers { + if voucher.local_state != VoucherLocalState::Available { + continue; + } + let value = context.value_in_planks(voucher.exponent); + if !voucher.remote_state.is_in_recycler() { + buckets.locked_planks = buckets.locked_planks.saturating_add(value); + } else { + match voucher.effective_privacy(now_ms) { + EffectivePrivacy::Full => { + buckets.full_privacy_planks = buckets.full_privacy_planks.saturating_add(value); + }, + EffectivePrivacy::Degraded => { + buckets.degraded_planks = buckets.degraded_planks.saturating_add(value); + }, + } + } + } + buckets } pub fn next_unlock_at_ms(vouchers: &[Voucher], now_ms: i64) -> Option { - vouchers - .iter() - .filter(|v| { - v.privacy == VoucherPrivacyLevel::Full - && v.local_state == VoucherLocalState::Available - && v.remote_state.is_in_recycler() - && v.ready_at_ms > now_ms - }) - .map(|v| v.ready_at_ms) - .min() + vouchers + .iter() + .filter(|v| { + v.privacy == VoucherPrivacyLevel::Full && + v.local_state == VoucherLocalState::Available && + v.remote_state.is_in_recycler() && + v.ready_at_ms > now_ms + }) + .map(|v| v.ready_at_ms) + .min() } #[cfg(test)] mod tests { - use super::*; - use crate::model::VoucherRemoteState; + use super::*; + use crate::model::VoucherRemoteState; - fn ctx() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 10, - max_exponent: 4, - min_exponent: 0, - precision: 10, - } - } + fn ctx() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 10, + max_exponent: 4, + min_exponent: 0, + precision: 10, + } + } - fn coin(index: u32, exponent: i16, age: Option, state: CoinState) -> Coin { - Coin { - exponent, - derivation_index: index, - age, - state, - } - } + fn coin(index: u32, exponent: i16, age: Option, state: CoinState) -> Coin { + Coin { exponent, derivation_index: index, age, state } + } - fn voucher( - index: u32, - exponent: i16, - remote: VoucherRemoteState, - local: VoucherLocalState, - privacy: VoucherPrivacyLevel, - ready_at_ms: i64, - ) -> Voucher { - Voucher { - exponent, - derivation_index: index, - allocated_at_ms: 0, - ready_at_ms, - remote_state: remote, - local_state: local, - privacy, - } - } + fn voucher( + index: u32, + exponent: i16, + remote: VoucherRemoteState, + local: VoucherLocalState, + privacy: VoucherPrivacyLevel, + ready_at_ms: i64, + ) -> Voucher { + Voucher { + exponent, + derivation_index: index, + allocated_at_ms: 0, + ready_at_ms, + remote_state: remote, + local_state: local, + privacy, + } + } - const NOW: i64 = 10_000; - const IN_RECYCLER: VoucherRemoteState = VoucherRemoteState::InRecycler { recycler_index: 0 }; + const NOW: i64 = 10_000; + const IN_RECYCLER: VoucherRemoteState = VoucherRemoteState::InRecycler { recycler_index: 0 }; - #[test] - fn decomposition_with_known_coin_and_voucher_sets() { - let coins = [ - coin(1, 0, Some(3), CoinState::Available), // 10 → full - coin(2, 1, None, CoinState::Available), // 20 → full (unsynced age) - coin(3, 2, Some(14), CoinState::Available), // 40 → locked (expiring) - coin(4, 3, Some(2), CoinState::Recycling), // 80 → locked - coin(5, 4, Some(2), CoinState::PendingTransfer), // reserved → nowhere - coin(6, 4, Some(2), CoinState::Spent), // gone → nowhere - ]; - let vouchers = [ - // 10 → full (ready, full privacy, in recycler). - voucher( - 10, - 0, - IN_RECYCLER, - VoucherLocalState::Available, - VoucherPrivacyLevel::Full, - NOW, - ), - // 20 → degraded (full privacy but not ready yet). - voucher( - 11, - 1, - IN_RECYCLER, - VoucherLocalState::Available, - VoucherPrivacyLevel::Full, - NOW + 1, - ), - // 40 → degraded (degraded at onboarding). - voucher( - 12, - 2, - IN_RECYCLER, - VoucherLocalState::Available, - VoucherPrivacyLevel::Degraded, - 0, - ), - // 80 → locked (not in a recycler yet). - voucher( - 13, - 3, - VoucherRemoteState::Onboarding, - VoucherLocalState::Available, - VoucherPrivacyLevel::Full, - 0, - ), - // reserved → nowhere. - voucher( - 14, - 4, - IN_RECYCLER, - VoucherLocalState::PendingTransfer, - VoucherPrivacyLevel::Full, - 0, - ), - ]; - let buckets = compute_balance(&coins, &vouchers, &ctx(), NOW); - assert_eq!(buckets.full_privacy_planks, 10 + 20 + 10); - assert_eq!(buckets.degraded_planks, 20 + 40); - assert_eq!(buckets.locked_planks, 40 + 80 + 80); - assert_eq!(buckets.total_planks(), 300); - } + #[test] + fn decomposition_with_known_coin_and_voucher_sets() { + let coins = [ + coin(1, 0, Some(3), CoinState::Available), // 10 → full + coin(2, 1, None, CoinState::Available), // 20 → full (unsynced age) + coin(3, 2, Some(14), CoinState::Available), // 40 → locked (expiring) + coin(4, 3, Some(2), CoinState::Recycling), // 80 → locked + coin(5, 4, Some(2), CoinState::PendingTransfer), // reserved → nowhere + coin(6, 4, Some(2), CoinState::Spent), // gone → nowhere + ]; + let vouchers = [ + // 10 → full (ready, full privacy, in recycler). + voucher( + 10, + 0, + IN_RECYCLER, + VoucherLocalState::Available, + VoucherPrivacyLevel::Full, + NOW, + ), + // 20 → degraded (full privacy but not ready yet). + voucher( + 11, + 1, + IN_RECYCLER, + VoucherLocalState::Available, + VoucherPrivacyLevel::Full, + NOW + 1, + ), + // 40 → degraded (degraded at onboarding). + voucher( + 12, + 2, + IN_RECYCLER, + VoucherLocalState::Available, + VoucherPrivacyLevel::Degraded, + 0, + ), + // 80 → locked (not in a recycler yet). + voucher( + 13, + 3, + VoucherRemoteState::Onboarding, + VoucherLocalState::Available, + VoucherPrivacyLevel::Full, + 0, + ), + // reserved → nowhere. + voucher( + 14, + 4, + IN_RECYCLER, + VoucherLocalState::PendingTransfer, + VoucherPrivacyLevel::Full, + 0, + ), + ]; + let buckets = compute_balance(&coins, &vouchers, &ctx(), NOW); + assert_eq!(buckets.full_privacy_planks, 10 + 20 + 10); + assert_eq!(buckets.degraded_planks, 20 + 40); + assert_eq!(buckets.locked_planks, 40 + 80 + 80); + assert_eq!(buckets.total_planks(), 300); + } - #[test] - fn empty_wallet_is_all_zero() { - assert_eq!( - compute_balance(&[], &[], &ctx(), NOW), - BalanceBuckets::default() - ); - } + #[test] + fn empty_wallet_is_all_zero() { + assert_eq!(compute_balance(&[], &[], &ctx(), NOW), BalanceBuckets::default()); + } - #[test] - fn next_unlock_picks_the_earliest_upgradeable_voucher() { - let vouchers = [ - voucher( - 1, - 0, - IN_RECYCLER, - VoucherLocalState::Available, - VoucherPrivacyLevel::Full, - NOW + 500, - ), - voucher( - 2, - 0, - IN_RECYCLER, - VoucherLocalState::Available, - VoucherPrivacyLevel::Full, - NOW + 100, - ), - // Already ready → no timer needed for it. - voucher( - 3, - 0, - IN_RECYCLER, - VoucherLocalState::Available, - VoucherPrivacyLevel::Full, - NOW, - ), - // Degraded privacy never upgrades → ignored. - voucher( - 4, - 0, - IN_RECYCLER, - VoucherLocalState::Available, - VoucherPrivacyLevel::Degraded, - NOW + 50, - ), - // Not in a recycler → ignored. - voucher( - 5, - 0, - VoucherRemoteState::Unlocated, - VoucherLocalState::Available, - VoucherPrivacyLevel::Full, - NOW + 10, - ), - ]; - assert_eq!(next_unlock_at_ms(&vouchers, NOW), Some(NOW + 100)); - assert_eq!(next_unlock_at_ms(&vouchers[2..], NOW), None); - } + #[test] + fn next_unlock_picks_the_earliest_upgradeable_voucher() { + let vouchers = [ + voucher( + 1, + 0, + IN_RECYCLER, + VoucherLocalState::Available, + VoucherPrivacyLevel::Full, + NOW + 500, + ), + voucher( + 2, + 0, + IN_RECYCLER, + VoucherLocalState::Available, + VoucherPrivacyLevel::Full, + NOW + 100, + ), + // Already ready → no timer needed for it. + voucher( + 3, + 0, + IN_RECYCLER, + VoucherLocalState::Available, + VoucherPrivacyLevel::Full, + NOW, + ), + // Degraded privacy never upgrades → ignored. + voucher( + 4, + 0, + IN_RECYCLER, + VoucherLocalState::Available, + VoucherPrivacyLevel::Degraded, + NOW + 50, + ), + // Not in a recycler → ignored. + voucher( + 5, + 0, + VoucherRemoteState::Unlocated, + VoucherLocalState::Available, + VoucherPrivacyLevel::Full, + NOW + 10, + ), + ]; + assert_eq!(next_unlock_at_ms(&vouchers, NOW), Some(NOW + 100)); + assert_eq!(next_unlock_at_ms(&vouchers[2..], NOW), None); + } } diff --git a/rust/crates/truapi-coinage/src/claim.rs b/rust/crates/truapi-coinage/src/claim.rs index 41aa15488a..43a391b529 100644 --- a/rust/crates/truapi-coinage/src/claim.rs +++ b/rust/crates/truapi-coinage/src/claim.rs @@ -2,169 +2,174 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use std::collections::{HashMap, HashSet}; -use {parking_lot::Mutex, std::sync::Arc}; +use parking_lot::Mutex; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use async_trait::async_trait; use tokio::sync::watch; use tracing::warn; -use crate::claim_plan::{ClaimPlan, ClaimPlanStatus, ClaimPlanStore, CodableClaimPlanEntry}; -use crate::constants::SEND_VERIFY_BLOCK_TIMEOUT; -use crate::denomination::DenominationBreakdownContext; +use crate::{ + claim_plan::{ClaimPlan, ClaimPlanStatus, ClaimPlanStore, CodableClaimPlanEntry}, + constants::SEND_VERIFY_BLOCK_TIMEOUT, + denomination::DenominationBreakdownContext, +}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum ClaimStatus { - /// Waiting for the send to appear on-chain. - Detecting, - /// Coins confirmed on-chain, awaiting claim. - Sent, - /// Claim extrinsic in flight. - Claiming, - Finished { - claimed_amount: u128, - }, - Error, + /// Waiting for the send to appear on-chain. + Detecting, + /// Coins confirmed on-chain, awaiting claim. + Sent, + /// Claim extrinsic in flight. + Claiming, + Finished { + claimed_amount: u128, + }, + Error, } impl ClaimStatus { - pub fn is_terminal(&self) -> bool { - matches!(self, ClaimStatus::Finished { .. } | ClaimStatus::Error) - } + pub fn is_terminal(&self) -> bool { + matches!(self, ClaimStatus::Finished { .. } | ClaimStatus::Error) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SendConfirmation { - OnChain, - AlreadyClaimed, + OnChain, + AlreadyClaimed, } #[async_trait] pub trait TransferSendVerifying: Send + Sync { - /// Resolves when the memo's coins are on-chain; errors on timeout. - async fn await_send_on_chain( - &self, - memo_key: &[u8; 32], - block_timeout: u32, - ) -> Result<(), String>; - - /// Resolves when the memo's coins have left the chain (claimed). - async fn await_claim_on_chain( - &self, - memo_key: &[u8; 32], - block_timeout: u32, - ) -> Result<(), String>; - - async fn await_send_or_claimed( - &self, - memo_key: &[u8; 32], - block_timeout: u32, - ) -> Result; + /// Resolves when the memo's coins are on-chain; errors on timeout. + async fn await_send_on_chain( + &self, + memo_key: &[u8; 32], + block_timeout: u32, + ) -> Result<(), String>; + + /// Resolves when the memo's coins have left the chain (claimed). + async fn await_claim_on_chain( + &self, + memo_key: &[u8; 32], + block_timeout: u32, + ) -> Result<(), String>; + + async fn await_send_or_claimed( + &self, + memo_key: &[u8; 32], + block_timeout: u32, + ) -> Result; } #[async_trait] pub trait ClaimExecutor: Send + Sync { - async fn claim( - &self, - memo_key: &[u8; 32], - message_id: &str, - ) -> Result, String>; + async fn claim( + &self, + memo_key: &[u8; 32], + message_id: &str, + ) -> Result, String>; } pub fn claimed_amount_from_plan(plan: &ClaimPlan, context: &DenominationBreakdownContext) -> u128 { - if plan.entries.is_empty() { - return plan.total_value; - } - plan.entries.iter().fold(0u128, |acc, entry| { - acc.saturating_add(context.value_in_planks(entry.exponent)) - }) + if plan.entries.is_empty() { + return plan.total_value; + } + plan.entries + .iter() + .fold(0u128, |acc, entry| acc.saturating_add(context.value_in_planks(entry.exponent))) } #[derive(Default)] pub struct ClaimStatusStore { - subjects: Mutex>>, - terminal: Mutex>, + subjects: Mutex>>, + terminal: Mutex>, } impl ClaimStatusStore { - /// Emits the current status immediately (the watch receiver's seed - /// value), then streams updates for live claims. For a terminal - /// message the receiver completes right after that seed read. - /// Returns `None` for a message id that was never seen. - pub fn watch_status(&self, message_id: &str) -> Option> { - if let Some(sender) = self.subjects.lock().get(message_id) { - return Some(sender.subscribe()); - } - let terminal = self.terminal.lock(); - let status = terminal.get(message_id)?; - // One-shot: seed a fresh channel and drop the sender so - // `changed` completes immediately after the seed read. - let (tx, rx) = watch::channel(status.clone()); - drop(tx); - Some(rx) - } - - /// Current status snapshot. - pub fn status(&self, message_id: &str) -> Option { - if let Some(sender) = self.subjects.lock().get(message_id) { - return Some(sender.borrow().clone()); - } - self.terminal.lock().get(message_id).cloned() - } - - pub fn update_status(&self, message_id: &str, status: ClaimStatus) { - let mut subjects = self.subjects.lock(); - if status.is_terminal() { - if let Some(sender) = subjects.remove(message_id) { - let _ = sender.send(status.clone()); - // Sender drops here → subscriber streams close. - } - self.terminal.lock().insert(message_id.to_string(), status); - return; - } - match subjects.get(message_id) { - Some(sender) => { - let _ = sender.send(status); - } - None => { - let (sender, _) = watch::channel(status); - subjects.insert(message_id.to_string(), sender); - } - } - } + /// Emits the current status immediately (the watch receiver's seed + /// value), then streams updates for live claims. For a terminal + /// message the receiver completes right after that seed read. + /// Returns `None` for a message id that was never seen. + pub fn watch_status(&self, message_id: &str) -> Option> { + if let Some(sender) = self.subjects.lock().get(message_id) { + return Some(sender.subscribe()); + } + let terminal = self.terminal.lock(); + let status = terminal.get(message_id)?; + // One-shot: seed a fresh channel and drop the sender so + // `changed` completes immediately after the seed read. + let (tx, rx) = watch::channel(status.clone()); + drop(tx); + Some(rx) + } + + /// Current status snapshot. + pub fn status(&self, message_id: &str) -> Option { + if let Some(sender) = self.subjects.lock().get(message_id) { + return Some(sender.borrow().clone()); + } + self.terminal.lock().get(message_id).cloned() + } + + pub fn update_status(&self, message_id: &str, status: ClaimStatus) { + let mut subjects = self.subjects.lock(); + if status.is_terminal() { + if let Some(sender) = subjects.remove(message_id) { + let _ = sender.send(status.clone()); + // Sender drops here → subscriber streams close. + } + self.terminal.lock().insert(message_id.to_string(), status); + return; + } + match subjects.get(message_id) { + Some(sender) => { + let _ = sender.send(status); + }, + None => { + let (sender, _) = watch::channel(status); + subjects.insert(message_id.to_string(), sender); + }, + } + } } pub fn restore_persisted_statuses(plans: &[ClaimPlan], store: &ClaimStatusStore) { - for plan in plans { - let Some(message_id) = &plan.message_id else { - continue; - }; - let status = match plan.status { - ClaimPlanStatus::Processing => ClaimStatus::Detecting, - ClaimPlanStatus::Detected => ClaimStatus::Sent, - ClaimPlanStatus::Finished => ClaimStatus::Finished { - claimed_amount: plan.claimed_amount.unwrap_or(plan.total_value), - }, - ClaimPlanStatus::Error => ClaimStatus::Error, - }; - store.update_status(message_id, status); - } + for plan in plans { + let Some(message_id) = &plan.message_id else { + continue; + }; + let status = match plan.status { + ClaimPlanStatus::Processing => ClaimStatus::Detecting, + ClaimPlanStatus::Detected => ClaimStatus::Sent, + ClaimPlanStatus::Finished => ClaimStatus::Finished { + claimed_amount: plan.claimed_amount.unwrap_or(plan.total_value), + }, + ClaimPlanStatus::Error => ClaimStatus::Error, + }; + store.update_status(message_id, status); + } } /// Claim orchestration errors. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ClaimError { - AlreadyClaiming, - Failed(String), + AlreadyClaiming, + Failed(String), } impl std::fmt::Display for ClaimError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - ClaimError::AlreadyClaiming => write!(f, "already claiming this memo"), - ClaimError::Failed(message) => write!(f, "{message}"), - } - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ClaimError::AlreadyClaiming => write!(f, "already claiming this memo"), + ClaimError::Failed(message) => write!(f, "{message}"), + } + } } impl std::error::Error for ClaimError {} @@ -172,584 +177,501 @@ impl std::error::Error for ClaimError {} /// One incoming `coinageSend` to claim. #[derive(Debug, Clone)] pub struct IncomingClaim { - pub memo_key: [u8; 32], - pub message_id: String, - pub total_value: u128, + pub memo_key: [u8; 32], + pub message_id: String, + pub total_value: u128, } pub struct ClaimOrchestrator { - plans: Arc, - verifier: Arc, - executor: Arc, - statuses: Arc, - context: DenominationBreakdownContext, - claiming_memos: Mutex>, + plans: Arc, + verifier: Arc, + executor: Arc, + statuses: Arc, + context: DenominationBreakdownContext, + claiming_memos: Mutex>, } impl ClaimOrchestrator { - pub fn new( - plans: Arc, - verifier: Arc, - executor: Arc, - statuses: Arc, - context: DenominationBreakdownContext, - ) -> Self { - Self { - plans, - verifier, - executor, - statuses, - context, - claiming_memos: Mutex::new(HashSet::new()), - } - } - - pub async fn restore_persisted_statuses(&self) -> Result<(), String> { - let plans = self.plans.load_all().await?; - restore_persisted_statuses(&plans, &self.statuses); - Ok(()) - } - - /// Claims one incoming memo; resolves the claimed planks. - pub async fn claim_incoming(&self, incoming: IncomingClaim) -> Result { - { - let mut claiming = self.claiming_memos.lock(); - if !claiming.insert(incoming.memo_key) { - return Err(ClaimError::AlreadyClaiming); - } - } - let _guard = ClaimingGuard { - memo_key: incoming.memo_key, - claiming: &self.claiming_memos, - }; - - let outcome = self.claim_inner(&incoming).await; - if let Err(ClaimError::Failed(message)) = &outcome { - warn!(message, message_id = incoming.message_id, "claim failed"); - if let Err(error) = self - .plans - .update_status(&incoming.memo_key, ClaimPlanStatus::Error, None) - .await - { - warn!(error, "claim error status stamp failed"); - } - self.statuses - .update_status(&incoming.message_id, ClaimStatus::Error); - } - outcome - } - - async fn claim_inner(&self, incoming: &IncomingClaim) -> Result { - let existing = self - .plans - .plan(&incoming.memo_key) - .await - .map_err(ClaimError::Failed)?; - - match &existing { - Some(plan) if plan.status == ClaimPlanStatus::Finished => { - let claimed = plan - .claimed_amount - .unwrap_or_else(|| claimed_amount_from_plan(plan, &self.context)); - self.statuses.update_status( - &incoming.message_id, - ClaimStatus::Finished { - claimed_amount: claimed, - }, - ); - return Ok(claimed); - } - Some(_) => {} - None => { - self.statuses - .update_status(&incoming.message_id, ClaimStatus::Detecting); - self.verifier - .await_send_on_chain(&incoming.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) - .await - .map_err(ClaimError::Failed)?; - self.plans - .save(&ClaimPlan { - memo_key: incoming.memo_key, - message_id: Some(incoming.message_id.clone()), - entries: Vec::new(), - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Processing, - claimed_amount: None, - total_value: incoming.total_value, - markers: crate::claim_plan::ClaimMarkers::default(), - }) - .await - .map_err(ClaimError::Failed)?; - } - } - - self.statuses - .update_status(&incoming.message_id, ClaimStatus::Claiming); - let entries = self - .executor - .claim(&incoming.memo_key, &incoming.message_id) - .await - .map_err(ClaimError::Failed)?; - - let finished = ClaimPlan { - memo_key: incoming.memo_key, - message_id: Some(incoming.message_id.clone()), - entries, - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Finished, - claimed_amount: None, - total_value: incoming.total_value, - markers: crate::claim_plan::ClaimMarkers::default(), - }; - let claimed = claimed_amount_from_plan(&finished, &self.context); - self.plans - .update_status(&incoming.memo_key, ClaimPlanStatus::Finished, Some(claimed)) - .await - .map_err(ClaimError::Failed)?; - self.statuses.update_status( - &incoming.message_id, - ClaimStatus::Finished { - claimed_amount: claimed, - }, - ); - Ok(claimed) - } + pub fn new( + plans: Arc, + verifier: Arc, + executor: Arc, + statuses: Arc, + context: DenominationBreakdownContext, + ) -> Self { + Self { + plans, + verifier, + executor, + statuses, + context, + claiming_memos: Mutex::new(HashSet::new()), + } + } + + pub async fn restore_persisted_statuses(&self) -> Result<(), String> { + let plans = self.plans.load_all().await?; + restore_persisted_statuses(&plans, &self.statuses); + Ok(()) + } + + /// Claims one incoming memo; resolves the claimed planks. + pub async fn claim_incoming(&self, incoming: IncomingClaim) -> Result { + { + let mut claiming = self.claiming_memos.lock(); + if !claiming.insert(incoming.memo_key) { + return Err(ClaimError::AlreadyClaiming); + } + } + let _guard = ClaimingGuard { memo_key: incoming.memo_key, claiming: &self.claiming_memos }; + + let outcome = self.claim_inner(&incoming).await; + if let Err(ClaimError::Failed(message)) = &outcome { + warn!(message, message_id = incoming.message_id, "claim failed"); + if let Err(error) = + self.plans.update_status(&incoming.memo_key, ClaimPlanStatus::Error, None).await + { + warn!(error, "claim error status stamp failed"); + } + self.statuses.update_status(&incoming.message_id, ClaimStatus::Error); + } + outcome + } + + async fn claim_inner(&self, incoming: &IncomingClaim) -> Result { + let existing = self.plans.plan(&incoming.memo_key).await.map_err(ClaimError::Failed)?; + + match &existing { + Some(plan) if plan.status == ClaimPlanStatus::Finished => { + let claimed = plan + .claimed_amount + .unwrap_or_else(|| claimed_amount_from_plan(plan, &self.context)); + self.statuses.update_status( + &incoming.message_id, + ClaimStatus::Finished { claimed_amount: claimed }, + ); + return Ok(claimed); + }, + Some(_) => {}, + None => { + self.statuses.update_status(&incoming.message_id, ClaimStatus::Detecting); + self.verifier + .await_send_on_chain(&incoming.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) + .await + .map_err(ClaimError::Failed)?; + self.plans + .save(&ClaimPlan { + memo_key: incoming.memo_key, + message_id: Some(incoming.message_id.clone()), + entries: Vec::new(), + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Processing, + claimed_amount: None, + total_value: incoming.total_value, + markers: crate::claim_plan::ClaimMarkers::default(), + }) + .await + .map_err(ClaimError::Failed)?; + }, + } + + self.statuses.update_status(&incoming.message_id, ClaimStatus::Claiming); + let entries = self + .executor + .claim(&incoming.memo_key, &incoming.message_id) + .await + .map_err(ClaimError::Failed)?; + + let finished = ClaimPlan { + memo_key: incoming.memo_key, + message_id: Some(incoming.message_id.clone()), + entries, + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Finished, + claimed_amount: None, + total_value: incoming.total_value, + markers: crate::claim_plan::ClaimMarkers::default(), + }; + let claimed = claimed_amount_from_plan(&finished, &self.context); + self.plans + .update_status(&incoming.memo_key, ClaimPlanStatus::Finished, Some(claimed)) + .await + .map_err(ClaimError::Failed)?; + self.statuses + .update_status(&incoming.message_id, ClaimStatus::Finished { claimed_amount: claimed }); + Ok(claimed) + } } struct ClaimingGuard<'a> { - memo_key: [u8; 32], - claiming: &'a Mutex>, + memo_key: [u8; 32], + claiming: &'a Mutex>, } impl Drop for ClaimingGuard<'_> { - fn drop(&mut self) { - self.claiming.lock().remove(&self.memo_key); - } + fn drop(&mut self) { + self.claiming.lock().remove(&self.memo_key); + } } #[cfg(test)] mod tests { - use std::sync::atomic::{AtomicUsize, Ordering}; - - use super::*; - - fn ctx() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 10, - max_exponent: 4, - min_exponent: 0, - precision: 10, - } - } - - fn entry(exponent: i16) -> CodableClaimPlanEntry { - CodableClaimPlanEntry { - entry_index: 0, - exponent, - derivation_index: 1, - } - } - - fn plan(entries: Vec, status: ClaimPlanStatus) -> ClaimPlan { - ClaimPlan { - memo_key: [7; 32], - message_id: Some("m1".into()), - entries, - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status, - claimed_amount: None, - total_value: 990, - markers: crate::claim_plan::ClaimMarkers::default(), - } - } - - #[test] - fn claimed_amount_sums_entry_denominations() { - let plan = plan( - vec![entry(4), entry(2), entry(0)], - ClaimPlanStatus::Finished, - ); - assert_eq!(claimed_amount_from_plan(&plan, &ctx()), 210); - } - - #[test] - fn claimed_amount_falls_back_to_total_value() { - let plan = plan(Vec::new(), ClaimPlanStatus::Finished); - assert_eq!(claimed_amount_from_plan(&plan, &ctx()), 990); - } - - #[tokio::test] - async fn watch_emits_current_then_streams_updates() { - let store = ClaimStatusStore::default(); - store.update_status("m1", ClaimStatus::Detecting); - let mut rx = store.watch_status("m1").unwrap(); - assert_eq!( - *rx.borrow(), - ClaimStatus::Detecting, - "immediate current value" - ); - store.update_status("m1", ClaimStatus::Claiming); - rx.changed().await.unwrap(); - assert_eq!(*rx.borrow(), ClaimStatus::Claiming); - } - - #[tokio::test] - async fn terminal_status_closes_and_cleans_up() { - let store = ClaimStatusStore::default(); - store.update_status("m1", ClaimStatus::Claiming); - let mut live = store.watch_status("m1").unwrap(); - - store.update_status("m1", ClaimStatus::Finished { claimed_amount: 5 }); - live.changed().await.unwrap(); - assert_eq!(*live.borrow(), ClaimStatus::Finished { claimed_amount: 5 }); - assert!( - live.changed().await.is_err(), - "stream completes after terminal" - ); - assert!( - store.subjects.lock().is_empty(), - "subject removed after terminal send" - ); - - // Late watcher: value once, then complete. - let mut late = store.watch_status("m1").unwrap(); - assert_eq!(*late.borrow(), ClaimStatus::Finished { claimed_amount: 5 }); - assert!(late.changed().await.is_err()); - assert!(store.watch_status("unknown").is_none()); - } - - #[test] - fn restore_maps_plan_statuses_to_claim_statuses() { - let store = ClaimStatusStore::default(); - let mut processing = plan(Vec::new(), ClaimPlanStatus::Processing); - processing.message_id = Some("p".into()); - let mut detected = plan(Vec::new(), ClaimPlanStatus::Detected); - detected.message_id = Some("d".into()); - let mut finished = plan(Vec::new(), ClaimPlanStatus::Finished); - finished.message_id = Some("f".into()); - finished.claimed_amount = Some(123); - let mut finished_no_amount = plan(Vec::new(), ClaimPlanStatus::Finished); - finished_no_amount.message_id = Some("f2".into()); - let mut errored = plan(Vec::new(), ClaimPlanStatus::Error); - errored.message_id = Some("e".into()); - let mut no_message = plan(Vec::new(), ClaimPlanStatus::Processing); - no_message.message_id = None; - - restore_persisted_statuses( - &[ - processing, - detected, - finished, - finished_no_amount, - errored, - no_message, - ], - &store, - ); - assert_eq!(store.status("p"), Some(ClaimStatus::Detecting)); - assert_eq!(store.status("d"), Some(ClaimStatus::Sent)); - assert_eq!( - store.status("f"), - Some(ClaimStatus::Finished { - claimed_amount: 123 - }) - ); - assert_eq!( - store.status("f2"), - Some(ClaimStatus::Finished { - claimed_amount: 990 - }), - "missing claimed_amount falls back to total_value" - ); - assert_eq!(store.status("e"), Some(ClaimStatus::Error)); - } - - // — orchestrator plumbing — - - #[derive(Default)] - struct MemPlans { - plans: Mutex>, - saves: AtomicUsize, - } - - #[async_trait] - impl ClaimPlanStore for MemPlans { - async fn save(&self, plan: &ClaimPlan) -> Result<(), String> { - self.saves.fetch_add(1, Ordering::SeqCst); - self.plans.lock().insert(plan.memo_key, plan.clone()); - Ok(()) - } - async fn plan(&self, memo_key: &[u8; 32]) -> Result, String> { - Ok(self.plans.lock().get(memo_key).cloned()) - } - async fn load_all(&self) -> Result, String> { - Ok(self.plans.lock().values().cloned().collect()) - } - async fn update_status( - &self, - memo_key: &[u8; 32], - status: ClaimPlanStatus, - claimed_amount: Option, - ) -> Result<(), String> { - let mut plans = self.plans.lock(); - let plan = plans.get_mut(memo_key).ok_or("plan not found")?; - plan.status = status; - plan.claimed_amount = claimed_amount; - Ok(()) - } - async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String> { - self.plans.lock().remove(memo_key); - Ok(()) - } - } - - #[derive(Default)] - struct MockVerifier { - send_awaits: AtomicUsize, - } - - #[async_trait] - impl TransferSendVerifying for MockVerifier { - async fn await_send_on_chain( - &self, - _memo_key: &[u8; 32], - block_timeout: u32, - ) -> Result<(), String> { - assert_eq!(block_timeout, 100, "COINM-024: 100-block timeout"); - self.send_awaits.fetch_add(1, Ordering::SeqCst); - Ok(()) - } - async fn await_claim_on_chain( - &self, - _memo_key: &[u8; 32], - _block_timeout: u32, - ) -> Result<(), String> { - Ok(()) - } - async fn await_send_or_claimed( - &self, - _memo_key: &[u8; 32], - _block_timeout: u32, - ) -> Result { - Ok(SendConfirmation::OnChain) - } - } - - struct MockExecutor { - plans: Arc, - saves_seen_at_claim: AtomicUsize, - calls: AtomicUsize, - outcome: Result, String>, - release: Option>, - } - - #[async_trait] - impl ClaimExecutor for MockExecutor { - async fn claim( - &self, - memo_key: &[u8; 32], - _message_id: &str, - ) -> Result, String> { - self.calls.fetch_add(1, Ordering::SeqCst); - self.saves_seen_at_claim - .store(self.plans.saves.load(Ordering::SeqCst), Ordering::SeqCst); - assert!( - self.plans.plan(memo_key).await.unwrap().is_some(), - "plan must be persisted before the claim executor runs (COINA-016)" - ); - if let Some(release) = &self.release { - let mut release = release.clone(); - while !*release.borrow() { - if release.changed().await.is_err() { - break; - } - } - } - self.outcome.clone() - } - } - - fn orchestrator( - plans: Arc, - verifier: Arc, - executor: Arc, - ) -> ClaimOrchestrator { - ClaimOrchestrator::new( - plans, - verifier, - executor, - Arc::new(ClaimStatusStore::default()), - ctx(), - ) - } - - fn incoming() -> IncomingClaim { - IncomingClaim { - memo_key: [7; 32], - message_id: "m1".into(), - total_value: 990, - } - } - - #[tokio::test] - async fn fresh_claim_saves_plan_before_submitting() { - let plans = Arc::new(MemPlans::default()); - let verifier = Arc::new(MockVerifier::default()); - let executor = Arc::new(MockExecutor { - plans: Arc::clone(&plans), - saves_seen_at_claim: AtomicUsize::new(0), - calls: AtomicUsize::new(0), - outcome: Ok(vec![entry(2), entry(0)]), // 40 + 10 - release: None, - }); - let orchestrator = orchestrator( - Arc::clone(&plans), - Arc::clone(&verifier), - Arc::clone(&executor), - ); - - let claimed = orchestrator.claim_incoming(incoming()).await.unwrap(); - assert_eq!(claimed, 50); - assert_eq!(verifier.send_awaits.load(Ordering::SeqCst), 1); - assert!( - executor.saves_seen_at_claim.load(Ordering::SeqCst) >= 1, - "save-before-submit (COINA-016)" - ); - let stored = plans.plan(&[7; 32]).await.unwrap().unwrap(); - assert_eq!(stored.status, ClaimPlanStatus::Finished); - assert_eq!(stored.claimed_amount, Some(50)); - assert!( - stored.entries.is_empty(), - "finish is the status-only path — entries_data untouched (COINM-006)" - ); - assert_eq!( - orchestrator.statuses.status("m1"), - Some(ClaimStatus::Finished { claimed_amount: 50 }) - ); - } - - #[tokio::test] - async fn existing_plan_short_circuits_the_send_await() { - let plans = Arc::new(MemPlans::default()); - plans - .save(&plan(Vec::new(), ClaimPlanStatus::Processing)) - .await - .unwrap(); - let verifier = Arc::new(MockVerifier::default()); - let executor = Arc::new(MockExecutor { - plans: Arc::clone(&plans), - saves_seen_at_claim: AtomicUsize::new(0), - calls: AtomicUsize::new(0), - outcome: Ok(vec![entry(0)]), - release: None, - }); - let orchestrator = orchestrator( - Arc::clone(&plans), - Arc::clone(&verifier), - Arc::clone(&executor), - ); - - let claimed = orchestrator.claim_incoming(incoming()).await.unwrap(); - assert_eq!(claimed, 10); - assert_eq!( - verifier.send_awaits.load(Ordering::SeqCst), - 0, - "crash-recovery safety: input coins may already be spent (COINM-022)" - ); - assert_eq!(executor.calls.load(Ordering::SeqCst), 1, "claim still runs"); - } - - #[tokio::test] - async fn finished_plan_is_reported_without_reclaiming() { - let plans = Arc::new(MemPlans::default()); - let mut finished = plan(Vec::new(), ClaimPlanStatus::Finished); - finished.claimed_amount = Some(321); - plans.save(&finished).await.unwrap(); - let verifier = Arc::new(MockVerifier::default()); - let executor = Arc::new(MockExecutor { - plans: Arc::clone(&plans), - saves_seen_at_claim: AtomicUsize::new(0), - calls: AtomicUsize::new(0), - outcome: Ok(Vec::new()), - release: None, - }); - let orchestrator = orchestrator(plans, verifier.clone(), Arc::clone(&executor)); - - assert_eq!(orchestrator.claim_incoming(incoming()).await.unwrap(), 321); - assert_eq!(verifier.send_awaits.load(Ordering::SeqCst), 0); - assert_eq!(executor.calls.load(Ordering::SeqCst), 0); - } - - #[tokio::test] - async fn concurrent_claim_for_the_same_memo_is_rejected() { - let (release_tx, release_rx) = watch::channel(false); - let plans = Arc::new(MemPlans::default()); - plans - .save(&plan(Vec::new(), ClaimPlanStatus::Processing)) - .await - .unwrap(); - let executor = Arc::new(MockExecutor { - plans: Arc::clone(&plans), - saves_seen_at_claim: AtomicUsize::new(0), - calls: AtomicUsize::new(0), - outcome: Ok(Vec::new()), - release: Some(release_rx), - }); - let orchestrator = Arc::new(orchestrator( - plans, - Arc::new(MockVerifier::default()), - executor, - )); - - let first = tokio::spawn({ - let orchestrator = Arc::clone(&orchestrator); - async move { orchestrator.claim_incoming(incoming()).await } - }); - // Let the first claim reach the stalled executor. - for _ in 0..32 { - tokio::task::yield_now().await; - } - assert_eq!( - orchestrator.claim_incoming(incoming()).await, - Err(ClaimError::AlreadyClaiming) - ); - release_tx.send(true).unwrap(); - first.await.unwrap().unwrap(); - assert!(orchestrator.claim_incoming(incoming()).await.is_ok()); - } - - #[tokio::test] - async fn failed_claim_stamps_error() { - let plans = Arc::new(MemPlans::default()); - plans - .save(&plan(Vec::new(), ClaimPlanStatus::Processing)) - .await - .unwrap(); - let executor = Arc::new(MockExecutor { - plans: Arc::clone(&plans), - saves_seen_at_claim: AtomicUsize::new(0), - calls: AtomicUsize::new(0), - outcome: Err("CoinPayment: Unavailable".into()), - release: None, - }); - let orchestrator = orchestrator( - Arc::clone(&plans), - Arc::new(MockVerifier::default()), - executor, - ); - - let outcome = orchestrator.claim_incoming(incoming()).await; - assert_eq!( - outcome, - Err(ClaimError::Failed("CoinPayment: Unavailable".into())) - ); - assert_eq!( - plans.plan(&[7; 32]).await.unwrap().unwrap().status, - ClaimPlanStatus::Error - ); - assert_eq!(orchestrator.statuses.status("m1"), Some(ClaimStatus::Error)); - } + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + + fn ctx() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 10, + max_exponent: 4, + min_exponent: 0, + precision: 10, + } + } + + fn entry(exponent: i16) -> CodableClaimPlanEntry { + CodableClaimPlanEntry { entry_index: 0, exponent, derivation_index: 1 } + } + + fn plan(entries: Vec, status: ClaimPlanStatus) -> ClaimPlan { + ClaimPlan { + memo_key: [7; 32], + message_id: Some("m1".into()), + entries, + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status, + claimed_amount: None, + total_value: 990, + markers: crate::claim_plan::ClaimMarkers::default(), + } + } + + #[test] + fn claimed_amount_sums_entry_denominations() { + let plan = plan(vec![entry(4), entry(2), entry(0)], ClaimPlanStatus::Finished); + assert_eq!(claimed_amount_from_plan(&plan, &ctx()), 210); + } + + #[test] + fn claimed_amount_falls_back_to_total_value() { + let plan = plan(Vec::new(), ClaimPlanStatus::Finished); + assert_eq!(claimed_amount_from_plan(&plan, &ctx()), 990); + } + + #[tokio::test] + async fn watch_emits_current_then_streams_updates() { + let store = ClaimStatusStore::default(); + store.update_status("m1", ClaimStatus::Detecting); + let mut rx = store.watch_status("m1").unwrap(); + assert_eq!(*rx.borrow(), ClaimStatus::Detecting, "immediate current value"); + store.update_status("m1", ClaimStatus::Claiming); + rx.changed().await.unwrap(); + assert_eq!(*rx.borrow(), ClaimStatus::Claiming); + } + + #[tokio::test] + async fn terminal_status_closes_and_cleans_up() { + let store = ClaimStatusStore::default(); + store.update_status("m1", ClaimStatus::Claiming); + let mut live = store.watch_status("m1").unwrap(); + + store.update_status("m1", ClaimStatus::Finished { claimed_amount: 5 }); + live.changed().await.unwrap(); + assert_eq!(*live.borrow(), ClaimStatus::Finished { claimed_amount: 5 }); + assert!(live.changed().await.is_err(), "stream completes after terminal"); + assert!(store.subjects.lock().is_empty(), "subject removed after terminal send"); + + // Late watcher: value once, then complete. + let mut late = store.watch_status("m1").unwrap(); + assert_eq!(*late.borrow(), ClaimStatus::Finished { claimed_amount: 5 }); + assert!(late.changed().await.is_err()); + assert!(store.watch_status("unknown").is_none()); + } + + #[test] + fn restore_maps_plan_statuses_to_claim_statuses() { + let store = ClaimStatusStore::default(); + let mut processing = plan(Vec::new(), ClaimPlanStatus::Processing); + processing.message_id = Some("p".into()); + let mut detected = plan(Vec::new(), ClaimPlanStatus::Detected); + detected.message_id = Some("d".into()); + let mut finished = plan(Vec::new(), ClaimPlanStatus::Finished); + finished.message_id = Some("f".into()); + finished.claimed_amount = Some(123); + let mut finished_no_amount = plan(Vec::new(), ClaimPlanStatus::Finished); + finished_no_amount.message_id = Some("f2".into()); + let mut errored = plan(Vec::new(), ClaimPlanStatus::Error); + errored.message_id = Some("e".into()); + let mut no_message = plan(Vec::new(), ClaimPlanStatus::Processing); + no_message.message_id = None; + + restore_persisted_statuses( + &[processing, detected, finished, finished_no_amount, errored, no_message], + &store, + ); + assert_eq!(store.status("p"), Some(ClaimStatus::Detecting)); + assert_eq!(store.status("d"), Some(ClaimStatus::Sent)); + assert_eq!(store.status("f"), Some(ClaimStatus::Finished { claimed_amount: 123 })); + assert_eq!( + store.status("f2"), + Some(ClaimStatus::Finished { claimed_amount: 990 }), + "missing claimed_amount falls back to total_value" + ); + assert_eq!(store.status("e"), Some(ClaimStatus::Error)); + } + + // — orchestrator plumbing — + + #[derive(Default)] + struct MemPlans { + plans: Mutex>, + saves: AtomicUsize, + } + + #[async_trait] + impl ClaimPlanStore for MemPlans { + async fn save(&self, plan: &ClaimPlan) -> Result<(), String> { + self.saves.fetch_add(1, Ordering::SeqCst); + self.plans.lock().insert(plan.memo_key, plan.clone()); + Ok(()) + } + async fn plan(&self, memo_key: &[u8; 32]) -> Result, String> { + Ok(self.plans.lock().get(memo_key).cloned()) + } + async fn load_all(&self) -> Result, String> { + Ok(self.plans.lock().values().cloned().collect()) + } + async fn update_status( + &self, + memo_key: &[u8; 32], + status: ClaimPlanStatus, + claimed_amount: Option, + ) -> Result<(), String> { + let mut plans = self.plans.lock(); + let plan = plans.get_mut(memo_key).ok_or("plan not found")?; + plan.status = status; + plan.claimed_amount = claimed_amount; + Ok(()) + } + async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String> { + self.plans.lock().remove(memo_key); + Ok(()) + } + } + + #[derive(Default)] + struct MockVerifier { + send_awaits: AtomicUsize, + } + + #[async_trait] + impl TransferSendVerifying for MockVerifier { + async fn await_send_on_chain( + &self, + _memo_key: &[u8; 32], + block_timeout: u32, + ) -> Result<(), String> { + assert_eq!(block_timeout, 100, "COINM-024: 100-block timeout"); + self.send_awaits.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + async fn await_claim_on_chain( + &self, + _memo_key: &[u8; 32], + _block_timeout: u32, + ) -> Result<(), String> { + Ok(()) + } + async fn await_send_or_claimed( + &self, + _memo_key: &[u8; 32], + _block_timeout: u32, + ) -> Result { + Ok(SendConfirmation::OnChain) + } + } + + struct MockExecutor { + plans: Arc, + saves_seen_at_claim: AtomicUsize, + calls: AtomicUsize, + outcome: Result, String>, + release: Option>, + } + + #[async_trait] + impl ClaimExecutor for MockExecutor { + async fn claim( + &self, + memo_key: &[u8; 32], + _message_id: &str, + ) -> Result, String> { + self.calls.fetch_add(1, Ordering::SeqCst); + self.saves_seen_at_claim + .store(self.plans.saves.load(Ordering::SeqCst), Ordering::SeqCst); + assert!( + self.plans.plan(memo_key).await.unwrap().is_some(), + "plan must be persisted before the claim executor runs (COINA-016)" + ); + if let Some(release) = &self.release { + let mut release = release.clone(); + while !*release.borrow() { + if release.changed().await.is_err() { + break; + } + } + } + self.outcome.clone() + } + } + + fn orchestrator( + plans: Arc, + verifier: Arc, + executor: Arc, + ) -> ClaimOrchestrator { + ClaimOrchestrator::new( + plans, + verifier, + executor, + Arc::new(ClaimStatusStore::default()), + ctx(), + ) + } + + fn incoming() -> IncomingClaim { + IncomingClaim { memo_key: [7; 32], message_id: "m1".into(), total_value: 990 } + } + + #[tokio::test] + async fn fresh_claim_saves_plan_before_submitting() { + let plans = Arc::new(MemPlans::default()); + let verifier = Arc::new(MockVerifier::default()); + let executor = Arc::new(MockExecutor { + plans: Arc::clone(&plans), + saves_seen_at_claim: AtomicUsize::new(0), + calls: AtomicUsize::new(0), + outcome: Ok(vec![entry(2), entry(0)]), // 40 + 10 + release: None, + }); + let orchestrator = + orchestrator(Arc::clone(&plans), Arc::clone(&verifier), Arc::clone(&executor)); + + let claimed = orchestrator.claim_incoming(incoming()).await.unwrap(); + assert_eq!(claimed, 50); + assert_eq!(verifier.send_awaits.load(Ordering::SeqCst), 1); + assert!( + executor.saves_seen_at_claim.load(Ordering::SeqCst) >= 1, + "save-before-submit (COINA-016)" + ); + let stored = plans.plan(&[7; 32]).await.unwrap().unwrap(); + assert_eq!(stored.status, ClaimPlanStatus::Finished); + assert_eq!(stored.claimed_amount, Some(50)); + assert!( + stored.entries.is_empty(), + "finish is the status-only path — entries_data untouched (COINM-006)" + ); + assert_eq!( + orchestrator.statuses.status("m1"), + Some(ClaimStatus::Finished { claimed_amount: 50 }) + ); + } + + #[tokio::test] + async fn existing_plan_short_circuits_the_send_await() { + let plans = Arc::new(MemPlans::default()); + plans.save(&plan(Vec::new(), ClaimPlanStatus::Processing)).await.unwrap(); + let verifier = Arc::new(MockVerifier::default()); + let executor = Arc::new(MockExecutor { + plans: Arc::clone(&plans), + saves_seen_at_claim: AtomicUsize::new(0), + calls: AtomicUsize::new(0), + outcome: Ok(vec![entry(0)]), + release: None, + }); + let orchestrator = + orchestrator(Arc::clone(&plans), Arc::clone(&verifier), Arc::clone(&executor)); + + let claimed = orchestrator.claim_incoming(incoming()).await.unwrap(); + assert_eq!(claimed, 10); + assert_eq!( + verifier.send_awaits.load(Ordering::SeqCst), + 0, + "crash-recovery safety: input coins may already be spent (COINM-022)" + ); + assert_eq!(executor.calls.load(Ordering::SeqCst), 1, "claim still runs"); + } + + #[tokio::test] + async fn finished_plan_is_reported_without_reclaiming() { + let plans = Arc::new(MemPlans::default()); + let mut finished = plan(Vec::new(), ClaimPlanStatus::Finished); + finished.claimed_amount = Some(321); + plans.save(&finished).await.unwrap(); + let verifier = Arc::new(MockVerifier::default()); + let executor = Arc::new(MockExecutor { + plans: Arc::clone(&plans), + saves_seen_at_claim: AtomicUsize::new(0), + calls: AtomicUsize::new(0), + outcome: Ok(Vec::new()), + release: None, + }); + let orchestrator = orchestrator(plans, verifier.clone(), Arc::clone(&executor)); + + assert_eq!(orchestrator.claim_incoming(incoming()).await.unwrap(), 321); + assert_eq!(verifier.send_awaits.load(Ordering::SeqCst), 0); + assert_eq!(executor.calls.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn concurrent_claim_for_the_same_memo_is_rejected() { + let (release_tx, release_rx) = watch::channel(false); + let plans = Arc::new(MemPlans::default()); + plans.save(&plan(Vec::new(), ClaimPlanStatus::Processing)).await.unwrap(); + let executor = Arc::new(MockExecutor { + plans: Arc::clone(&plans), + saves_seen_at_claim: AtomicUsize::new(0), + calls: AtomicUsize::new(0), + outcome: Ok(Vec::new()), + release: Some(release_rx), + }); + let orchestrator = + Arc::new(orchestrator(plans, Arc::new(MockVerifier::default()), executor)); + + let first = tokio::spawn({ + let orchestrator = Arc::clone(&orchestrator); + async move { orchestrator.claim_incoming(incoming()).await } + }); + // Let the first claim reach the stalled executor. + for _ in 0..32 { + tokio::task::yield_now().await; + } + assert_eq!(orchestrator.claim_incoming(incoming()).await, Err(ClaimError::AlreadyClaiming)); + release_tx.send(true).unwrap(); + first.await.unwrap().unwrap(); + assert!(orchestrator.claim_incoming(incoming()).await.is_ok()); + } + + #[tokio::test] + async fn failed_claim_stamps_error() { + let plans = Arc::new(MemPlans::default()); + plans.save(&plan(Vec::new(), ClaimPlanStatus::Processing)).await.unwrap(); + let executor = Arc::new(MockExecutor { + plans: Arc::clone(&plans), + saves_seen_at_claim: AtomicUsize::new(0), + calls: AtomicUsize::new(0), + outcome: Err("CoinPayment: Unavailable".into()), + release: None, + }); + let orchestrator = + orchestrator(Arc::clone(&plans), Arc::new(MockVerifier::default()), executor); + + let outcome = orchestrator.claim_incoming(incoming()).await; + assert_eq!(outcome, Err(ClaimError::Failed("CoinPayment: Unavailable".into()))); + assert_eq!(plans.plan(&[7; 32]).await.unwrap().unwrap().status, ClaimPlanStatus::Error); + assert_eq!(orchestrator.statuses.status("m1"), Some(ClaimStatus::Error)); + } } diff --git a/rust/crates/truapi-coinage/src/claim_plan.rs b/rust/crates/truapi-coinage/src/claim_plan.rs index 2ca940defc..121f98032a 100644 --- a/rust/crates/truapi-coinage/src/claim_plan.rs +++ b/rust/crates/truapi-coinage/src/claim_plan.rs @@ -7,170 +7,155 @@ use parity_scale_codec::{Decode, Encode}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub struct CodableClaimPlanEntry { - pub entry_index: i16, - /// The destination coin's denomination exponent. - pub exponent: i16, - /// The destination coin's derivation index. - pub derivation_index: u32, + pub entry_index: i16, + /// The destination coin's denomination exponent. + pub exponent: i16, + /// The destination coin's derivation index. + pub derivation_index: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ClaimPlanStatus { - Processing, - /// Coins confirmed on-chain (outgoing: awaiting recipient claim; - /// incoming: ready to submit the claim extrinsic). - Detected, - Finished, - Error, + Processing, + /// Coins confirmed on-chain (outgoing: awaiting recipient claim; + /// incoming: ready to submit the claim extrinsic). + Detected, + Finished, + Error, } impl ClaimPlanStatus { - pub fn as_raw(self) -> i64 { - match self { - ClaimPlanStatus::Processing => 0, - ClaimPlanStatus::Detected => 1, - ClaimPlanStatus::Finished => 2, - ClaimPlanStatus::Error => 3, - } - } - - pub fn from_raw(raw: i64) -> Option { - Some(match raw { - 0 => ClaimPlanStatus::Processing, - 1 => ClaimPlanStatus::Detected, - 2 => ClaimPlanStatus::Finished, - 3 => ClaimPlanStatus::Error, - _ => return None, - }) - } + pub fn as_raw(self) -> i64 { + match self { + ClaimPlanStatus::Processing => 0, + ClaimPlanStatus::Detected => 1, + ClaimPlanStatus::Finished => 2, + ClaimPlanStatus::Error => 3, + } + } + + pub fn from_raw(raw: i64) -> Option { + Some(match raw { + 0 => ClaimPlanStatus::Processing, + 1 => ClaimPlanStatus::Detected, + 2 => ClaimPlanStatus::Finished, + 3 => ClaimPlanStatus::Error, + _ => return None, + }) + } } /// Durable per-entry progress for a claim of externally supplied secrets. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ClaimMarkers { - /// Entries whose transfer this wallet submitted, recorded before submission. - pub submitted: Vec, - /// Entries absent at finalized state that this wallet never submitted: - /// their source was spent elsewhere, so they can never be credited. - pub forfeited: Vec, - /// Total value of the forfeited entries. - pub forfeited_value: u128, + /// Entries whose transfer this wallet submitted, recorded before submission. + pub submitted: Vec, + /// Entries absent at finalized state that this wallet never submitted: + /// their source was spent elsewhere, so they can never be credited. + pub forfeited: Vec, + /// Total value of the forfeited entries. + pub forfeited_value: u128, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClaimPlan { - pub memo_key: [u8; 32], - /// The chat message carrying the memo, when known. - pub message_id: Option, - pub entries: Vec, - pub outgoing_public_keys: Vec<[u8; 32]>, - /// Best-effort finalized snapshot captured before durable chat - /// acceptance. Exact/pass-through coins may already be visible here, - /// which provides historical evidence for an ultra-fast recipient claim. - pub detection_anchor: Option<[u8; 32]>, - pub status: ClaimPlanStatus, - /// Value of the processed entry prefix, including forfeited entries. - pub claimed_amount: Option, - pub total_value: u128, - pub markers: ClaimMarkers, + pub memo_key: [u8; 32], + /// The chat message carrying the memo, when known. + pub message_id: Option, + pub entries: Vec, + pub outgoing_public_keys: Vec<[u8; 32]>, + /// Best-effort finalized snapshot captured before durable chat + /// acceptance. Exact/pass-through coins may already be visible here, + /// which provides historical evidence for an ultra-fast recipient claim. + pub detection_anchor: Option<[u8; 32]>, + pub status: ClaimPlanStatus, + /// Value of the processed entry prefix, including forfeited entries. + pub claimed_amount: Option, + pub total_value: u128, + pub markers: ClaimMarkers, } impl ClaimPlan { - /// Value actually credited to this wallet: the processed prefix without - /// forfeited entries. `None` when nothing was processed or the markers - /// exceed the prefix. - pub fn credited_amount(&self) -> Option { - self.claimed_amount? - .checked_sub(self.markers.forfeited_value) - } + /// Value actually credited to this wallet: the processed prefix without + /// forfeited entries. `None` when nothing was processed or the markers + /// exceed the prefix. + pub fn credited_amount(&self) -> Option { + self.claimed_amount?.checked_sub(self.markers.forfeited_value) + } } /// SCALE-encode the entries blob for `claim_plans.entries_data`. pub fn encode_claim_plan_entries(entries: &[CodableClaimPlanEntry]) -> Vec { - entries.encode() + entries.encode() } /// Decode an `entries_data` blob; errors on malformed or trailing bytes. pub fn decode_claim_plan_entries(bytes: &[u8]) -> Result, String> { - let mut input = bytes; - let entries = Vec::::decode(&mut input) - .map_err(|error| format!("claim plan entries: {error}"))?; - if !input.is_empty() { - return Err("claim plan entries: trailing bytes".into()); - } - Ok(entries) + let mut input = bytes; + let entries = Vec::::decode(&mut input) + .map_err(|error| format!("claim plan entries: {error}"))?; + if !input.is_empty() { + return Err("claim plan entries: trailing bytes".into()); + } + Ok(entries) } #[async_trait] pub trait ClaimPlanStore: Send + Sync { - /// Full save (insert or replace, re-encoding entries). - async fn save(&self, plan: &ClaimPlan) -> Result<(), String>; + /// Full save (insert or replace, re-encoding entries). + async fn save(&self, plan: &ClaimPlan) -> Result<(), String>; - /// Lookup by memo key. - async fn plan(&self, memo_key: &[u8; 32]) -> Result, String>; + /// Lookup by memo key. + async fn plan(&self, memo_key: &[u8; 32]) -> Result, String>; - async fn load_all(&self) -> Result, String>; + async fn load_all(&self) -> Result, String>; - async fn update_status( - &self, - memo_key: &[u8; 32], - status: ClaimPlanStatus, - claimed_amount: Option, - ) -> Result<(), String>; + async fn update_status( + &self, + memo_key: &[u8; 32], + status: ClaimPlanStatus, + claimed_amount: Option, + ) -> Result<(), String>; - async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String>; + async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String>; } #[cfg(test)] mod tests { - use super::*; - - #[test] - fn entry_scale_layout_is_pinned() { - let entry = CodableClaimPlanEntry { - entry_index: 1, - exponent: -2, - derivation_index: 0x0403_0201, - }; - // i16 LE ++ i16 LE ++ u32 LE = 8 bytes, fixed. - assert_eq!(entry.encode(), vec![1, 0, 0xFE, 0xFF, 1, 2, 3, 4]); - } - - #[test] - fn entries_blob_round_trips() { - let entries = vec![ - CodableClaimPlanEntry { - entry_index: 0, - exponent: 3, - derivation_index: 7, - }, - CodableClaimPlanEntry { - entry_index: 1, - exponent: -1, - derivation_index: 8, - }, - ]; - let blob = encode_claim_plan_entries(&entries); - assert_eq!(decode_claim_plan_entries(&blob).unwrap(), entries); - assert!( - decode_claim_plan_entries(&[]).is_err(), - "empty blob is malformed" - ); - let mut trailing = blob.clone(); - trailing.push(0); - assert!(decode_claim_plan_entries(&trailing).is_err()); - } - - #[test] - fn status_raw_round_trips() { - for status in [ - ClaimPlanStatus::Processing, - ClaimPlanStatus::Detected, - ClaimPlanStatus::Finished, - ClaimPlanStatus::Error, - ] { - assert_eq!(ClaimPlanStatus::from_raw(status.as_raw()), Some(status)); - } - assert_eq!(ClaimPlanStatus::from_raw(4), None); - } + use super::*; + + #[test] + fn entry_scale_layout_is_pinned() { + let entry = + CodableClaimPlanEntry { entry_index: 1, exponent: -2, derivation_index: 0x0403_0201 }; + // i16 LE ++ i16 LE ++ u32 LE = 8 bytes, fixed. + assert_eq!(entry.encode(), vec![1, 0, 0xFE, 0xFF, 1, 2, 3, 4]); + } + + #[test] + fn entries_blob_round_trips() { + let entries = vec![ + CodableClaimPlanEntry { entry_index: 0, exponent: 3, derivation_index: 7 }, + CodableClaimPlanEntry { entry_index: 1, exponent: -1, derivation_index: 8 }, + ]; + let blob = encode_claim_plan_entries(&entries); + assert_eq!(decode_claim_plan_entries(&blob).unwrap(), entries); + assert!(decode_claim_plan_entries(&[]).is_err(), "empty blob is malformed"); + let mut trailing = blob.clone(); + trailing.push(0); + assert!(decode_claim_plan_entries(&trailing).is_err()); + } + + #[test] + fn status_raw_round_trips() { + for status in [ + ClaimPlanStatus::Processing, + ClaimPlanStatus::Detected, + ClaimPlanStatus::Finished, + ClaimPlanStatus::Error, + ] { + assert_eq!(ClaimPlanStatus::from_raw(status.as_raw()), Some(status)); + } + assert_eq!(ClaimPlanStatus::from_raw(4), None); + } } diff --git a/rust/crates/truapi-coinage/src/clock.rs b/rust/crates/truapi-coinage/src/clock.rs index 7c9df7c73d..736474f9f2 100644 --- a/rust/crates/truapi-coinage/src/clock.rs +++ b/rust/crates/truapi-coinage/src/clock.rs @@ -8,26 +8,26 @@ /// Milliseconds since the unix epoch. pub trait Clock: Send + Sync { - fn now_ms(&self) -> i64; + fn now_ms(&self) -> i64; } /// Production clock. pub struct SystemClock; impl Clock for SystemClock { - fn now_ms(&self) -> i64 { - web_time::SystemTime::now() - .duration_since(web_time::UNIX_EPOCH) - .map(|d| d.as_millis() as i64) - .unwrap_or(0) - } + fn now_ms(&self) -> i64 { + web_time::SystemTime::now() + .duration_since(web_time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) + } } /// Fixed clock for tests. pub struct FixedClock(pub i64); impl Clock for FixedClock { - fn now_ms(&self) -> i64 { - self.0 - } + fn now_ms(&self) -> i64 { + self.0 + } } diff --git a/rust/crates/truapi-coinage/src/constants.rs b/rust/crates/truapi-coinage/src/constants.rs index a11326cc3c..0bd98ba4fb 100644 --- a/rust/crates/truapi-coinage/src/constants.rs +++ b/rust/crates/truapi-coinage/src/constants.rs @@ -32,18 +32,18 @@ pub const SEND_VERIFY_BLOCK_TIMEOUT: u32 = 100; #[cfg(test)] mod tests { - use super::*; - - #[test] - fn protocol_constants_are_pinned() { - assert_eq!(COIN_MAX_AGE, 16); - assert_eq!(RECYCLE_AT_AGE, 14); - assert_eq!(COIN_MAX_AGE - 2, RECYCLE_AT_AGE); - assert_eq!(MINIMUM_RING_SIZE, 10); - assert_eq!(WAL_MORTALITY_BLOCKS, 300); - assert_eq!(MAX_VOUCHER_WAIT_TIME, Duration::from_secs(21_600)); - assert_eq!(SEND_VERIFY_BLOCK_TIMEOUT, 100); - assert_eq!(CASH_ASSET_PRECISION, 6); - assert_eq!(CASH_PLANKS_PER_CENT, 10_000); - } + use super::*; + + #[test] + fn protocol_constants_are_pinned() { + assert_eq!(COIN_MAX_AGE, 16); + assert_eq!(RECYCLE_AT_AGE, 14); + assert_eq!(COIN_MAX_AGE - 2, RECYCLE_AT_AGE); + assert_eq!(MINIMUM_RING_SIZE, 10); + assert_eq!(WAL_MORTALITY_BLOCKS, 300); + assert_eq!(MAX_VOUCHER_WAIT_TIME, Duration::from_secs(21_600)); + assert_eq!(SEND_VERIFY_BLOCK_TIMEOUT, 100); + assert_eq!(CASH_ASSET_PRECISION, 6); + assert_eq!(CASH_PLANKS_PER_CENT, 10_000); + } } diff --git a/rust/crates/truapi-coinage/src/denomination.rs b/rust/crates/truapi-coinage/src/denomination.rs index 4c4cd6e8b5..651deb433f 100644 --- a/rust/crates/truapi-coinage/src/denomination.rs +++ b/rust/crates/truapi-coinage/src/denomination.rs @@ -5,7 +5,7 @@ /// One power-of-two denomination. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Denomination { - pub exponent: i16, + pub exponent: i16, } /// Greedy decomposition outcome: the denominations that fit, plus the @@ -13,222 +13,202 @@ pub struct Denomination { /// exactly representable). #[derive(Debug, Clone, PartialEq, Eq)] pub struct DenominationBreakdown { - pub denominations: Vec, - pub remainder: u128, + pub denominations: Vec, + pub remainder: u128, } impl DenominationBreakdown { - pub fn is_exact(&self) -> bool { - self.remainder == 0 - } + pub fn is_exact(&self) -> bool { + self.remainder == 0 + } } /// The pallet-constant context driving all denomination math. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DenominationBreakdownContext { - /// `UnderlyingAssetUnit` pallet constant, in planks. - pub asset_unit: u128, - /// `MaximumExponent` pallet constant. - pub max_exponent: i16, - /// `MinimumExponent` pallet constant (may be negative). - pub min_exponent: i16, - pub precision: u8, + /// `UnderlyingAssetUnit` pallet constant, in planks. + pub asset_unit: u128, + /// `MaximumExponent` pallet constant. + pub max_exponent: i16, + /// `MinimumExponent` pallet constant (may be negative). + pub min_exponent: i16, + pub precision: u8, } impl DenominationBreakdownContext { - /// Converts the UI/protocol CASH balance unit (one cent) into the raw - /// planks consumed by Coinage selection and emitted in transfer memos. - /// `UnderlyingAssetUnit` is exactly that cent in the active asset. - pub fn cash_cents_to_planks(&self, cents: u128) -> Option { - cents.checked_mul(self.asset_unit) - } - - /// Converts raw Coinage planks back into whole CASH cents. A remainder - /// is rejected rather than rounded across a payment confirmation edge. - pub fn cash_cents_from_planks(&self, planks: u128) -> Option { - (self.asset_unit != 0 && planks.is_multiple_of(self.asset_unit)) - .then(|| planks / self.asset_unit) - } - - /// Denomination value in planks: `unit << exponent` for non-negative - /// exponents, `unit >> -exponent` for negative ones. Each direction - /// saturates (`u128::MAX` or `0`) rather than panicking on an absurd - /// shift amount. - pub fn value_in_planks(&self, exponent: i16) -> u128 { - if exponent >= 0 { - self.asset_unit - .checked_shl(u32::from(exponent as u16)) - .unwrap_or(u128::MAX) - } else { - let shift = u32::from(exponent.unsigned_abs()); - if shift >= 128 { - 0 - } else { - self.asset_unit >> shift - } - } - } - - /// Greedy binary decomposition from `max_exponent` down to `min_exponent`, - /// taking as many of each denomination as fit; anything below the - /// smallest denomination is returned as `remainder`. - pub fn breakdown(&self, amount_planks: u128) -> DenominationBreakdown { - let mut remaining = amount_planks; - let mut denominations = Vec::new(); - let mut exponent = self.max_exponent; - while exponent >= self.min_exponent { - let value = self.value_in_planks(exponent); - if value > 0 { - while remaining >= value { - denominations.push(Denomination { exponent }); - remaining -= value; - } - } - exponent -= 1; - } - DenominationBreakdown { - denominations, - remainder: remaining, - } - } - - /// Total planks of a denomination list. - pub fn total_value(&self, denominations: &[Denomination]) -> u128 { - denominations.iter().fold(0u128, |acc, d| { - acc.saturating_add(self.value_in_planks(d.exponent)) - }) - } + /// Converts the UI/protocol CASH balance unit (one cent) into the raw + /// planks consumed by Coinage selection and emitted in transfer memos. + /// `UnderlyingAssetUnit` is exactly that cent in the active asset. + pub fn cash_cents_to_planks(&self, cents: u128) -> Option { + cents.checked_mul(self.asset_unit) + } + + /// Converts raw Coinage planks back into whole CASH cents. A remainder + /// is rejected rather than rounded across a payment confirmation edge. + pub fn cash_cents_from_planks(&self, planks: u128) -> Option { + (self.asset_unit != 0 && planks.is_multiple_of(self.asset_unit)) + .then(|| planks / self.asset_unit) + } + + /// Denomination value in planks: `unit << exponent` for non-negative + /// exponents, `unit >> -exponent` for negative ones. Each direction + /// saturates (`u128::MAX` or `0`) rather than panicking on an absurd + /// shift amount. + pub fn value_in_planks(&self, exponent: i16) -> u128 { + if exponent >= 0 { + self.asset_unit.checked_shl(u32::from(exponent as u16)).unwrap_or(u128::MAX) + } else { + let shift = u32::from(exponent.unsigned_abs()); + if shift >= 128 { 0 } else { self.asset_unit >> shift } + } + } + + /// Greedy binary decomposition from `max_exponent` down to `min_exponent`, + /// taking as many of each denomination as fit; anything below the + /// smallest denomination is returned as `remainder`. + pub fn breakdown(&self, amount_planks: u128) -> DenominationBreakdown { + let mut remaining = amount_planks; + let mut denominations = Vec::new(); + let mut exponent = self.max_exponent; + while exponent >= self.min_exponent { + let value = self.value_in_planks(exponent); + if value > 0 { + while remaining >= value { + denominations.push(Denomination { exponent }); + remaining -= value; + } + } + exponent -= 1; + } + DenominationBreakdown { denominations, remainder: remaining } + } + + /// Total planks of a denomination list. + pub fn total_value(&self, denominations: &[Denomination]) -> u128 { + denominations + .iter() + .fold(0u128, |acc, d| acc.saturating_add(self.value_in_planks(d.exponent))) + } } #[cfg(test)] mod tests { - use super::*; - - /// Unit 10, exponents 0..=4 → denominations 10, 20, 40, 80, 160. - fn ctx() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 10, - max_exponent: 4, - min_exponent: 0, - precision: 10, - } - } - - #[test] - fn value_in_planks_shifts_both_directions() { - let ctx = ctx(); - assert_eq!(ctx.value_in_planks(0), 10); - assert_eq!(ctx.value_in_planks(3), 80); - let fractional = DenominationBreakdownContext { - asset_unit: 16, - max_exponent: 2, - min_exponent: -2, - precision: 0, - }; - assert_eq!(fractional.value_in_planks(-1), 8); - assert_eq!(fractional.value_in_planks(-2), 4); - } - - #[test] - fn cash_cents_and_asset_planks_have_an_explicit_exact_boundary() { - let context = DenominationBreakdownContext { - asset_unit: 10_000, - max_exponent: 16, - min_exponent: 0, - precision: 6, - }; - - for (cash, cents, planks) in [ - (1, 100, 1_000_000), - (10, 1_000, 10_000_000), - (100, 10_000, 100_000_000), - (200, 20_000, 200_000_000), - ] { - assert_eq!( - context.cash_cents_to_planks(cents), - Some(planks), - "{cash} CASH" - ); - assert_eq!( - context.cash_cents_from_planks(planks), - Some(cents), - "{cash} CASH" - ); - } - assert_eq!(context.cash_cents_from_planks(9_999), None); - assert_eq!(context.cash_cents_to_planks(u128::MAX), None); - } - - #[test] - fn breakdown_of_known_amounts_is_greedy_largest_first() { - let ctx = ctx(); - // 230 = 160 + 40 + 20 + 10. - let b = ctx.breakdown(230); - assert_eq!( - b.denominations, - [ - Denomination { exponent: 4 }, - Denomination { exponent: 2 }, - Denomination { exponent: 1 }, - Denomination { exponent: 0 }, - ] - ); - assert!(b.is_exact()); - // 320 = 160 + 160 (repeated denominations allowed). - let b = ctx.breakdown(320); - assert_eq!( - b.denominations, - [Denomination { exponent: 4 }, Denomination { exponent: 4 }] - ); - assert!(b.is_exact()); - } - - #[test] - fn breakdown_reports_sub_denomination_remainder() { - let ctx = ctx(); - let b = ctx.breakdown(235); - assert_eq!(b.remainder, 5, "5 planks sit below the 10-plank unit"); - assert!(!b.is_exact()); - assert_eq!(ctx.total_value(&b.denominations), 230); - } - - #[test] - fn breakdown_of_zero_is_empty_and_exact() { - let b = ctx().breakdown(0); - assert!(b.denominations.is_empty()); - assert!(b.is_exact()); - } - - #[test] - fn negative_exponents_extend_below_the_unit() { - let ctx = DenominationBreakdownContext { - asset_unit: 16, - max_exponent: 1, - min_exponent: -2, - precision: 0, - }; - // 28 = 16 + 8 + 4. - let b = ctx.breakdown(28); - assert_eq!( - b.denominations, - [ - Denomination { exponent: 0 }, - Denomination { exponent: -1 }, - Denomination { exponent: -2 }, - ] - ); - assert!(b.is_exact()); - } - - /// Breakdown reconstructs: `total_value(breakdown(x)) + remainder == x` - /// across a sweep — the invariant coin allocation relies on. - #[test] - fn breakdown_reconstructs_every_amount() { - let ctx = ctx(); - for amount in 0..2_000u128 { - let b = ctx.breakdown(amount); - assert_eq!(ctx.total_value(&b.denominations) + b.remainder, amount); - assert!(b.remainder < ctx.value_in_planks(ctx.min_exponent)); - } - } + use super::*; + + /// Unit 10, exponents 0..=4 → denominations 10, 20, 40, 80, 160. + fn ctx() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 10, + max_exponent: 4, + min_exponent: 0, + precision: 10, + } + } + + #[test] + fn value_in_planks_shifts_both_directions() { + let ctx = ctx(); + assert_eq!(ctx.value_in_planks(0), 10); + assert_eq!(ctx.value_in_planks(3), 80); + let fractional = DenominationBreakdownContext { + asset_unit: 16, + max_exponent: 2, + min_exponent: -2, + precision: 0, + }; + assert_eq!(fractional.value_in_planks(-1), 8); + assert_eq!(fractional.value_in_planks(-2), 4); + } + + #[test] + fn cash_cents_and_asset_planks_have_an_explicit_exact_boundary() { + let context = DenominationBreakdownContext { + asset_unit: 10_000, + max_exponent: 16, + min_exponent: 0, + precision: 6, + }; + + for (cash, cents, planks) in [ + (1, 100, 1_000_000), + (10, 1_000, 10_000_000), + (100, 10_000, 100_000_000), + (200, 20_000, 200_000_000), + ] { + assert_eq!(context.cash_cents_to_planks(cents), Some(planks), "{cash} CASH"); + assert_eq!(context.cash_cents_from_planks(planks), Some(cents), "{cash} CASH"); + } + assert_eq!(context.cash_cents_from_planks(9_999), None); + assert_eq!(context.cash_cents_to_planks(u128::MAX), None); + } + + #[test] + fn breakdown_of_known_amounts_is_greedy_largest_first() { + let ctx = ctx(); + // 230 = 160 + 40 + 20 + 10. + let b = ctx.breakdown(230); + assert_eq!( + b.denominations, + [ + Denomination { exponent: 4 }, + Denomination { exponent: 2 }, + Denomination { exponent: 1 }, + Denomination { exponent: 0 }, + ] + ); + assert!(b.is_exact()); + // 320 = 160 + 160 (repeated denominations allowed). + let b = ctx.breakdown(320); + assert_eq!(b.denominations, [Denomination { exponent: 4 }, Denomination { exponent: 4 }]); + assert!(b.is_exact()); + } + + #[test] + fn breakdown_reports_sub_denomination_remainder() { + let ctx = ctx(); + let b = ctx.breakdown(235); + assert_eq!(b.remainder, 5, "5 planks sit below the 10-plank unit"); + assert!(!b.is_exact()); + assert_eq!(ctx.total_value(&b.denominations), 230); + } + + #[test] + fn breakdown_of_zero_is_empty_and_exact() { + let b = ctx().breakdown(0); + assert!(b.denominations.is_empty()); + assert!(b.is_exact()); + } + + #[test] + fn negative_exponents_extend_below_the_unit() { + let ctx = DenominationBreakdownContext { + asset_unit: 16, + max_exponent: 1, + min_exponent: -2, + precision: 0, + }; + // 28 = 16 + 8 + 4. + let b = ctx.breakdown(28); + assert_eq!( + b.denominations, + [ + Denomination { exponent: 0 }, + Denomination { exponent: -1 }, + Denomination { exponent: -2 }, + ] + ); + assert!(b.is_exact()); + } + + /// Breakdown reconstructs: `total_value(breakdown(x)) + remainder == x` + /// across a sweep — the invariant coin allocation relies on. + #[test] + fn breakdown_reconstructs_every_amount() { + let ctx = ctx(); + for amount in 0..2_000u128 { + let b = ctx.breakdown(amount); + assert_eq!(ctx.total_value(&b.denominations) + b.remainder, amount); + assert!(b.remainder < ctx.value_in_planks(ctx.min_exponent)); + } + } } diff --git a/rust/crates/truapi-coinage/src/index_store.rs b/rust/crates/truapi-coinage/src/index_store.rs index 00ad142894..fe45bace5f 100644 --- a/rust/crates/truapi-coinage/src/index_store.rs +++ b/rust/crates/truapi-coinage/src/index_store.rs @@ -15,29 +15,29 @@ pub const VOUCHER_INDEX_KEY: &str = "voucher-index"; /// Which counter a call addresses. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum IndexKind { - Coin, - Voucher, + Coin, + Voucher, } impl IndexKind { - /// The platform storage key this counter lives under. - pub fn storage_key(self) -> &'static str { - match self { - IndexKind::Coin => COIN_INDEX_KEY, - IndexKind::Voucher => VOUCHER_INDEX_KEY, - } - } + /// The platform storage key this counter lives under. + pub fn storage_key(self) -> &'static str { + match self { + IndexKind::Coin => COIN_INDEX_KEY, + IndexKind::Voucher => VOUCHER_INDEX_KEY, + } + } } pub fn encode_index(index: u32) -> Vec { - index.encode() + index.encode() } /// Decode a stored counter; `None` on malformed bytes. pub fn decode_index(bytes: &[u8]) -> Option { - let mut input = bytes; - let value = u32::decode(&mut input).ok()?; - input.is_empty().then_some(value) + let mut input = bytes; + let value = u32::decode(&mut input).ok()?; + input.is_empty().then_some(value) } /// Durable, crash-safe monotonic counters. `get_next_index` is the @@ -45,117 +45,109 @@ pub fn decode_index(bytes: &[u8]) -> Option { /// (`CoinAllocator`/`VoucherAllocator`) receive each index exactly once. #[async_trait] pub trait CoinageIndexStore: Send + Sync { - async fn get_next_index(&self, kind: IndexKind) -> Result; + async fn get_next_index(&self, kind: IndexKind) -> Result; - /// The current high-water mark; `None` on a fresh install. - async fn current_index(&self, kind: IndexKind) -> Result, String>; + /// The current high-water mark; `None` on a fresh install. + async fn current_index(&self, kind: IndexKind) -> Result, String>; - /// Overwrites the counter (used for backup-recovery horizon writes): - /// only ever move it forward — a lower value re-issues already-used - /// indices and corrupts key derivation. - async fn set_index(&self, kind: IndexKind, index: u32) -> Result<(), String>; + /// Overwrites the counter (used for backup-recovery horizon writes): + /// only ever move it forward — a lower value re-issues already-used + /// indices and corrupts key derivation. + async fn set_index(&self, kind: IndexKind, index: u32) -> Result<(), String>; } /// Test/dev impl over a mutex-guarded map. Also the executable spec of /// the counter contract for the platform impls. #[derive(Default)] pub struct InMemoryCoinageIndexStore { - counters: Mutex>, + counters: Mutex>, } #[async_trait] impl CoinageIndexStore for InMemoryCoinageIndexStore { - async fn get_next_index(&self, kind: IndexKind) -> Result { - let mut counters = self.counters.lock(); - let next = match counters.get(&kind) { - None => 0, - Some(current) => current - .checked_add(1) - .ok_or_else(|| "derivation index space exhausted".to_string())?, - }; - counters.insert(kind, next); - Ok(next) - } - - async fn current_index(&self, kind: IndexKind) -> Result, String> { - Ok(self.counters.lock().get(&kind).copied()) - } - - async fn set_index(&self, kind: IndexKind, index: u32) -> Result<(), String> { - self.counters.lock().insert(kind, index); - Ok(()) - } + async fn get_next_index(&self, kind: IndexKind) -> Result { + let mut counters = self.counters.lock(); + let next = match counters.get(&kind) { + None => 0, + Some(current) => current + .checked_add(1) + .ok_or_else(|| "derivation index space exhausted".to_string())?, + }; + counters.insert(kind, next); + Ok(next) + } + + async fn current_index(&self, kind: IndexKind) -> Result, String> { + Ok(self.counters.lock().get(&kind).copied()) + } + + async fn set_index(&self, kind: IndexKind, index: u32) -> Result<(), String> { + self.counters.lock().insert(kind, index); + Ok(()) + } } #[cfg(test)] mod tests { - use super::*; - - #[tokio::test] - async fn fresh_counter_starts_at_zero_then_increments() { - let store = InMemoryCoinageIndexStore::default(); - assert_eq!(store.current_index(IndexKind::Coin).await.unwrap(), None); - assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 0); - assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 1); - assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 2); - assert_eq!(store.current_index(IndexKind::Coin).await.unwrap(), Some(2)); - } - - #[tokio::test] - async fn coin_and_voucher_counters_are_independent() { - let store = InMemoryCoinageIndexStore::default(); - assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 0); - assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 1); - assert_eq!(store.get_next_index(IndexKind::Voucher).await.unwrap(), 0); - assert_eq!( - store.current_index(IndexKind::Voucher).await.unwrap(), - Some(0) - ); - } - - #[tokio::test] - async fn horizon_write_moves_the_counter() { - let store = InMemoryCoinageIndexStore::default(); - store.set_index(IndexKind::Voucher, 41).await.unwrap(); - assert_eq!(store.get_next_index(IndexKind::Voucher).await.unwrap(), 42); - } - - /// Concurrent allocators must never observe the same index — the - /// atomicity contract platform impls have to uphold. - #[tokio::test] - async fn concurrent_allocation_yields_unique_indices() { - use std::collections::HashSet; - use std::sync::Arc; - let store = Arc::new(InMemoryCoinageIndexStore::default()); - let mut handles = Vec::new(); - for _ in 0..64 { - let store = Arc::clone(&store); - handles.push(tokio::spawn(async move { - store.get_next_index(IndexKind::Coin).await.unwrap() - })); - } - let mut seen = HashSet::new(); - for handle in handles { - assert!(seen.insert(handle.await.unwrap()), "index issued twice"); - } - assert_eq!(seen.len(), 64); - } - - #[test] - fn index_codec_is_scale_u32() { - assert_eq!(encode_index(7), 7u32.encode()); - assert_eq!(decode_index(&encode_index(0xDEAD_BEEF)), Some(0xDEAD_BEEF)); - assert_eq!(decode_index(&[1, 2, 3]), None, "short read is malformed"); - assert_eq!( - decode_index(&[1, 2, 3, 4, 5]), - None, - "trailing bytes are malformed" - ); - } - - #[test] - fn storage_keys_are_pinned() { - assert_eq!(IndexKind::Coin.storage_key(), "coin-index"); - assert_eq!(IndexKind::Voucher.storage_key(), "voucher-index"); - } + use super::*; + + #[tokio::test] + async fn fresh_counter_starts_at_zero_then_increments() { + let store = InMemoryCoinageIndexStore::default(); + assert_eq!(store.current_index(IndexKind::Coin).await.unwrap(), None); + assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 0); + assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 1); + assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 2); + assert_eq!(store.current_index(IndexKind::Coin).await.unwrap(), Some(2)); + } + + #[tokio::test] + async fn coin_and_voucher_counters_are_independent() { + let store = InMemoryCoinageIndexStore::default(); + assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 0); + assert_eq!(store.get_next_index(IndexKind::Coin).await.unwrap(), 1); + assert_eq!(store.get_next_index(IndexKind::Voucher).await.unwrap(), 0); + assert_eq!(store.current_index(IndexKind::Voucher).await.unwrap(), Some(0)); + } + + #[tokio::test] + async fn horizon_write_moves_the_counter() { + let store = InMemoryCoinageIndexStore::default(); + store.set_index(IndexKind::Voucher, 41).await.unwrap(); + assert_eq!(store.get_next_index(IndexKind::Voucher).await.unwrap(), 42); + } + + /// Concurrent allocators must never observe the same index — the + /// atomicity contract platform impls have to uphold. + #[tokio::test] + async fn concurrent_allocation_yields_unique_indices() { + use std::{collections::HashSet, sync::Arc}; + let store = Arc::new(InMemoryCoinageIndexStore::default()); + let mut handles = Vec::new(); + for _ in 0..64 { + let store = Arc::clone(&store); + handles.push(tokio::spawn(async move { + store.get_next_index(IndexKind::Coin).await.unwrap() + })); + } + let mut seen = HashSet::new(); + for handle in handles { + assert!(seen.insert(handle.await.unwrap()), "index issued twice"); + } + assert_eq!(seen.len(), 64); + } + + #[test] + fn index_codec_is_scale_u32() { + assert_eq!(encode_index(7), 7u32.encode()); + assert_eq!(decode_index(&encode_index(0xDEAD_BEEF)), Some(0xDEAD_BEEF)); + assert_eq!(decode_index(&[1, 2, 3]), None, "short read is malformed"); + assert_eq!(decode_index(&[1, 2, 3, 4, 5]), None, "trailing bytes are malformed"); + } + + #[test] + fn storage_keys_are_pinned() { + assert_eq!(IndexKind::Coin.storage_key(), "coin-index"); + assert_eq!(IndexKind::Voucher.storage_key(), "voucher-index"); + } } diff --git a/rust/crates/truapi-coinage/src/keys.rs b/rust/crates/truapi-coinage/src/keys.rs index a219db0603..6084642653 100644 --- a/rust/crates/truapi-coinage/src/keys.rs +++ b/rust/crates/truapi-coinage/src/keys.rs @@ -16,71 +16,71 @@ pub const RECYCLER_ALIAS_CONTEXT: &[u8; 32] = b"pop:polkadot.network/coinrecyclr /// parent junctions and a soft item junction. The cached parent is zeroized on drop. /// Callers must not reuse indices persisted under a different purse layout. pub struct CoinKeypairFactory { - parent: Result, + parent: Result, } impl Zeroize for CoinKeypairFactory { - fn zeroize(&mut self) { - // Dropping the cached Schnorrkel keypair zeroizes its secret. Leave no - // usable parent after explicit clearing, and do not allocate on drop. - self.parent = Err(String::new()); - } + fn zeroize(&mut self) { + // Dropping the cached Schnorrkel keypair zeroizes its secret. Leave no + // usable parent after explicit clearing, and do not allocate on drop. + self.parent = Err(String::new()); + } } impl Drop for CoinKeypairFactory { - fn drop(&mut self) { - self.zeroize(); - } + fn drop(&mut self) { + self.zeroize(); + } } impl ZeroizeOnDrop for CoinKeypairFactory {} impl CoinKeypairFactory { - pub fn new(entropy: &[u8]) -> Self { - let parent = derive_sr25519_hard_path( - entropy, - &[ - junction_chain_code("coinage"), - junction_chain_code(u64::from(MAIN_PURSE)), - junction_chain_code(u64::from(PAGE)), - ], - ) - .map_err(|error| format!("coin key derivation: {error}")); - Self { parent } - } - - /// The full keypair for one coin index. - pub fn keypair(&self, index: u32) -> Result { - use rand::SeedableRng; - use schnorrkel::derive::{ChainCode, Derivation}; - - // Recovery derives thousands of children; expand BIP-39 and the three - // hard parents once per factory, not once per scanned index. - let parent = self.parent.as_ref().map_err(Clone::clone)?; - // Only the HDKD auxiliary randomness is fixed. Schnorrkel mixes the - // parent secret and nonce into its witness RNG; the scalar/public key - // retain standard soft derivation. This makes the complete exported - // 64-byte secret stable so a durable handoff replays the same memo. - // Signing continues to use Schnorrkel's ordinary randomized path. - Ok(parent - .derived_key_simple_rng( - ChainCode(junction_chain_code(u64::from(index))), - [], - rand_chacha::ChaCha20Rng::from_seed([0; 32]), - ) - .0) - } - - /// The coin's on-chain identity (`CoinsByOwner` storage key part). - pub fn public_key(&self, index: u32) -> Result<[u8; 32], String> { - Ok(self.keypair(index)?.public.to_bytes()) - } - - /// The raw 64-byte expanded secret — the exact layout - /// `schnorrkel::SecretKey::from_bytes` reconstructs a signer from. - pub fn secret_bytes(&self, index: u32) -> Result<[u8; 64], String> { - Ok(self.keypair(index)?.secret.to_bytes()) - } + pub fn new(entropy: &[u8]) -> Self { + let parent = derive_sr25519_hard_path( + entropy, + &[ + junction_chain_code("coinage"), + junction_chain_code(u64::from(MAIN_PURSE)), + junction_chain_code(u64::from(PAGE)), + ], + ) + .map_err(|error| format!("coin key derivation: {error}")); + Self { parent } + } + + /// The full keypair for one coin index. + pub fn keypair(&self, index: u32) -> Result { + use rand::SeedableRng; + use schnorrkel::derive::{ChainCode, Derivation}; + + // Recovery derives thousands of children; expand BIP-39 and the three + // hard parents once per factory, not once per scanned index. + let parent = self.parent.as_ref().map_err(Clone::clone)?; + // Only the HDKD auxiliary randomness is fixed. Schnorrkel mixes the + // parent secret and nonce into its witness RNG; the scalar/public key + // retain standard soft derivation. This makes the complete exported + // 64-byte secret stable so a durable handoff replays the same memo. + // Signing continues to use Schnorrkel's ordinary randomized path. + Ok(parent + .derived_key_simple_rng( + ChainCode(junction_chain_code(u64::from(index))), + [], + rand_chacha::ChaCha20Rng::from_seed([0; 32]), + ) + .0) + } + + /// The coin's on-chain identity (`CoinsByOwner` storage key part). + pub fn public_key(&self, index: u32) -> Result<[u8; 32], String> { + Ok(self.keypair(index)?.public.to_bytes()) + } + + /// The raw 64-byte expanded secret — the exact layout + /// `schnorrkel::SecretKey::from_bytes` reconstructs a signer from. + pub fn secret_bytes(&self, index: u32) -> Result<[u8; 64], String> { + Ok(self.keypair(index)?.secret.to_bytes()) + } } /// A derived voucher seed (32 bytes). Secret material: the Bandersnatch @@ -89,10 +89,10 @@ impl CoinKeypairFactory { pub struct VoucherSeed(pub [u8; 32]); impl std::fmt::Debug for VoucherSeed { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // Never print seed bytes. - f.write_str("VoucherSeed(..)") - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Never print seed bytes. + f.write_str("VoucherSeed(..)") + } } /// Derives vouchers at `//coinage-ring-vrf//4294967295//0//`. @@ -100,287 +100,266 @@ impl std::fmt::Debug for VoucherSeed { /// BIP-39 expansion. Callers must keep persisted indices scoped to this layout. #[derive(Zeroize, ZeroizeOnDrop)] pub struct VoucherKeypairFactory { - entropy: Vec, + entropy: Vec, } impl VoucherKeypairFactory { - pub fn new(entropy: &[u8]) -> Self { - Self { - entropy: entropy.to_vec(), - } - } - - /// The chained seed for one voucher index. - pub fn seed(&self, index: u32) -> VoucherSeed { - let mut seed = VoucherSeed(keyed_blake2b_256( - &self.entropy, - &junction_chain_code("coinage-ring-vrf"), - )); - for junction in [MAIN_PURSE, PAGE, index] { - let chain_code = junction_chain_code(u64::from(junction)); - seed.0 = keyed_blake2b_256(&seed.0, &chain_code); - } - seed - } - - /// The member key used by Coinage and Members storage. - pub fn public_key( - &self, - index: u32, - crypto: &dyn VoucherCryptography, - ) -> Result<[u8; 32], String> { - crypto.member_key(&self.seed(index)) - } - - /// Ownership signature binding the member key to an input coin. - pub fn proof_of_ownership( - &self, - index: u32, - message: &[u8], - crypto: &dyn VoucherCryptography, - ) -> Result<[u8; 64], String> { - crypto.sign(&self.seed(index), message) - } - - /// The context-specific recycler alias, independent of the implication. - pub fn alias( - &self, - index: u32, - context: &[u8], - crypto: &dyn VoucherCryptography, - ) -> Result<[u8; 32], String> { - crypto.alias(&self.seed(index), context) - } - - /// Transaction-bound Bandersnatch membership proof at a finalized ring. - pub fn ring_vrf_proof( - &self, - index: u32, - ring_exponent: u8, - ring_members: &[[u8; 32]], - context: &[u8], - message: &[u8], - crypto: &dyn VoucherCryptography, - ) -> Result, String> { - crypto.ring_vrf_proof( - &self.seed(index), - ring_exponent, - ring_members, - context, - message, - ) - } + pub fn new(entropy: &[u8]) -> Self { + Self { entropy: entropy.to_vec() } + } + + /// The chained seed for one voucher index. + pub fn seed(&self, index: u32) -> VoucherSeed { + let mut seed = + VoucherSeed(keyed_blake2b_256(&self.entropy, &junction_chain_code("coinage-ring-vrf"))); + for junction in [MAIN_PURSE, PAGE, index] { + let chain_code = junction_chain_code(u64::from(junction)); + seed.0 = keyed_blake2b_256(&seed.0, &chain_code); + } + seed + } + + /// The member key used by Coinage and Members storage. + pub fn public_key( + &self, + index: u32, + crypto: &dyn VoucherCryptography, + ) -> Result<[u8; 32], String> { + crypto.member_key(&self.seed(index)) + } + + /// Ownership signature binding the member key to an input coin. + pub fn proof_of_ownership( + &self, + index: u32, + message: &[u8], + crypto: &dyn VoucherCryptography, + ) -> Result<[u8; 64], String> { + crypto.sign(&self.seed(index), message) + } + + /// The context-specific recycler alias, independent of the implication. + pub fn alias( + &self, + index: u32, + context: &[u8], + crypto: &dyn VoucherCryptography, + ) -> Result<[u8; 32], String> { + crypto.alias(&self.seed(index), context) + } + + /// Transaction-bound Bandersnatch membership proof at a finalized ring. + pub fn ring_vrf_proof( + &self, + index: u32, + ring_exponent: u8, + ring_members: &[[u8; 32]], + context: &[u8], + message: &[u8], + crypto: &dyn VoucherCryptography, + ) -> Result, String> { + crypto.ring_vrf_proof(&self.seed(index), ring_exponent, ring_members, context, message) + } } /// SCALE-encoded Substrate junction → 32-byte chain code. Numeric path /// components must be passed as `u64`, even though purse/page/item are `u32`. /// Oversized encodings hash through BLAKE2b-256; short ones zero-pad. fn junction_chain_code(junction: impl Encode) -> [u8; 32] { - let mut chain_code = [0u8; 32]; - if junction.encoded_size() > chain_code.len() { - chain_code = blake2b_256(&junction.encode()); - } else { - junction.encode_to(&mut &mut chain_code[..]); - } - chain_code + let mut chain_code = [0u8; 32]; + if junction.encoded_size() > chain_code.len() { + chain_code = blake2b_256(&junction.encode()); + } else { + junction.encode_to(&mut &mut chain_code[..]); + } + chain_code } fn keyed_blake2b_256(message: &[u8], key: &[u8]) -> [u8; 32] { - let mut params = blake2b_simd::Params::new(); - params.hash_length(32).key(key); - params - .hash(message) - .as_bytes() - .try_into() - .expect("BLAKE2b-256 returns 32 bytes") + let mut params = blake2b_simd::Params::new(); + params.hash_length(32).key(key); + params + .hash(message) + .as_bytes() + .try_into() + .expect("BLAKE2b-256 returns 32 bytes") } fn blake2b_256(message: &[u8]) -> [u8; 32] { - blake2b_simd::Params::new() - .hash_length(32) - .hash(message) - .as_bytes() - .try_into() - .expect("BLAKE2b-256 returns 32 bytes") + blake2b_simd::Params::new() + .hash_length(32) + .hash(message) + .as_bytes() + .try_into() + .expect("BLAKE2b-256 returns 32 bytes") } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CoinDerivedWalletError { - /// The requesting signer's account id is not this coin's public key. - UnexpectedAccount, + /// The requesting signer's account id is not this coin's public key. + UnexpectedAccount, } impl std::fmt::Display for CoinDerivedWalletError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "signer account does not match the coin key") - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "signer account does not match the coin key") + } } impl std::error::Error for CoinDerivedWalletError {} pub struct CoinDerivedWallet { - keypair: schnorrkel::Keypair, + keypair: schnorrkel::Keypair, } impl CoinDerivedWallet { - pub fn new(keypair: schnorrkel::Keypair) -> Self { - Self { keypair } - } - - /// The wallet for one coin index. - pub fn for_index(factory: &CoinKeypairFactory, index: u32) -> Result { - Ok(Self::new(factory.keypair(index)?)) - } - - /// The coin's raw public key (== its sr25519 account id). - pub fn public_key(&self) -> [u8; 32] { - self.keypair.public.to_bytes() - } - - pub fn fetch_signer_secret( - &self, - signer_account_id: &[u8; 32], - ) -> Result<[u8; 64], CoinDerivedWalletError> { - if *signer_account_id != self.public_key() { - return Err(CoinDerivedWalletError::UnexpectedAccount); - } - Ok(self.keypair.secret.to_bytes()) - } + pub fn new(keypair: schnorrkel::Keypair) -> Self { + Self { keypair } + } + + /// The wallet for one coin index. + pub fn for_index(factory: &CoinKeypairFactory, index: u32) -> Result { + Ok(Self::new(factory.keypair(index)?)) + } + + /// The coin's raw public key (== its sr25519 account id). + pub fn public_key(&self) -> [u8; 32] { + self.keypair.public.to_bytes() + } + + pub fn fetch_signer_secret( + &self, + signer_account_id: &[u8; 32], + ) -> Result<[u8; 64], CoinDerivedWalletError> { + if *signer_account_id != self.public_key() { + return Err(CoinDerivedWalletError::UnexpectedAccount); + } + Ok(self.keypair.secret.to_bytes()) + } } #[cfg(test)] mod tests { - use super::*; - - const ENTROPY: [u8; 16] = [7u8; 16]; - - #[test] - fn coin_keys_are_distinct_per_index_and_deterministic() { - let factory = CoinKeypairFactory::new(&ENTROPY); - let a0 = factory.public_key(0).unwrap(); - let a1 = factory.public_key(1).unwrap(); - assert_ne!(a0, a1, "indices must never collide"); - assert_eq!(a0, CoinKeypairFactory::new(&ENTROPY).public_key(0).unwrap()); - } - - #[test] - fn clearing_cached_coin_parent_prevents_further_derivation() { - let mut factory = CoinKeypairFactory::new(&ENTROPY); - factory.public_key(0).unwrap(); - factory.zeroize(); - assert!(factory.public_key(0).is_err()); - assert!(factory.secret_bytes(1).is_err()); - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn coin_keys_match_canonical_main_purse_with_soft_items() { - use subxt_signer::{SecretUri, bip39::Mnemonic, sr25519}; - - let mnemonic = Mnemonic::from_entropy(&ENTROPY).unwrap(); - for index in [0, u32::MAX] { - let soft_uri: SecretUri = format!("{mnemonic}//coinage//4294967295//0/{index}") - .parse() - .unwrap(); - let hard_uri: SecretUri = format!("{mnemonic}//coinage//4294967295//0//{index}") - .parse() - .unwrap(); - let actual = CoinKeypairFactory::new(&ENTROPY).keypair(index).unwrap(); - let expected = sr25519::Keypair::from_uri(&soft_uri).unwrap(); - assert_eq!(actual.public.to_bytes(), expected.public_key().0); - assert_ne!( - actual.public.to_bytes(), - sr25519::Keypair::from_uri(&hard_uri) - .unwrap() - .public_key() - .0, - "coin items must be soft, unlike voucher items" - ); - let message = b"coin main-purse signing regression"; - let signature = actual.sign_simple(b"substrate", message); - assert!(sr25519::verify( - &sr25519::Signature(signature.to_bytes()), - message, - &expected.public_key(), - )); - } - } - - #[test] - fn coin_secret_bytes_are_64_and_rebuild_the_keypair() { - let factory = CoinKeypairFactory::new(&ENTROPY); - let secret = factory.secret_bytes(3).unwrap(); - let rebuilt = schnorrkel::SecretKey::from_bytes(&secret).unwrap(); - assert_eq!( - rebuilt.to_public().to_bytes(), - factory.public_key(3).unwrap(), - "memo secret bytes must reconstruct the coin's public identity" - ); - } - - #[test] - fn voucher_seeds_are_deterministic_and_distinct() { - let factory = VoucherKeypairFactory::new(&ENTROPY); - assert_eq!( - factory.seed(0), - VoucherKeypairFactory::new(&ENTROPY).seed(0) - ); - assert_ne!(factory.seed(0), factory.seed(1)); - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn voucher_entropy_matches_canonical_full_path_fold() { - use blake2::{ - Blake2bMac, - digest::{KeyInit, Mac, consts::U32}, - }; - use subxt_signer::{DeriveJunction, SecretUri}; - - // Independent URI parser and BLAKE2 implementation: no production - // chain-code helper, path constants, or keyed-hash helper is reused. - let uri: SecretUri = "//coinage-ring-vrf//4294967295//0//5".parse().unwrap(); - let mut expected = ENTROPY.to_vec(); - for junction in uri.junctions { - let DeriveJunction::Hard(chain_code) = junction else { - panic!("voucher reference path must be entirely hard"); - }; - let mut hash = as KeyInit>::new_from_slice(&chain_code).unwrap(); - Mac::update(&mut hash, &expected); - expected = hash.finalize().into_bytes().to_vec(); - } - assert_eq!( - VoucherKeypairFactory::new(&ENTROPY).seed(5).0.as_slice(), - expected - ); - } - - /// The voucher path must not shadow the coin path from the same - /// entropy — different junction lists, different key material. - #[test] - fn voucher_path_diverges_from_coin_path() { - let coins = CoinKeypairFactory::new(&ENTROPY); - let vouchers = VoucherKeypairFactory::new(&ENTROPY); - assert_ne!(vouchers.seed(0).0, coins.secret_bytes(0).unwrap()[..32]); - } - - #[test] - fn coin_derived_wallet_guards_the_signer_secret() { - let factory = CoinKeypairFactory::new(&ENTROPY); - let wallet = CoinDerivedWallet::for_index(&factory, 3).unwrap(); - let account_id = wallet.public_key(); - - let secret = wallet.fetch_signer_secret(&account_id).unwrap(); - let rebuilt = schnorrkel::SecretKey::from_bytes(&secret).unwrap(); - assert_eq!(rebuilt.to_public().to_bytes(), account_id); - - let mut wrong = account_id; - wrong[0] ^= 1; - assert_eq!( - wallet.fetch_signer_secret(&wrong), - Err(CoinDerivedWalletError::UnexpectedAccount) - ); - } + use super::*; + + const ENTROPY: [u8; 16] = [7u8; 16]; + + #[test] + fn coin_keys_are_distinct_per_index_and_deterministic() { + let factory = CoinKeypairFactory::new(&ENTROPY); + let a0 = factory.public_key(0).unwrap(); + let a1 = factory.public_key(1).unwrap(); + assert_ne!(a0, a1, "indices must never collide"); + assert_eq!(a0, CoinKeypairFactory::new(&ENTROPY).public_key(0).unwrap()); + } + + #[test] + fn clearing_cached_coin_parent_prevents_further_derivation() { + let mut factory = CoinKeypairFactory::new(&ENTROPY); + factory.public_key(0).unwrap(); + factory.zeroize(); + assert!(factory.public_key(0).is_err()); + assert!(factory.secret_bytes(1).is_err()); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn coin_keys_match_canonical_main_purse_with_soft_items() { + use subxt_signer::{SecretUri, bip39::Mnemonic, sr25519}; + + let mnemonic = Mnemonic::from_entropy(&ENTROPY).unwrap(); + for index in [0, u32::MAX] { + let soft_uri: SecretUri = + format!("{mnemonic}//coinage//4294967295//0/{index}").parse().unwrap(); + let hard_uri: SecretUri = + format!("{mnemonic}//coinage//4294967295//0//{index}").parse().unwrap(); + let actual = CoinKeypairFactory::new(&ENTROPY).keypair(index).unwrap(); + let expected = sr25519::Keypair::from_uri(&soft_uri).unwrap(); + assert_eq!(actual.public.to_bytes(), expected.public_key().0); + assert_ne!( + actual.public.to_bytes(), + sr25519::Keypair::from_uri(&hard_uri).unwrap().public_key().0, + "coin items must be soft, unlike voucher items" + ); + let message = b"coin main-purse signing regression"; + let signature = actual.sign_simple(b"substrate", message); + assert!(sr25519::verify( + &sr25519::Signature(signature.to_bytes()), + message, + &expected.public_key(), + )); + } + } + + #[test] + fn coin_secret_bytes_are_64_and_rebuild_the_keypair() { + let factory = CoinKeypairFactory::new(&ENTROPY); + let secret = factory.secret_bytes(3).unwrap(); + let rebuilt = schnorrkel::SecretKey::from_bytes(&secret).unwrap(); + assert_eq!( + rebuilt.to_public().to_bytes(), + factory.public_key(3).unwrap(), + "memo secret bytes must reconstruct the coin's public identity" + ); + } + + #[test] + fn voucher_seeds_are_deterministic_and_distinct() { + let factory = VoucherKeypairFactory::new(&ENTROPY); + assert_eq!(factory.seed(0), VoucherKeypairFactory::new(&ENTROPY).seed(0)); + assert_ne!(factory.seed(0), factory.seed(1)); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn voucher_entropy_matches_canonical_full_path_fold() { + use blake2::{ + Blake2bMac, + digest::{KeyInit, Mac, consts::U32}, + }; + use subxt_signer::{DeriveJunction, SecretUri}; + + // Independent URI parser and BLAKE2 implementation: no production + // chain-code helper, path constants, or keyed-hash helper is reused. + let uri: SecretUri = "//coinage-ring-vrf//4294967295//0//5".parse().unwrap(); + let mut expected = ENTROPY.to_vec(); + for junction in uri.junctions { + let DeriveJunction::Hard(chain_code) = junction else { + panic!("voucher reference path must be entirely hard"); + }; + let mut hash = as KeyInit>::new_from_slice(&chain_code).unwrap(); + Mac::update(&mut hash, &expected); + expected = hash.finalize().into_bytes().to_vec(); + } + assert_eq!(VoucherKeypairFactory::new(&ENTROPY).seed(5).0.as_slice(), expected); + } + + /// The voucher path must not shadow the coin path from the same + /// entropy — different junction lists, different key material. + #[test] + fn voucher_path_diverges_from_coin_path() { + let coins = CoinKeypairFactory::new(&ENTROPY); + let vouchers = VoucherKeypairFactory::new(&ENTROPY); + assert_ne!(vouchers.seed(0).0, coins.secret_bytes(0).unwrap()[..32]); + } + + #[test] + fn coin_derived_wallet_guards_the_signer_secret() { + let factory = CoinKeypairFactory::new(&ENTROPY); + let wallet = CoinDerivedWallet::for_index(&factory, 3).unwrap(); + let account_id = wallet.public_key(); + + let secret = wallet.fetch_signer_secret(&account_id).unwrap(); + let rebuilt = schnorrkel::SecretKey::from_bytes(&secret).unwrap(); + assert_eq!(rebuilt.to_public().to_bytes(), account_id); + + let mut wrong = account_id; + wrong[0] ^= 1; + assert_eq!( + wallet.fetch_signer_secret(&wrong), + Err(CoinDerivedWalletError::UnexpectedAccount) + ); + } } /// Required exact Bandersnatch primitive implementation. The ring exponent is @@ -388,51 +367,49 @@ mod tests { /// Adapters must use the deployed Bandersnatch suite; a different curve or /// synthetic proof is not a valid implementation. Seeds must not be retained. pub trait VoucherCryptography: Send + Sync { - /// Derive the Bandersnatch public member key. - fn member_key(&self, seed: &VoucherSeed) -> Result<[u8; 32], String>; - /// Sign an ownership message with the derived Bandersnatch key. - fn sign(&self, seed: &VoucherSeed, message: &[u8]) -> Result<[u8; 64], String>; - /// Derive the context-bound alias for this voucher. - fn alias(&self, seed: &VoucherSeed, context: &[u8]) -> Result<[u8; 32], String>; - /// Generate the canonical 785-byte ring-VRF proof. - fn ring_vrf_proof( - &self, - seed: &VoucherSeed, - ring_exponent: u8, - ring_members: &[[u8; 32]], - context: &[u8], - message: &[u8], - ) -> Result, String>; + /// Derive the Bandersnatch public member key. + fn member_key(&self, seed: &VoucherSeed) -> Result<[u8; 32], String>; + /// Sign an ownership message with the derived Bandersnatch key. + fn sign(&self, seed: &VoucherSeed, message: &[u8]) -> Result<[u8; 64], String>; + /// Derive the context-bound alias for this voucher. + fn alias(&self, seed: &VoucherSeed, context: &[u8]) -> Result<[u8; 32], String>; + /// Generate the canonical 785-byte ring-VRF proof. + fn ring_vrf_proof( + &self, + seed: &VoucherSeed, + ring_exponent: u8, + ring_members: &[[u8; 32]], + context: &[u8], + message: &[u8], + ) -> Result, String>; } // Derived from MIT-licensed host-rust-core product_account.rs. Copyright // (c) 2026 Parity Technologies. The complete MIT notice is in LICENSE-MIT. fn derive_sr25519_hard_path( - entropy: &[u8], - junctions: &[[u8; 32]], + entropy: &[u8], + junctions: &[[u8; 32]], ) -> Result { - use schnorrkel::{ExpansionMode, derive::ChainCode}; - let mini_secret = substrate_bip39::mini_secret_from_entropy(entropy, "") - .map_err(|error| format!("invalid BIP-39 entropy: {error:?}"))?; - let mut keypair = mini_secret.expand_to_keypair(ExpansionMode::Ed25519); - for junction in junctions { - let chain_code = ChainCode(*junction); - let (mini_secret, _) = keypair - .secret - .hard_derive_mini_secret_key(Some(chain_code), b""); - keypair = mini_secret.expand_to_keypair(ExpansionMode::Ed25519); - } - Ok(keypair) + use schnorrkel::{ExpansionMode, derive::ChainCode}; + let mini_secret = substrate_bip39::mini_secret_from_entropy(entropy, "") + .map_err(|error| format!("invalid BIP-39 entropy: {error:?}"))?; + let mut keypair = mini_secret.expand_to_keypair(ExpansionMode::Ed25519); + for junction in junctions { + let chain_code = ChainCode(*junction); + let (mini_secret, _) = keypair.secret.hard_derive_mini_secret_key(Some(chain_code), b""); + keypair = mini_secret.expand_to_keypair(ExpansionMode::Ed25519); + } + Ok(keypair) } #[cfg(test)] mod root_derivation_tests { - #[test] - fn entropy_expansion_matches_deployed_host() { - let root = super::derive_sr25519_hard_path(&[0xAB; 16], &[]).unwrap(); - assert_eq!( - hex::encode(root.public.to_bytes()), - "0062ba8ae929ea64bc2ad6f21359e96a29e236a41d376d1c5ba76491da94fc72" - ); - } + #[test] + fn entropy_expansion_matches_deployed_host() { + let root = super::derive_sr25519_hard_path(&[0xAB; 16], &[]).unwrap(); + assert_eq!( + hex::encode(root.public.to_bytes()), + "0062ba8ae929ea64bc2ad6f21359e96a29e236a41d376d1c5ba76491da94fc72" + ); + } } diff --git a/rust/crates/truapi-coinage/src/lib.rs b/rust/crates/truapi-coinage/src/lib.rs index 0205af17f5..24d04662dd 100644 --- a/rust/crates/truapi-coinage/src/lib.rs +++ b/rust/crates/truapi-coinage/src/lib.rs @@ -77,89 +77,87 @@ pub mod wal; pub type Spawner = std::sync::Arc) + Send + Sync>; pub use allocator::{ - CoinAllocator, FixedDelayProvider, SystemJitterDelayProvider, VoucherAllocator, - VoucherDelayProvider, + CoinAllocator, FixedDelayProvider, SystemJitterDelayProvider, VoucherAllocator, + VoucherDelayProvider, }; pub use balance::{BalanceBuckets, compute_balance, next_unlock_at_ms}; pub use claim::{ - ClaimError, ClaimExecutor, ClaimOrchestrator, ClaimStatus, ClaimStatusStore, IncomingClaim, - SendConfirmation, TransferSendVerifying, claimed_amount_from_plan, restore_persisted_statuses, + ClaimError, ClaimExecutor, ClaimOrchestrator, ClaimStatus, ClaimStatusStore, IncomingClaim, + SendConfirmation, TransferSendVerifying, claimed_amount_from_plan, restore_persisted_statuses, }; pub use claim_plan::{ - ClaimPlan, ClaimPlanStatus, ClaimPlanStore, CodableClaimPlanEntry, decode_claim_plan_entries, - encode_claim_plan_entries, + ClaimPlan, ClaimPlanStatus, ClaimPlanStore, CodableClaimPlanEntry, decode_claim_plan_entries, + encode_claim_plan_entries, }; pub use clock::{Clock, FixedClock, SystemClock}; pub use constants::{ - CASH_ASSET_PRECISION, CASH_PLANKS_PER_CENT, COIN_MAX_AGE, MAX_VOUCHER_WAIT_TIME, - MINIMUM_RING_SIZE, RECYCLE_AT_AGE, SEND_VERIFY_BLOCK_TIMEOUT, WAL_MORTALITY_BLOCKS, + CASH_ASSET_PRECISION, CASH_PLANKS_PER_CENT, COIN_MAX_AGE, MAX_VOUCHER_WAIT_TIME, + MINIMUM_RING_SIZE, RECYCLE_AT_AGE, SEND_VERIFY_BLOCK_TIMEOUT, WAL_MORTALITY_BLOCKS, }; pub use denomination::{Denomination, DenominationBreakdown, DenominationBreakdownContext}; pub use index_store::{ - COIN_INDEX_KEY, CoinageIndexStore, InMemoryCoinageIndexStore, IndexKind, VOUCHER_INDEX_KEY, - decode_index, encode_index, + COIN_INDEX_KEY, CoinageIndexStore, InMemoryCoinageIndexStore, IndexKind, VOUCHER_INDEX_KEY, + decode_index, encode_index, }; -pub use keys::VoucherCryptography; pub use keys::{ - CoinDerivedWallet, CoinKeypairFactory, MAIN_PURSE, PAGE, VoucherKeypairFactory, VoucherSeed, + CoinDerivedWallet, CoinKeypairFactory, MAIN_PURSE, PAGE, VoucherCryptography, + VoucherKeypairFactory, VoucherSeed, }; pub use memo::{MemoEntry, TransferMemo}; pub use model::{ - Coin, CoinState, EffectivePrivacy, Voucher, VoucherLocalState, VoucherPrivacyLevel, - VoucherRemoteState, ring_readiness_upgraded, + Coin, CoinState, EffectivePrivacy, Voucher, VoucherLocalState, VoucherPrivacyLevel, + VoucherRemoteState, ring_readiness_upgraded, }; pub use outgoing_transfer::{ - OutgoingCoinTransferParts, OutgoingCoinTransferService, OutgoingHandoffRejected, - OutgoingTransferError, OutgoingTransferReconciliation, + OutgoingCoinTransferParts, OutgoingCoinTransferService, OutgoingHandoffRejected, + OutgoingTransferError, OutgoingTransferReconciliation, }; pub use query::{ - AliasState, CoinOnChainQueryService, CoinageQueryError, CoinageStorageKey, CoinageStorageQuery, - LockInfo, LockReason, QueryVoucherLocationSubscriber, RecyclerReadinessLoader, - RecyclerRevisionSnapshot, VoucherOnChainInfo, VoucherOnChainQueryService, + AliasState, CoinOnChainQueryService, CoinageQueryError, CoinageStorageKey, CoinageStorageQuery, + LockInfo, LockReason, QueryVoucherLocationSubscriber, RecyclerReadinessLoader, + RecyclerRevisionSnapshot, VoucherOnChainInfo, VoucherOnChainQueryService, }; pub use recipient::{CoinageSendMessage, TransferRecipientService}; pub use recovery::{RecoveryChainProbe, RecoveryReport, TransferRecoveryService}; pub use repo::{ - CoinRepository, InMemoryCoinRepository, InMemoryVoucherRepository, TransferContext, - TransferStateCommitter, VoucherRepository, + CoinRepository, InMemoryCoinRepository, InMemoryVoucherRepository, TransferContext, + TransferStateCommitter, VoucherRepository, }; -pub use ring_proof::BandersnatchRingProofProvider; -pub use ring_proof::PersonRingProofSigner; pub use ring_proof::{ - FREE_UNLOAD_TOKEN_CONTEXT_PREFIX, PersonOriginKind, RECYCLER_ALIAS_CONTEXT, RING_VRF_PROOF_LEN, - ResolvedUnloadToken, RingProofError, RingProofParams, RingProofProvider, UnloadProofRequest, - UnloadTokenProof, + BandersnatchRingProofProvider, FREE_UNLOAD_TOKEN_CONTEXT_PREFIX, PersonOriginKind, + PersonRingProofSigner, RECYCLER_ALIAS_CONTEXT, RING_VRF_PROOF_LEN, ResolvedUnloadToken, + RingProofError, RingProofParams, RingProofProvider, UnloadProofRequest, UnloadTokenProof, }; pub use secret_claim::{ - ExternalCoinTransferBackend, ExternalCoinTransferRequest, ExternalSecretClaimService, - SpentCoinTransferRecoveryReport, SpentCoinTransferRecoveryService, external_claim_message_id, + ExternalCoinTransferBackend, ExternalCoinTransferRequest, ExternalMemoClaiming, + ExternalSecretClaimService, SpentCoinTransferRecoveryReport, SpentCoinTransferRecoveryService, + SpentCoinsRecovering, external_claim_message_id, }; -pub use secret_claim::{ExternalMemoClaiming, SpentCoinsRecovering}; pub use selection::{ - CoinSelectionError, CoinSelectionResult, CoinSelector, PrivacyLevel, RecyclerKey, - TransferStrategy, VoucherGroup, find_exact_match, + CoinSelectionError, CoinSelectionResult, CoinSelector, PrivacyLevel, RecyclerKey, + TransferStrategy, VoucherGroup, find_exact_match, }; pub use sync::{ - CoinStateSubscriber, CoinStateSyncService, CoinStateUpdate, CoinageDatabaseDependencyFactory, - NotifyingCoinRepository, NotifyingVoucherRepository, OnChainCoin, + CoinStateSubscriber, CoinStateSyncService, CoinStateUpdate, CoinageDatabaseDependencyFactory, + NotifyingCoinRepository, NotifyingVoucherRepository, OnChainCoin, }; pub use tasks::ActiveTaskRegistry; pub use transfer_sender::{ - OpaqueTransferPreview, PreparedUnloadGroup, RegularCoinTransferParts, - RegularCoinTransferService, RegularTransferError, RegularTransferSubmitter, - SplitTransferSubmission, TransferPreviewChoice, TransferPreviewStrategy, UnloadGroupDraft, - UnloadOriginPreparation, VoucherSelectionDiagnostic, voucher_selection_diagnostics, + OpaqueTransferPreview, PreparedUnloadGroup, RegularCoinTransferParts, + RegularCoinTransferService, RegularTransferError, RegularTransferSubmitter, + SplitTransferSubmission, TransferPreviewChoice, TransferPreviewStrategy, UnloadGroupDraft, + UnloadOriginPreparation, VoucherSelectionDiagnostic, voucher_selection_diagnostics, }; pub use voucher_location::{ - RingPosition, RingStatus, VoucherLocationService, VoucherLocationSubscriber, - VoucherLocationUpdate, + RingPosition, RingStatus, VoucherLocationService, VoucherLocationSubscriber, + VoucherLocationUpdate, }; #[cfg(test)] fn test_spawner() -> Spawner { - std::sync::Arc::new(|future| { - tokio::spawn(future); - }) + std::sync::Arc::new(|future| { + tokio::spawn(future); + }) } pub use wal::{CheckpointBlock, TransferWalEntry, WalCoinRef, WalOperation, WalPayload, WalStore}; diff --git a/rust/crates/truapi-coinage/src/members.rs b/rust/crates/truapi-coinage/src/members.rs index 43a8e88eec..0345dd102a 100644 --- a/rust/crates/truapi-coinage/src/members.rs +++ b/rust/crates/truapi-coinage/src/members.rs @@ -17,16 +17,12 @@ pub type RingIndex = u32; /// (`indiv_support::traits::reality::RingPosition`). #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub enum RingPosition { - #[codec(index = 0)] - Onboarding { queue_page: u32, queued_at: u64 }, - #[codec(index = 1)] - Included { - ring_index: u32, - ring_page: u32, - ring_position: u32, - }, - #[codec(index = 2)] - Suspended, + #[codec(index = 0)] + Onboarding { queue_page: u32, queued_at: u64 }, + #[codec(index = 1)] + Included { ring_index: u32, ring_page: u32, ring_position: u32 }, + #[codec(index = 2)] + Suspended, } /// `Members.RingKeysStatus` value (`indiv_support::…::RingStatus`). It @@ -34,17 +30,17 @@ pub enum RingPosition { /// timestamp the ring became immutable. #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub struct RingStatus { - pub total: u32, - pub included: u32, - /// Seconds timestamp once the ring stopped accepting keys. - pub immutable_since: Option, + pub total: u32, + pub included: u32, + /// Seconds timestamp once the ring stopped accepting keys. + pub immutable_since: Option, } impl RingStatus { - /// Keys queued behind the proof set. - pub fn queued(&self) -> u32 { - self.total.saturating_sub(self.included) - } + /// Keys queued behind the proof set. + pub fn queued(&self) -> u32 { + self.total.saturating_sub(self.included) + } } /// `Members.Root` value: the current ring root commitment. @@ -54,7 +50,7 @@ impl RingStatus { /// `brevity-ffi/examples/ring_root_type_probe.rs`). #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct RingRoot { - pub root: [u8; 288], - pub revision: u32, - pub intermediate: [u8; 848], + pub root: [u8; 288], + pub revision: u32, + pub intermediate: [u8; 848], } diff --git a/rust/crates/truapi-coinage/src/memo.rs b/rust/crates/truapi-coinage/src/memo.rs index 57da358c70..abb23c3442 100644 --- a/rust/crates/truapi-coinage/src/memo.rs +++ b/rust/crates/truapi-coinage/src/memo.rs @@ -2,9 +2,10 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use blake2::Blake2b; -use blake2::digest::Digest; -use blake2::digest::consts::U32; +use blake2::{ + Blake2b, + digest::{Digest, consts::U32}, +}; use parity_scale_codec::{Compact, Decode, Encode, Input}; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -13,228 +14,199 @@ use zeroize::{Zeroize, ZeroizeOnDrop}; pub struct MemoEntry(pub [u8; 64]); impl std::fmt::Debug for MemoEntry { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("MemoEntry(..)") - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("MemoEntry(..)") + } } /// The transfer memo: entries plus the expected total value in planks. #[derive(Zeroize, ZeroizeOnDrop)] pub struct TransferMemo { - pub entries: Vec, - pub total_value: u128, + pub entries: Vec, + pub total_value: u128, } impl std::fmt::Debug for TransferMemo { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "TransferMemo {{ entries: {}, .. }}", self.entries.len()) - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "TransferMemo {{ entries: {}, .. }}", self.entries.len()) + } } impl TransferMemo { - /// Exact iOS `TransferMemo.encode(scaleEncoder:)` layout: SCALE - /// `Vec>` entries followed by a SCALE compact `BigUInt` - /// total. The returned bytes are secret material: callers must retain - /// them only in zeroizing buffers and must never log or expose them. - pub fn scale_encoded(&self) -> Vec { - let count = u32::try_from(self.entries.len()).expect("memo entry count fits SCALE u32"); - let mut encoded = - Vec::with_capacity(self.entries.len().saturating_mul(66).saturating_add(22)); - Compact(count).encode_to(&mut encoded); - for entry in &self.entries { - Compact(64u32).encode_to(&mut encoded); - encoded.extend_from_slice(&entry.0); - } - Compact(self.total_value).encode_to(&mut encoded); - encoded - } - - /// Strict inverse of [`Self::scale_encoded`]. Every entry must be one - /// 64-byte expanded sr25519 secret, and trailing bytes reject. - /// Partially decoded keys are wiped on every exit. - pub fn from_scale_encoded(bytes: &[u8]) -> Result { - let mut input = bytes; - let count = Compact::::decode(&mut input) - .map_err(|error| format!("transfer memo entry count decode failed: {error}"))? - .0 as usize; - if count > input.len() / 66 { - return Err("transfer memo entries exceed its encoded length".into()); - } - let mut entries = Vec::with_capacity(count); - for _ in 0..count { - let length = Compact::::decode(&mut input) - .map_err(|error| format!("transfer memo entry length decode failed: {error}"))? - .0; - if length != 64 { - return Err(format!( - "transfer memo entry is {length} bytes; expected 64" - )); - } - let mut entry = MemoEntry([0; 64]); - input - .read(&mut entry.0) - .map_err(|error| format!("transfer memo entry decode failed: {error}"))?; - entries.push(entry); - } - let total_value = Compact::::decode(&mut input) - .map_err(|error| format!("transfer memo total decode failed: {error}"))? - .0; - if !input.is_empty() { - return Err("transfer memo has trailing bytes".into()); - } - Ok(Self { - entries, - total_value, - }) - } - - pub fn identifier(&self) -> [u8; 32] { - let value_be = self.total_value.to_be_bytes(); - let first_nonzero = value_be - .iter() - .position(|byte| *byte != 0) - .unwrap_or(value_be.len()); - let value = &value_be[first_nonzero..]; - let Some((first, rest)) = self.entries.split_first() else { - return blake2b_256(value); - }; - let mut acc = blake2b_256_keyed(&first.0, value); - for entry in rest { - acc = blake2b_256_keyed(&entry.0, &acc); - } - acc - } + /// Exact iOS `TransferMemo.encode(scaleEncoder:)` layout: SCALE + /// `Vec>` entries followed by a SCALE compact `BigUInt` + /// total. The returned bytes are secret material: callers must retain + /// them only in zeroizing buffers and must never log or expose them. + pub fn scale_encoded(&self) -> Vec { + let count = u32::try_from(self.entries.len()).expect("memo entry count fits SCALE u32"); + let mut encoded = + Vec::with_capacity(self.entries.len().saturating_mul(66).saturating_add(22)); + Compact(count).encode_to(&mut encoded); + for entry in &self.entries { + Compact(64u32).encode_to(&mut encoded); + encoded.extend_from_slice(&entry.0); + } + Compact(self.total_value).encode_to(&mut encoded); + encoded + } + + /// Strict inverse of [`Self::scale_encoded`]. Every entry must be one + /// 64-byte expanded sr25519 secret, and trailing bytes reject. + /// Partially decoded keys are wiped on every exit. + pub fn from_scale_encoded(bytes: &[u8]) -> Result { + let mut input = bytes; + let count = Compact::::decode(&mut input) + .map_err(|error| format!("transfer memo entry count decode failed: {error}"))? + .0 as usize; + if count > input.len() / 66 { + return Err("transfer memo entries exceed its encoded length".into()); + } + let mut entries = Vec::with_capacity(count); + for _ in 0..count { + let length = Compact::::decode(&mut input) + .map_err(|error| format!("transfer memo entry length decode failed: {error}"))? + .0; + if length != 64 { + return Err(format!("transfer memo entry is {length} bytes; expected 64")); + } + let mut entry = MemoEntry([0; 64]); + input + .read(&mut entry.0) + .map_err(|error| format!("transfer memo entry decode failed: {error}"))?; + entries.push(entry); + } + let total_value = Compact::::decode(&mut input) + .map_err(|error| format!("transfer memo total decode failed: {error}"))? + .0; + if !input.is_empty() { + return Err("transfer memo has trailing bytes".into()); + } + Ok(Self { entries, total_value }) + } + + pub fn identifier(&self) -> [u8; 32] { + let value_be = self.total_value.to_be_bytes(); + let first_nonzero = value_be.iter().position(|byte| *byte != 0).unwrap_or(value_be.len()); + let value = &value_be[first_nonzero..]; + let Some((first, rest)) = self.entries.split_first() else { + return blake2b_256(value); + }; + let mut acc = blake2b_256_keyed(&first.0, value); + for entry in rest { + acc = blake2b_256_keyed(&entry.0, &acc); + } + acc + } } fn blake2b_256(data: &[u8]) -> [u8; 32] { - let mut hasher = Blake2b::::new(); - hasher.update(data); - hasher.finalize().into() + let mut hasher = Blake2b::::new(); + hasher.update(data); + hasher.finalize().into() } fn blake2b_256_keyed(key: &[u8], data: &[u8]) -> [u8; 32] { - let hash = blake2b_simd::Params::new() - .hash_length(32) - .key(key) - .hash(data); - <[u8; 32]>::try_from(hash.as_bytes()).expect("hash_length is 32") + let hash = blake2b_simd::Params::new().hash_length(32).key(key).hash(data); + <[u8; 32]>::try_from(hash.as_bytes()).expect("hash_length is 32") } #[cfg(test)] mod tests { - use super::*; - - fn memo() -> TransferMemo { - TransferMemo { - entries: vec![MemoEntry([1u8; 64]), MemoEntry([2u8; 64])], - total_value: 1_234_567, - } - } - - #[test] - fn identifier_is_deterministic() { - assert_eq!(memo().identifier(), memo().identifier()); - } - - #[test] - fn identifier_matches_the_reference_fold_layout() { - let memo = TransferMemo { - entries: vec![MemoEntry([0x11; 64]), MemoEntry([0x22; 64])], - total_value: 100, - }; - // BigUInt(100).serialize == [0x64] — one byte, not 16. - let step1 = blake2b_simd::Params::new() - .hash_length(32) - .key(&[0x11; 64]) - .hash(&[0x64]); - let step2 = blake2b_simd::Params::new() - .hash_length(32) - .key(&[0x22; 64]) - .hash(step1.as_bytes()); - assert_eq!( - memo.identifier(), - <[u8; 32]>::try_from(step2.as_bytes()).unwrap() - ); - - // BigUInt(0).serialize is EMPTY — the fold starts from zero bytes. - let zero = TransferMemo { - entries: vec![MemoEntry([0x11; 64])], - total_value: 0, - }; - let expected = blake2b_simd::Params::new() - .hash_length(32) - .key(&[0x11; 64]) - .hash(&[]); - assert_eq!( - zero.identifier(), - <[u8; 32]>::try_from(expected.as_bytes()).unwrap() - ); - } - - #[test] - fn scale_layout_matches_ios_vec_data_then_compact_biguint() { - let memo = TransferMemo { - entries: vec![MemoEntry([0xAB; 64])], - total_value: 1_000, - }; - let encoded = memo.scale_encoded(); - assert_eq!(encoded[0], 0x04, "one-entry Vec compact prefix"); - assert_eq!(&encoded[1..3], &[0x01, 0x01], "64-byte Data prefix"); - assert_eq!(&encoded[3..67], &[0xAB; 64]); - assert_eq!(&encoded[67..], &[0xA1, 0x0F], "compact 1000"); - - let decoded = TransferMemo::from_scale_encoded(&encoded).unwrap(); - assert_eq!(decoded.entries, memo.entries); - assert_eq!(decoded.total_value, memo.total_value); - } - - #[test] - fn scale_decode_rejects_wrong_key_lengths_and_trailing_bytes() { - let mut wrong = vec![vec![1u8; 63]].encode(); - Compact(1u128).encode_to(&mut wrong); - assert!(TransferMemo::from_scale_encoded(&wrong).is_err()); - - let mut trailing = memo().scale_encoded(); - trailing.push(0); - assert!(TransferMemo::from_scale_encoded(&trailing).is_err()); - } - - #[test] - fn identifier_binds_value_entries_and_order() { - let base = memo().identifier(); - let mut other = memo(); - other.total_value += 1; - assert_ne!(base, other.identifier(), "total value is bound"); - - let mut reordered = memo(); - reordered.entries.reverse(); - assert_ne!(base, reordered.identifier(), "entry order is bound"); - - let mut truncated = memo(); - truncated.entries.pop(); - assert_ne!(base, truncated.identifier(), "every entry is bound"); - } - - #[test] - fn zeroize_clears_entry_bytes() { - let mut entry = MemoEntry([0xAB; 64]); - entry.zeroize(); - assert_eq!(entry.0, [0u8; 64]); - } - - #[test] - fn zeroize_clears_the_whole_memo() { - let mut memo = memo(); - memo.zeroize(); - assert!(memo.entries.is_empty(), "entries are dropped and wiped"); - assert_eq!(memo.total_value, 0); - } - - #[test] - fn debug_never_prints_key_bytes() { - let rendered = format!("{:?} {:?}", memo(), MemoEntry([0xCD; 64])); - assert!(!rendered.contains("205"), "no decimal byte dump"); - assert!(!rendered.to_lowercase().contains("cd"), "no hex byte dump"); - assert_eq!(rendered, "TransferMemo { entries: 2, .. } MemoEntry(..)"); - } + use super::*; + + fn memo() -> TransferMemo { + TransferMemo { + entries: vec![MemoEntry([1u8; 64]), MemoEntry([2u8; 64])], + total_value: 1_234_567, + } + } + + #[test] + fn identifier_is_deterministic() { + assert_eq!(memo().identifier(), memo().identifier()); + } + + #[test] + fn identifier_matches_the_reference_fold_layout() { + let memo = TransferMemo { + entries: vec![MemoEntry([0x11; 64]), MemoEntry([0x22; 64])], + total_value: 100, + }; + // BigUInt(100).serialize == [0x64] — one byte, not 16. + let step1 = blake2b_simd::Params::new().hash_length(32).key(&[0x11; 64]).hash(&[0x64]); + let step2 = blake2b_simd::Params::new() + .hash_length(32) + .key(&[0x22; 64]) + .hash(step1.as_bytes()); + assert_eq!(memo.identifier(), <[u8; 32]>::try_from(step2.as_bytes()).unwrap()); + + // BigUInt(0).serialize is EMPTY — the fold starts from zero bytes. + let zero = TransferMemo { entries: vec![MemoEntry([0x11; 64])], total_value: 0 }; + let expected = blake2b_simd::Params::new().hash_length(32).key(&[0x11; 64]).hash(&[]); + assert_eq!(zero.identifier(), <[u8; 32]>::try_from(expected.as_bytes()).unwrap()); + } + + #[test] + fn scale_layout_matches_ios_vec_data_then_compact_biguint() { + let memo = TransferMemo { entries: vec![MemoEntry([0xAB; 64])], total_value: 1_000 }; + let encoded = memo.scale_encoded(); + assert_eq!(encoded[0], 0x04, "one-entry Vec compact prefix"); + assert_eq!(&encoded[1..3], &[0x01, 0x01], "64-byte Data prefix"); + assert_eq!(&encoded[3..67], &[0xAB; 64]); + assert_eq!(&encoded[67..], &[0xA1, 0x0F], "compact 1000"); + + let decoded = TransferMemo::from_scale_encoded(&encoded).unwrap(); + assert_eq!(decoded.entries, memo.entries); + assert_eq!(decoded.total_value, memo.total_value); + } + + #[test] + fn scale_decode_rejects_wrong_key_lengths_and_trailing_bytes() { + let mut wrong = vec![vec![1u8; 63]].encode(); + Compact(1u128).encode_to(&mut wrong); + assert!(TransferMemo::from_scale_encoded(&wrong).is_err()); + + let mut trailing = memo().scale_encoded(); + trailing.push(0); + assert!(TransferMemo::from_scale_encoded(&trailing).is_err()); + } + + #[test] + fn identifier_binds_value_entries_and_order() { + let base = memo().identifier(); + let mut other = memo(); + other.total_value += 1; + assert_ne!(base, other.identifier(), "total value is bound"); + + let mut reordered = memo(); + reordered.entries.reverse(); + assert_ne!(base, reordered.identifier(), "entry order is bound"); + + let mut truncated = memo(); + truncated.entries.pop(); + assert_ne!(base, truncated.identifier(), "every entry is bound"); + } + + #[test] + fn zeroize_clears_entry_bytes() { + let mut entry = MemoEntry([0xAB; 64]); + entry.zeroize(); + assert_eq!(entry.0, [0u8; 64]); + } + + #[test] + fn zeroize_clears_the_whole_memo() { + let mut memo = memo(); + memo.zeroize(); + assert!(memo.entries.is_empty(), "entries are dropped and wiped"); + assert_eq!(memo.total_value, 0); + } + + #[test] + fn debug_never_prints_key_bytes() { + let rendered = format!("{:?} {:?}", memo(), MemoEntry([0xCD; 64])); + assert!(!rendered.contains("205"), "no decimal byte dump"); + assert!(!rendered.to_lowercase().contains("cd"), "no hex byte dump"); + assert_eq!(rendered, "TransferMemo { entries: 2, .. } MemoEntry(..)"); + } } diff --git a/rust/crates/truapi-coinage/src/model.rs b/rust/crates/truapi-coinage/src/model.rs index 7082461d4a..85fbfb4ff6 100644 --- a/rust/crates/truapi-coinage/src/model.rs +++ b/rust/crates/truapi-coinage/src/model.rs @@ -6,280 +6,275 @@ use crate::constants::{COIN_MAX_AGE, MINIMUM_RING_SIZE, RECYCLE_AT_AGE}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CoinState { - Available, - /// A recycle-into-voucher extrinsic is in flight. - Recycling, - /// Reserved for an outgoing transfer (set before submission, - /// reverted on failure). - PendingTransfer, - Spent, + Available, + /// A recycle-into-voucher extrinsic is in flight. + Recycling, + /// Reserved for an outgoing transfer (set before submission, + /// reverted on failure). + PendingTransfer, + Spent, } impl CoinState { - pub fn can_transition_to(self, to: CoinState) -> bool { - use CoinState::*; - matches!( - (self, to), - (Available, Recycling) - | (Available, PendingTransfer) - | (Recycling, Spent) - | (Recycling, Available) - | (PendingTransfer, Spent) - | (PendingTransfer, Available) - | (Spent, Available) - ) - } - - /// Stable integer for the `coins.state` column. - pub fn as_raw(self) -> i64 { - match self { - CoinState::Available => 0, - CoinState::Recycling => 1, - CoinState::PendingTransfer => 2, - CoinState::Spent => 3, - } - } - - pub fn from_raw(raw: i64) -> Option { - Some(match raw { - 0 => CoinState::Available, - 1 => CoinState::Recycling, - 2 => CoinState::PendingTransfer, - 3 => CoinState::Spent, - _ => return None, - }) - } + pub fn can_transition_to(self, to: CoinState) -> bool { + use CoinState::*; + matches!( + (self, to), + (Available, Recycling) | + (Available, PendingTransfer) | + (Recycling, Spent) | + (Recycling, Available) | + (PendingTransfer, Spent) | + (PendingTransfer, Available) | + (Spent, Available) + ) + } + + /// Stable integer for the `coins.state` column. + pub fn as_raw(self) -> i64 { + match self { + CoinState::Available => 0, + CoinState::Recycling => 1, + CoinState::PendingTransfer => 2, + CoinState::Spent => 3, + } + } + + pub fn from_raw(raw: i64) -> Option { + Some(match raw { + 0 => CoinState::Available, + 1 => CoinState::Recycling, + 2 => CoinState::PendingTransfer, + 3 => CoinState::Spent, + _ => return None, + }) + } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Coin { - pub exponent: i16, - pub derivation_index: u32, - pub age: Option, - pub state: CoinState, + pub exponent: i16, + pub derivation_index: u32, + pub age: Option, + pub state: CoinState, } impl Coin { - pub fn is_expiring_soon(&self) -> bool { - matches!(self.age, Some(age) if age >= RECYCLE_AT_AGE) - } - - pub fn is_chain_invalid(&self) -> bool { - matches!(self.age, Some(age) if age >= COIN_MAX_AGE) - } - - /// Eligible for transfer selection: available and not expiring soon. - pub fn is_selectable(&self) -> bool { - self.state == CoinState::Available && !self.is_expiring_soon() - } + pub fn is_expiring_soon(&self) -> bool { + matches!(self.age, Some(age) if age >= RECYCLE_AT_AGE) + } + + pub fn is_chain_invalid(&self) -> bool { + matches!(self.age, Some(age) if age >= COIN_MAX_AGE) + } + + /// Eligible for transfer selection: available and not expiring soon. + pub fn is_selectable(&self) -> bool { + self.state == CoinState::Available && !self.is_expiring_soon() + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum VoucherRemoteState { - /// Not yet observed anywhere on-chain (also the state of freshly - /// recovered vouchers before `VoucherLocationService` reconciles). - Unlocated, - /// Ring membership submitted, not yet included. - Onboarding, - /// Included in a recycler ring at this index. - InRecycler { recycler_index: u32 }, - /// Consumed by an unload extrinsic. - Unloaded, + /// Not yet observed anywhere on-chain (also the state of freshly + /// recovered vouchers before `VoucherLocationService` reconciles). + Unlocated, + /// Ring membership submitted, not yet included. + Onboarding, + /// Included in a recycler ring at this index. + InRecycler { recycler_index: u32 }, + /// Consumed by an unload extrinsic. + Unloaded, } impl VoucherRemoteState { - pub fn is_in_recycler(&self) -> bool { - matches!(self, VoucherRemoteState::InRecycler { .. }) - } + pub fn is_in_recycler(&self) -> bool { + matches!(self, VoucherRemoteState::InRecycler { .. }) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum VoucherLocalState { - Available, - PendingTransfer, - PendingOnboarding, - Spent, + Available, + PendingTransfer, + PendingOnboarding, + Spent, } impl VoucherLocalState { - pub fn as_raw(self) -> i64 { - match self { - VoucherLocalState::Available => 0, - VoucherLocalState::PendingTransfer => 1, - VoucherLocalState::PendingOnboarding => 2, - VoucherLocalState::Spent => 3, - } - } - - pub fn from_raw(raw: i64) -> Option { - Some(match raw { - 0 => VoucherLocalState::Available, - 1 => VoucherLocalState::PendingTransfer, - 2 => VoucherLocalState::PendingOnboarding, - 3 => VoucherLocalState::Spent, - _ => return None, - }) - } + pub fn as_raw(self) -> i64 { + match self { + VoucherLocalState::Available => 0, + VoucherLocalState::PendingTransfer => 1, + VoucherLocalState::PendingOnboarding => 2, + VoucherLocalState::Spent => 3, + } + } + + pub fn from_raw(raw: i64) -> Option { + Some(match raw { + 0 => VoucherLocalState::Available, + 1 => VoucherLocalState::PendingTransfer, + 2 => VoucherLocalState::PendingOnboarding, + 3 => VoucherLocalState::Spent, + _ => return None, + }) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum VoucherPrivacyLevel { - Degraded, - Full, + Degraded, + Full, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum EffectivePrivacy { - Degraded, - Full, + Degraded, + Full, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Voucher { - pub exponent: i16, - pub derivation_index: u32, - pub allocated_at_ms: i64, - pub ready_at_ms: i64, - pub remote_state: VoucherRemoteState, - pub local_state: VoucherLocalState, - pub privacy: VoucherPrivacyLevel, + pub exponent: i16, + pub derivation_index: u32, + pub allocated_at_ms: i64, + pub ready_at_ms: i64, + pub remote_state: VoucherRemoteState, + pub local_state: VoucherLocalState, + pub privacy: VoucherPrivacyLevel, } impl Voucher { - pub fn effective_privacy(&self, now_ms: i64) -> EffectivePrivacy { - if self.privacy == VoucherPrivacyLevel::Full && now_ms >= self.ready_at_ms { - EffectivePrivacy::Full - } else { - EffectivePrivacy::Degraded - } - } - - /// Spendable through an unload strategy: locally available and - /// on-chain in a recycler. - pub fn is_unloadable(&self) -> bool { - self.local_state == VoucherLocalState::Available && self.remote_state.is_in_recycler() - } + pub fn effective_privacy(&self, now_ms: i64) -> EffectivePrivacy { + if self.privacy == VoucherPrivacyLevel::Full && now_ms >= self.ready_at_ms { + EffectivePrivacy::Full + } else { + EffectivePrivacy::Degraded + } + } + + /// Spendable through an unload strategy: locally available and + /// on-chain in a recycler. + pub fn is_unloadable(&self) -> bool { + self.local_state == VoucherLocalState::Available && self.remote_state.is_in_recycler() + } } pub fn ring_readiness_upgraded(included_members: u32) -> bool { - included_members >= MINIMUM_RING_SIZE + included_members >= MINIMUM_RING_SIZE } #[cfg(test)] mod tests { - use super::*; - - fn coin(age: Option, state: CoinState) -> Coin { - Coin { - exponent: 0, - derivation_index: 1, - age, - state, - } - } - - #[test] - fn coin_state_machine_progression() { - use CoinState::*; - // The forward paths. - assert!(Available.can_transition_to(Recycling)); - assert!(Available.can_transition_to(PendingTransfer)); - assert!(Recycling.can_transition_to(Spent)); - assert!(PendingTransfer.can_transition_to(Spent)); - assert!(Recycling.can_transition_to(Available)); - assert!(PendingTransfer.can_transition_to(Available)); - assert!(Spent.can_transition_to(Available)); - // Undocumented jumps are rejected. - assert!(!Available.can_transition_to(Spent)); - assert!(!Available.can_transition_to(Available)); - assert!(!Spent.can_transition_to(Recycling)); - assert!(!Spent.can_transition_to(PendingTransfer)); - assert!(!Recycling.can_transition_to(PendingTransfer)); - assert!(!PendingTransfer.can_transition_to(Recycling)); - } - - #[test] - fn coin_state_raw_round_trips() { - for state in [ - CoinState::Available, - CoinState::Recycling, - CoinState::PendingTransfer, - CoinState::Spent, - ] { - assert_eq!(CoinState::from_raw(state.as_raw()), Some(state)); - } - assert_eq!(CoinState::from_raw(9), None); - } - - #[test] - fn expiring_soon_at_the_recycle_age_boundary() { - assert!(!coin(Some(13), CoinState::Available).is_expiring_soon()); - assert!(coin(Some(14), CoinState::Available).is_expiring_soon()); - assert!(coin(Some(16), CoinState::Available).is_expiring_soon()); - assert!(!coin(None, CoinState::Available).is_expiring_soon()); - } - - #[test] - fn chain_invalid_at_max_age() { - assert!(!coin(Some(15), CoinState::Available).is_chain_invalid()); - assert!(coin(Some(16), CoinState::Available).is_chain_invalid()); - } - - #[test] - fn selectable_excludes_expiring_and_non_available() { - assert!(coin(Some(13), CoinState::Available).is_selectable()); - assert!(!coin(Some(14), CoinState::Available).is_selectable()); - assert!(!coin(Some(1), CoinState::Recycling).is_selectable()); - assert!(!coin(Some(1), CoinState::PendingTransfer).is_selectable()); - assert!(!coin(Some(1), CoinState::Spent).is_selectable()); - } - - fn voucher(privacy: VoucherPrivacyLevel, ready_at_ms: i64) -> Voucher { - Voucher { - exponent: 0, - derivation_index: 1, - allocated_at_ms: 0, - ready_at_ms, - remote_state: VoucherRemoteState::InRecycler { recycler_index: 0 }, - local_state: VoucherLocalState::Available, - privacy, - } - } - - #[test] - fn full_privacy_voucher_is_degraded_before_ready_at() { - let v = voucher(VoucherPrivacyLevel::Full, 1_000); - assert_eq!(v.effective_privacy(999), EffectivePrivacy::Degraded); - assert_eq!(v.effective_privacy(1_000), EffectivePrivacy::Full); - assert_eq!(v.effective_privacy(2_000), EffectivePrivacy::Full); - } - - #[test] - fn degraded_voucher_never_upgrades_by_time() { - let v = voucher(VoucherPrivacyLevel::Degraded, 1_000); - assert_eq!(v.effective_privacy(i64::MAX), EffectivePrivacy::Degraded); - } - - #[test] - fn ring_readiness_upgrades_exactly_at_the_minimum() { - assert!(!ring_readiness_upgraded(MINIMUM_RING_SIZE - 1)); - assert!(ring_readiness_upgraded(MINIMUM_RING_SIZE)); - assert!(ring_readiness_upgraded(MINIMUM_RING_SIZE + 1)); - } - - #[test] - fn minimum_ring_size_is_ten() { - assert_eq!(MINIMUM_RING_SIZE, 10); - } - - #[test] - fn unloadable_requires_local_available_and_in_recycler() { - let mut v = voucher(VoucherPrivacyLevel::Full, 0); - assert!(v.is_unloadable()); - v.remote_state = VoucherRemoteState::Onboarding; - assert!(!v.is_unloadable()); - v.remote_state = VoucherRemoteState::InRecycler { recycler_index: 2 }; - v.local_state = VoucherLocalState::PendingTransfer; - assert!(!v.is_unloadable()); - } + use super::*; + + fn coin(age: Option, state: CoinState) -> Coin { + Coin { exponent: 0, derivation_index: 1, age, state } + } + + #[test] + fn coin_state_machine_progression() { + use CoinState::*; + // The forward paths. + assert!(Available.can_transition_to(Recycling)); + assert!(Available.can_transition_to(PendingTransfer)); + assert!(Recycling.can_transition_to(Spent)); + assert!(PendingTransfer.can_transition_to(Spent)); + assert!(Recycling.can_transition_to(Available)); + assert!(PendingTransfer.can_transition_to(Available)); + assert!(Spent.can_transition_to(Available)); + // Undocumented jumps are rejected. + assert!(!Available.can_transition_to(Spent)); + assert!(!Available.can_transition_to(Available)); + assert!(!Spent.can_transition_to(Recycling)); + assert!(!Spent.can_transition_to(PendingTransfer)); + assert!(!Recycling.can_transition_to(PendingTransfer)); + assert!(!PendingTransfer.can_transition_to(Recycling)); + } + + #[test] + fn coin_state_raw_round_trips() { + for state in [ + CoinState::Available, + CoinState::Recycling, + CoinState::PendingTransfer, + CoinState::Spent, + ] { + assert_eq!(CoinState::from_raw(state.as_raw()), Some(state)); + } + assert_eq!(CoinState::from_raw(9), None); + } + + #[test] + fn expiring_soon_at_the_recycle_age_boundary() { + assert!(!coin(Some(13), CoinState::Available).is_expiring_soon()); + assert!(coin(Some(14), CoinState::Available).is_expiring_soon()); + assert!(coin(Some(16), CoinState::Available).is_expiring_soon()); + assert!(!coin(None, CoinState::Available).is_expiring_soon()); + } + + #[test] + fn chain_invalid_at_max_age() { + assert!(!coin(Some(15), CoinState::Available).is_chain_invalid()); + assert!(coin(Some(16), CoinState::Available).is_chain_invalid()); + } + + #[test] + fn selectable_excludes_expiring_and_non_available() { + assert!(coin(Some(13), CoinState::Available).is_selectable()); + assert!(!coin(Some(14), CoinState::Available).is_selectable()); + assert!(!coin(Some(1), CoinState::Recycling).is_selectable()); + assert!(!coin(Some(1), CoinState::PendingTransfer).is_selectable()); + assert!(!coin(Some(1), CoinState::Spent).is_selectable()); + } + + fn voucher(privacy: VoucherPrivacyLevel, ready_at_ms: i64) -> Voucher { + Voucher { + exponent: 0, + derivation_index: 1, + allocated_at_ms: 0, + ready_at_ms, + remote_state: VoucherRemoteState::InRecycler { recycler_index: 0 }, + local_state: VoucherLocalState::Available, + privacy, + } + } + + #[test] + fn full_privacy_voucher_is_degraded_before_ready_at() { + let v = voucher(VoucherPrivacyLevel::Full, 1_000); + assert_eq!(v.effective_privacy(999), EffectivePrivacy::Degraded); + assert_eq!(v.effective_privacy(1_000), EffectivePrivacy::Full); + assert_eq!(v.effective_privacy(2_000), EffectivePrivacy::Full); + } + + #[test] + fn degraded_voucher_never_upgrades_by_time() { + let v = voucher(VoucherPrivacyLevel::Degraded, 1_000); + assert_eq!(v.effective_privacy(i64::MAX), EffectivePrivacy::Degraded); + } + + #[test] + fn ring_readiness_upgrades_exactly_at_the_minimum() { + assert!(!ring_readiness_upgraded(MINIMUM_RING_SIZE - 1)); + assert!(ring_readiness_upgraded(MINIMUM_RING_SIZE)); + assert!(ring_readiness_upgraded(MINIMUM_RING_SIZE + 1)); + } + + #[test] + fn minimum_ring_size_is_ten() { + assert_eq!(MINIMUM_RING_SIZE, 10); + } + + #[test] + fn unloadable_requires_local_available_and_in_recycler() { + let mut v = voucher(VoucherPrivacyLevel::Full, 0); + assert!(v.is_unloadable()); + v.remote_state = VoucherRemoteState::Onboarding; + assert!(!v.is_unloadable()); + v.remote_state = VoucherRemoteState::InRecycler { recycler_index: 2 }; + v.local_state = VoucherLocalState::PendingTransfer; + assert!(!v.is_unloadable()); + } } diff --git a/rust/crates/truapi-coinage/src/outgoing_transfer.rs b/rust/crates/truapi-coinage/src/outgoing_transfer.rs index 03b6b9b7e0..8fd27ff8bf 100644 --- a/rust/crates/truapi-coinage/src/outgoing_transfer.rs +++ b/rust/crates/truapi-coinage/src/outgoing_transfer.rs @@ -2,38 +2,37 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use std::collections::HashMap; -use std::future::Future; -use {parking_lot::Mutex, std::sync::Arc}; +use parking_lot::Mutex; +use std::{collections::HashMap, future::Future, sync::Arc}; use futures::future::AbortHandle; use tokio::sync::Mutex as AsyncMutex; use tracing::warn; -use crate::clock::Clock; -use crate::denomination::DenominationBreakdownContext; -use crate::keys::CoinKeypairFactory; -use crate::memo::{MemoEntry, TransferMemo}; -use crate::model::{Coin, CoinState}; -use crate::query::CoinOnChainQueryService; -use crate::repo::{CoinRepository, TransferContext, VoucherRepository}; -use crate::selection::{CoinSelectionError, CoinSelector, TransferStrategy}; -use crate::wal::{ - CheckpointBlock, TransferWalEntry, WalCoinRef, WalOperation, WalPayload, WalStore, +use crate::{ + clock::Clock, + denomination::DenominationBreakdownContext, + keys::CoinKeypairFactory, + memo::{MemoEntry, TransferMemo}, + model::{Coin, CoinState}, + query::CoinOnChainQueryService, + repo::{CoinRepository, TransferContext, VoucherRepository}, + selection::{CoinSelectionError, CoinSelector, TransferStrategy}, + wal::{CheckpointBlock, TransferWalEntry, WalCoinRef, WalOperation, WalPayload, WalStore}, }; /// Dependencies that are stable for one active signing session. pub struct OutgoingCoinTransferParts { - pub spawner: crate::Spawner, - pub coins: Arc, - pub vouchers: Arc, - pub wal: Arc, - pub on_chain: Arc, - pub denominations: DenominationBreakdownContext, - pub clock: Arc, - /// Finalized heads allowed for the opportunistic live settlement watch. - /// A timeout retains the durable reservation for a later reconciliation. - pub settlement_timeout_heads: u32, + pub spawner: crate::Spawner, + pub coins: Arc, + pub vouchers: Arc, + pub wal: Arc, + pub on_chain: Arc, + pub denominations: DenominationBreakdownContext, + pub clock: Arc, + /// Finalized heads allowed for the opportunistic live settlement watch. + /// A timeout retains the durable reservation for a later reconciliation. + pub settlement_timeout_heads: u32, } /// The handoff returned a definitive *not accepted* result. @@ -44,9 +43,9 @@ pub struct OutgoingCoinTransferParts { pub struct OutgoingHandoffRejected; impl std::fmt::Display for OutgoingHandoffRejected { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str("outgoing coin memo was rejected before acceptance") - } + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("outgoing coin memo was rejected before acceptance") + } } impl std::error::Error for OutgoingHandoffRejected {} @@ -55,868 +54,806 @@ impl std::error::Error for OutgoingHandoffRejected {} /// coin keys. #[derive(Debug, Clone, PartialEq, Eq)] pub enum OutgoingTransferError { - Selection(CoinSelectionError), - /// The amount is representable and funded only by an on-chain split or - /// voucher unload. This service intentionally performs neither. - RequiresOnChainPreparation, - Query(String), - KeyDerivation(String), - Reservation(String), - Journal(String), - HandoffRejected, - /// An explicit pre-handoff rejection was received, but the durable - /// reservation could not be completely removed. Funds remain reserved. - Rollback(String), + Selection(CoinSelectionError), + /// The amount is representable and funded only by an on-chain split or + /// voucher unload. This service intentionally performs neither. + RequiresOnChainPreparation, + Query(String), + KeyDerivation(String), + Reservation(String), + Journal(String), + HandoffRejected, + /// An explicit pre-handoff rejection was received, but the durable + /// reservation could not be completely removed. Funds remain reserved. + Rollback(String), } impl std::fmt::Display for OutgoingTransferError { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Selection(error) => write!(formatter, "{error}"), - Self::RequiresOnChainPreparation => formatter - .write_str("exact whole coins are unavailable; on-chain preparation is required"), - Self::Query(error) => write!(formatter, "coin query failed: {error}"), - Self::KeyDerivation(error) => write!(formatter, "coin key derivation failed: {error}"), - Self::Reservation(error) => write!(formatter, "coin reservation failed: {error}"), - Self::Journal(error) => write!(formatter, "coin transfer journal failed: {error}"), - Self::HandoffRejected => { - formatter.write_str("outgoing coin memo was rejected before acceptance") - } - Self::Rollback(error) => { - write!( - formatter, - "outgoing coin reservation rollback failed: {error}" - ) - } - } - } + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Selection(error) => write!(formatter, "{error}"), + Self::RequiresOnChainPreparation => formatter + .write_str("exact whole coins are unavailable; on-chain preparation is required"), + Self::Query(error) => write!(formatter, "coin query failed: {error}"), + Self::KeyDerivation(error) => write!(formatter, "coin key derivation failed: {error}"), + Self::Reservation(error) => write!(formatter, "coin reservation failed: {error}"), + Self::Journal(error) => write!(formatter, "coin transfer journal failed: {error}"), + Self::HandoffRejected => { + formatter.write_str("outgoing coin memo was rejected before acceptance") + }, + Self::Rollback(error) => { + write!(formatter, "outgoing coin reservation rollback failed: {error}") + }, + } + } } impl std::error::Error for OutgoingTransferError {} impl From for OutgoingTransferError { - fn from(error: CoinSelectionError) -> Self { - Self::Selection(error) - } + fn from(error: CoinSelectionError) -> Self { + Self::Selection(error) + } } /// Outcome of one startup/manual pending-transfer reconciliation. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct OutgoingTransferReconciliation { - pub confirmed_spent: Vec, - pub still_pending: Vec, - pub completed_journals: usize, + pub confirmed_spent: Vec, + pub still_pending: Vec, + pub completed_journals: usize, } /// Outgoing transfer engine tied to exactly one root entropy. /// Construct a fresh instance on signing-session activation and drop (or /// [`shutdown`](Self::shutdown)) it on session teardown. pub struct OutgoingCoinTransferService { - spawner: crate::Spawner, - key_factory: Arc, - coins: Arc, - vouchers: Arc, - wal: Arc, - on_chain: Arc, - denominations: DenominationBreakdownContext, - clock: Arc, - settlement_timeout_heads: u32, - handoff_lock: AsyncMutex<()>, - settlement_tasks: Mutex>, + spawner: crate::Spawner, + key_factory: Arc, + coins: Arc, + vouchers: Arc, + wal: Arc, + on_chain: Arc, + denominations: DenominationBreakdownContext, + clock: Arc, + settlement_timeout_heads: u32, + handoff_lock: AsyncMutex<()>, + settlement_tasks: Mutex>, } impl OutgoingCoinTransferService { - pub fn new(root_entropy: &[u8], parts: OutgoingCoinTransferParts) -> Self { - Self { - key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), - coins: parts.coins, - vouchers: parts.vouchers, - wal: parts.wal, - on_chain: parts.on_chain, - denominations: parts.denominations, - clock: parts.clock, - settlement_timeout_heads: parts.settlement_timeout_heads.max(1), - handoff_lock: AsyncMutex::new(()), - settlement_tasks: Mutex::new(Vec::new()), - spawner: parts.spawner, - } - } - - /// Converts a W3S/UI CASH-cent amount to the raw planks required by the - /// exact-coin selector. - pub fn cash_cents_to_planks(&self, cents: u128) -> Option { - self.denominations.cash_cents_to_planks(cents) - } - - pub fn planks_per_cash_cent(&self) -> u128 { - self.denominations.asset_unit - } - - /// Selects and hands off exact whole coins. - /// `handoff` owns the memo and must return `Err` **only** when it can - /// certify that no recipient/transport durably accepted the secret. If - /// acceptance is ambiguous (timeout, cancellation after submit, lost - /// acknowledgement), it must return `Ok`; the normal payment/chat - /// tracker can report the transport uncertainty while the coin - /// reservation remains safe. - /// - /// For a host-correlated payment with durable preparation/restart - /// receipts, use `RegularCoinTransferService::confirm_operation`, which - /// also handles exact whole-coin transfers without chain preparation. - pub async fn handoff_exact( - &self, - amount_planks: u128, - handoff: F, - ) -> Result<(), OutgoingTransferError> - where - F: FnOnce(TransferMemo) -> Fut, - Fut: Future>, - { - // Selection + reservation is serialized per session so two callers - // cannot observe the same pre-reservation snapshot. - let _guard = self.handoff_lock.lock().await; - let present = self.present_local_coins().await?; - let selection = CoinSelector::new(self.denominations.clone(), usize::MAX).select( - amount_planks, - &present, - &[], - self.clock.now_ms(), - )?; - let selected = match selection.strategy { - TransferStrategy::ExactMatch { coins } => coins, - TransferStrategy::Split { .. } | TransferStrategy::UnloadIntoCoins { .. } => { - return Err(OutgoingTransferError::RequiresOnChainPreparation); - } - }; - - let indices = selected - .iter() - .map(|coin| coin.derivation_index) - .collect::>(); - let public_keys = indices - .iter() - .map(|index| { - self.key_factory - .public_key(*index) - .map_err(OutgoingTransferError::KeyDerivation) - }) - .collect::, _>>()?; - let entries = indices - .iter() - .map(|index| { - self.key_factory - .secret_bytes(*index) - .map(MemoEntry) - .map_err(OutgoingTransferError::KeyDerivation) - }) - .collect::, _>>()?; - let memo = TransferMemo { - entries, - total_value: amount_planks, - }; - let memo_identifier = memo.identifier(); - let entry_id = format!("secret-handoff-{}", hex::encode(memo_identifier)); - let journal = TransferWalEntry { - entry_id: entry_id.clone(), - operation: WalOperation::SecretHandoff, - payload: WalPayload { - input_coins: selected - .iter() - .map(|coin| WalCoinRef { - derivation_index: coin.derivation_index, - exponent: coin.exponent, - }) - .collect(), - ..WalPayload::default() - }, - // Secret handoffs ignore extrinsic mortality. Pending remains - // the truthful checkpoint because no extrinsic is broadcast. - checkpoint: CheckpointBlock::Pending, - created_at_ms: self.clock.now_ms(), - }; - - let context = Arc::new(TransferContext::new( - Arc::clone(&self.coins), - Arc::clone(&self.vouchers), - )); - if let Err(error) = context.reserve(&indices, &[]).await { - let rollback = context.revert().await; - return Err(match rollback { - Ok(()) => OutgoingTransferError::Reservation(error), - Err(rollback) => OutgoingTransferError::Rollback(format!( - "reserve error: {error}; state restore error: {rollback}" - )), - }); - } - if let Err(error) = self.wal.save(&journal).await { - // A local persistence failure is expected to mean no row, but - // delete the deterministic id first to close an ambiguous - // commit edge before making the inputs selectable again. - if let Err(cleanup) = self.wal.delete(&entry_id).await { - return Err(OutgoingTransferError::Rollback(format!( - "journal error: {error}; journal cleanup error: {cleanup}; inputs retained" - ))); - } - return match context.revert().await { - Ok(()) => Err(OutgoingTransferError::Journal(error)), - Err(rollback) => Err(OutgoingTransferError::Rollback(format!( - "journal error: {error}; state restore error: {rollback}" - ))), - }; - } - - if handoff(memo).await.is_err() { - // Delete protection before restoring availability. The opposite - // order leaves a crash window with an Available coin still - // referenced by an indefinite secret-handoff journal. - if let Err(error) = self.wal.delete(&entry_id).await { - return Err(OutgoingTransferError::Rollback(format!( - "handoff rejected; journal cleanup error: {error}; inputs retained" - ))); - } - if let Err(error) = context.revert().await { - return Err(OutgoingTransferError::Rollback(format!( - "handoff rejected; state restore error: {error}" - ))); - } - return Err(OutgoingTransferError::HandoffRejected); - } - - self.spawn_settlement_watch(context, indices, public_keys, entry_id); - Ok(()) - } - - /// Reconciles every durable secret-handoff entry in one ordered batch. - /// Absent inputs become `Spent`; present inputs remain (or are restored - /// to) `PendingTransfer`. A journal is removed only when all its inputs - /// are absent. - pub async fn reconcile_pending_transfers( - &self, - ) -> Result { - let journals = self - .wal - .load_all() - .await - .map_err(OutgoingTransferError::Journal)? - .into_iter() - // Correlated operations have a durable parent and are reconciled - // by TransferRecoveryService. In particular, Prepared must not be - // mistaken for a proven accepted handoff here. - .filter(|entry| { - entry.operation == WalOperation::SecretHandoff - && entry.operation_parent_id().is_none() - }) - .collect::>(); - if journals.is_empty() { - return Ok(OutgoingTransferReconciliation::default()); - } - - let mut references = Vec::new(); - for (journal_index, journal) in journals.iter().enumerate() { - for input in &journal.payload.input_coins { - let public_key = self - .key_factory - .public_key(input.derivation_index) - .map_err(OutgoingTransferError::KeyDerivation)?; - references.push((journal_index, input.derivation_index, public_key)); - } - } - let public_keys = references - .iter() - .map(|(_, _, key)| *key) - .collect::>(); - let remote = self - .on_chain - .fetch_coins(&public_keys, None) - .await - .map_err(|error| OutgoingTransferError::Query(error.to_string()))?; - if remote.len() != references.len() { - return Err(OutgoingTransferError::Query( - "coin query returned an incomplete batch".into(), - )); - } - let local_states = self - .coins - .list() - .await - .map_err(OutgoingTransferError::Reservation)? - .into_iter() - .map(|coin| (coin.derivation_index, coin.state)) - .collect::>(); - - let mut report = OutgoingTransferReconciliation::default(); - let mut journal_has_present = vec![false; journals.len()]; - for ((journal_index, derivation_index, _), reading) in references.into_iter().zip(remote) { - if reading.is_none() { - if local_states.get(&derivation_index) != Some(&CoinState::Spent) { - self.coins - .set_state(derivation_index, CoinState::Spent) - .await - .map_err(OutgoingTransferError::Reservation)?; - } - report.confirmed_spent.push(derivation_index); - } else { - journal_has_present[journal_index] = true; - if local_states.get(&derivation_index) == Some(&CoinState::Available) { - self.coins - .set_state(derivation_index, CoinState::PendingTransfer) - .await - .map_err(OutgoingTransferError::Reservation)?; - } - report.still_pending.push(derivation_index); - } - } - for (journal, has_present) in journals.iter().zip(journal_has_present) { - if !has_present && !journal.payload.input_coins.is_empty() { - self.wal - .delete(&journal.entry_id) - .await - .map_err(OutgoingTransferError::Journal)?; - report.completed_journals += 1; - } - } - report.confirmed_spent.sort_unstable(); - report.confirmed_spent.dedup(); - report.still_pending.sort_unstable(); - report.still_pending.dedup(); - Ok(report) - } - - /// Aborts live finalized-head waits. Durable journal rows and - /// reservations deliberately remain for the next session startup. - pub fn shutdown(&self) { - for task in self.settlement_tasks.lock().drain(..) { - task.abort(); - } - } - - async fn present_local_coins(&self) -> Result, OutgoingTransferError> { - let local = self - .coins - .list() - .await - .map_err(OutgoingTransferError::Reservation)?; - let candidates = local - .into_iter() - .filter(|coin| coin.is_selectable()) - .collect::>(); - let public_keys = candidates - .iter() - .map(|coin| { - self.key_factory - .public_key(coin.derivation_index) - .map_err(OutgoingTransferError::KeyDerivation) - }) - .collect::, _>>()?; - let remote = self - .on_chain - .fetch_coins(&public_keys, None) - .await - .map_err(|error| OutgoingTransferError::Query(error.to_string()))?; - if remote.len() != candidates.len() { - return Err(OutgoingTransferError::Query( - "coin query returned an incomplete batch".into(), - )); - } - Ok(candidates - .into_iter() - .zip(remote) - .filter_map(|(mut local, remote)| { - let remote = remote?; - local.exponent = remote.exponent; - local.age = Some(remote.age); - local.is_selectable().then_some(local) - }) - .collect()) - } - - fn spawn_settlement_watch( - &self, - context: Arc, - indices: Vec, - public_keys: Vec<[u8; 32]>, - entry_id: String, - ) { - let on_chain = Arc::clone(&self.on_chain); - let wal = Arc::clone(&self.wal); - let timeout = self.settlement_timeout_heads; - let task = crate::tasks::spawn_abortable(&self.spawner, async move { - match on_chain - .await_all_coins_off_chain(&public_keys, timeout) - .await - { - Ok(()) => { - if let Err(error) = context.process(&indices, &[]).await { - warn!( - %error, - coin_count = indices.len(), - "outgoing transfer settlement could not persist spent inputs" - ); - return; - } - if let Err(error) = wal.delete(&entry_id).await { - warn!( - %error, - coin_count = indices.len(), - "outgoing transfer settlement could not clear its journal" - ); - } - } - Err(error) => { - // Never revert after handoff. Startup/manual recovery - // can retry with a fresh connection. - warn!( - %error, - coin_count = indices.len(), - "outgoing transfer settlement watch ended; reservation retained" - ); - } - } - }); - self.settlement_tasks.lock().push(task); - } + pub fn new(root_entropy: &[u8], parts: OutgoingCoinTransferParts) -> Self { + Self { + key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), + coins: parts.coins, + vouchers: parts.vouchers, + wal: parts.wal, + on_chain: parts.on_chain, + denominations: parts.denominations, + clock: parts.clock, + settlement_timeout_heads: parts.settlement_timeout_heads.max(1), + handoff_lock: AsyncMutex::new(()), + settlement_tasks: Mutex::new(Vec::new()), + spawner: parts.spawner, + } + } + + /// Converts a W3S/UI CASH-cent amount to the raw planks required by the + /// exact-coin selector. + pub fn cash_cents_to_planks(&self, cents: u128) -> Option { + self.denominations.cash_cents_to_planks(cents) + } + + pub fn planks_per_cash_cent(&self) -> u128 { + self.denominations.asset_unit + } + + /// Selects and hands off exact whole coins. + /// `handoff` owns the memo and must return `Err` **only** when it can + /// certify that no recipient/transport durably accepted the secret. If + /// acceptance is ambiguous (timeout, cancellation after submit, lost + /// acknowledgement), it must return `Ok`; the normal payment/chat + /// tracker can report the transport uncertainty while the coin + /// reservation remains safe. + /// + /// For a host-correlated payment with durable preparation/restart + /// receipts, use `RegularCoinTransferService::confirm_operation`, which + /// also handles exact whole-coin transfers without chain preparation. + pub async fn handoff_exact( + &self, + amount_planks: u128, + handoff: F, + ) -> Result<(), OutgoingTransferError> + where + F: FnOnce(TransferMemo) -> Fut, + Fut: Future>, + { + // Selection + reservation is serialized per session so two callers + // cannot observe the same pre-reservation snapshot. + let _guard = self.handoff_lock.lock().await; + let present = self.present_local_coins().await?; + let selection = CoinSelector::new(self.denominations.clone(), usize::MAX).select( + amount_planks, + &present, + &[], + self.clock.now_ms(), + )?; + let selected = match selection.strategy { + TransferStrategy::ExactMatch { coins } => coins, + TransferStrategy::Split { .. } | TransferStrategy::UnloadIntoCoins { .. } => { + return Err(OutgoingTransferError::RequiresOnChainPreparation); + }, + }; + + let indices = selected.iter().map(|coin| coin.derivation_index).collect::>(); + let public_keys = indices + .iter() + .map(|index| { + self.key_factory + .public_key(*index) + .map_err(OutgoingTransferError::KeyDerivation) + }) + .collect::, _>>()?; + let entries = indices + .iter() + .map(|index| { + self.key_factory + .secret_bytes(*index) + .map(MemoEntry) + .map_err(OutgoingTransferError::KeyDerivation) + }) + .collect::, _>>()?; + let memo = TransferMemo { entries, total_value: amount_planks }; + let memo_identifier = memo.identifier(); + let entry_id = format!("secret-handoff-{}", hex::encode(memo_identifier)); + let journal = TransferWalEntry { + entry_id: entry_id.clone(), + operation: WalOperation::SecretHandoff, + payload: WalPayload { + input_coins: selected + .iter() + .map(|coin| WalCoinRef { + derivation_index: coin.derivation_index, + exponent: coin.exponent, + }) + .collect(), + ..WalPayload::default() + }, + // Secret handoffs ignore extrinsic mortality. Pending remains + // the truthful checkpoint because no extrinsic is broadcast. + checkpoint: CheckpointBlock::Pending, + created_at_ms: self.clock.now_ms(), + }; + + let context = + Arc::new(TransferContext::new(Arc::clone(&self.coins), Arc::clone(&self.vouchers))); + if let Err(error) = context.reserve(&indices, &[]).await { + let rollback = context.revert().await; + return Err(match rollback { + Ok(()) => OutgoingTransferError::Reservation(error), + Err(rollback) => OutgoingTransferError::Rollback(format!( + "reserve error: {error}; state restore error: {rollback}" + )), + }); + } + if let Err(error) = self.wal.save(&journal).await { + // A local persistence failure is expected to mean no row, but + // delete the deterministic id first to close an ambiguous + // commit edge before making the inputs selectable again. + if let Err(cleanup) = self.wal.delete(&entry_id).await { + return Err(OutgoingTransferError::Rollback(format!( + "journal error: {error}; journal cleanup error: {cleanup}; inputs retained" + ))); + } + return match context.revert().await { + Ok(()) => Err(OutgoingTransferError::Journal(error)), + Err(rollback) => Err(OutgoingTransferError::Rollback(format!( + "journal error: {error}; state restore error: {rollback}" + ))), + }; + } + + if handoff(memo).await.is_err() { + // Delete protection before restoring availability. The opposite + // order leaves a crash window with an Available coin still + // referenced by an indefinite secret-handoff journal. + if let Err(error) = self.wal.delete(&entry_id).await { + return Err(OutgoingTransferError::Rollback(format!( + "handoff rejected; journal cleanup error: {error}; inputs retained" + ))); + } + if let Err(error) = context.revert().await { + return Err(OutgoingTransferError::Rollback(format!( + "handoff rejected; state restore error: {error}" + ))); + } + return Err(OutgoingTransferError::HandoffRejected); + } + + self.spawn_settlement_watch(context, indices, public_keys, entry_id); + Ok(()) + } + + /// Reconciles every durable secret-handoff entry in one ordered batch. + /// Absent inputs become `Spent`; present inputs remain (or are restored + /// to) `PendingTransfer`. A journal is removed only when all its inputs + /// are absent. + pub async fn reconcile_pending_transfers( + &self, + ) -> Result { + let journals = self + .wal + .load_all() + .await + .map_err(OutgoingTransferError::Journal)? + .into_iter() + // Correlated operations have a durable parent and are reconciled + // by TransferRecoveryService. In particular, Prepared must not be + // mistaken for a proven accepted handoff here. + .filter(|entry| { + entry.operation == WalOperation::SecretHandoff && + entry.operation_parent_id().is_none() + }) + .collect::>(); + if journals.is_empty() { + return Ok(OutgoingTransferReconciliation::default()); + } + + let mut references = Vec::new(); + for (journal_index, journal) in journals.iter().enumerate() { + for input in &journal.payload.input_coins { + let public_key = self + .key_factory + .public_key(input.derivation_index) + .map_err(OutgoingTransferError::KeyDerivation)?; + references.push((journal_index, input.derivation_index, public_key)); + } + } + let public_keys = references.iter().map(|(_, _, key)| *key).collect::>(); + let remote = self + .on_chain + .fetch_coins(&public_keys, None) + .await + .map_err(|error| OutgoingTransferError::Query(error.to_string()))?; + if remote.len() != references.len() { + return Err(OutgoingTransferError::Query( + "coin query returned an incomplete batch".into(), + )); + } + let local_states = self + .coins + .list() + .await + .map_err(OutgoingTransferError::Reservation)? + .into_iter() + .map(|coin| (coin.derivation_index, coin.state)) + .collect::>(); + + let mut report = OutgoingTransferReconciliation::default(); + let mut journal_has_present = vec![false; journals.len()]; + for ((journal_index, derivation_index, _), reading) in references.into_iter().zip(remote) { + if reading.is_none() { + if local_states.get(&derivation_index) != Some(&CoinState::Spent) { + self.coins + .set_state(derivation_index, CoinState::Spent) + .await + .map_err(OutgoingTransferError::Reservation)?; + } + report.confirmed_spent.push(derivation_index); + } else { + journal_has_present[journal_index] = true; + if local_states.get(&derivation_index) == Some(&CoinState::Available) { + self.coins + .set_state(derivation_index, CoinState::PendingTransfer) + .await + .map_err(OutgoingTransferError::Reservation)?; + } + report.still_pending.push(derivation_index); + } + } + for (journal, has_present) in journals.iter().zip(journal_has_present) { + if !has_present && !journal.payload.input_coins.is_empty() { + self.wal + .delete(&journal.entry_id) + .await + .map_err(OutgoingTransferError::Journal)?; + report.completed_journals += 1; + } + } + report.confirmed_spent.sort_unstable(); + report.confirmed_spent.dedup(); + report.still_pending.sort_unstable(); + report.still_pending.dedup(); + Ok(report) + } + + /// Aborts live finalized-head waits. Durable journal rows and + /// reservations deliberately remain for the next session startup. + pub fn shutdown(&self) { + for task in self.settlement_tasks.lock().drain(..) { + task.abort(); + } + } + + async fn present_local_coins(&self) -> Result, OutgoingTransferError> { + let local = self.coins.list().await.map_err(OutgoingTransferError::Reservation)?; + let candidates = local.into_iter().filter(|coin| coin.is_selectable()).collect::>(); + let public_keys = candidates + .iter() + .map(|coin| { + self.key_factory + .public_key(coin.derivation_index) + .map_err(OutgoingTransferError::KeyDerivation) + }) + .collect::, _>>()?; + let remote = self + .on_chain + .fetch_coins(&public_keys, None) + .await + .map_err(|error| OutgoingTransferError::Query(error.to_string()))?; + if remote.len() != candidates.len() { + return Err(OutgoingTransferError::Query( + "coin query returned an incomplete batch".into(), + )); + } + Ok(candidates + .into_iter() + .zip(remote) + .filter_map(|(mut local, remote)| { + let remote = remote?; + local.exponent = remote.exponent; + local.age = Some(remote.age); + local.is_selectable().then_some(local) + }) + .collect()) + } + + fn spawn_settlement_watch( + &self, + context: Arc, + indices: Vec, + public_keys: Vec<[u8; 32]>, + entry_id: String, + ) { + let on_chain = Arc::clone(&self.on_chain); + let wal = Arc::clone(&self.wal); + let timeout = self.settlement_timeout_heads; + let task = crate::tasks::spawn_abortable(&self.spawner, async move { + match on_chain.await_all_coins_off_chain(&public_keys, timeout).await { + Ok(()) => { + if let Err(error) = context.process(&indices, &[]).await { + warn!( + %error, + coin_count = indices.len(), + "outgoing transfer settlement could not persist spent inputs" + ); + return; + } + if let Err(error) = wal.delete(&entry_id).await { + warn!( + %error, + coin_count = indices.len(), + "outgoing transfer settlement could not clear its journal" + ); + } + }, + Err(error) => { + // Never revert after handoff. Startup/manual recovery + // can retry with a fresh connection. + warn!( + %error, + coin_count = indices.len(), + "outgoing transfer settlement watch ended; reservation retained" + ); + }, + } + }); + self.settlement_tasks.lock().push(task); + } } impl Drop for OutgoingCoinTransferService { - fn drop(&mut self) { - for task in self.settlement_tasks.get_mut().drain(..) { - task.abort(); - } - } + fn drop(&mut self) { + for task in self.settlement_tasks.get_mut().drain(..) { + task.abort(); + } + } } #[cfg(test)] mod tests { - use std::collections::HashMap; - - use async_trait::async_trait; - use futures::StreamExt; - use futures::channel::mpsc; - use futures::stream::{self, BoxStream}; - use parity_scale_codec::Encode; - - use super::*; - use crate::clock::FixedClock; - use crate::query::{CoinageStorageKey, CoinageStorageQuery}; - use crate::repo::{InMemoryCoinRepository, InMemoryVoucherRepository}; - - const ENTROPY: [u8; 16] = [0x17; 16]; - type HeadReceiver = mpsc::UnboundedReceiver>; - - #[derive(Default)] - struct MemWal { - entries: Mutex>, - } - - #[async_trait] - impl WalStore for MemWal { - async fn save(&self, entry: &TransferWalEntry) -> Result<(), String> { - let mut entries = self.entries.lock(); - if entries.iter().any(|saved| saved.entry_id == entry.entry_id) { - return Err("duplicate journal".into()); - } - entries.push(entry.clone()); - Ok(()) - } - - async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String> { - for entry in entries { - self.save(entry).await?; - } - Ok(()) - } - - async fn update_checkpoint( - &self, - entry_id: &str, - checkpoint: CheckpointBlock, - ) -> Result<(), String> { - let mut entries = self.entries.lock(); - let entry = entries - .iter_mut() - .find(|entry| entry.entry_id == entry_id) - .ok_or_else(|| "journal not found".to_string())?; - entry.checkpoint = checkpoint; - Ok(()) - } - - async fn load_all(&self) -> Result, String> { - Ok(self.entries.lock().clone()) - } - - async fn delete(&self, entry_id: &str) -> Result<(), String> { - self.entries - .lock() - .retain(|entry| entry.entry_id != entry_id); - Ok(()) - } - } - - struct TestStorage { - values: Mutex>>, - heads: Mutex>, - } - - impl Default for TestStorage { - fn default() -> Self { - Self { - values: Mutex::new(HashMap::new()), - heads: Mutex::new(None), - } - } - } - - impl TestStorage { - fn set_coin(&self, public_key: [u8; 32], exponent: i8, age: u16) { - self.values.lock().insert( - CoinageStorageKey::Coin(public_key), - (exponent, age).encode(), - ); - } - - fn remove_coin(&self, public_key: [u8; 32]) { - self.values - .lock() - .remove(&CoinageStorageKey::Coin(public_key)); - } - - fn head_channel(&self) -> mpsc::UnboundedSender> { - let (sender, receiver) = mpsc::unbounded(); - *self.heads.lock() = Some(receiver); - sender - } - } - - #[async_trait] - impl CoinageStorageQuery for TestStorage { - async fn query( - &self, - keys: &[CoinageStorageKey], - _at: Option<[u8; 32]>, - ) -> Result>>, String> { - let values = self.values.lock(); - Ok(keys.iter().map(|key| values.get(key).cloned()).collect()) - } - - fn finalized_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>> { - self.heads - .lock() - .take() - .map(StreamExt::boxed) - .unwrap_or_else(|| stream::pending().boxed()) - } - } - - struct Harness { - service: OutgoingCoinTransferService, - coins: Arc, - wal: Arc, - storage: Arc, - } - - fn coin(index: u32) -> Coin { - Coin { - // Deliberately stale: selection must use the on-chain value. - exponent: 0, - derivation_index: index, - age: None, - state: CoinState::Available, - } - } - - fn denominations() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 10, - max_exponent: 6, - min_exponent: 0, - precision: 2, - } - } - - fn harness(local: Vec) -> Harness { - let coins = Arc::new(InMemoryCoinRepository::with_coins(local)); - let wal = Arc::new(MemWal::default()); - let storage = Arc::new(TestStorage::default()); - let service = OutgoingCoinTransferService::new( - &ENTROPY, - OutgoingCoinTransferParts { - spawner: crate::test_spawner(), - coins: Arc::clone(&coins) as Arc<_>, - vouchers: Arc::new(InMemoryVoucherRepository::default()), - wal: Arc::clone(&wal) as Arc<_>, - on_chain: Arc::new(CoinOnChainQueryService::new(Arc::clone(&storage) as Arc<_>)), - denominations: denominations(), - clock: Arc::new(FixedClock(1_234)), - settlement_timeout_heads: 3, - }, - ); - Harness { - service, - coins, - wal, - storage, - } - } - - async fn state(coins: &InMemoryCoinRepository, index: u32) -> CoinState { - coins - .list() - .await - .unwrap() - .into_iter() - .find(|coin| coin.derivation_index == index) - .unwrap() - .state - } - - #[tokio::test] - async fn exact_on_chain_selection_reserves_before_handoff_and_settles_on_absence() { - let harness = harness(vec![coin(1), coin(2), coin(3)]); - let keys = CoinKeypairFactory::new(&ENTROPY); - harness.storage.set_coin(keys.public_key(1).unwrap(), 2, 1); // 40 - harness.storage.set_coin(keys.public_key(2).unwrap(), 1, 1); // 20 - harness.storage.set_coin(keys.public_key(3).unwrap(), 0, 1); // 10 - let heads = harness.storage.head_channel(); - let observed = Arc::new(Mutex::new(None)); - - harness - .service - .handoff_exact(60, { - let observed = Arc::clone(&observed); - let coins = Arc::clone(&harness.coins); - move |memo| async move { - assert_eq!(state(&coins, 1).await, CoinState::PendingTransfer); - assert_eq!(state(&coins, 2).await, CoinState::PendingTransfer); - assert_eq!(state(&coins, 3).await, CoinState::Available); - *observed.lock() = Some(( - memo.total_value, - memo.entries.iter().map(|entry| entry.0).collect::>(), - )); - Ok(()) - } - }) - .await - .unwrap(); - - let observed = observed.lock().take().unwrap(); - assert_eq!(observed.0, 60); - assert_eq!( - observed.1, - vec![keys.secret_bytes(1).unwrap(), keys.secret_bytes(2).unwrap()] - ); - let journal = harness.wal.load_all().await.unwrap(); - assert_eq!(journal.len(), 1); - assert_eq!(journal[0].operation, WalOperation::SecretHandoff); - assert_eq!(journal[0].created_at_ms, 1_234); - - harness.storage.remove_coin(keys.public_key(1).unwrap()); - harness.storage.remove_coin(keys.public_key(2).unwrap()); - heads.unbounded_send(Ok([9; 32])).unwrap(); - for _ in 0..40 { - if state(&harness.coins, 1).await == CoinState::Spent { - break; - } - tokio::task::yield_now().await; - } - assert_eq!(state(&harness.coins, 1).await, CoinState::Spent); - assert_eq!(state(&harness.coins, 2).await, CoinState::Spent); - assert!(harness.wal.load_all().await.unwrap().is_empty()); - } - - #[tokio::test] - async fn rejects_insufficient_nonrepresentable_and_preparation_only_amounts() { - let harness = harness(vec![coin(1)]); - let keys = CoinKeypairFactory::new(&ENTROPY); - harness.storage.set_coin(keys.public_key(1).unwrap(), 2, 1); // 40 - - let never = |_memo| async { Ok::<(), OutgoingHandoffRejected>(()) }; - assert_eq!( - harness.service.handoff_exact(5, never).await, - Err(OutgoingTransferError::Selection( - CoinSelectionError::AmountNotRepresentable { remainder: 5 } - )) - ); - assert_eq!( - harness - .service - .handoff_exact(80, |_memo| async { Ok(()) }) - .await, - Err(OutgoingTransferError::Selection( - CoinSelectionError::InsufficientFunds - )) - ); - assert_eq!( - harness - .service - .handoff_exact(20, |_memo| async { Ok(()) }) - .await, - Err(OutgoingTransferError::RequiresOnChainPreparation) - ); - assert_eq!(state(&harness.coins, 1).await, CoinState::Available); - assert!(harness.wal.load_all().await.unwrap().is_empty()); - } - - #[tokio::test] - async fn explicit_pre_handoff_rejection_removes_journal_then_rolls_back() { - let harness = harness(vec![coin(4)]); - let keys = CoinKeypairFactory::new(&ENTROPY); - harness.storage.set_coin(keys.public_key(4).unwrap(), 1, 1); - let saw_commit_boundary = Arc::new(Mutex::new(false)); - - let result = harness - .service - .handoff_exact(20, { - let saw_commit_boundary = Arc::clone(&saw_commit_boundary); - let coins = Arc::clone(&harness.coins); - let wal = Arc::clone(&harness.wal); - move |_memo| async move { - assert_eq!(state(&coins, 4).await, CoinState::PendingTransfer); - assert_eq!(wal.load_all().await.unwrap().len(), 1); - *saw_commit_boundary.lock() = true; - Err(OutgoingHandoffRejected) - } - }) - .await; - - assert_eq!(result, Err(OutgoingTransferError::HandoffRejected)); - assert!(*saw_commit_boundary.lock()); - assert_eq!(state(&harness.coins, 4).await, CoinState::Available); - assert!(harness.wal.load_all().await.unwrap().is_empty()); - } - - #[tokio::test] - async fn accepted_handoff_stays_pending_and_cannot_be_selected_twice() { - let harness = harness(vec![coin(5)]); - let keys = CoinKeypairFactory::new(&ENTROPY); - harness.storage.set_coin(keys.public_key(5).unwrap(), 2, 1); - harness - .service - .handoff_exact(40, |_memo| async { Ok(()) }) - .await - .unwrap(); - - assert_eq!(state(&harness.coins, 5).await, CoinState::PendingTransfer); - assert_eq!(harness.wal.load_all().await.unwrap().len(), 1); - assert_eq!( - harness - .service - .handoff_exact(40, |_memo| async { Ok(()) }) - .await, - Err(OutgoingTransferError::Selection( - CoinSelectionError::EmptyWallet - )) - ); - let report = harness.service.reconcile_pending_transfers().await.unwrap(); - assert_eq!(report.still_pending, [5]); - assert!(report.confirmed_spent.is_empty()); - assert_eq!(harness.wal.load_all().await.unwrap().len(), 1); - } - - #[tokio::test] - async fn startup_reconciliation_retires_absent_handoffs() { - let harness = harness(vec![coin(6)]); - let keys = CoinKeypairFactory::new(&ENTROPY); - let public_key = keys.public_key(6).unwrap(); - harness.storage.set_coin(public_key, 0, 1); - harness - .service - .handoff_exact(10, |_memo| async { Ok(()) }) - .await - .unwrap(); - harness.service.shutdown(); - harness.storage.remove_coin(public_key); - - let report = harness.service.reconcile_pending_transfers().await.unwrap(); - assert_eq!(report.confirmed_spent, [6]); - assert!(report.still_pending.is_empty()); - assert_eq!(report.completed_journals, 1); - assert_eq!(state(&harness.coins, 6).await, CoinState::Spent); - assert!(harness.wal.load_all().await.unwrap().is_empty()); - } - - #[tokio::test] - async fn diagnostics_never_render_expanded_coin_secrets() { - let harness = harness(vec![coin(7)]); - let keys = CoinKeypairFactory::new(&ENTROPY); - harness.storage.set_coin(keys.public_key(7).unwrap(), 0, 1); - let secret_hex = hex::encode(keys.secret_bytes(7).unwrap()); - let rendered_memo = Arc::new(Mutex::new(String::new())); - - let error = harness - .service - .handoff_exact(10, { - let rendered_memo = Arc::clone(&rendered_memo); - move |memo| async move { - *rendered_memo.lock() = format!("{memo:?}"); - Err(OutgoingHandoffRejected) - } - }) - .await - .unwrap_err(); - let diagnostics = format!("{error:?} {error} {}", rendered_memo.lock()); - assert!(!diagnostics.contains(&secret_hex)); - } - - struct FailingReservationRepository { - inner: Arc, - fail_index: u32, - } - - #[async_trait] - impl CoinRepository for FailingReservationRepository { - async fn list(&self) -> Result, String> { - self.inner.list().await - } - - async fn upsert(&self, coin: &Coin) -> Result<(), String> { - self.inner.upsert(coin).await - } - - async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String> { - if derivation_index == self.fail_index && state == CoinState::PendingTransfer { - return Err("injected reservation failure".into()); - } - self.inner.set_state(derivation_index, state).await - } - - async fn remove(&self, derivation_index: u32) -> Result<(), String> { - self.inner.remove(derivation_index).await - } - } - - #[tokio::test] - async fn partial_reservation_failure_restores_every_prior_input() { - let inner = Arc::new(InMemoryCoinRepository::with_coins([coin(1), coin(2)])); - let coins = Arc::new(FailingReservationRepository { - inner: Arc::clone(&inner), - fail_index: 2, - }); - let storage = Arc::new(TestStorage::default()); - let keys = CoinKeypairFactory::new(&ENTROPY); - storage.set_coin(keys.public_key(1).unwrap(), 1, 1); // 20 - storage.set_coin(keys.public_key(2).unwrap(), 0, 1); // 10 - let wal = Arc::new(MemWal::default()); - let service = OutgoingCoinTransferService::new( - &ENTROPY, - OutgoingCoinTransferParts { - spawner: crate::test_spawner(), - coins, - vouchers: Arc::new(InMemoryVoucherRepository::default()), - wal: Arc::clone(&wal) as Arc<_>, - on_chain: Arc::new(CoinOnChainQueryService::new(storage)), - denominations: denominations(), - clock: Arc::new(FixedClock(0)), - settlement_timeout_heads: 1, - }, - ); - - let error = service - .handoff_exact(30, |_memo| async { Ok(()) }) - .await - .unwrap_err(); - assert!(matches!(error, OutgoingTransferError::Reservation(_))); - assert_eq!(state(&inner, 1).await, CoinState::Available); - assert_eq!(state(&inner, 2).await, CoinState::Available); - assert!(wal.load_all().await.unwrap().is_empty()); - } + use std::collections::HashMap; + + use async_trait::async_trait; + use futures::{ + StreamExt, + channel::mpsc, + stream::{self, BoxStream}, + }; + use parity_scale_codec::Encode; + + use super::*; + use crate::{ + clock::FixedClock, + query::{CoinageStorageKey, CoinageStorageQuery}, + repo::{InMemoryCoinRepository, InMemoryVoucherRepository}, + }; + + const ENTROPY: [u8; 16] = [0x17; 16]; + type HeadReceiver = mpsc::UnboundedReceiver>; + + #[derive(Default)] + struct MemWal { + entries: Mutex>, + } + + #[async_trait] + impl WalStore for MemWal { + async fn save(&self, entry: &TransferWalEntry) -> Result<(), String> { + let mut entries = self.entries.lock(); + if entries.iter().any(|saved| saved.entry_id == entry.entry_id) { + return Err("duplicate journal".into()); + } + entries.push(entry.clone()); + Ok(()) + } + + async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String> { + for entry in entries { + self.save(entry).await?; + } + Ok(()) + } + + async fn update_checkpoint( + &self, + entry_id: &str, + checkpoint: CheckpointBlock, + ) -> Result<(), String> { + let mut entries = self.entries.lock(); + let entry = entries + .iter_mut() + .find(|entry| entry.entry_id == entry_id) + .ok_or_else(|| "journal not found".to_string())?; + entry.checkpoint = checkpoint; + Ok(()) + } + + async fn load_all(&self) -> Result, String> { + Ok(self.entries.lock().clone()) + } + + async fn delete(&self, entry_id: &str) -> Result<(), String> { + self.entries.lock().retain(|entry| entry.entry_id != entry_id); + Ok(()) + } + } + + struct TestStorage { + values: Mutex>>, + heads: Mutex>, + } + + impl Default for TestStorage { + fn default() -> Self { + Self { values: Mutex::new(HashMap::new()), heads: Mutex::new(None) } + } + } + + impl TestStorage { + fn set_coin(&self, public_key: [u8; 32], exponent: i8, age: u16) { + self.values + .lock() + .insert(CoinageStorageKey::Coin(public_key), (exponent, age).encode()); + } + + fn remove_coin(&self, public_key: [u8; 32]) { + self.values.lock().remove(&CoinageStorageKey::Coin(public_key)); + } + + fn head_channel(&self) -> mpsc::UnboundedSender> { + let (sender, receiver) = mpsc::unbounded(); + *self.heads.lock() = Some(receiver); + sender + } + } + + #[async_trait] + impl CoinageStorageQuery for TestStorage { + async fn query( + &self, + keys: &[CoinageStorageKey], + _at: Option<[u8; 32]>, + ) -> Result>>, String> { + let values = self.values.lock(); + Ok(keys.iter().map(|key| values.get(key).cloned()).collect()) + } + + fn finalized_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>> { + self.heads + .lock() + .take() + .map(StreamExt::boxed) + .unwrap_or_else(|| stream::pending().boxed()) + } + } + + struct Harness { + service: OutgoingCoinTransferService, + coins: Arc, + wal: Arc, + storage: Arc, + } + + fn coin(index: u32) -> Coin { + Coin { + // Deliberately stale: selection must use the on-chain value. + exponent: 0, + derivation_index: index, + age: None, + state: CoinState::Available, + } + } + + fn denominations() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 10, + max_exponent: 6, + min_exponent: 0, + precision: 2, + } + } + + fn harness(local: Vec) -> Harness { + let coins = Arc::new(InMemoryCoinRepository::with_coins(local)); + let wal = Arc::new(MemWal::default()); + let storage = Arc::new(TestStorage::default()); + let service = OutgoingCoinTransferService::new( + &ENTROPY, + OutgoingCoinTransferParts { + spawner: crate::test_spawner(), + coins: Arc::clone(&coins) as Arc<_>, + vouchers: Arc::new(InMemoryVoucherRepository::default()), + wal: Arc::clone(&wal) as Arc<_>, + on_chain: Arc::new(CoinOnChainQueryService::new(Arc::clone(&storage) as Arc<_>)), + denominations: denominations(), + clock: Arc::new(FixedClock(1_234)), + settlement_timeout_heads: 3, + }, + ); + Harness { service, coins, wal, storage } + } + + async fn state(coins: &InMemoryCoinRepository, index: u32) -> CoinState { + coins + .list() + .await + .unwrap() + .into_iter() + .find(|coin| coin.derivation_index == index) + .unwrap() + .state + } + + #[tokio::test] + async fn exact_on_chain_selection_reserves_before_handoff_and_settles_on_absence() { + let harness = harness(vec![coin(1), coin(2), coin(3)]); + let keys = CoinKeypairFactory::new(&ENTROPY); + harness.storage.set_coin(keys.public_key(1).unwrap(), 2, 1); // 40 + harness.storage.set_coin(keys.public_key(2).unwrap(), 1, 1); // 20 + harness.storage.set_coin(keys.public_key(3).unwrap(), 0, 1); // 10 + let heads = harness.storage.head_channel(); + let observed = Arc::new(Mutex::new(None)); + + harness + .service + .handoff_exact(60, { + let observed = Arc::clone(&observed); + let coins = Arc::clone(&harness.coins); + move |memo| async move { + assert_eq!(state(&coins, 1).await, CoinState::PendingTransfer); + assert_eq!(state(&coins, 2).await, CoinState::PendingTransfer); + assert_eq!(state(&coins, 3).await, CoinState::Available); + *observed.lock() = Some(( + memo.total_value, + memo.entries.iter().map(|entry| entry.0).collect::>(), + )); + Ok(()) + } + }) + .await + .unwrap(); + + let observed = observed.lock().take().unwrap(); + assert_eq!(observed.0, 60); + assert_eq!(observed.1, vec![keys.secret_bytes(1).unwrap(), keys.secret_bytes(2).unwrap()]); + let journal = harness.wal.load_all().await.unwrap(); + assert_eq!(journal.len(), 1); + assert_eq!(journal[0].operation, WalOperation::SecretHandoff); + assert_eq!(journal[0].created_at_ms, 1_234); + + harness.storage.remove_coin(keys.public_key(1).unwrap()); + harness.storage.remove_coin(keys.public_key(2).unwrap()); + heads.unbounded_send(Ok([9; 32])).unwrap(); + for _ in 0..40 { + if state(&harness.coins, 1).await == CoinState::Spent { + break; + } + tokio::task::yield_now().await; + } + assert_eq!(state(&harness.coins, 1).await, CoinState::Spent); + assert_eq!(state(&harness.coins, 2).await, CoinState::Spent); + assert!(harness.wal.load_all().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn rejects_insufficient_nonrepresentable_and_preparation_only_amounts() { + let harness = harness(vec![coin(1)]); + let keys = CoinKeypairFactory::new(&ENTROPY); + harness.storage.set_coin(keys.public_key(1).unwrap(), 2, 1); // 40 + + let never = |_memo| async { Ok::<(), OutgoingHandoffRejected>(()) }; + assert_eq!( + harness.service.handoff_exact(5, never).await, + Err(OutgoingTransferError::Selection(CoinSelectionError::AmountNotRepresentable { + remainder: 5 + })) + ); + assert_eq!( + harness.service.handoff_exact(80, |_memo| async { Ok(()) }).await, + Err(OutgoingTransferError::Selection(CoinSelectionError::InsufficientFunds)) + ); + assert_eq!( + harness.service.handoff_exact(20, |_memo| async { Ok(()) }).await, + Err(OutgoingTransferError::RequiresOnChainPreparation) + ); + assert_eq!(state(&harness.coins, 1).await, CoinState::Available); + assert!(harness.wal.load_all().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn explicit_pre_handoff_rejection_removes_journal_then_rolls_back() { + let harness = harness(vec![coin(4)]); + let keys = CoinKeypairFactory::new(&ENTROPY); + harness.storage.set_coin(keys.public_key(4).unwrap(), 1, 1); + let saw_commit_boundary = Arc::new(Mutex::new(false)); + + let result = harness + .service + .handoff_exact(20, { + let saw_commit_boundary = Arc::clone(&saw_commit_boundary); + let coins = Arc::clone(&harness.coins); + let wal = Arc::clone(&harness.wal); + move |_memo| async move { + assert_eq!(state(&coins, 4).await, CoinState::PendingTransfer); + assert_eq!(wal.load_all().await.unwrap().len(), 1); + *saw_commit_boundary.lock() = true; + Err(OutgoingHandoffRejected) + } + }) + .await; + + assert_eq!(result, Err(OutgoingTransferError::HandoffRejected)); + assert!(*saw_commit_boundary.lock()); + assert_eq!(state(&harness.coins, 4).await, CoinState::Available); + assert!(harness.wal.load_all().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn accepted_handoff_stays_pending_and_cannot_be_selected_twice() { + let harness = harness(vec![coin(5)]); + let keys = CoinKeypairFactory::new(&ENTROPY); + harness.storage.set_coin(keys.public_key(5).unwrap(), 2, 1); + harness.service.handoff_exact(40, |_memo| async { Ok(()) }).await.unwrap(); + + assert_eq!(state(&harness.coins, 5).await, CoinState::PendingTransfer); + assert_eq!(harness.wal.load_all().await.unwrap().len(), 1); + assert_eq!( + harness.service.handoff_exact(40, |_memo| async { Ok(()) }).await, + Err(OutgoingTransferError::Selection(CoinSelectionError::EmptyWallet)) + ); + let report = harness.service.reconcile_pending_transfers().await.unwrap(); + assert_eq!(report.still_pending, [5]); + assert!(report.confirmed_spent.is_empty()); + assert_eq!(harness.wal.load_all().await.unwrap().len(), 1); + } + + #[tokio::test] + async fn startup_reconciliation_retires_absent_handoffs() { + let harness = harness(vec![coin(6)]); + let keys = CoinKeypairFactory::new(&ENTROPY); + let public_key = keys.public_key(6).unwrap(); + harness.storage.set_coin(public_key, 0, 1); + harness.service.handoff_exact(10, |_memo| async { Ok(()) }).await.unwrap(); + harness.service.shutdown(); + harness.storage.remove_coin(public_key); + + let report = harness.service.reconcile_pending_transfers().await.unwrap(); + assert_eq!(report.confirmed_spent, [6]); + assert!(report.still_pending.is_empty()); + assert_eq!(report.completed_journals, 1); + assert_eq!(state(&harness.coins, 6).await, CoinState::Spent); + assert!(harness.wal.load_all().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn diagnostics_never_render_expanded_coin_secrets() { + let harness = harness(vec![coin(7)]); + let keys = CoinKeypairFactory::new(&ENTROPY); + harness.storage.set_coin(keys.public_key(7).unwrap(), 0, 1); + let secret_hex = hex::encode(keys.secret_bytes(7).unwrap()); + let rendered_memo = Arc::new(Mutex::new(String::new())); + + let error = harness + .service + .handoff_exact(10, { + let rendered_memo = Arc::clone(&rendered_memo); + move |memo| async move { + *rendered_memo.lock() = format!("{memo:?}"); + Err(OutgoingHandoffRejected) + } + }) + .await + .unwrap_err(); + let diagnostics = format!("{error:?} {error} {}", rendered_memo.lock()); + assert!(!diagnostics.contains(&secret_hex)); + } + + struct FailingReservationRepository { + inner: Arc, + fail_index: u32, + } + + #[async_trait] + impl CoinRepository for FailingReservationRepository { + async fn list(&self) -> Result, String> { + self.inner.list().await + } + + async fn upsert(&self, coin: &Coin) -> Result<(), String> { + self.inner.upsert(coin).await + } + + async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String> { + if derivation_index == self.fail_index && state == CoinState::PendingTransfer { + return Err("injected reservation failure".into()); + } + self.inner.set_state(derivation_index, state).await + } + + async fn remove(&self, derivation_index: u32) -> Result<(), String> { + self.inner.remove(derivation_index).await + } + } + + #[tokio::test] + async fn partial_reservation_failure_restores_every_prior_input() { + let inner = Arc::new(InMemoryCoinRepository::with_coins([coin(1), coin(2)])); + let coins = + Arc::new(FailingReservationRepository { inner: Arc::clone(&inner), fail_index: 2 }); + let storage = Arc::new(TestStorage::default()); + let keys = CoinKeypairFactory::new(&ENTROPY); + storage.set_coin(keys.public_key(1).unwrap(), 1, 1); // 20 + storage.set_coin(keys.public_key(2).unwrap(), 0, 1); // 10 + let wal = Arc::new(MemWal::default()); + let service = OutgoingCoinTransferService::new( + &ENTROPY, + OutgoingCoinTransferParts { + spawner: crate::test_spawner(), + coins, + vouchers: Arc::new(InMemoryVoucherRepository::default()), + wal: Arc::clone(&wal) as Arc<_>, + on_chain: Arc::new(CoinOnChainQueryService::new(storage)), + denominations: denominations(), + clock: Arc::new(FixedClock(0)), + settlement_timeout_heads: 1, + }, + ); + + let error = service.handoff_exact(30, |_memo| async { Ok(()) }).await.unwrap_err(); + assert!(matches!(error, OutgoingTransferError::Reservation(_))); + assert_eq!(state(&inner, 1).await, CoinState::Available); + assert_eq!(state(&inner, 2).await, CoinState::Available); + assert!(wal.load_all().await.unwrap().is_empty()); + } } diff --git a/rust/crates/truapi-coinage/src/pallet.rs b/rust/crates/truapi-coinage/src/pallet.rs index 52109a779e..29e3b6d4a5 100644 --- a/rust/crates/truapi-coinage/src/pallet.rs +++ b/rust/crates/truapi-coinage/src/pallet.rs @@ -12,26 +12,26 @@ pub const PALLET_NAME: &str = "Coinage"; pub const AS_COINAGE_EXTENSION_ID: &str = "AsCoinage"; pub mod storage { - pub const COINS_BY_OWNER: &str = "CoinsByOwner"; - pub const RECYCLERS_COIN_TO_RECYCLER: &str = "RecyclersCoinToRecycler"; - /// Alias state storage. The Host resolves legacy denomination/ring/alias - /// keys or asset-instance-prefixed keys from runtime metadata. - pub const RECYCLER_ALIAS_STATES: &str = "RecyclerAliasStates"; - pub const CONSUMED_FREE_UNLOAD_TOKENS: &str = "ConsumedFreeUnloadTokens"; + pub const COINS_BY_OWNER: &str = "CoinsByOwner"; + pub const RECYCLERS_COIN_TO_RECYCLER: &str = "RecyclersCoinToRecycler"; + /// Alias state storage. The Host resolves legacy denomination/ring/alias + /// keys or asset-instance-prefixed keys from runtime metadata. + pub const RECYCLER_ALIAS_STATES: &str = "RecyclerAliasStates"; + pub const CONSUMED_FREE_UNLOAD_TOKENS: &str = "ConsumedFreeUnloadTokens"; } /// Call names, exactly as the runtime metadata spells them. pub mod calls { - pub const LOAD_EXTERNAL_ASSET_UNPAID_BATCH: &str = - "load_recycler_with_external_asset_unpaid_batch"; - pub const SPLIT: &str = "split"; - pub const UNLOAD_RECYCLER_INTO_COINS: &str = "unload_recycler_into_coins"; - pub const LOAD_RECYCLER_WITH_COIN: &str = "load_recycler_with_coin"; - pub const UNLOAD_RECYCLER_INTO_EXTERNAL_ASSET: &str = "unload_recycler_into_external_asset"; - /// 2026-08 upgrade rename of `…_and_vouchers`. - pub const UNLOAD_RECYCLER_INTO_EXTERNAL_ASSET_AND_LOADED_COINS: &str = - "unload_recycler_into_external_asset_and_loaded_coins"; - pub const TRANSFER: &str = "transfer"; + pub const LOAD_EXTERNAL_ASSET_UNPAID_BATCH: &str = + "load_recycler_with_external_asset_unpaid_batch"; + pub const SPLIT: &str = "split"; + pub const UNLOAD_RECYCLER_INTO_COINS: &str = "unload_recycler_into_coins"; + pub const LOAD_RECYCLER_WITH_COIN: &str = "load_recycler_with_coin"; + pub const UNLOAD_RECYCLER_INTO_EXTERNAL_ASSET: &str = "unload_recycler_into_external_asset"; + /// 2026-08 upgrade rename of `…_and_vouchers`. + pub const UNLOAD_RECYCLER_INTO_EXTERNAL_ASSET_AND_LOADED_COINS: &str = + "unload_recycler_into_external_asset_and_loaded_coins"; + pub const TRANSFER: &str = "transfer"; } /// `Coinage.load_recycler_with_coin(member_key, proof_of_ownership)`. @@ -39,16 +39,16 @@ pub mod calls { /// SCALE representation is the raw bytes with no compact length prefix. /// Pallet/call indices are resolved from runtime metadata by the host. pub fn load_recycler_with_coin_call( - pallet_index: u8, - call_index: u8, - member_key: &[u8; 32], - proof_of_ownership: &[u8; 64], + pallet_index: u8, + call_index: u8, + member_key: &[u8; 32], + proof_of_ownership: &[u8; 64], ) -> Vec { - let mut call = Vec::with_capacity(2 + member_key.len() + proof_of_ownership.len()); - call.extend_from_slice(&[pallet_index, call_index]); - call.extend_from_slice(member_key); - call.extend_from_slice(proof_of_ownership); - call + let mut call = Vec::with_capacity(2 + member_key.len() + proof_of_ownership.len()); + call.extend_from_slice(&[pallet_index, call_index]); + call.extend_from_slice(member_key); + call.extend_from_slice(proof_of_ownership); + call } /// `Coinage.transfer(to)`. @@ -58,10 +58,10 @@ pub fn load_recycler_with_coin_call( /// signer's sr25519 account id. Keeping this builder fixed-width prevents /// accidentally encoding the recipient as a SCALE `Vec`. pub fn transfer_call(pallet_index: u8, call_index: u8, recipient: &[u8; 32]) -> Vec { - let mut call = Vec::with_capacity(2 + recipient.len()); - call.extend_from_slice(&[pallet_index, call_index]); - call.extend_from_slice(recipient); - call + let mut call = Vec::with_capacity(2 + recipient.len()); + call.extend_from_slice(&[pallet_index, call_index]); + call.extend_from_slice(recipient); + call } /// Physical Members collection for a runtime-selected Coinage ABI. @@ -70,54 +70,54 @@ pub fn transfer_call(pallet_index: u8, call_index: u8, recipient: &[u8; 32]) -> /// byte 20, matching native `RecyclerCollectionIdentifier`. /// The Host validates the runtime denomination before calling this helper. pub fn recycler_collection_identifier(instance_id: Option, coin_value: i16) -> [u8; 32] { - let mut id = [0u8; 32]; - id[..16].copy_from_slice(b"coinage/recycler"); - let denomination_offset = if let Some(instance_id) = instance_id { - id[16..20].copy_from_slice(&instance_id.to_le_bytes()); - 20 - } else { - 16 - }; - id[denomination_offset] = coin_value.clamp(0, u8::MAX as i16) as u8; - id + let mut id = [0u8; 32]; + id[..16].copy_from_slice(b"coinage/recycler"); + let denomination_offset = if let Some(instance_id) = instance_id { + id[16..20].copy_from_slice(&instance_id.to_le_bytes()); + 20 + } else { + 16 + }; + id[denomination_offset] = coin_value.clamp(0, u8::MAX as i16) as u8; + id } fn hex_value(bytes: &[u8]) -> Value { - Value::String(format!("0x{}", hex::encode(bytes))) + Value::String(format!("0x{}", hex::encode(bytes))) } fn string_number(value: impl ToString) -> Value { - Value::String(value.to_string()) + Value::String(value.to_string()) } /// `Preservation` of an unpaid external-asset load (tagged union, payload /// always null). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Preservation { - Protect, - Preserve, - Expendable, + Protect, + Preserve, + Expendable, } impl Preservation { - fn to_json(self) -> Value { - let tag = match self { - Preservation::Protect => "Protect", - Preservation::Preserve => "Preserve", - Preservation::Expendable => "Expendable", - }; - json!([tag, null]) - } - - /// Pinned from the live `CodecPreservation` metadata variant indices, - /// which are NOT the declaration order of this enum. - fn scale_index(self) -> u8 { - match self { - Self::Expendable => 0, - Self::Protect => 1, - Self::Preserve => 2, - } - } + fn to_json(self) -> Value { + let tag = match self { + Preservation::Protect => "Protect", + Preservation::Preserve => "Preserve", + Preservation::Expendable => "Expendable", + }; + json!([tag, null]) + } + + /// Pinned from the live `CodecPreservation` metadata variant indices, + /// which are NOT the declaration order of this enum. + fn scale_index(self) -> u8 { + match self { + Self::Expendable => 0, + Self::Protect => 1, + Self::Preserve => 2, + } + } } /// One item of `load_recycler_with_external_asset_unpaid_batch`. @@ -129,46 +129,43 @@ impl Preservation { /// `MaximumExponent` 14). #[derive(Debug, Clone)] pub struct UnpaidLoadInput { - pub value: i8, - pub preservation: Preservation, - pub member_key: [u8; 32], - pub proof_of_ownership: Vec, + pub value: i8, + pub preservation: Preservation, + pub member_key: [u8; 32], + pub proof_of_ownership: Vec, } impl UnpaidLoadInput { - pub fn to_json(&self) -> Value { - json!({ - "value": string_number(self.value), - "preservation": self.preservation.to_json(), - "memberKey": hex_value(&self.member_key), - "proofOfOwnership": hex_value(&self.proof_of_ownership), - }) - } + pub fn to_json(&self) -> Value { + json!({ + "value": string_number(self.value), + "preservation": self.preservation.to_json(), + "memberKey": hex_value(&self.member_key), + "proofOfOwnership": hex_value(&self.proof_of_ownership), + }) + } } #[derive(Debug, Clone)] pub struct SplitDestination { - pub exponent: i16, - pub accounts: Vec<[u8; 32]>, + pub exponent: i16, + pub accounts: Vec<[u8; 32]>, } impl SplitDestination { - pub fn to_json(&self) -> Value { - json!([ - string_number(self.exponent), - self.accounts - .iter() - .map(|a| hex_value(a)) - .collect::>(), - ]) - } + pub fn to_json(&self) -> Value { + json!([ + string_number(self.exponent), + self.accounts.iter().map(|a| hex_value(a)).collect::>(), + ]) + } } /// The `split` call args (`split_into`). pub fn split_args(split_into: &[SplitDestination]) -> Value { - json!({ - "split_into": split_into.iter().map(SplitDestination::to_json).collect::>(), - }) + json!({ + "split_into": split_into.iter().map(SplitDestination::to_json).collect::>(), + }) } /// SCALE call bytes for `Coinage.split(split_into)`. @@ -177,33 +174,33 @@ pub fn split_args(split_into: &[SplitDestination]) -> Value { /// share the denomination domain; this boundary rejects an exponent that the /// runtime cannot represent rather than truncating it. pub fn split_call( - pallet_index: u8, - call_index: u8, - split_into: &[SplitDestination], + pallet_index: u8, + call_index: u8, + split_into: &[SplitDestination], ) -> Result, String> { - let count = u32::try_from(split_into.len()) - .map_err(|_| "Coinage split destination list is too large".to_string())?; - let mut call = Vec::new(); - call.extend_from_slice(&[pallet_index, call_index]); - call.extend_from_slice(&Compact(count).encode()); - for destination in split_into { - let exponent = i8::try_from(destination.exponent).map_err(|_| { - format!( - "Coinage split exponent {} does not fit the live i8 field", - destination.exponent - ) - })?; - call.push(exponent as u8); - call.extend_from_slice(&destination.accounts.encode()); - } - Ok(call) + let count = u32::try_from(split_into.len()) + .map_err(|_| "Coinage split destination list is too large".to_string())?; + let mut call = Vec::new(); + call.extend_from_slice(&[pallet_index, call_index]); + call.extend_from_slice(&Compact(count).encode()); + for destination in split_into { + let exponent = i8::try_from(destination.exponent).map_err(|_| { + format!( + "Coinage split exponent {} does not fit the live i8 field", + destination.exponent + ) + })?; + call.push(exponent as u8); + call.extend_from_slice(&destination.accounts.encode()); + } + Ok(call) } /// The batch-load call args (`items`). pub fn load_external_asset_unpaid_batch_args(items: &[UnpaidLoadInput]) -> Value { - json!({ - "items": items.iter().map(UnpaidLoadInput::to_json).collect::>(), - }) + json!({ + "items": items.iter().map(UnpaidLoadInput::to_json).collect::>(), + }) } /// SCALE call bytes for @@ -213,64 +210,64 @@ pub fn load_external_asset_unpaid_batch_args(items: &[UnpaidLoadInput]) -> Value /// length check at this boundary prevents a JSON-era `Vec` assumption /// from silently producing a different call layout. pub fn load_external_asset_unpaid_batch_call( - pallet_index: u8, - call_index: u8, - items: &[UnpaidLoadInput], + pallet_index: u8, + call_index: u8, + items: &[UnpaidLoadInput], ) -> Result, String> { - let item_count = u32::try_from(items.len()) - .map_err(|_| "Coinage unpaid voucher batch is too large".to_string())?; - let mut call = Vec::with_capacity(2 + 5 + items.len().saturating_mul(99)); - call.extend_from_slice(&[pallet_index, call_index]); - call.extend_from_slice(&Compact(item_count).encode()); - for item in items { - let proof: &[u8; 64] = item.proof_of_ownership.as_slice().try_into().map_err( - |_: std::array::TryFromSliceError| { - format!( - "Coinage unpaid voucher proof has {} bytes; expected 64", - item.proof_of_ownership.len() - ) - }, - )?; - // `preservation` precedes `value` in the runtime composite, and - // `value` is one byte — the reverse of both was a silent - // field-shift that made the node's decode panic. - call.push(item.preservation.scale_index()); - call.extend_from_slice(&item.value.to_le_bytes()); - call.extend_from_slice(&item.member_key); - call.extend_from_slice(proof); - } - Ok(call) + let item_count = u32::try_from(items.len()) + .map_err(|_| "Coinage unpaid voucher batch is too large".to_string())?; + let mut call = Vec::with_capacity(2 + 5 + items.len().saturating_mul(99)); + call.extend_from_slice(&[pallet_index, call_index]); + call.extend_from_slice(&Compact(item_count).encode()); + for item in items { + let proof: &[u8; 64] = item.proof_of_ownership.as_slice().try_into().map_err( + |_: std::array::TryFromSliceError| { + format!( + "Coinage unpaid voucher proof has {} bytes; expected 64", + item.proof_of_ownership.len() + ) + }, + )?; + // `preservation` precedes `value` in the runtime composite, and + // `value` is one byte — the reverse of both was a silent + // field-shift that made the node's decode panic. + call.push(item.preservation.scale_index()); + call.extend_from_slice(&item.value.to_le_bytes()); + call.extend_from_slice(&item.member_key); + call.extend_from_slice(proof); + } + Ok(call) } fn aliases_json(aliases: &[Vec]) -> Vec { - aliases.iter().map(|alias| hex_value(alias)).collect() + aliases.iter().map(|alias| hex_value(alias)).collect() } #[derive(Debug, Clone)] pub struct UnloadRecyclerIntoCoinsArgs { - pub aliases: Vec>, - pub value: i8, - pub index: u32, - pub revision: u32, - pub split_into: Vec, - pub max_fee: u128, + pub aliases: Vec>, + pub value: i8, + pub index: u32, + pub revision: u32, + pub split_into: Vec, + pub max_fee: u128, } impl UnloadRecyclerIntoCoinsArgs { - pub fn to_json(&self) -> Value { - json!({ - "aliases": aliases_json(&self.aliases), - "value": string_number(self.value), - "index": string_number(self.index), - "revision": string_number(self.revision), - "split_into": self - .split_into - .iter() - .map(SplitDestination::to_json) - .collect::>(), - "max_fee": string_number(self.max_fee), - }) - } + pub fn to_json(&self) -> Value { + json!({ + "aliases": aliases_json(&self.aliases), + "value": string_number(self.value), + "index": string_number(self.index), + "revision": string_number(self.revision), + "split_into": self + .split_into + .iter() + .map(SplitDestination::to_json) + .collect::>(), + "max_fee": string_number(self.max_fee), + }) + } } /// SCALE call bytes for `Coinage.unload_recycler_into_coins`. @@ -283,127 +280,127 @@ impl UnloadRecyclerIntoCoinsArgs { /// value cannot shift every following field. #[allow(clippy::too_many_arguments)] pub fn unload_recycler_into_coins_call( - pallet_index: u8, - call_index: u8, - instance_id: Option, - aliases: &[[u8; 32]], - value: i8, - index: u32, - revision: u32, - split_into: &[SplitDestination], - max_fee: u128, + pallet_index: u8, + call_index: u8, + instance_id: Option, + aliases: &[[u8; 32]], + value: i8, + index: u32, + revision: u32, + split_into: &[SplitDestination], + max_fee: u128, ) -> Result, String> { - let mut call = Vec::new(); - call.extend_from_slice(&[pallet_index, call_index]); - if let Some(instance_id) = instance_id { - call.extend_from_slice(&instance_id.to_le_bytes()); - } - call.extend_from_slice(&aliases.encode()); - call.push(value as u8); - call.extend_from_slice(&index.to_le_bytes()); - call.extend_from_slice(&revision.to_le_bytes()); - - let count = u32::try_from(split_into.len()) - .map_err(|_| "Coinage unload destination list is too large".to_string())?; - call.extend_from_slice(&Compact(count).encode()); - for destination in split_into { - let exponent = i8::try_from(destination.exponent).map_err(|_| { - format!( - "Coinage unload destination exponent {} does not fit the live i8 field", - destination.exponent - ) - })?; - call.push(exponent as u8); - call.extend_from_slice(&destination.accounts.encode()); - } - call.extend_from_slice(&max_fee.to_le_bytes()); - Ok(call) + let mut call = Vec::new(); + call.extend_from_slice(&[pallet_index, call_index]); + if let Some(instance_id) = instance_id { + call.extend_from_slice(&instance_id.to_le_bytes()); + } + call.extend_from_slice(&aliases.encode()); + call.push(value as u8); + call.extend_from_slice(&index.to_le_bytes()); + call.extend_from_slice(&revision.to_le_bytes()); + + let count = u32::try_from(split_into.len()) + .map_err(|_| "Coinage unload destination list is too large".to_string())?; + call.extend_from_slice(&Compact(count).encode()); + for destination in split_into { + let exponent = i8::try_from(destination.exponent).map_err(|_| { + format!( + "Coinage unload destination exponent {} does not fit the live i8 field", + destination.exponent + ) + })?; + call.push(exponent as u8); + call.extend_from_slice(&destination.accounts.encode()); + } + call.extend_from_slice(&max_fee.to_le_bytes()); + Ok(call) } /// Arguments for `Coinage.unload_recycler_into_external_asset`. #[derive(Debug, Clone)] pub struct UnloadRecyclerIntoExternalAssetArgs { - pub aliases: Vec>, - pub value: i8, - pub index: u32, - pub revision: u32, - pub to: [u8; 32], + pub aliases: Vec>, + pub value: i8, + pub index: u32, + pub revision: u32, + pub to: [u8; 32], } impl UnloadRecyclerIntoExternalAssetArgs { - pub fn to_json(&self) -> Value { - json!({ - "aliases": aliases_json(&self.aliases), - "value": string_number(self.value), - "index": string_number(self.index), - "revision": string_number(self.revision), - "to": hex_value(&self.to), - }) - } + pub fn to_json(&self) -> Value { + json!({ + "aliases": aliases_json(&self.aliases), + "value": string_number(self.value), + "index": string_number(self.index), + "revision": string_number(self.revision), + "to": hex_value(&self.to), + }) + } } /// SCALE call bytes for `unload_recycler_into_external_asset`. /// Live metadata: `Vec<[u8; 32]>`, `i8`, `u32`, `u32`, `[u8; 32]`. pub fn unload_recycler_into_external_asset_call( - pallet_index: u8, - call_index: u8, - aliases: &[[u8; 32]], - value: i8, - index: u32, - revision: u32, - to: &[u8; 32], + pallet_index: u8, + call_index: u8, + aliases: &[[u8; 32]], + value: i8, + index: u32, + revision: u32, + to: &[u8; 32], ) -> Vec { - let mut call = Vec::new(); - call.extend_from_slice(&[pallet_index, call_index]); - call.extend_from_slice(&aliases.encode()); - call.push(value as u8); - call.extend_from_slice(&index.to_le_bytes()); - call.extend_from_slice(&revision.to_le_bytes()); - call.extend_from_slice(to); - call + let mut call = Vec::new(); + call.extend_from_slice(&[pallet_index, call_index]); + call.extend_from_slice(&aliases.encode()); + call.push(value as u8); + call.extend_from_slice(&index.to_le_bytes()); + call.extend_from_slice(&revision.to_le_bytes()); + call.extend_from_slice(to); + call } #[derive(Debug, Clone)] pub struct NewVoucher { - pub coin_value: i8, - pub member_key: [u8; 32], + pub coin_value: i8, + pub member_key: [u8; 32], } impl NewVoucher { - pub fn to_json(&self) -> Value { - json!([string_number(self.coin_value), hex_value(&self.member_key),]) - } + pub fn to_json(&self) -> Value { + json!([string_number(self.coin_value), hex_value(&self.member_key),]) + } } /// Arguments for /// `Coinage.unload_recycler_into_external_asset_and_vouchers`. #[derive(Debug, Clone)] pub struct UnloadRecyclerIntoExternalAssetAndVouchersArgs { - pub aliases: Vec>, - pub value: i8, - pub index: u32, - pub revision: u32, - pub to: [u8; 32], - pub external_asset_amount: u128, - pub new_vouchers: Vec, + pub aliases: Vec>, + pub value: i8, + pub index: u32, + pub revision: u32, + pub to: [u8; 32], + pub external_asset_amount: u128, + pub new_vouchers: Vec, } impl UnloadRecyclerIntoExternalAssetAndVouchersArgs { - pub fn to_json(&self) -> Value { - json!({ - "aliases": aliases_json(&self.aliases), - "value": string_number(self.value), - "index": string_number(self.index), - "revision": string_number(self.revision), - "to": hex_value(&self.to), - "external_asset_amount": string_number(self.external_asset_amount), - "new_vouchers": self - .new_vouchers - .iter() - .map(NewVoucher::to_json) - .collect::>(), - }) - } + pub fn to_json(&self) -> Value { + json!({ + "aliases": aliases_json(&self.aliases), + "value": string_number(self.value), + "index": string_number(self.index), + "revision": string_number(self.revision), + "to": hex_value(&self.to), + "external_asset_amount": string_number(self.external_asset_amount), + "new_vouchers": self + .new_vouchers + .iter() + .map(NewVoucher::to_json) + .collect::>(), + }) + } } /// SCALE call bytes for @@ -412,552 +409,496 @@ impl UnloadRecyclerIntoExternalAssetAndVouchersArgs { /// amount is a fixed-width little-endian `u128`, as pinned by live metadata. #[allow(clippy::too_many_arguments)] pub fn unload_recycler_into_external_asset_and_vouchers_call( - pallet_index: u8, - call_index: u8, - aliases: &[[u8; 32]], - value: i8, - index: u32, - revision: u32, - to: &[u8; 32], - external_asset_amount: u128, - new_vouchers: &[NewVoucher], + pallet_index: u8, + call_index: u8, + aliases: &[[u8; 32]], + value: i8, + index: u32, + revision: u32, + to: &[u8; 32], + external_asset_amount: u128, + new_vouchers: &[NewVoucher], ) -> Vec { - let mut call = Vec::new(); - call.extend_from_slice(&[pallet_index, call_index]); - call.extend_from_slice(&aliases.encode()); - call.push(value as u8); - call.extend_from_slice(&index.to_le_bytes()); - call.extend_from_slice(&revision.to_le_bytes()); - call.extend_from_slice(to); - call.extend_from_slice(&external_asset_amount.to_le_bytes()); - call.extend_from_slice(&Compact(new_vouchers.len() as u32).encode()); - for voucher in new_vouchers { - call.push(voucher.coin_value as u8); - call.extend_from_slice(&voucher.member_key); - } - call + let mut call = Vec::new(); + call.extend_from_slice(&[pallet_index, call_index]); + call.extend_from_slice(&aliases.encode()); + call.push(value as u8); + call.extend_from_slice(&index.to_le_bytes()); + call.extend_from_slice(&revision.to_le_bytes()); + call.extend_from_slice(to); + call.extend_from_slice(&external_asset_amount.to_le_bytes()); + call.extend_from_slice(&Compact(new_vouchers.len() as u32).encode()); + for voucher in new_vouchers { + call.push(voucher.coin_value as u8); + call.extend_from_slice(&voucher.member_key); + } + call } /// The personhood half of an unload-token proof: the ring-VRF proof and /// the ring it opens against. #[derive(Debug, Clone)] pub struct PeopleProof { - pub proof: Vec, - pub ring: u32, - /// The ring revision the proof was built against — required by the - /// 2026-08 runtime's `MembershipProof` (spec 1000032). - pub revision: u32, + pub proof: Vec, + pub ring: u32, + /// The ring revision the proof was built against — required by the + /// 2026-08 runtime's `MembershipProof` (spec 1000032). + pub revision: u32, } impl PeopleProof { - fn to_json(&self) -> Value { - json!({ - "proof": hex_value(&self.proof), - "ring": string_number(self.ring), - "revision": string_number(self.revision), - }) - } + fn to_json(&self) -> Value { + json!({ + "proof": hex_value(&self.proof), + "ring": string_number(self.ring), + "revision": string_number(self.revision), + }) + } } #[derive(Debug, Clone)] pub enum AsCoinageMode { - /// Sr25519 coin-keypair origin — the variant tag is the whole payload. - AsCoin, - /// Full-person unload token: people-ring proof + per-voucher recycler - /// alias proofs. - AsUnloadTokenPeople { - proof: PeopleProof, - period: u32, - counter: u32, - alias_proofs: Vec>, - }, - /// Lite-person unload token (same payload as the full-person mode). - AsUnloadTokenLitePeople { - proof: PeopleProof, - period: u32, - counter: u32, - alias_proofs: Vec>, - }, - /// Pre-computed proof from the PAID unload-token ring. - AsUnloadTokenPaid { - proof: Vec, - period: u32, - paid_token_ring_index: u32, - paid_token_ring_revision: u32, - alias_proofs: Vec>, - }, - /// Fee recycler output as the token (first alias proof = fee coin). - /// `retry_counter` joined in the 2026-08 runtime (spec 1000032). - AsUnloadTokenFromOutput { - fee_recycler_value: i8, - fee_recycler_index: u32, - fee_recycler_revision: u32, - retry_counter: u8, - alias_proofs: Vec>, - }, - InfallibleUnpaidSigned { - nonce: u32, - }, + /// Sr25519 coin-keypair origin — the variant tag is the whole payload. + AsCoin, + /// Full-person unload token: people-ring proof + per-voucher recycler + /// alias proofs. + AsUnloadTokenPeople { + proof: PeopleProof, + period: u32, + counter: u32, + alias_proofs: Vec>, + }, + /// Lite-person unload token (same payload as the full-person mode). + AsUnloadTokenLitePeople { + proof: PeopleProof, + period: u32, + counter: u32, + alias_proofs: Vec>, + }, + /// Pre-computed proof from the PAID unload-token ring. + AsUnloadTokenPaid { + proof: Vec, + period: u32, + paid_token_ring_index: u32, + paid_token_ring_revision: u32, + alias_proofs: Vec>, + }, + /// Fee recycler output as the token (first alias proof = fee coin). + /// `retry_counter` joined in the 2026-08 runtime (spec 1000032). + AsUnloadTokenFromOutput { + fee_recycler_value: i8, + fee_recycler_index: u32, + fee_recycler_revision: u32, + retry_counter: u8, + alias_proofs: Vec>, + }, + InfallibleUnpaidSigned { + nonce: u32, + }, } impl AsCoinageMode { - /// The `["TagName", null | payload]` JSON the dynamic SCALE layer - /// consumes. - pub fn to_json(&self) -> Value { - let alias_list = - |proofs: &[Vec]| proofs.iter().map(|p| hex_value(p)).collect::>(); - match self { - AsCoinageMode::AsCoin => json!(["AsCoin", null]), - AsCoinageMode::AsUnloadTokenPeople { - proof, - period, - counter, - alias_proofs, - } => json!([ - "AsUnloadTokenPeople", - { - "proof": proof.to_json(), - "period": string_number(period), - "counter": string_number(counter), - "aliasProofs": alias_list(alias_proofs), - } - ]), - AsCoinageMode::AsUnloadTokenLitePeople { - proof, - period, - counter, - alias_proofs, - } => json!([ - "AsUnloadTokenLitePeople", - { - "proof": proof.to_json(), - "period": string_number(period), - "counter": string_number(counter), - "aliasProofs": alias_list(alias_proofs), - } - ]), - AsCoinageMode::AsUnloadTokenPaid { - proof, - period, - paid_token_ring_index, - paid_token_ring_revision, - alias_proofs, - } => json!([ - "AsUnloadTokenPaid", - { - "proof": hex_value(proof), - "period": string_number(period), - "paidTokenRingIndex": string_number(paid_token_ring_index), - "paidTokenRingRevision": string_number(paid_token_ring_revision), - "aliasProofs": alias_list(alias_proofs), - } - ]), - AsCoinageMode::AsUnloadTokenFromOutput { - fee_recycler_value, - fee_recycler_index, - fee_recycler_revision, - retry_counter, - alias_proofs, - } => json!([ - "AsUnloadTokenFromOutput", - { - "feeRecyclerValue": string_number(fee_recycler_value), - "feeRecyclerIndex": string_number(fee_recycler_index), - "feeRecyclerRevision": string_number(fee_recycler_revision), - "retryCounter": string_number(retry_counter), - "aliasProofs": alias_list(alias_proofs), - } - ]), - AsCoinageMode::InfallibleUnpaidSigned { nonce } => json!([ - "InfallibleUnpaidSigned", - { "nonce": string_number(nonce) } - ]), - } - } + /// The `["TagName", null | payload]` JSON the dynamic SCALE layer + /// consumes. + pub fn to_json(&self) -> Value { + let alias_list = + |proofs: &[Vec]| proofs.iter().map(|p| hex_value(p)).collect::>(); + match self { + AsCoinageMode::AsCoin => json!(["AsCoin", null]), + AsCoinageMode::AsUnloadTokenPeople { proof, period, counter, alias_proofs } => json!([ + "AsUnloadTokenPeople", + { + "proof": proof.to_json(), + "period": string_number(period), + "counter": string_number(counter), + "aliasProofs": alias_list(alias_proofs), + } + ]), + AsCoinageMode::AsUnloadTokenLitePeople { proof, period, counter, alias_proofs } => { + json!([ + "AsUnloadTokenLitePeople", + { + "proof": proof.to_json(), + "period": string_number(period), + "counter": string_number(counter), + "aliasProofs": alias_list(alias_proofs), + } + ]) + }, + AsCoinageMode::AsUnloadTokenPaid { + proof, + period, + paid_token_ring_index, + paid_token_ring_revision, + alias_proofs, + } => json!([ + "AsUnloadTokenPaid", + { + "proof": hex_value(proof), + "period": string_number(period), + "paidTokenRingIndex": string_number(paid_token_ring_index), + "paidTokenRingRevision": string_number(paid_token_ring_revision), + "aliasProofs": alias_list(alias_proofs), + } + ]), + AsCoinageMode::AsUnloadTokenFromOutput { + fee_recycler_value, + fee_recycler_index, + fee_recycler_revision, + retry_counter, + alias_proofs, + } => json!([ + "AsUnloadTokenFromOutput", + { + "feeRecyclerValue": string_number(fee_recycler_value), + "feeRecyclerIndex": string_number(fee_recycler_index), + "feeRecyclerRevision": string_number(fee_recycler_revision), + "retryCounter": string_number(retry_counter), + "aliasProofs": alias_list(alias_proofs), + } + ]), + AsCoinageMode::InfallibleUnpaidSigned { nonce } => json!([ + "InfallibleUnpaidSigned", + { "nonce": string_number(nonce) } + ]), + } + } } #[cfg(test)] mod tests { - use super::*; - - #[test] - fn load_recycler_with_coin_call_has_fixed_array_arguments() { - let call = load_recycler_with_coin_call(52, 2, &[0x11; 32], &[0x22; 64]); - assert_eq!(call.len(), 98); - assert_eq!(&call[..2], &[52, 2]); - assert_eq!(&call[2..34], &[0x11; 32]); - assert_eq!(&call[34..], &[0x22; 64]); - } - - #[test] - fn unpaid_external_asset_batch_call_matches_fixed_runtime_layout() { - let call = load_external_asset_unpaid_batch_call( - 52, - 1, - &[ - UnpaidLoadInput { - value: -2, - preservation: Preservation::Expendable, - member_key: [0x11; 32], - proof_of_ownership: vec![0x22; 64], - }, - UnpaidLoadInput { - value: 3, - preservation: Preservation::Protect, - member_key: [0x33; 32], - proof_of_ownership: vec![0x44; 64], - }, - ], - ) - .unwrap(); - // Pinned from the live `UnpaidLoadInput` composite: preservation - // (1 byte, live variant indices) then value (1 byte), member key, - // proof. Getting either the order or the value width wrong shifts - // every later field and the node's decode panics. - assert_eq!(&call[..3], &[52, 1, 8], "two-item Compact"); - assert_eq!(call[3], 0, "Expendable variant"); - assert_eq!(call[4] as i8, -2i8); - assert_eq!(&call[5..37], &[0x11; 32]); - assert_eq!(&call[37..101], &[0x22; 64]); - assert_eq!(call[101], 1, "Protect variant"); - assert_eq!(call[102] as i8, 3i8); - assert_eq!(&call[103..135], &[0x33; 32]); - assert_eq!(&call[135..199], &[0x44; 64]); - assert_eq!(call.len(), 199, "2 + 1 + 2 * (1 + 1 + 32 + 64)"); - } - - #[test] - fn unpaid_external_asset_batch_rejects_variable_length_proof() { - let error = load_external_asset_unpaid_batch_call( - 1, - 2, - &[UnpaidLoadInput { - value: 0, - preservation: Preservation::Preserve, - member_key: [0; 32], - proof_of_ownership: vec![0; 63], - }], - ) - .unwrap_err(); - assert!(error.contains("63 bytes; expected 64")); - } - - #[test] - fn transfer_call_has_one_fixed_account_argument() { - let call = transfer_call(52, 6, &[0xA5; 32]); - assert_eq!(call.len(), 34); - assert_eq!(&call[..2], &[52, 6]); - assert_eq!(&call[2..], &[0xA5; 32]); - } - - #[test] - fn split_call_matches_live_scale_layout() { - let call = split_call( - 52, - 3, - &[ - SplitDestination { - exponent: -1, - accounts: vec![[0x11; 32], [0x22; 32]], - }, - SplitDestination { - exponent: 4, - accounts: vec![[0x33; 32]], - }, - ], - ) - .unwrap(); - assert_eq!(&call[..3], &[52, 3, 8], "two destination tuples"); - assert_eq!(call[3], 0xff, "i8 exponent"); - assert_eq!(call[4], 8, "two accounts"); - assert_eq!(&call[5..37], &[0x11; 32]); - assert_eq!(&call[37..69], &[0x22; 32]); - assert_eq!(call[69], 4); - assert_eq!(call[70], 4, "one account"); - assert_eq!(&call[71..103], &[0x33; 32]); - assert_eq!(call.len(), 103); - } - - #[test] - fn unload_into_coins_call_matches_legacy_scale_layout() { - let call = unload_recycler_into_coins_call( - 52, - 4, - None, - &[[0xAA; 32], [0xBB; 32]], - -2, - 0x1122_3344, - 0x5566_7788, - &[SplitDestination { - exponent: 3, - accounts: vec![[0xCC; 32]], - }], - 9, - ) - .unwrap(); - assert_eq!(&call[..3], &[52, 4, 8], "two aliases"); - assert_eq!(&call[3..35], &[0xAA; 32]); - assert_eq!(&call[35..67], &[0xBB; 32]); - assert_eq!(call[67], 0xfe); - assert_eq!(&call[68..72], &0x1122_3344u32.to_le_bytes()); - assert_eq!(&call[72..76], &0x5566_7788u32.to_le_bytes()); - assert_eq!(call[76], 4, "one split tuple"); - assert_eq!(call[77], 3); - assert_eq!(call[78], 4, "one account"); - assert_eq!(&call[79..111], &[0xCC; 32]); - assert_eq!(&call[111..], &9u128.to_le_bytes()); - assert_eq!(call.len(), 127); - } - - #[test] - fn unload_into_coins_call_matches_asset_instance_scale_layout() { - let call = unload_recycler_into_coins_call( - 52, - 4, - Some(0x1122_3344), - &[[0xAA; 32], [0xBB; 32]], - -2, - 0x5566_7788, - 0x99AA_BBCC, - &[SplitDestination { - exponent: 3, - accounts: vec![[0xCC; 32]], - }], - 9, - ) - .unwrap(); - // The complete runtime argument tuple catches an Option tag, misplaced - // instance, variable-width alias or shifted trailing argument. - let expected = ( - 52u8, - 4u8, - 0x1122_3344u32, - vec![[0xAAu8; 32], [0xBB; 32]], - -2i8, - 0x5566_7788u32, - 0x99AA_BBCCu32, - vec![(3i8, vec![[0xCCu8; 32]])], - 9u128, - ) - .encode(); - assert_eq!(call, expected); - } - - #[test] - fn coin_output_calls_reject_exponents_outside_live_i8() { - for exponent in [-129, 128] { - let destinations = [SplitDestination { - exponent, - accounts: vec![[0; 32]], - }]; - assert!(split_call(1, 2, &destinations).is_err()); - for instance_id in [None, Some(0x1122_3344)] { - assert!( - unload_recycler_into_coins_call( - 1, - 2, - instance_id, - &[], - 0, - 0, - 0, - &destinations, - 0, - ) - .is_err() - ); - } - } - } - - #[test] - fn recycler_collection_matches_legacy_and_asset_instance_wire_layouts() { - assert_eq!( - recycler_collection_identifier(None, 5), - *b"coinage/recycler\x05\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" - ); - assert_eq!( - recycler_collection_identifier(Some(0x1122_3344), 5), - *b"coinage/recycler\x44\x33\x22\x11\x05\0\0\0\0\0\0\0\0\0\0\0" - ); - } - - #[test] - fn as_coinage_modes_match_the_reference_json() { - assert_eq!(AsCoinageMode::AsCoin.to_json(), json!(["AsCoin", null])); - assert_eq!( - AsCoinageMode::InfallibleUnpaidSigned { nonce: 7 }.to_json(), - json!(["InfallibleUnpaidSigned", { "nonce": "7" }]) - ); - let people = AsCoinageMode::AsUnloadTokenPeople { - proof: PeopleProof { - proof: vec![0xAA], - ring: 2, - revision: 6, - }, - period: 9, - counter: 1, - alias_proofs: vec![vec![0xBB], vec![0xCC]], - } - .to_json(); - assert_eq!( - people, - json!([ - "AsUnloadTokenPeople", - { - "proof": { "proof": "0xaa", "ring": "2", "revision": "6" }, - "period": "9", - "counter": "1", - "aliasProofs": ["0xbb", "0xcc"], - } - ]) - ); - let from_output = AsCoinageMode::AsUnloadTokenFromOutput { - fee_recycler_value: -1, - fee_recycler_index: 3, - fee_recycler_revision: 4, - retry_counter: 2, - alias_proofs: vec![], - } - .to_json(); - assert_eq!( - from_output[1]["feeRecyclerValue"], - Value::String("-1".into()) - ); - } - - #[test] - fn call_args_match_the_reference_json() { - let split = split_args(&[SplitDestination { - exponent: 3, - accounts: vec![[1u8; 32]], - }]); - assert_eq!(split["split_into"][0][0], Value::String("3".into())); - assert!( - split["split_into"][0][1][0] - .as_str() - .unwrap() - .starts_with("0x0101") - ); - - let batch = load_external_asset_unpaid_batch_args(&[UnpaidLoadInput { - value: 2, - preservation: Preservation::Expendable, - member_key: [9u8; 32], - proof_of_ownership: vec![0xDD], - }]); - let item = &batch["items"][0]; - assert_eq!(item["value"], Value::String("2".into())); - assert_eq!(item["preservation"], json!(["Expendable", null])); - assert_eq!(item["proofOfOwnership"], Value::String("0xdd".into())); - } - - #[test] - fn unload_call_args_match_the_reference_json() { - let into_coins = UnloadRecyclerIntoCoinsArgs { - aliases: vec![vec![0xAA; 32]], - value: -2, - index: 7, - revision: 9, - split_into: vec![SplitDestination { - exponent: 3, - accounts: vec![[0x11; 32]], - }], - max_fee: 0, - } - .to_json(); - assert_eq!( - into_coins, - json!({ - "aliases": [format!("0x{}", "aa".repeat(32))], - "value": "-2", - "index": "7", - "revision": "9", - "split_into": [[ - "3", - [format!("0x{}", "11".repeat(32))] - ]], - "max_fee": "0", - }) - ); - - let into_asset = UnloadRecyclerIntoExternalAssetArgs { - aliases: vec![vec![0xBB; 32], vec![0xCC; 32]], - value: 4, - index: 10, - revision: 11, - to: [0x22; 32], - } - .to_json(); - assert_eq!(into_asset["aliases"].as_array().unwrap().len(), 2); - assert_eq!(into_asset["value"], "4"); - assert_eq!(into_asset["index"], "10"); - assert_eq!(into_asset["revision"], "11"); - assert_eq!( - into_asset["to"], - Value::String(format!("0x{}", "22".repeat(32))) - ); - - let with_change = UnloadRecyclerIntoExternalAssetAndVouchersArgs { - aliases: vec![vec![0xDD; 32]], - value: 5, - index: 12, - revision: 13, - to: [0x33; 32], - external_asset_amount: u128::MAX, - new_vouchers: vec![NewVoucher { - coin_value: -1, - member_key: [0x44; 32], - }], - } - .to_json(); - assert_eq!( - with_change["external_asset_amount"], - Value::String(u128::MAX.to_string()) - ); - assert_eq!( - with_change["new_vouchers"][0], - json!(["-1", format!("0x{}", "44".repeat(32)),]) - ); - assert!(with_change.get("externalAssetAmount").is_none()); - assert!(with_change.get("newVouchers").is_none()); - } - - #[test] - fn external_asset_unload_calls_match_live_scale_layout() { - let aliases = [[0x11; 32], [0x22; 32]]; - let plain = - unload_recycler_into_external_asset_call(68, 5, &aliases, -2, 7, 9, &[0x33; 32]); - assert_eq!(&plain[..3], &[68, 5, 8], "two aliases, compact len 2"); - assert_eq!(&plain[3..35], &[0x11; 32]); - assert_eq!(&plain[35..67], &[0x22; 32]); - assert_eq!(plain[67], (-2i8) as u8); - assert_eq!(&plain[68..72], &7u32.to_le_bytes()); - assert_eq!(&plain[72..76], &9u32.to_le_bytes()); - assert_eq!(&plain[76..], &[0x33; 32]); - - let with_change = unload_recycler_into_external_asset_and_vouchers_call( - 68, - 9, - &aliases[..1], - 4, - 10, - 11, - &[0x44; 32], - 123, - &[NewVoucher { - coin_value: -1, - member_key: [0x55; 32], - }], - ); - assert_eq!(&with_change[..3], &[68, 9, 4], "one alias"); - let amount_offset = 3 + 32 + 1 + 4 + 4 + 32; - assert_eq!( - &with_change[amount_offset..amount_offset + 16], - &123u128.to_le_bytes() - ); - assert_eq!(with_change[amount_offset + 16], 4, "one voucher"); - assert_eq!(with_change[amount_offset + 17], (-1i8) as u8); - assert_eq!(&with_change[amount_offset + 18..], &[0x55; 32]); - } + use super::*; + + #[test] + fn load_recycler_with_coin_call_has_fixed_array_arguments() { + let call = load_recycler_with_coin_call(52, 2, &[0x11; 32], &[0x22; 64]); + assert_eq!(call.len(), 98); + assert_eq!(&call[..2], &[52, 2]); + assert_eq!(&call[2..34], &[0x11; 32]); + assert_eq!(&call[34..], &[0x22; 64]); + } + + #[test] + fn unpaid_external_asset_batch_call_matches_fixed_runtime_layout() { + let call = load_external_asset_unpaid_batch_call( + 52, + 1, + &[ + UnpaidLoadInput { + value: -2, + preservation: Preservation::Expendable, + member_key: [0x11; 32], + proof_of_ownership: vec![0x22; 64], + }, + UnpaidLoadInput { + value: 3, + preservation: Preservation::Protect, + member_key: [0x33; 32], + proof_of_ownership: vec![0x44; 64], + }, + ], + ) + .unwrap(); + // Pinned from the live `UnpaidLoadInput` composite: preservation + // (1 byte, live variant indices) then value (1 byte), member key, + // proof. Getting either the order or the value width wrong shifts + // every later field and the node's decode panics. + assert_eq!(&call[..3], &[52, 1, 8], "two-item Compact"); + assert_eq!(call[3], 0, "Expendable variant"); + assert_eq!(call[4] as i8, -2i8); + assert_eq!(&call[5..37], &[0x11; 32]); + assert_eq!(&call[37..101], &[0x22; 64]); + assert_eq!(call[101], 1, "Protect variant"); + assert_eq!(call[102] as i8, 3i8); + assert_eq!(&call[103..135], &[0x33; 32]); + assert_eq!(&call[135..199], &[0x44; 64]); + assert_eq!(call.len(), 199, "2 + 1 + 2 * (1 + 1 + 32 + 64)"); + } + + #[test] + fn unpaid_external_asset_batch_rejects_variable_length_proof() { + let error = load_external_asset_unpaid_batch_call( + 1, + 2, + &[UnpaidLoadInput { + value: 0, + preservation: Preservation::Preserve, + member_key: [0; 32], + proof_of_ownership: vec![0; 63], + }], + ) + .unwrap_err(); + assert!(error.contains("63 bytes; expected 64")); + } + + #[test] + fn transfer_call_has_one_fixed_account_argument() { + let call = transfer_call(52, 6, &[0xA5; 32]); + assert_eq!(call.len(), 34); + assert_eq!(&call[..2], &[52, 6]); + assert_eq!(&call[2..], &[0xA5; 32]); + } + + #[test] + fn split_call_matches_live_scale_layout() { + let call = split_call( + 52, + 3, + &[ + SplitDestination { exponent: -1, accounts: vec![[0x11; 32], [0x22; 32]] }, + SplitDestination { exponent: 4, accounts: vec![[0x33; 32]] }, + ], + ) + .unwrap(); + assert_eq!(&call[..3], &[52, 3, 8], "two destination tuples"); + assert_eq!(call[3], 0xff, "i8 exponent"); + assert_eq!(call[4], 8, "two accounts"); + assert_eq!(&call[5..37], &[0x11; 32]); + assert_eq!(&call[37..69], &[0x22; 32]); + assert_eq!(call[69], 4); + assert_eq!(call[70], 4, "one account"); + assert_eq!(&call[71..103], &[0x33; 32]); + assert_eq!(call.len(), 103); + } + + #[test] + fn unload_into_coins_call_matches_legacy_scale_layout() { + let call = unload_recycler_into_coins_call( + 52, + 4, + None, + &[[0xAA; 32], [0xBB; 32]], + -2, + 0x1122_3344, + 0x5566_7788, + &[SplitDestination { exponent: 3, accounts: vec![[0xCC; 32]] }], + 9, + ) + .unwrap(); + assert_eq!(&call[..3], &[52, 4, 8], "two aliases"); + assert_eq!(&call[3..35], &[0xAA; 32]); + assert_eq!(&call[35..67], &[0xBB; 32]); + assert_eq!(call[67], 0xfe); + assert_eq!(&call[68..72], &0x1122_3344u32.to_le_bytes()); + assert_eq!(&call[72..76], &0x5566_7788u32.to_le_bytes()); + assert_eq!(call[76], 4, "one split tuple"); + assert_eq!(call[77], 3); + assert_eq!(call[78], 4, "one account"); + assert_eq!(&call[79..111], &[0xCC; 32]); + assert_eq!(&call[111..], &9u128.to_le_bytes()); + assert_eq!(call.len(), 127); + } + + #[test] + fn unload_into_coins_call_matches_asset_instance_scale_layout() { + let call = unload_recycler_into_coins_call( + 52, + 4, + Some(0x1122_3344), + &[[0xAA; 32], [0xBB; 32]], + -2, + 0x5566_7788, + 0x99AA_BBCC, + &[SplitDestination { exponent: 3, accounts: vec![[0xCC; 32]] }], + 9, + ) + .unwrap(); + // The complete runtime argument tuple catches an Option tag, misplaced + // instance, variable-width alias or shifted trailing argument. + let expected = ( + 52u8, + 4u8, + 0x1122_3344u32, + vec![[0xAAu8; 32], [0xBB; 32]], + -2i8, + 0x5566_7788u32, + 0x99AA_BBCCu32, + vec![(3i8, vec![[0xCCu8; 32]])], + 9u128, + ) + .encode(); + assert_eq!(call, expected); + } + + #[test] + fn coin_output_calls_reject_exponents_outside_live_i8() { + for exponent in [-129, 128] { + let destinations = [SplitDestination { exponent, accounts: vec![[0; 32]] }]; + assert!(split_call(1, 2, &destinations).is_err()); + for instance_id in [None, Some(0x1122_3344)] { + assert!( + unload_recycler_into_coins_call( + 1, + 2, + instance_id, + &[], + 0, + 0, + 0, + &destinations, + 0, + ) + .is_err() + ); + } + } + } + + #[test] + fn recycler_collection_matches_legacy_and_asset_instance_wire_layouts() { + assert_eq!( + recycler_collection_identifier(None, 5), + *b"coinage/recycler\x05\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + ); + assert_eq!( + recycler_collection_identifier(Some(0x1122_3344), 5), + *b"coinage/recycler\x44\x33\x22\x11\x05\0\0\0\0\0\0\0\0\0\0\0" + ); + } + + #[test] + fn as_coinage_modes_match_the_reference_json() { + assert_eq!(AsCoinageMode::AsCoin.to_json(), json!(["AsCoin", null])); + assert_eq!( + AsCoinageMode::InfallibleUnpaidSigned { nonce: 7 }.to_json(), + json!(["InfallibleUnpaidSigned", { "nonce": "7" }]) + ); + let people = AsCoinageMode::AsUnloadTokenPeople { + proof: PeopleProof { proof: vec![0xAA], ring: 2, revision: 6 }, + period: 9, + counter: 1, + alias_proofs: vec![vec![0xBB], vec![0xCC]], + } + .to_json(); + assert_eq!( + people, + json!([ + "AsUnloadTokenPeople", + { + "proof": { "proof": "0xaa", "ring": "2", "revision": "6" }, + "period": "9", + "counter": "1", + "aliasProofs": ["0xbb", "0xcc"], + } + ]) + ); + let from_output = AsCoinageMode::AsUnloadTokenFromOutput { + fee_recycler_value: -1, + fee_recycler_index: 3, + fee_recycler_revision: 4, + retry_counter: 2, + alias_proofs: vec![], + } + .to_json(); + assert_eq!(from_output[1]["feeRecyclerValue"], Value::String("-1".into())); + } + + #[test] + fn call_args_match_the_reference_json() { + let split = split_args(&[SplitDestination { exponent: 3, accounts: vec![[1u8; 32]] }]); + assert_eq!(split["split_into"][0][0], Value::String("3".into())); + assert!(split["split_into"][0][1][0].as_str().unwrap().starts_with("0x0101")); + + let batch = load_external_asset_unpaid_batch_args(&[UnpaidLoadInput { + value: 2, + preservation: Preservation::Expendable, + member_key: [9u8; 32], + proof_of_ownership: vec![0xDD], + }]); + let item = &batch["items"][0]; + assert_eq!(item["value"], Value::String("2".into())); + assert_eq!(item["preservation"], json!(["Expendable", null])); + assert_eq!(item["proofOfOwnership"], Value::String("0xdd".into())); + } + + #[test] + fn unload_call_args_match_the_reference_json() { + let into_coins = UnloadRecyclerIntoCoinsArgs { + aliases: vec![vec![0xAA; 32]], + value: -2, + index: 7, + revision: 9, + split_into: vec![SplitDestination { exponent: 3, accounts: vec![[0x11; 32]] }], + max_fee: 0, + } + .to_json(); + assert_eq!( + into_coins, + json!({ + "aliases": [format!("0x{}", "aa".repeat(32))], + "value": "-2", + "index": "7", + "revision": "9", + "split_into": [[ + "3", + [format!("0x{}", "11".repeat(32))] + ]], + "max_fee": "0", + }) + ); + + let into_asset = UnloadRecyclerIntoExternalAssetArgs { + aliases: vec![vec![0xBB; 32], vec![0xCC; 32]], + value: 4, + index: 10, + revision: 11, + to: [0x22; 32], + } + .to_json(); + assert_eq!(into_asset["aliases"].as_array().unwrap().len(), 2); + assert_eq!(into_asset["value"], "4"); + assert_eq!(into_asset["index"], "10"); + assert_eq!(into_asset["revision"], "11"); + assert_eq!(into_asset["to"], Value::String(format!("0x{}", "22".repeat(32)))); + + let with_change = UnloadRecyclerIntoExternalAssetAndVouchersArgs { + aliases: vec![vec![0xDD; 32]], + value: 5, + index: 12, + revision: 13, + to: [0x33; 32], + external_asset_amount: u128::MAX, + new_vouchers: vec![NewVoucher { coin_value: -1, member_key: [0x44; 32] }], + } + .to_json(); + assert_eq!(with_change["external_asset_amount"], Value::String(u128::MAX.to_string())); + assert_eq!( + with_change["new_vouchers"][0], + json!(["-1", format!("0x{}", "44".repeat(32)),]) + ); + assert!(with_change.get("externalAssetAmount").is_none()); + assert!(with_change.get("newVouchers").is_none()); + } + + #[test] + fn external_asset_unload_calls_match_live_scale_layout() { + let aliases = [[0x11; 32], [0x22; 32]]; + let plain = + unload_recycler_into_external_asset_call(68, 5, &aliases, -2, 7, 9, &[0x33; 32]); + assert_eq!(&plain[..3], &[68, 5, 8], "two aliases, compact len 2"); + assert_eq!(&plain[3..35], &[0x11; 32]); + assert_eq!(&plain[35..67], &[0x22; 32]); + assert_eq!(plain[67], (-2i8) as u8); + assert_eq!(&plain[68..72], &7u32.to_le_bytes()); + assert_eq!(&plain[72..76], &9u32.to_le_bytes()); + assert_eq!(&plain[76..], &[0x33; 32]); + + let with_change = unload_recycler_into_external_asset_and_vouchers_call( + 68, + 9, + &aliases[..1], + 4, + 10, + 11, + &[0x44; 32], + 123, + &[NewVoucher { coin_value: -1, member_key: [0x55; 32] }], + ); + assert_eq!(&with_change[..3], &[68, 9, 4], "one alias"); + let amount_offset = 3 + 32 + 1 + 4 + 4 + 32; + assert_eq!(&with_change[amount_offset..amount_offset + 16], &123u128.to_le_bytes()); + assert_eq!(with_change[amount_offset + 16], 4, "one voucher"); + assert_eq!(with_change[amount_offset + 17], (-1i8) as u8); + assert_eq!(&with_change[amount_offset + 18..], &[0x55; 32]); + } } diff --git a/rust/crates/truapi-coinage/src/query.rs b/rust/crates/truapi-coinage/src/query.rs index 94446c1986..315ec04ffe 100644 --- a/rust/crates/truapi-coinage/src/query.rs +++ b/rust/crates/truapi-coinage/src/query.rs @@ -2,26 +2,24 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use std::collections::HashMap; -use std::fmt; -use std::sync::Arc; -use std::time::Duration; +use std::{collections::HashMap, fmt, sync::Arc, time::Duration}; use crate::members::{self, RingPosition, RingRoot}; use async_trait::async_trait; -use futures::stream::BoxStream; -use futures::{FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, stream::BoxStream}; use parity_scale_codec::{Decode, DecodeAll, Encode}; use tokio::sync::mpsc; use tracing::warn; -use crate::claim::SendConfirmation; -use crate::repo::VoucherRepository; -use crate::selection::RecyclerKey; -use crate::sync::OnChainCoin; -use crate::voucher_location::{ - RingPosition as VoucherRingPosition, RingStatus as VoucherRingStatus, - VoucherLocationSubscriber, VoucherLocationUpdate, +use crate::{ + claim::SendConfirmation, + repo::VoucherRepository, + selection::RecyclerKey, + sync::OnChainCoin, + voucher_location::{ + RingPosition as VoucherRingPosition, RingStatus as VoucherRingStatus, + VoucherLocationSubscriber, VoucherLocationUpdate, + }, }; /// Semantic Coinage storage requests. The Host resolves physical keys @@ -29,134 +27,97 @@ use crate::voucher_location::{ /// instance. Recycler collections are never encoded by the portable engine. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum CoinageStorageKey { - Coin([u8; 32]), - Recycler([u8; 32]), - RecyclerAlias { - exponent: i8, - ring_index: u32, - alias: [u8; 32], - }, - Member { - exponent: i16, - member: [u8; 32], - }, - Root { - exponent: i16, - ring_index: u32, - }, - RingKeysStatus { - exponent: i16, - ring_index: u32, - }, + Coin([u8; 32]), + Recycler([u8; 32]), + RecyclerAlias { exponent: i8, ring_index: u32, alias: [u8; 32] }, + Member { exponent: i16, member: [u8; 32] }, + Root { exponent: i16, ring_index: u32 }, + RingKeysStatus { exponent: i16, ring_index: u32 }, } impl CoinageStorageKey { - fn recycler_alias( - exponent: i16, - ring_index: u32, - alias: [u8; 32], - ) -> Result { - let exponent = - i8::try_from(exponent).map_err(|_| CoinageQueryError::InvalidExponent(exponent))?; - Ok(Self::RecyclerAlias { - exponent, - ring_index, - alias, - }) - } + fn recycler_alias( + exponent: i16, + ring_index: u32, + alias: [u8; 32], + ) -> Result { + let exponent = + i8::try_from(exponent).map_err(|_| CoinageQueryError::InvalidExponent(exponent))?; + Ok(Self::RecyclerAlias { exponent, ring_index, alias }) + } } /// The storage/finalized-head effect. Production uses a Host RPC /// adapter; tests provide a deterministic batch source. #[async_trait] pub trait CoinageStorageQuery: Send + Sync { - /// One head-pinned query, resolving semantic keys against that head's - /// runtime metadata and configured asset instance, preserving request order. - /// - /// Values are canonical engine SCALE rows, not raw runtime storage bytes: - /// `Coin` is `(i8, u16)`, `Recycler` is `i8`, `RecyclerAlias` is `AliasState`, - /// `Member` is `RingPosition`, `Root` is `RingRoot`, and `RingKeysStatus` is - /// `members::RingStatus`. The Host must validate each complete runtime value - /// against metadata and the selected asset before removing runtime-specific - /// instance fields and returning the canonical row. - async fn query( - &self, - keys: &[CoinageStorageKey], - at: Option<[u8; 32]>, - ) -> Result>>, String>; - - /// The canonical finalized head used to pin a coherent multi-stage - /// query. Test/deterministic sources may supply it through their - /// finalized stream; the RPC adapter uses the direct one-shot method. - async fn finalized_head(&self) -> Result<[u8; 32], String> { - let mut heads = self.finalized_heads(); - heads - .next() - .await - .ok_or_else(|| "finalized-head subscription terminated".to_string())? - } - - /// A fresh finalized-head stream. Consumers race this against their - /// storage condition and block timeout. - fn finalized_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>>; - - fn observation_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>> { - self.finalized_heads() - } + /// One head-pinned query, resolving semantic keys against that head's + /// runtime metadata and configured asset instance, preserving request order. + /// + /// Values are canonical engine SCALE rows, not raw runtime storage bytes: + /// `Coin` is `(i8, u16)`, `Recycler` is `i8`, `RecyclerAlias` is `AliasState`, + /// `Member` is `RingPosition`, `Root` is `RingRoot`, and `RingKeysStatus` is + /// `members::RingStatus`. The Host must validate each complete runtime value + /// against metadata and the selected asset before removing runtime-specific + /// instance fields and returning the canonical row. + async fn query( + &self, + keys: &[CoinageStorageKey], + at: Option<[u8; 32]>, + ) -> Result>>, String>; + + /// The canonical finalized head used to pin a coherent multi-stage + /// query. Test/deterministic sources may supply it through their + /// finalized stream; the RPC adapter uses the direct one-shot method. + async fn finalized_head(&self) -> Result<[u8; 32], String> { + let mut heads = self.finalized_heads(); + heads + .next() + .await + .ok_or_else(|| "finalized-head subscription terminated".to_string())? + } + + /// A fresh finalized-head stream. Consumers race this against their + /// storage condition and block timeout. + fn finalized_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>>; + + fn observation_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>> { + self.finalized_heads() + } } /// Typed failures from the query layer. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CoinageQueryError { - Storage(String), - Decode { - storage: &'static str, - message: String, - }, - ResponseLength { - storage: &'static str, - expected: usize, - actual: usize, - }, - SubscriptionTerminated, - Timeout { - finalized_heads: u32, - }, - InvalidExponent(i16), + Storage(String), + Decode { storage: &'static str, message: String }, + ResponseLength { storage: &'static str, expected: usize, actual: usize }, + SubscriptionTerminated, + Timeout { finalized_heads: u32 }, + InvalidExponent(i16), } impl fmt::Display for CoinageQueryError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Storage(message) => formatter.write_str(message), - Self::Decode { storage, message } => { - write!(formatter, "{storage} SCALE decode failed: {message}") - } - Self::ResponseLength { - storage, - expected, - actual, - } => write!( - formatter, - "{storage} returned {actual} values for {expected} keys" - ), - Self::SubscriptionTerminated => { - formatter.write_str("finalized-head subscription terminated") - } - Self::Timeout { finalized_heads } => { - write!( - formatter, - "coin query timed out after {finalized_heads} finalized heads" - ) - } - Self::InvalidExponent(exponent) => { - write!( - formatter, - "coinage exponent {exponent} does not fit the runtime i8" - ) - } - } - } + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Storage(message) => formatter.write_str(message), + Self::Decode { storage, message } => { + write!(formatter, "{storage} SCALE decode failed: {message}") + }, + Self::ResponseLength { storage, expected, actual } => { + write!(formatter, "{storage} returned {actual} values for {expected} keys") + }, + Self::SubscriptionTerminated => { + formatter.write_str("finalized-head subscription terminated") + }, + Self::Timeout { finalized_heads } => { + write!(formatter, "coin query timed out after {finalized_heads} finalized heads") + }, + Self::InvalidExponent(exponent) => { + write!(formatter, "coinage exponent {exponent} does not fit the runtime i8") + }, + } + } } impl std::error::Error for CoinageQueryError {} @@ -165,294 +126,268 @@ impl std::error::Error for CoinageQueryError {} /// (`indiv_pallet_coinage::pallet::AliasState`). #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub enum AliasState { - /// Load/unload is locked until the carried seconds timestamp - /// (`LockInfo { reason: LockReason::FailedDispatch(u8), until: u64 }`). - #[codec(index = 0)] - Locked(LockInfo), - #[codec(index = 1)] - Unloaded, + /// Load/unload is locked until the carried seconds timestamp + /// (`LockInfo { reason: LockReason::FailedDispatch(u8), until: u64 }`). + #[codec(index = 0)] + Locked(LockInfo), + #[codec(index = 1)] + Unloaded, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub struct LockInfo { - pub reason: LockReason, - pub until: u64, + pub reason: LockReason, + pub until: u64, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub enum LockReason { - #[codec(index = 0)] - FailedDispatch(u8), + #[codec(index = 0)] + FailedDispatch(u8), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] struct RawOnChainCoin { - value: i8, - age: u16, + value: i8, + age: u16, } fn decode_coin(bytes: &[u8]) -> Result { - let raw = - RawOnChainCoin::decode_all(&mut &bytes[..]).map_err(|error| CoinageQueryError::Decode { - storage: "Coinage.CoinsByOwner", - message: error.to_string(), - })?; - let age = i16::try_from(raw.age).map_err(|_| CoinageQueryError::Decode { - storage: "Coinage.CoinsByOwner", - message: format!("age {} does not fit i16", raw.age), - })?; - Ok(OnChainCoin { - exponent: i16::from(raw.value), - age, - }) + let raw = RawOnChainCoin::decode_all(&mut &bytes[..]).map_err(|error| { + CoinageQueryError::Decode { storage: "Coinage.CoinsByOwner", message: error.to_string() } + })?; + let age = i16::try_from(raw.age).map_err(|_| CoinageQueryError::Decode { + storage: "Coinage.CoinsByOwner", + message: format!("age {} does not fit i16", raw.age), + })?; + Ok(OnChainCoin { exponent: i16::from(raw.value), age }) } fn decode_optional( - bytes: Option>, - storage: &'static str, + bytes: Option>, + storage: &'static str, ) -> Result, CoinageQueryError> { - bytes - .map(|bytes| { - T::decode_all(&mut &bytes[..]).map_err(|error| CoinageQueryError::Decode { - storage, - message: error.to_string(), - }) - }) - .transpose() + bytes + .map(|bytes| { + T::decode_all(&mut &bytes[..]) + .map_err(|error| CoinageQueryError::Decode { storage, message: error.to_string() }) + }) + .transpose() } fn ensure_response_len( - storage: &'static str, - expected: usize, - actual: usize, + storage: &'static str, + expected: usize, + actual: usize, ) -> Result<(), CoinageQueryError> { - if expected == actual { - Ok(()) - } else { - Err(CoinageQueryError::ResponseLength { - storage, - expected, - actual, - }) - } + if expected == actual { + Ok(()) + } else { + Err(CoinageQueryError::ResponseLength { storage, expected, actual }) + } } /// Batch coin fetch + finalized-head-raced presence/claim waits. pub struct CoinOnChainQueryService { - storage: Arc, + storage: Arc, } impl CoinOnChainQueryService { - pub fn new(storage: Arc) -> Self { - Self { storage } - } - - /// Fetches N `CoinsByOwner` entries in one RPC, preserving input - /// order. `at` enables the historical anchor probe used after a fast - /// claim. - pub async fn fetch_coins( - &self, - public_keys: &[[u8; 32]], - at: Option<[u8; 32]>, - ) -> Result>, CoinageQueryError> { - if public_keys.is_empty() { - return Ok(Vec::new()); - } - let keys = public_keys - .iter() - .copied() - .map(CoinageStorageKey::Coin) - .collect::>(); - let values = self - .storage - .query(&keys, at) - .await - .map_err(CoinageQueryError::Storage)?; - ensure_response_len("Coinage.CoinsByOwner", keys.len(), values.len())?; - values - .into_iter() - .map(|value| value.map(|bytes| decode_coin(&bytes)).transpose()) - .collect() - } - - /// Resolves once every key has been observed present. Presence is - /// accumulated across finalized heads because a storage subscription - /// may emit only the keys changed in a block, and an early coin may - /// already be claimed by the time a later one appears. - pub async fn await_all_coins_on_chain( - &self, - public_keys: &[[u8; 32]], - block_timeout: u32, - ) -> Result<(), CoinageQueryError> { - self.await_all_coins_sent_or_claimed(public_keys, block_timeout) - .await - .map(|_| ()) - } - - /// Resolves once every key is absent (claimed/spent). - pub async fn await_all_coins_off_chain( - &self, - public_keys: &[[u8; 32]], - block_timeout: u32, - ) -> Result<(), CoinageQueryError> { - self.await_condition(public_keys, block_timeout, |coins| { - coins.iter().all(Option::is_none).then_some(()) - }) - .await - } - - /// Accumulates `seen` across partial lifecycle observations: once all - /// keys have appeared at least once, returns whether any remains - /// present. This distinguishes `OnChain` from an ultra-fast - /// `AlreadyClaimed` completion and races the finalized-head count. - pub async fn await_all_coins_sent_or_claimed( - &self, - public_keys: &[[u8; 32]], - block_timeout: u32, - ) -> Result { - if public_keys.is_empty() { - return Ok(true); - } - let mut heads = self.storage.finalized_heads(); - let mut seen = vec![false; public_keys.len()]; - let mut present = vec![false; public_keys.len()]; - let limit = block_timeout.max(1); - let mut count = 0u32; - while let Some(head) = heads.next().await { - let head = head.map_err(CoinageQueryError::Storage)?; - count = count.saturating_add(1); - let coins = self.fetch_coins(public_keys, Some(head)).await?; - for (index, coin) in coins.into_iter().enumerate() { - present[index] = coin.is_some(); - if present[index] { - seen[index] = true; - } - } - if seen.iter().all(|value| *value) { - return Ok(present.iter().any(|value| *value)); - } - if count >= limit { - return Err(CoinageQueryError::Timeout { - finalized_heads: limit, - }); - } - } - Err(CoinageQueryError::SubscriptionTerminated) - } - - pub async fn await_send_or_claimed( - &self, - public_keys: &[[u8; 32]], - anchor_hash: Option<[u8; 32]>, - block_timeout: u32, - ) -> Result { - if public_keys.is_empty() { - return Ok(SendConfirmation::OnChain); - } - let mut confirmed = vec![false; public_keys.len()]; - let current = self.fetch_coins(public_keys, None).await?; - let mut any_present = false; - for (index, coin) in current.into_iter().enumerate() { - if coin.is_some() { - confirmed[index] = true; - any_present = true; - } - } - - if confirmed.iter().any(|value| !*value) - && let Some(anchor_hash) = anchor_hash - { - let absent_offsets = confirmed - .iter() - .enumerate() - .filter_map(|(index, confirmed)| (!confirmed).then_some(index)) - .collect::>(); - let absent_keys = absent_offsets - .iter() - .map(|index| public_keys[*index]) - .collect::>(); - let historical = self.fetch_coins(&absent_keys, Some(anchor_hash)).await?; - for (offset, coin) in historical.into_iter().enumerate() { - if coin.is_some() { - confirmed[absent_offsets[offset]] = true; - } - } - } - - if confirmed.iter().all(|value| *value) { - return Ok(if any_present { - SendConfirmation::OnChain - } else { - SendConfirmation::AlreadyClaimed - }); - } - - let remaining = confirmed - .iter() - .enumerate() - .filter_map(|(index, confirmed)| (!confirmed).then_some(public_keys[index])) - .collect::>(); - let any_remaining_present = self - .await_all_coins_sent_or_claimed(&remaining, block_timeout) - .await?; - Ok(if any_present || any_remaining_present { - SendConfirmation::OnChain - } else { - SendConfirmation::AlreadyClaimed - }) - } - - async fn await_condition( - &self, - public_keys: &[[u8; 32]], - block_timeout: u32, - condition: impl Fn(&[Option]) -> Option, - ) -> Result { - if public_keys.is_empty() { - return condition(&[]).ok_or(CoinageQueryError::SubscriptionTerminated); - } - let mut heads = self.storage.finalized_heads(); - let limit = block_timeout.max(1); - let mut count = 0u32; - while let Some(head) = heads.next().await { - let head = head.map_err(CoinageQueryError::Storage)?; - count = count.saturating_add(1); - let coins = self.fetch_coins(public_keys, Some(head)).await?; - if let Some(output) = condition(&coins) { - return Ok(output); - } - if count >= limit { - return Err(CoinageQueryError::Timeout { - finalized_heads: limit, - }); - } - } - Err(CoinageQueryError::SubscriptionTerminated) - } + pub fn new(storage: Arc) -> Self { + Self { storage } + } + + /// Fetches N `CoinsByOwner` entries in one RPC, preserving input + /// order. `at` enables the historical anchor probe used after a fast + /// claim. + pub async fn fetch_coins( + &self, + public_keys: &[[u8; 32]], + at: Option<[u8; 32]>, + ) -> Result>, CoinageQueryError> { + if public_keys.is_empty() { + return Ok(Vec::new()); + } + let keys = public_keys.iter().copied().map(CoinageStorageKey::Coin).collect::>(); + let values = self.storage.query(&keys, at).await.map_err(CoinageQueryError::Storage)?; + ensure_response_len("Coinage.CoinsByOwner", keys.len(), values.len())?; + values + .into_iter() + .map(|value| value.map(|bytes| decode_coin(&bytes)).transpose()) + .collect() + } + + /// Resolves once every key has been observed present. Presence is + /// accumulated across finalized heads because a storage subscription + /// may emit only the keys changed in a block, and an early coin may + /// already be claimed by the time a later one appears. + pub async fn await_all_coins_on_chain( + &self, + public_keys: &[[u8; 32]], + block_timeout: u32, + ) -> Result<(), CoinageQueryError> { + self.await_all_coins_sent_or_claimed(public_keys, block_timeout) + .await + .map(|_| ()) + } + + /// Resolves once every key is absent (claimed/spent). + pub async fn await_all_coins_off_chain( + &self, + public_keys: &[[u8; 32]], + block_timeout: u32, + ) -> Result<(), CoinageQueryError> { + self.await_condition(public_keys, block_timeout, |coins| { + coins.iter().all(Option::is_none).then_some(()) + }) + .await + } + + /// Accumulates `seen` across partial lifecycle observations: once all + /// keys have appeared at least once, returns whether any remains + /// present. This distinguishes `OnChain` from an ultra-fast + /// `AlreadyClaimed` completion and races the finalized-head count. + pub async fn await_all_coins_sent_or_claimed( + &self, + public_keys: &[[u8; 32]], + block_timeout: u32, + ) -> Result { + if public_keys.is_empty() { + return Ok(true); + } + let mut heads = self.storage.finalized_heads(); + let mut seen = vec![false; public_keys.len()]; + let mut present = vec![false; public_keys.len()]; + let limit = block_timeout.max(1); + let mut count = 0u32; + while let Some(head) = heads.next().await { + let head = head.map_err(CoinageQueryError::Storage)?; + count = count.saturating_add(1); + let coins = self.fetch_coins(public_keys, Some(head)).await?; + for (index, coin) in coins.into_iter().enumerate() { + present[index] = coin.is_some(); + if present[index] { + seen[index] = true; + } + } + if seen.iter().all(|value| *value) { + return Ok(present.iter().any(|value| *value)); + } + if count >= limit { + return Err(CoinageQueryError::Timeout { finalized_heads: limit }); + } + } + Err(CoinageQueryError::SubscriptionTerminated) + } + + pub async fn await_send_or_claimed( + &self, + public_keys: &[[u8; 32]], + anchor_hash: Option<[u8; 32]>, + block_timeout: u32, + ) -> Result { + if public_keys.is_empty() { + return Ok(SendConfirmation::OnChain); + } + let mut confirmed = vec![false; public_keys.len()]; + let current = self.fetch_coins(public_keys, None).await?; + let mut any_present = false; + for (index, coin) in current.into_iter().enumerate() { + if coin.is_some() { + confirmed[index] = true; + any_present = true; + } + } + + if confirmed.iter().any(|value| !*value) && + let Some(anchor_hash) = anchor_hash + { + let absent_offsets = confirmed + .iter() + .enumerate() + .filter_map(|(index, confirmed)| (!confirmed).then_some(index)) + .collect::>(); + let absent_keys = + absent_offsets.iter().map(|index| public_keys[*index]).collect::>(); + let historical = self.fetch_coins(&absent_keys, Some(anchor_hash)).await?; + for (offset, coin) in historical.into_iter().enumerate() { + if coin.is_some() { + confirmed[absent_offsets[offset]] = true; + } + } + } + + if confirmed.iter().all(|value| *value) { + return Ok(if any_present { + SendConfirmation::OnChain + } else { + SendConfirmation::AlreadyClaimed + }); + } + + let remaining = confirmed + .iter() + .enumerate() + .filter_map(|(index, confirmed)| (!confirmed).then_some(public_keys[index])) + .collect::>(); + let any_remaining_present = + self.await_all_coins_sent_or_claimed(&remaining, block_timeout).await?; + Ok(if any_present || any_remaining_present { + SendConfirmation::OnChain + } else { + SendConfirmation::AlreadyClaimed + }) + } + + async fn await_condition( + &self, + public_keys: &[[u8; 32]], + block_timeout: u32, + condition: impl Fn(&[Option]) -> Option, + ) -> Result { + if public_keys.is_empty() { + return condition(&[]).ok_or(CoinageQueryError::SubscriptionTerminated); + } + let mut heads = self.storage.finalized_heads(); + let limit = block_timeout.max(1); + let mut count = 0u32; + while let Some(head) = heads.next().await { + let head = head.map_err(CoinageQueryError::Storage)?; + count = count.saturating_add(1); + let coins = self.fetch_coins(public_keys, Some(head)).await?; + if let Some(output) = condition(&coins) { + return Ok(output); + } + if count >= limit { + return Err(CoinageQueryError::Timeout { finalized_heads: limit }); + } + } + Err(CoinageQueryError::SubscriptionTerminated) + } } /// Complete on-chain voucher observation after the four query stages. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VoucherOnChainInfo { - pub exponent: i16, - pub ring_position: RingPosition, - pub is_unloaded: bool, + pub exponent: i16, + pub ring_position: RingPosition, + pub is_unloaded: bool, } type KeyProvider = dyn Fn(u32) -> Result<[u8; 32], String> + Send + Sync; #[derive(Debug, Clone)] enum VoucherLocationRequest { - Position { derivation_index: u32 }, - Status { derivation_index: u32 }, + Position { derivation_index: u32 }, + Status { derivation_index: u32 }, } pub struct QueryVoucherLocationSubscriber { - spawner: crate::Spawner, - storage: Arc, - vouchers: Arc, - public_key_provider: Arc, - observation_refresh_interval: Duration, + spawner: crate::Spawner, + storage: Arc, + vouchers: Arc, + public_key_provider: Arc, + observation_refresh_interval: Duration, } /// A head notification is the fast path, while this current-best refresh is @@ -462,404 +397,366 @@ pub struct QueryVoucherLocationSubscriber { const VOUCHER_LOCATION_OBSERVATION_REFRESH: Duration = Duration::from_secs(8); impl QueryVoucherLocationSubscriber { - pub fn new( - storage: Arc, - vouchers: Arc, - public_key_provider: Arc, - spawner: crate::Spawner, - ) -> Self { - Self { - storage, - vouchers, - public_key_provider, - observation_refresh_interval: VOUCHER_LOCATION_OBSERVATION_REFRESH, - spawner, - } - } - - #[cfg(test)] - fn with_observation_refresh_interval(mut self, interval: Duration) -> Self { - self.observation_refresh_interval = interval; - self - } - - async fn requests( - &self, - pending: Vec, - included: Vec<(u32, u32)>, - degraded: Vec<(u32, u32)>, - ) -> Result, String> { - let vouchers = self - .vouchers - .list() - .await? - .into_iter() - .map(|voucher| (voucher.derivation_index, voucher)) - .collect::>(); - let voucher = |index: u32| { - vouchers - .get(&index) - .ok_or_else(|| format!("voucher {index} disappeared before location subscribe")) - }; - - let mut requests = Vec::with_capacity(pending.len() + included.len() + degraded.len()); - for derivation_index in pending { - let voucher = voucher(derivation_index)?; - let member = (self.public_key_provider)(derivation_index)?; - requests.push(( - VoucherLocationRequest::Position { derivation_index }, - CoinageStorageKey::Member { - exponent: voucher.exponent, - member, - }, - )); - } - for (derivation_index, ring_index) in included.into_iter().chain(degraded) { - let voucher = voucher(derivation_index)?; - requests.push(( - VoucherLocationRequest::Status { derivation_index }, - CoinageStorageKey::RingKeysStatus { - exponent: voucher.exponent, - ring_index, - }, - )); - } - Ok(requests) - } + pub fn new( + storage: Arc, + vouchers: Arc, + public_key_provider: Arc, + spawner: crate::Spawner, + ) -> Self { + Self { + storage, + vouchers, + public_key_provider, + observation_refresh_interval: VOUCHER_LOCATION_OBSERVATION_REFRESH, + spawner, + } + } + + #[cfg(test)] + fn with_observation_refresh_interval(mut self, interval: Duration) -> Self { + self.observation_refresh_interval = interval; + self + } + + async fn requests( + &self, + pending: Vec, + included: Vec<(u32, u32)>, + degraded: Vec<(u32, u32)>, + ) -> Result, String> { + let vouchers = self + .vouchers + .list() + .await? + .into_iter() + .map(|voucher| (voucher.derivation_index, voucher)) + .collect::>(); + let voucher = |index: u32| { + vouchers + .get(&index) + .ok_or_else(|| format!("voucher {index} disappeared before location subscribe")) + }; + + let mut requests = Vec::with_capacity(pending.len() + included.len() + degraded.len()); + for derivation_index in pending { + let voucher = voucher(derivation_index)?; + let member = (self.public_key_provider)(derivation_index)?; + requests.push(( + VoucherLocationRequest::Position { derivation_index }, + CoinageStorageKey::Member { exponent: voucher.exponent, member }, + )); + } + for (derivation_index, ring_index) in included.into_iter().chain(degraded) { + let voucher = voucher(derivation_index)?; + requests.push(( + VoucherLocationRequest::Status { derivation_index }, + CoinageStorageKey::RingKeysStatus { exponent: voucher.exponent, ring_index }, + )); + } + Ok(requests) + } } async fn fetch_voucher_location_update( - storage: &dyn CoinageStorageQuery, - requests: &[(VoucherLocationRequest, CoinageStorageKey)], - at: Option<[u8; 32]>, + storage: &dyn CoinageStorageQuery, + requests: &[(VoucherLocationRequest, CoinageStorageKey)], + at: Option<[u8; 32]>, ) -> Result { - let keys = requests.iter().map(|(_, key)| *key).collect::>(); - let values = storage - .query(&keys, at) - .await - .map_err(CoinageQueryError::Storage)?; - ensure_response_len( - "Members voucher-location batch", - requests.len(), - values.len(), - )?; - - let mut update = VoucherLocationUpdate::default(); - for ((request, _), value) in requests.iter().zip(values) { - match request { - VoucherLocationRequest::Position { derivation_index } => { - let position = - decode_optional::(value, "Members.Members")?.map(|position| { - match position { - RingPosition::Included { - ring_index, - ring_position, - .. - } => VoucherRingPosition::Included { - ring_index, - included_at: ring_position, - }, - RingPosition::Onboarding { .. } | RingPosition::Suspended => { - VoucherRingPosition::Onboarding - } - } - }); - update.ring_positions.push((*derivation_index, position)); - } - VoucherLocationRequest::Status { derivation_index } => { - if let Some(status) = - decode_optional::(value, "Members.RingKeysStatus")? - { - update.ring_statuses.push(( - *derivation_index, - VoucherRingStatus { - included_members: status.included, - }, - )); - } - } - } - } - Ok(update) + let keys = requests.iter().map(|(_, key)| *key).collect::>(); + let values = storage.query(&keys, at).await.map_err(CoinageQueryError::Storage)?; + ensure_response_len("Members voucher-location batch", requests.len(), values.len())?; + + let mut update = VoucherLocationUpdate::default(); + for ((request, _), value) in requests.iter().zip(values) { + match request { + VoucherLocationRequest::Position { derivation_index } => { + let position = + decode_optional::(value, "Members.Members")?.map(|position| { + match position { + RingPosition::Included { ring_index, ring_position, .. } => { + VoucherRingPosition::Included { + ring_index, + included_at: ring_position, + } + }, + RingPosition::Onboarding { .. } | RingPosition::Suspended => { + VoucherRingPosition::Onboarding + }, + } + }); + update.ring_positions.push((*derivation_index, position)); + }, + VoucherLocationRequest::Status { derivation_index } => { + if let Some(status) = + decode_optional::(value, "Members.RingKeysStatus")? + { + update.ring_statuses.push(( + *derivation_index, + VoucherRingStatus { included_members: status.included }, + )); + } + }, + } + } + Ok(update) } #[async_trait] impl VoucherLocationSubscriber for QueryVoucherLocationSubscriber { - async fn subscribe( - &self, - pending: Vec, - included: Vec<(u32, u32)>, - degraded: Vec<(u32, u32)>, - ) -> Result, String> { - let requests = self.requests(pending, included, degraded).await?; - let storage = Arc::clone(&self.storage); - let observation_refresh_interval = self.observation_refresh_interval; - let (sender, receiver) = mpsc::channel(4); - (self.spawner)(Box::pin(async move { - // Start the live observer before the initial snapshot so a best - // change racing the query is buffered rather than lost. `None` - // makes `state_queryStorageAt` read the current best state, which - // is the same visibility used by the iOS storage subscription. - let mut heads = storage.observation_heads(); - match fetch_voucher_location_update(storage.as_ref(), &requests, None).await { - Ok(update) => { - if sender.send(update).await.is_err() { - return; - } - } - Err(error) => warn!(%error, "initial voucher location query failed"), - } - - let mut heads_open = true; - let refresh = crate::timer::sleep(observation_refresh_interval).fuse(); - futures::pin_mut!(refresh); - loop { - let open = heads_open; - let next_head = async { - if open { - heads.next().await - } else { - futures::future::pending().await - } - } - .fuse(); - let closed = sender.closed().fuse(); - futures::pin_mut!(next_head, closed); - let at = futures::select! { - head = next_head => match head { - Some(Ok(head)) => Some(head), - Some(Err(error)) => { - warn!(%error, "voucher location head update failed"); - continue; - } - None => { - heads_open = false; - continue; - } - }, - _ = refresh => { - refresh.set(crate::timer::sleep(observation_refresh_interval).fuse()); - None - }, - _ = closed => return, - }; - - if sender.is_closed() { - return; - } - match fetch_voucher_location_update(storage.as_ref(), &requests, at).await { - Ok(update) => { - if sender.send(update).await.is_err() { - return; - } - } - Err(error) => warn!(%error, "voucher location query failed"), - } - } - })); - Ok(receiver) - } + async fn subscribe( + &self, + pending: Vec, + included: Vec<(u32, u32)>, + degraded: Vec<(u32, u32)>, + ) -> Result, String> { + let requests = self.requests(pending, included, degraded).await?; + let storage = Arc::clone(&self.storage); + let observation_refresh_interval = self.observation_refresh_interval; + let (sender, receiver) = mpsc::channel(4); + (self.spawner)(Box::pin(async move { + // Start the live observer before the initial snapshot so a best + // change racing the query is buffered rather than lost. `None` + // makes `state_queryStorageAt` read the current best state, which + // is the same visibility used by the iOS storage subscription. + let mut heads = storage.observation_heads(); + match fetch_voucher_location_update(storage.as_ref(), &requests, None).await { + Ok(update) => { + if sender.send(update).await.is_err() { + return; + } + }, + Err(error) => warn!(%error, "initial voucher location query failed"), + } + + let mut heads_open = true; + let refresh = crate::timer::sleep(observation_refresh_interval).fuse(); + futures::pin_mut!(refresh); + loop { + let open = heads_open; + let next_head = async { + if open { heads.next().await } else { futures::future::pending().await } + } + .fuse(); + let closed = sender.closed().fuse(); + futures::pin_mut!(next_head, closed); + let at = futures::select! { + head = next_head => match head { + Some(Ok(head)) => Some(head), + Some(Err(error)) => { + warn!(%error, "voucher location head update failed"); + continue; + } + None => { + heads_open = false; + continue; + } + }, + _ = refresh => { + refresh.set(crate::timer::sleep(observation_refresh_interval).fuse()); + None + }, + _ = closed => return, + }; + + if sender.is_closed() { + return; + } + match fetch_voucher_location_update(storage.as_ref(), &requests, at).await { + Ok(update) => { + if sender.send(update).await.is_err() { + return; + } + }, + Err(error) => warn!(%error, "voucher location query failed"), + } + } + })); + Ok(receiver) + } } /// Four-stage voucher query (`RecyclersCoinToRecycler` → `Members` → /// `RecyclerAliasStates`), preserving the original derivation-index order. pub struct VoucherOnChainQueryService { - storage: Arc, - public_key_provider: Arc, - alias_provider: Arc, + storage: Arc, + public_key_provider: Arc, + alias_provider: Arc, } impl VoucherOnChainQueryService { - pub fn new( - storage: Arc, - public_key_provider: Arc, - alias_provider: Arc, - ) -> Self { - Self { - storage, - public_key_provider, - alias_provider, - } - } - - pub async fn fetch_vouchers( - &self, - derivation_indices: &[u32], - at: Option<[u8; 32]>, - ) -> Result>, CoinageQueryError> { - self.fetch_voucher_observations(derivation_indices, at, false) - .await - } - - /// Recovery must observe every assigned derivation index, not only keys - /// already included in a recycler ring. Otherwise onboarding/suspended - /// keys could be allocated again after restoring the wallet. - /// - /// Every stage is pinned to the caller's finalized recovery snapshot. - /// An assignment without a Members row is ambiguous, not an empty index. - pub async fn fetch_recovery_vouchers( - &self, - derivation_indices: &[u32], - at: [u8; 32], - ) -> Result>, CoinageQueryError> { - self.fetch_voucher_observations(derivation_indices, Some(at), true) - .await - } - - async fn fetch_voucher_observations( - &self, - derivation_indices: &[u32], - at: Option<[u8; 32]>, - recovery: bool, - ) -> Result>, CoinageQueryError> { - if derivation_indices.is_empty() { - return Ok(Vec::new()); - } - let mut output = vec![None; derivation_indices.len()]; - - struct Candidate { - output_index: usize, - derivation_index: u32, - exponent: i16, - position: RingPosition, - ring_index: u32, - } - - // Step 1: key derivation. - let indexed_keys = derivation_indices - .iter() - .copied() - .enumerate() - .map(|(output_index, derivation_index)| { - (self.public_key_provider)(derivation_index) - .map(|public_key| (output_index, derivation_index, public_key)) - .map_err(CoinageQueryError::Storage) - }) - .collect::, _>>()?; - - // Step 2: recycler denomination. - let exponent_keys = indexed_keys - .iter() - .map(|(_, _, public_key)| CoinageStorageKey::Recycler(*public_key)) - .collect::>(); - let exponent_values = self - .storage - .query(&exponent_keys, at) - .await - .map_err(CoinageQueryError::Storage)?; - ensure_response_len( - "Coinage.RecyclersCoinToRecycler", - exponent_keys.len(), - exponent_values.len(), - )?; - let mut with_exponents = Vec::new(); - for ((output_index, derivation_index, public_key), value) in - indexed_keys.into_iter().zip(exponent_values) - { - if let Some(exponent) = decode_optional::(value, "Coinage.RecyclersCoinToRecycler")? - { - with_exponents.push(( - output_index, - derivation_index, - public_key, - i16::from(exponent), - )); - } - } - if with_exponents.is_empty() { - return Ok(output); - } - - // Step 3: Members position under the denomination's recycler - // collection. Normal unload queries exclude onboarding/suspended - // rows; recovery retains them as used, non-unloadable indices. - let position_keys = with_exponents - .iter() - .map(|(_, _, public_key, exponent)| CoinageStorageKey::Member { - exponent: *exponent, - member: *public_key, - }) - .collect::>(); - let position_values = self - .storage - .query(&position_keys, at) - .await - .map_err(CoinageQueryError::Storage)?; - ensure_response_len( - "Members.Members", - position_keys.len(), - position_values.len(), - )?; - let mut with_positions = Vec::::new(); - for ((output_index, derivation_index, _public_key, exponent), value) in - with_exponents.into_iter().zip(position_values) - { - let Some(position) = decode_optional::(value, "Members.Members")? else { - if recovery { - return Err(CoinageQueryError::Storage( - "Coinage recovery found a recycler assignment without a Members row".into(), - )); - } - continue; - }; - let RingPosition::Included { ring_index, .. } = position else { - if recovery { - output[output_index] = Some(VoucherOnChainInfo { - exponent, - ring_position: position, - is_unloaded: false, - }); - } - continue; - }; - with_positions.push(Candidate { - output_index, - derivation_index, - exponent, - position, - ring_index, - }); - } - if with_positions.is_empty() { - return Ok(output); - } - - // Step 4: alias state. A missing row is a loaded, unlocked alias; - // only an explicit `AliasState::Unloaded` counts as unloaded (a - // `Locked` row is still loaded — the lock only gates dispatch). - let state_keys = with_positions - .iter() - .map(|candidate| { - let alias = (self.alias_provider)(candidate.derivation_index) - .map_err(CoinageQueryError::Storage)?; - CoinageStorageKey::recycler_alias(candidate.exponent, candidate.ring_index, alias) - }) - .collect::, _>>()?; - let state_values = self - .storage - .query(&state_keys, at) - .await - .map_err(CoinageQueryError::Storage)?; - ensure_response_len( - "Coinage.RecyclerAliasStates", - state_keys.len(), - state_values.len(), - )?; - - for (candidate, state) in with_positions.into_iter().zip(state_values) { - let state = decode_optional::(state, "Coinage.RecyclerAliasStates")?; - output[candidate.output_index] = Some(VoucherOnChainInfo { - exponent: candidate.exponent, - ring_position: candidate.position, - is_unloaded: state == Some(AliasState::Unloaded), - }); - } - Ok(output) - } + pub fn new( + storage: Arc, + public_key_provider: Arc, + alias_provider: Arc, + ) -> Self { + Self { storage, public_key_provider, alias_provider } + } + + pub async fn fetch_vouchers( + &self, + derivation_indices: &[u32], + at: Option<[u8; 32]>, + ) -> Result>, CoinageQueryError> { + self.fetch_voucher_observations(derivation_indices, at, false).await + } + + /// Recovery must observe every assigned derivation index, not only keys + /// already included in a recycler ring. Otherwise onboarding/suspended + /// keys could be allocated again after restoring the wallet. + /// + /// Every stage is pinned to the caller's finalized recovery snapshot. + /// An assignment without a Members row is ambiguous, not an empty index. + pub async fn fetch_recovery_vouchers( + &self, + derivation_indices: &[u32], + at: [u8; 32], + ) -> Result>, CoinageQueryError> { + self.fetch_voucher_observations(derivation_indices, Some(at), true).await + } + + async fn fetch_voucher_observations( + &self, + derivation_indices: &[u32], + at: Option<[u8; 32]>, + recovery: bool, + ) -> Result>, CoinageQueryError> { + if derivation_indices.is_empty() { + return Ok(Vec::new()); + } + let mut output = vec![None; derivation_indices.len()]; + + struct Candidate { + output_index: usize, + derivation_index: u32, + exponent: i16, + position: RingPosition, + ring_index: u32, + } + + // Step 1: key derivation. + let indexed_keys = derivation_indices + .iter() + .copied() + .enumerate() + .map(|(output_index, derivation_index)| { + (self.public_key_provider)(derivation_index) + .map(|public_key| (output_index, derivation_index, public_key)) + .map_err(CoinageQueryError::Storage) + }) + .collect::, _>>()?; + + // Step 2: recycler denomination. + let exponent_keys = indexed_keys + .iter() + .map(|(_, _, public_key)| CoinageStorageKey::Recycler(*public_key)) + .collect::>(); + let exponent_values = self + .storage + .query(&exponent_keys, at) + .await + .map_err(CoinageQueryError::Storage)?; + ensure_response_len( + "Coinage.RecyclersCoinToRecycler", + exponent_keys.len(), + exponent_values.len(), + )?; + let mut with_exponents = Vec::new(); + for ((output_index, derivation_index, public_key), value) in + indexed_keys.into_iter().zip(exponent_values) + { + if let Some(exponent) = decode_optional::(value, "Coinage.RecyclersCoinToRecycler")? + { + with_exponents.push(( + output_index, + derivation_index, + public_key, + i16::from(exponent), + )); + } + } + if with_exponents.is_empty() { + return Ok(output); + } + + // Step 3: Members position under the denomination's recycler + // collection. Normal unload queries exclude onboarding/suspended + // rows; recovery retains them as used, non-unloadable indices. + let position_keys = with_exponents + .iter() + .map(|(_, _, public_key, exponent)| CoinageStorageKey::Member { + exponent: *exponent, + member: *public_key, + }) + .collect::>(); + let position_values = self + .storage + .query(&position_keys, at) + .await + .map_err(CoinageQueryError::Storage)?; + ensure_response_len("Members.Members", position_keys.len(), position_values.len())?; + let mut with_positions = Vec::::new(); + for ((output_index, derivation_index, _public_key, exponent), value) in + with_exponents.into_iter().zip(position_values) + { + let Some(position) = decode_optional::(value, "Members.Members")? else { + if recovery { + return Err(CoinageQueryError::Storage( + "Coinage recovery found a recycler assignment without a Members row".into(), + )); + } + continue; + }; + let RingPosition::Included { ring_index, .. } = position else { + if recovery { + output[output_index] = Some(VoucherOnChainInfo { + exponent, + ring_position: position, + is_unloaded: false, + }); + } + continue; + }; + with_positions.push(Candidate { + output_index, + derivation_index, + exponent, + position, + ring_index, + }); + } + if with_positions.is_empty() { + return Ok(output); + } + + // Step 4: alias state. A missing row is a loaded, unlocked alias; + // only an explicit `AliasState::Unloaded` counts as unloaded (a + // `Locked` row is still loaded — the lock only gates dispatch). + let state_keys = with_positions + .iter() + .map(|candidate| { + let alias = (self.alias_provider)(candidate.derivation_index) + .map_err(CoinageQueryError::Storage)?; + CoinageStorageKey::recycler_alias(candidate.exponent, candidate.ring_index, alias) + }) + .collect::, _>>()?; + let state_values = + self.storage.query(&state_keys, at).await.map_err(CoinageQueryError::Storage)?; + ensure_response_len("Coinage.RecyclerAliasStates", state_keys.len(), state_values.len())?; + + for (candidate, state) in with_positions.into_iter().zip(state_values) { + let state = decode_optional::(state, "Coinage.RecyclerAliasStates")?; + output[candidate.output_index] = Some(VoucherOnChainInfo { + exponent: candidate.exponent, + ring_position: candidate.position, + is_unloaded: state == Some(AliasState::Unloaded), + }); + } + Ok(output) + } } pub struct RecyclerReadinessLoader { - storage: Arc, + storage: Arc, } /// One coherent recycler-readiness snapshot. Every revision was read from @@ -867,575 +764,408 @@ pub struct RecyclerReadinessLoader { /// preparation rather than mixing roots observed at different heads. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RecyclerRevisionSnapshot { - pub block_hash: [u8; 32], - pub revisions: HashMap, + pub block_hash: [u8; 32], + pub revisions: HashMap, } impl RecyclerReadinessLoader { - pub fn new(storage: Arc) -> Self { - Self { storage } - } - - /// Captures the canonical finalized head and pins the complete revision - /// batch to it. This is the production entry point for unload - /// preparation: a missing root stays missing and must fail the caller - /// rather than being replaced by a guessed revision. - pub async fn fetch_finalized_revisions( - &self, - recycler_keys: &[RecyclerKey], - ) -> Result { - let block_hash = self - .storage - .finalized_head() - .await - .map_err(CoinageQueryError::Storage)?; - let revisions = self - .fetch_revisions(recycler_keys, Some(block_hash)) - .await?; - Ok(RecyclerRevisionSnapshot { - block_hash, - revisions, - }) - } - - pub async fn fetch_revisions( - &self, - recycler_keys: &[RecyclerKey], - at: Option<[u8; 32]>, - ) -> Result, CoinageQueryError> { - if recycler_keys.is_empty() { - return Ok(HashMap::new()); - } - let keys = recycler_keys - .iter() - .map(|recycler| CoinageStorageKey::Root { - exponent: recycler.exponent, - ring_index: recycler.index, - }) - .collect::>(); - let values = self - .storage - .query(&keys, at) - .await - .map_err(CoinageQueryError::Storage)?; - ensure_response_len("Members.Root", keys.len(), values.len())?; - let mut revisions = HashMap::new(); - for (recycler, value) in recycler_keys.iter().copied().zip(values) { - if let Some(root) = decode_optional::(value, "Members.Root")? { - revisions.insert(recycler, root.revision); - } - } - Ok(revisions) - } + pub fn new(storage: Arc) -> Self { + Self { storage } + } + + /// Captures the canonical finalized head and pins the complete revision + /// batch to it. This is the production entry point for unload + /// preparation: a missing root stays missing and must fail the caller + /// rather than being replaced by a guessed revision. + pub async fn fetch_finalized_revisions( + &self, + recycler_keys: &[RecyclerKey], + ) -> Result { + let block_hash = self.storage.finalized_head().await.map_err(CoinageQueryError::Storage)?; + let revisions = self.fetch_revisions(recycler_keys, Some(block_hash)).await?; + Ok(RecyclerRevisionSnapshot { block_hash, revisions }) + } + + pub async fn fetch_revisions( + &self, + recycler_keys: &[RecyclerKey], + at: Option<[u8; 32]>, + ) -> Result, CoinageQueryError> { + if recycler_keys.is_empty() { + return Ok(HashMap::new()); + } + let keys = recycler_keys + .iter() + .map(|recycler| CoinageStorageKey::Root { + exponent: recycler.exponent, + ring_index: recycler.index, + }) + .collect::>(); + let values = self.storage.query(&keys, at).await.map_err(CoinageQueryError::Storage)?; + ensure_response_len("Members.Root", keys.len(), values.len())?; + let mut revisions = HashMap::new(); + for (recycler, value) in recycler_keys.iter().copied().zip(values) { + if let Some(root) = decode_optional::(value, "Members.Root")? { + revisions.insert(recycler, root.revision); + } + } + Ok(revisions) + } } #[cfg(test)] mod tests { - use parking_lot::Mutex; - use std::collections::VecDeque; - use std::time::Duration; - - use futures::stream; - - use super::*; - - type QueryRecord = (Vec, Option<[u8; 32]>); - type QueryResponse = Result>>, String>; - type HeadBatch = Vec>; - - #[derive(Default)] - struct ScriptedStorage { - queries: Mutex>, - responses: Mutex>, - heads: Mutex>, - } - - impl ScriptedStorage { - fn push_response(&self, response: Vec>>) { - self.responses.lock().push_back(Ok(response)); - } - - fn push_heads(&self, heads: impl IntoIterator) { - self.heads - .lock() - .push_back(heads.into_iter().map(|byte| Ok([byte; 32])).collect()); - } - } - - #[async_trait] - impl CoinageStorageQuery for ScriptedStorage { - async fn query( - &self, - keys: &[CoinageStorageKey], - at: Option<[u8; 32]>, - ) -> Result>>, String> { - self.queries.lock().push((keys.to_vec(), at)); - self.responses - .lock() - .pop_front() - .expect("missing scripted response") - } - - fn finalized_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>> { - Box::pin(stream::iter( - self.heads - .lock() - .pop_front() - .expect("missing scripted heads"), - )) - } - } - - fn raw_coin(value: i8, age: u16) -> Vec { - RawOnChainCoin { value, age }.encode() - } - - fn location_voucher(derivation_index: u32, exponent: i16) -> crate::Voucher { - crate::Voucher { - exponent, - derivation_index, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: crate::VoucherRemoteState::Unlocated, - local_state: crate::VoucherLocalState::Available, - privacy: crate::VoucherPrivacyLevel::Degraded, - } - } - - #[test] - fn alias_query_rejects_out_of_range_exponent() { - assert!(matches!( - CoinageStorageKey::recycler_alias(500, 0, [0; 32]), - Err(CoinageQueryError::InvalidExponent(500)) - )); - } - - #[test] - fn alias_state_scale_wire_boundary() { - // AliasState wire shape: Unloaded is the bare variant 1; Locked - // carries reason + until. - assert_eq!(AliasState::Unloaded.encode(), vec![1]); - let locked = AliasState::Locked(LockInfo { - reason: LockReason::FailedDispatch(2), - until: 99, - }); - let encoded = locked.encode(); - assert_eq!(encoded[0], 0); - assert_eq!(encoded.len(), 1 + 1 + 1 + 8); - assert_eq!(AliasState::decode(&mut &encoded[..]).unwrap(), locked); - } - - #[tokio::test] - async fn voucher_location_batch_decodes_included_position_and_coverage() { - let storage = ScriptedStorage::default(); - storage.push_response(vec![ - Some( - RingPosition::Included { - ring_index: 7, - ring_page: 2, - ring_position: 4, - } - .encode(), - ), - Some( - members::RingStatus { - total: 9, - included: 5, - immutable_since: None, - } - .encode(), - ), - ]); - let requests = vec![ - ( - VoucherLocationRequest::Position { - derivation_index: 11, - }, - CoinageStorageKey::Member { - exponent: 3, - member: [11; 32], - }, - ), - ( - VoucherLocationRequest::Status { - derivation_index: 11, - }, - CoinageStorageKey::RingKeysStatus { - exponent: 3, - ring_index: 7, - }, - ), - ]; - - assert_eq!( - fetch_voucher_location_update(&storage, &requests, Some([9; 32])) - .await - .unwrap(), - VoucherLocationUpdate { - ring_positions: vec![( - 11, - Some(VoucherRingPosition::Included { - ring_index: 7, - included_at: 4, - }), - )], - ring_statuses: vec![( - 11, - VoucherRingStatus { - included_members: 5, - }, - )], - } - ); - } - - #[tokio::test] - async fn voucher_location_reads_current_best_then_follows_live_best_changes() { - let storage = Arc::new(ScriptedStorage::default()); - storage.push_response(vec![Some( - RingPosition::Onboarding { - queue_page: 0, - queued_at: 10, - } - .encode(), - )]); - storage.push_response(vec![Some( - RingPosition::Included { - ring_index: 4, - ring_page: 0, - ring_position: 2, - } - .encode(), - )]); - storage.push_heads([0xA5]); - let vouchers = Arc::new(crate::InMemoryVoucherRepository::with_vouchers([ - location_voucher(7, 3), - ])); - let subscriber = QueryVoucherLocationSubscriber::new( - Arc::clone(&storage) as Arc, - vouchers, - Arc::new(|_| Ok([7; 32])), - crate::test_spawner(), - ); - - let mut updates = subscriber.subscribe(vec![7], vec![], vec![]).await.unwrap(); - assert_eq!( - updates.recv().await.unwrap().ring_positions, - vec![(7, Some(VoucherRingPosition::Onboarding))] - ); - assert_eq!( - updates.recv().await.unwrap().ring_positions, - vec![( - 7, - Some(VoucherRingPosition::Included { - ring_index: 4, - included_at: 2, - }), - )] - ); - - let queries = storage.queries.lock(); - assert_eq!(queries.len(), 2); - assert_eq!(queries[0].1, None, "initial snapshot is current best"); - assert_eq!( - queries[1].1, - Some([0xA5; 32]), - "live best change pins the follow-up batch" - ); - } - - /// A `chainHead` follow can be rejected or terminate after the first - /// snapshot. The location observer must still re-read current best state, - /// otherwise a member position seen before `RingKeysStatus.included` - /// advances remains pending forever. - #[tokio::test] - async fn voucher_location_periodically_reconciles_after_head_stream_ends() { - let storage = Arc::new(ScriptedStorage::default()); - storage.push_response(vec![Some( - RingPosition::Onboarding { - queue_page: 0, - queued_at: 10, - } - .encode(), - )]); - storage.push_response(vec![Some( - RingPosition::Included { - ring_index: 4, - ring_page: 0, - ring_position: 2, - } - .encode(), - )]); - storage.push_heads([]); - let vouchers = Arc::new(crate::InMemoryVoucherRepository::with_vouchers([ - location_voucher(7, 3), - ])); - let subscriber = QueryVoucherLocationSubscriber::new( - Arc::clone(&storage) as Arc, - vouchers, - Arc::new(|_| Ok([7; 32])), - crate::test_spawner(), - ) - .with_observation_refresh_interval(Duration::from_millis(10)); - - let mut updates = subscriber.subscribe(vec![7], vec![], vec![]).await.unwrap(); - assert_eq!( - updates.recv().await.unwrap().ring_positions, - vec![(7, Some(VoucherRingPosition::Onboarding))] - ); - assert_eq!( - tokio::time::timeout(Duration::from_secs(1), updates.recv()) - .await - .expect("periodic current-best reconciliation timed out") - .unwrap() - .ring_positions, - vec![( - 7, - Some(VoucherRingPosition::Included { - ring_index: 4, - included_at: 2, - }), - )] - ); - - let queries = storage.queries.lock(); - assert_eq!(queries.len(), 2); - assert_eq!(queries[0].1, None); - assert_eq!(queries[1].1, None, "fallback re-reads current best"); - } - - #[tokio::test] - async fn coin_batch_fetch_preserves_order_and_strictly_decodes() { - let storage = Arc::new(ScriptedStorage::default()); - storage.push_response(vec![Some(raw_coin(4, 12)), None, Some(raw_coin(-2, 1))]); - let service = CoinOnChainQueryService::new(storage.clone()); - let keys = [[1; 32], [2; 32], [3; 32]]; - assert_eq!( - service.fetch_coins(&keys, Some([9; 32])).await.unwrap(), - vec![ - Some(OnChainCoin { - exponent: 4, - age: 12 - }), - None, - Some(OnChainCoin { - exponent: -2, - age: 1 - }) - ] - ); - let calls = storage.queries.lock(); - assert_eq!(calls.len(), 1, "one batch RPC"); - assert_eq!(calls[0].0.len(), 3); - assert_eq!(calls[0].1, Some([9; 32])); - } - - #[tokio::test] - async fn sent_or_claimed_accumulates_seen_after_an_earlier_coin_is_claimed() { - let storage = Arc::new(ScriptedStorage::default()); - storage.push_heads([1, 2, 3]); - storage.push_response(vec![Some(raw_coin(1, 0)), None]); - storage.push_response(vec![None, Some(raw_coin(1, 0))]); - let service = CoinOnChainQueryService::new(storage); - let keys = [[1; 32], [2; 32]]; - assert!( - service - .await_all_coins_sent_or_claimed(&keys, 3) - .await - .unwrap(), - "the first key stays confirmed after it is spent; the second remains present" - ); - } - - #[tokio::test] - async fn sent_or_claimed_races_the_finalized_head_timeout() { - let storage = Arc::new(ScriptedStorage::default()); - storage.push_heads([1, 2]); - storage.push_response(vec![None]); - storage.push_response(vec![None]); - let service = CoinOnChainQueryService::new(storage); - assert_eq!( - service - .await_all_coins_sent_or_claimed(&[[1; 32]], 2) - .await - .unwrap_err(), - CoinageQueryError::Timeout { finalized_heads: 2 } - ); - } - - #[tokio::test] - async fn historical_probe_confirms_a_fast_claim_without_a_live_wait() { - let storage = Arc::new(ScriptedStorage::default()); - // Current: both absent. Anchor: both were present. - storage.push_response(vec![None, None]); - storage.push_response(vec![Some(raw_coin(1, 0)), Some(raw_coin(2, 0))]); - let service = CoinOnChainQueryService::new(storage.clone()); - let result = service - .await_send_or_claimed(&[[1; 32], [2; 32]], Some([7; 32]), 10) - .await - .unwrap(); - assert_eq!(result, SendConfirmation::AlreadyClaimed); - let calls = storage.queries.lock(); - assert_eq!(calls.len(), 2); - assert_eq!(calls[0].1, None); - assert_eq!(calls[1].1, Some([7; 32])); - } - - #[tokio::test] - async fn voucher_query_is_four_stages_and_preserves_nil_slots() { - let storage = Arc::new(ScriptedStorage::default()); - // Exponents: index 11 is not a recycler member. - storage.push_response(vec![Some(3i8.encode()), None, Some(5i8.encode())]); - // Positions for indices 10 and 12: index 12 is onboarding. - storage.push_response(vec![ - Some( - RingPosition::Included { - ring_index: 7, - ring_page: 0, - ring_position: 4, - } - .encode(), - ), - Some( - RingPosition::Onboarding { - queue_page: 1, - queued_at: 2, - } - .encode(), - ), - ]); - // An explicit `AliasState::Unloaded` row means unloaded. - storage.push_response(vec![Some(AliasState::Unloaded.encode())]); - - let public_key_provider: Arc = - Arc::new(|index| Ok([u8::try_from(index).unwrap(); 32])); - let alias_provider: Arc = - Arc::new(|index| Ok([u8::try_from(index + 1).unwrap(); 32])); - let service = - VoucherOnChainQueryService::new(storage.clone(), public_key_provider, alias_provider); - let result = service - .fetch_vouchers(&[10, 11, 12], Some([4; 32])) - .await - .unwrap(); - assert_eq!( - result, - vec![ - Some(VoucherOnChainInfo { - exponent: 3, - ring_position: RingPosition::Included { - ring_index: 7, - ring_page: 0, - ring_position: 4, - }, - is_unloaded: true, - }), - None, - None, - ] - ); - let calls = storage.queries.lock(); - assert_eq!(calls.len(), 3, "derivation plus three serial RPC batches"); - assert_eq!( - calls.iter().map(|call| call.0.len()).collect::>(), - [3, 2, 1] - ); - assert!(calls.iter().all(|call| call.1 == Some([4; 32]))); - } - - #[tokio::test] - async fn voucher_query_short_circuits_when_no_recycler_rows_exist() { - let storage = Arc::new(ScriptedStorage::default()); - storage.push_response(vec![None, None]); - let service = VoucherOnChainQueryService::new( - storage.clone(), - Arc::new(|index| Ok([index as u8; 32])), - Arc::new(|index| Ok([(index + 1) as u8; 32])), - ); - assert_eq!( - service.fetch_vouchers(&[1, 2], None).await.unwrap(), - vec![None, None] - ); - assert_eq!( - storage.queries.lock().len(), - 1, - "an empty first stage must not issue empty RPC batches" - ); - } - - #[tokio::test] - async fn recycler_revision_fetch_omits_missing_roots() { - let storage = Arc::new(ScriptedStorage::default()); - let root = RingRoot { - root: [1; 288], - revision: 42, - intermediate: [2; 848], - }; - storage.push_response(vec![Some(root.encode()), None]); - let loader = RecyclerReadinessLoader::new(storage.clone()); - let first = RecyclerKey { - exponent: 3, - index: 7, - }; - let second = RecyclerKey { - exponent: 5, - index: 9, - }; - let revisions = loader - .fetch_revisions(&[first, second], Some([8; 32])) - .await - .unwrap(); - assert_eq!(revisions, HashMap::from([(first, 42)])); - let calls = storage.queries.lock(); - assert_eq!(calls.len(), 1); - assert_eq!(calls[0].0.len(), 2); - assert_eq!(calls[0].1, Some([8; 32])); - } - - #[tokio::test] - async fn recycler_readiness_uses_one_finalized_head_for_the_batch() { - let storage = Arc::new(ScriptedStorage::default()); - storage.push_heads([0xA5]); - storage.push_response(vec![ - Some( - RingRoot { - root: [1; 288], - revision: 17, - intermediate: [2; 848], - } - .encode(), - ), - Some( - RingRoot { - root: [3; 288], - revision: 23, - intermediate: [4; 848], - } - .encode(), - ), - ]); - let loader = RecyclerReadinessLoader::new(storage.clone()); - let first = RecyclerKey { - exponent: 2, - index: 4, - }; - let second = RecyclerKey { - exponent: 7, - index: 9, - }; - - let snapshot = loader - .fetch_finalized_revisions(&[first, second]) - .await - .unwrap(); - - assert_eq!(snapshot.block_hash, [0xA5; 32]); - assert_eq!( - snapshot.revisions, - HashMap::from([(first, 17), (second, 23)]) - ); - let calls = storage.queries.lock(); - assert_eq!(calls.len(), 1, "one Members.Root batch"); - assert_eq!(calls[0].0.len(), 2); - assert_eq!(calls[0].1, Some([0xA5; 32])); - } + use parking_lot::Mutex; + use std::{collections::VecDeque, time::Duration}; + + use futures::stream; + + use super::*; + + type QueryRecord = (Vec, Option<[u8; 32]>); + type QueryResponse = Result>>, String>; + type HeadBatch = Vec>; + + #[derive(Default)] + struct ScriptedStorage { + queries: Mutex>, + responses: Mutex>, + heads: Mutex>, + } + + impl ScriptedStorage { + fn push_response(&self, response: Vec>>) { + self.responses.lock().push_back(Ok(response)); + } + + fn push_heads(&self, heads: impl IntoIterator) { + self.heads + .lock() + .push_back(heads.into_iter().map(|byte| Ok([byte; 32])).collect()); + } + } + + #[async_trait] + impl CoinageStorageQuery for ScriptedStorage { + async fn query( + &self, + keys: &[CoinageStorageKey], + at: Option<[u8; 32]>, + ) -> Result>>, String> { + self.queries.lock().push((keys.to_vec(), at)); + self.responses.lock().pop_front().expect("missing scripted response") + } + + fn finalized_heads(&self) -> BoxStream<'static, Result<[u8; 32], String>> { + Box::pin(stream::iter(self.heads.lock().pop_front().expect("missing scripted heads"))) + } + } + + fn raw_coin(value: i8, age: u16) -> Vec { + RawOnChainCoin { value, age }.encode() + } + + fn location_voucher(derivation_index: u32, exponent: i16) -> crate::Voucher { + crate::Voucher { + exponent, + derivation_index, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: crate::VoucherRemoteState::Unlocated, + local_state: crate::VoucherLocalState::Available, + privacy: crate::VoucherPrivacyLevel::Degraded, + } + } + + #[test] + fn alias_query_rejects_out_of_range_exponent() { + assert!(matches!( + CoinageStorageKey::recycler_alias(500, 0, [0; 32]), + Err(CoinageQueryError::InvalidExponent(500)) + )); + } + + #[test] + fn alias_state_scale_wire_boundary() { + // AliasState wire shape: Unloaded is the bare variant 1; Locked + // carries reason + until. + assert_eq!(AliasState::Unloaded.encode(), vec![1]); + let locked = + AliasState::Locked(LockInfo { reason: LockReason::FailedDispatch(2), until: 99 }); + let encoded = locked.encode(); + assert_eq!(encoded[0], 0); + assert_eq!(encoded.len(), 1 + 1 + 1 + 8); + assert_eq!(AliasState::decode(&mut &encoded[..]).unwrap(), locked); + } + + #[tokio::test] + async fn voucher_location_batch_decodes_included_position_and_coverage() { + let storage = ScriptedStorage::default(); + storage.push_response(vec![ + Some(RingPosition::Included { ring_index: 7, ring_page: 2, ring_position: 4 }.encode()), + Some(members::RingStatus { total: 9, included: 5, immutable_since: None }.encode()), + ]); + let requests = vec![ + ( + VoucherLocationRequest::Position { derivation_index: 11 }, + CoinageStorageKey::Member { exponent: 3, member: [11; 32] }, + ), + ( + VoucherLocationRequest::Status { derivation_index: 11 }, + CoinageStorageKey::RingKeysStatus { exponent: 3, ring_index: 7 }, + ), + ]; + + assert_eq!( + fetch_voucher_location_update(&storage, &requests, Some([9; 32])).await.unwrap(), + VoucherLocationUpdate { + ring_positions: vec![( + 11, + Some(VoucherRingPosition::Included { ring_index: 7, included_at: 4 }), + )], + ring_statuses: vec![(11, VoucherRingStatus { included_members: 5 },)], + } + ); + } + + #[tokio::test] + async fn voucher_location_reads_current_best_then_follows_live_best_changes() { + let storage = Arc::new(ScriptedStorage::default()); + storage.push_response(vec![Some( + RingPosition::Onboarding { queue_page: 0, queued_at: 10 }.encode(), + )]); + storage.push_response(vec![Some( + RingPosition::Included { ring_index: 4, ring_page: 0, ring_position: 2 }.encode(), + )]); + storage.push_heads([0xA5]); + let vouchers = + Arc::new(crate::InMemoryVoucherRepository::with_vouchers([location_voucher(7, 3)])); + let subscriber = QueryVoucherLocationSubscriber::new( + Arc::clone(&storage) as Arc, + vouchers, + Arc::new(|_| Ok([7; 32])), + crate::test_spawner(), + ); + + let mut updates = subscriber.subscribe(vec![7], vec![], vec![]).await.unwrap(); + assert_eq!( + updates.recv().await.unwrap().ring_positions, + vec![(7, Some(VoucherRingPosition::Onboarding))] + ); + assert_eq!( + updates.recv().await.unwrap().ring_positions, + vec![(7, Some(VoucherRingPosition::Included { ring_index: 4, included_at: 2 }),)] + ); + + let queries = storage.queries.lock(); + assert_eq!(queries.len(), 2); + assert_eq!(queries[0].1, None, "initial snapshot is current best"); + assert_eq!(queries[1].1, Some([0xA5; 32]), "live best change pins the follow-up batch"); + } + + /// A `chainHead` follow can be rejected or terminate after the first + /// snapshot. The location observer must still re-read current best state, + /// otherwise a member position seen before `RingKeysStatus.included` + /// advances remains pending forever. + #[tokio::test] + async fn voucher_location_periodically_reconciles_after_head_stream_ends() { + let storage = Arc::new(ScriptedStorage::default()); + storage.push_response(vec![Some( + RingPosition::Onboarding { queue_page: 0, queued_at: 10 }.encode(), + )]); + storage.push_response(vec![Some( + RingPosition::Included { ring_index: 4, ring_page: 0, ring_position: 2 }.encode(), + )]); + storage.push_heads([]); + let vouchers = + Arc::new(crate::InMemoryVoucherRepository::with_vouchers([location_voucher(7, 3)])); + let subscriber = QueryVoucherLocationSubscriber::new( + Arc::clone(&storage) as Arc, + vouchers, + Arc::new(|_| Ok([7; 32])), + crate::test_spawner(), + ) + .with_observation_refresh_interval(Duration::from_millis(10)); + + let mut updates = subscriber.subscribe(vec![7], vec![], vec![]).await.unwrap(); + assert_eq!( + updates.recv().await.unwrap().ring_positions, + vec![(7, Some(VoucherRingPosition::Onboarding))] + ); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), updates.recv()) + .await + .expect("periodic current-best reconciliation timed out") + .unwrap() + .ring_positions, + vec![(7, Some(VoucherRingPosition::Included { ring_index: 4, included_at: 2 }),)] + ); + + let queries = storage.queries.lock(); + assert_eq!(queries.len(), 2); + assert_eq!(queries[0].1, None); + assert_eq!(queries[1].1, None, "fallback re-reads current best"); + } + + #[tokio::test] + async fn coin_batch_fetch_preserves_order_and_strictly_decodes() { + let storage = Arc::new(ScriptedStorage::default()); + storage.push_response(vec![Some(raw_coin(4, 12)), None, Some(raw_coin(-2, 1))]); + let service = CoinOnChainQueryService::new(storage.clone()); + let keys = [[1; 32], [2; 32], [3; 32]]; + assert_eq!( + service.fetch_coins(&keys, Some([9; 32])).await.unwrap(), + vec![ + Some(OnChainCoin { exponent: 4, age: 12 }), + None, + Some(OnChainCoin { exponent: -2, age: 1 }) + ] + ); + let calls = storage.queries.lock(); + assert_eq!(calls.len(), 1, "one batch RPC"); + assert_eq!(calls[0].0.len(), 3); + assert_eq!(calls[0].1, Some([9; 32])); + } + + #[tokio::test] + async fn sent_or_claimed_accumulates_seen_after_an_earlier_coin_is_claimed() { + let storage = Arc::new(ScriptedStorage::default()); + storage.push_heads([1, 2, 3]); + storage.push_response(vec![Some(raw_coin(1, 0)), None]); + storage.push_response(vec![None, Some(raw_coin(1, 0))]); + let service = CoinOnChainQueryService::new(storage); + let keys = [[1; 32], [2; 32]]; + assert!( + service.await_all_coins_sent_or_claimed(&keys, 3).await.unwrap(), + "the first key stays confirmed after it is spent; the second remains present" + ); + } + + #[tokio::test] + async fn sent_or_claimed_races_the_finalized_head_timeout() { + let storage = Arc::new(ScriptedStorage::default()); + storage.push_heads([1, 2]); + storage.push_response(vec![None]); + storage.push_response(vec![None]); + let service = CoinOnChainQueryService::new(storage); + assert_eq!( + service.await_all_coins_sent_or_claimed(&[[1; 32]], 2).await.unwrap_err(), + CoinageQueryError::Timeout { finalized_heads: 2 } + ); + } + + #[tokio::test] + async fn historical_probe_confirms_a_fast_claim_without_a_live_wait() { + let storage = Arc::new(ScriptedStorage::default()); + // Current: both absent. Anchor: both were present. + storage.push_response(vec![None, None]); + storage.push_response(vec![Some(raw_coin(1, 0)), Some(raw_coin(2, 0))]); + let service = CoinOnChainQueryService::new(storage.clone()); + let result = service + .await_send_or_claimed(&[[1; 32], [2; 32]], Some([7; 32]), 10) + .await + .unwrap(); + assert_eq!(result, SendConfirmation::AlreadyClaimed); + let calls = storage.queries.lock(); + assert_eq!(calls.len(), 2); + assert_eq!(calls[0].1, None); + assert_eq!(calls[1].1, Some([7; 32])); + } + + #[tokio::test] + async fn voucher_query_is_four_stages_and_preserves_nil_slots() { + let storage = Arc::new(ScriptedStorage::default()); + // Exponents: index 11 is not a recycler member. + storage.push_response(vec![Some(3i8.encode()), None, Some(5i8.encode())]); + // Positions for indices 10 and 12: index 12 is onboarding. + storage.push_response(vec![ + Some(RingPosition::Included { ring_index: 7, ring_page: 0, ring_position: 4 }.encode()), + Some(RingPosition::Onboarding { queue_page: 1, queued_at: 2 }.encode()), + ]); + // An explicit `AliasState::Unloaded` row means unloaded. + storage.push_response(vec![Some(AliasState::Unloaded.encode())]); + + let public_key_provider: Arc = + Arc::new(|index| Ok([u8::try_from(index).unwrap(); 32])); + let alias_provider: Arc = + Arc::new(|index| Ok([u8::try_from(index + 1).unwrap(); 32])); + let service = + VoucherOnChainQueryService::new(storage.clone(), public_key_provider, alias_provider); + let result = service.fetch_vouchers(&[10, 11, 12], Some([4; 32])).await.unwrap(); + assert_eq!( + result, + vec![ + Some(VoucherOnChainInfo { + exponent: 3, + ring_position: RingPosition::Included { + ring_index: 7, + ring_page: 0, + ring_position: 4, + }, + is_unloaded: true, + }), + None, + None, + ] + ); + let calls = storage.queries.lock(); + assert_eq!(calls.len(), 3, "derivation plus three serial RPC batches"); + assert_eq!(calls.iter().map(|call| call.0.len()).collect::>(), [3, 2, 1]); + assert!(calls.iter().all(|call| call.1 == Some([4; 32]))); + } + + #[tokio::test] + async fn voucher_query_short_circuits_when_no_recycler_rows_exist() { + let storage = Arc::new(ScriptedStorage::default()); + storage.push_response(vec![None, None]); + let service = VoucherOnChainQueryService::new( + storage.clone(), + Arc::new(|index| Ok([index as u8; 32])), + Arc::new(|index| Ok([(index + 1) as u8; 32])), + ); + assert_eq!(service.fetch_vouchers(&[1, 2], None).await.unwrap(), vec![None, None]); + assert_eq!( + storage.queries.lock().len(), + 1, + "an empty first stage must not issue empty RPC batches" + ); + } + + #[tokio::test] + async fn recycler_revision_fetch_omits_missing_roots() { + let storage = Arc::new(ScriptedStorage::default()); + let root = RingRoot { root: [1; 288], revision: 42, intermediate: [2; 848] }; + storage.push_response(vec![Some(root.encode()), None]); + let loader = RecyclerReadinessLoader::new(storage.clone()); + let first = RecyclerKey { exponent: 3, index: 7 }; + let second = RecyclerKey { exponent: 5, index: 9 }; + let revisions = loader.fetch_revisions(&[first, second], Some([8; 32])).await.unwrap(); + assert_eq!(revisions, HashMap::from([(first, 42)])); + let calls = storage.queries.lock(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].0.len(), 2); + assert_eq!(calls[0].1, Some([8; 32])); + } + + #[tokio::test] + async fn recycler_readiness_uses_one_finalized_head_for_the_batch() { + let storage = Arc::new(ScriptedStorage::default()); + storage.push_heads([0xA5]); + storage.push_response(vec![ + Some(RingRoot { root: [1; 288], revision: 17, intermediate: [2; 848] }.encode()), + Some(RingRoot { root: [3; 288], revision: 23, intermediate: [4; 848] }.encode()), + ]); + let loader = RecyclerReadinessLoader::new(storage.clone()); + let first = RecyclerKey { exponent: 2, index: 4 }; + let second = RecyclerKey { exponent: 7, index: 9 }; + + let snapshot = loader.fetch_finalized_revisions(&[first, second]).await.unwrap(); + + assert_eq!(snapshot.block_hash, [0xA5; 32]); + assert_eq!(snapshot.revisions, HashMap::from([(first, 17), (second, 23)])); + let calls = storage.queries.lock(); + assert_eq!(calls.len(), 1, "one Members.Root batch"); + assert_eq!(calls[0].0.len(), 2); + assert_eq!(calls[0].1, Some([0xA5; 32])); + } } diff --git a/rust/crates/truapi-coinage/src/recipient.rs b/rust/crates/truapi-coinage/src/recipient.rs index 32ca9feaaa..b9164f2b33 100644 --- a/rust/crates/truapi-coinage/src/recipient.rs +++ b/rust/crates/truapi-coinage/src/recipient.rs @@ -2,581 +2,517 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use {parking_lot::Mutex, std::sync::Arc}; +use parking_lot::Mutex; +use std::sync::Arc; use futures::future::AbortHandle; use tokio::sync::mpsc; use tracing::{info, warn}; -use crate::claim::{ - ClaimError, ClaimOrchestrator, ClaimStatus, ClaimStatusStore, IncomingClaim, SendConfirmation, - TransferSendVerifying, +use crate::{ + claim::{ + ClaimError, ClaimOrchestrator, ClaimStatus, ClaimStatusStore, IncomingClaim, + SendConfirmation, TransferSendVerifying, + }, + claim_plan::{ClaimPlan, ClaimPlanStatus, ClaimPlanStore}, + constants::SEND_VERIFY_BLOCK_TIMEOUT, + tasks::ActiveTaskRegistry, }; -use crate::claim_plan::{ClaimPlan, ClaimPlanStatus, ClaimPlanStore}; -use crate::constants::SEND_VERIFY_BLOCK_TIMEOUT; -use crate::tasks::ActiveTaskRegistry; /// One `coinageSend` chat message, already decoded by the chat layer: /// `memo_key = TransferMemo::identifier` and the memo's declared total. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CoinageSendMessage { - pub message_id: String, - pub memo_key: [u8; 32], - pub total_value: u128, + pub message_id: String, + pub memo_key: [u8; 32], + pub total_value: u128, } pub struct TransferRecipientService { - spawner: crate::Spawner, - orchestrator: Arc, - plans: Arc, - verifier: Arc, - statuses: Arc, - registry: Arc, - loops: Mutex>, + spawner: crate::Spawner, + orchestrator: Arc, + plans: Arc, + verifier: Arc, + statuses: Arc, + registry: Arc, + loops: Mutex>, } impl TransferRecipientService { - /// `statuses` must be the same store injected into `orchestrator`, so - /// incoming and outgoing pushes land on one per-message channel. - pub fn new( - orchestrator: Arc, - plans: Arc, - verifier: Arc, - statuses: Arc, - spawner: crate::Spawner, - ) -> Self { - Self { - orchestrator, - plans, - verifier, - statuses, - registry: Arc::new(ActiveTaskRegistry::new(Arc::clone(&spawner))), - spawner, - loops: Mutex::new(Vec::new()), - } - } - - pub fn registry(&self) -> Arc { - Arc::clone(&self.registry) - } - - pub async fn start( - self: &Arc, - incoming: mpsc::Receiver, - outgoing: mpsc::Receiver, - ) -> Result<(), String> { - self.orchestrator.restore_persisted_statuses().await?; - let mut loops = self.loops.lock(); - loops.push(self.spawn_loop(incoming, Direction::Incoming)); - loops.push(self.spawn_loop(outgoing, Direction::Outgoing)); - Ok(()) - } - - pub fn throttle(&self) { - for handle in self.loops.lock().drain(..) { - handle.abort(); - } - self.registry.cancel_all(); - } - - fn spawn_loop( - self: &Arc, - mut messages: mpsc::Receiver, - direction: Direction, - ) -> AbortHandle { - let service = Arc::clone(self); - crate::tasks::spawn_abortable(&self.spawner, async move { - while let Some(message) = messages.recv().await { - service.dispatch(message, direction); - } - }) - } - - fn dispatch(self: &Arc, message: CoinageSendMessage, direction: Direction) { - if matches!( - self.statuses.status(&message.message_id), - Some(ClaimStatus::Finished { .. }) - ) { - return; - } - let service = Arc::clone(self); - let id = message.message_id.clone(); - self.registry.try_start(&id, async move { - match direction { - Direction::Incoming => service.run_incoming(message).await, - Direction::Outgoing => service.run_outgoing(message).await, - } - }); - } - - async fn run_incoming(&self, message: CoinageSendMessage) { - let outcome = self - .orchestrator - .claim_incoming(IncomingClaim { - memo_key: message.memo_key, - message_id: message.message_id.clone(), - total_value: message.total_value, - }) - .await; - match outcome { - Ok(claimed) => info!( - message_id = message.message_id, - claimed, "incoming coinage send claimed" - ), - Err(ClaimError::AlreadyClaiming) => { - info!( - message_id = message.message_id, - "claim already in flight for this memo" - ); - } - Err(ClaimError::Failed(error)) => { - warn!( - error, - message_id = message.message_id, - "incoming claim failed" - ); - } - } - } - - async fn run_outgoing(&self, message: CoinageSendMessage) { - if let Err(error) = self.verify_outgoing(&message).await { - warn!( - error, - message_id = message.message_id, - "outgoing send verification failed" - ); - if let Err(stamp_error) = self - .plans - .update_status(&message.memo_key, ClaimPlanStatus::Error, None) - .await - { - warn!(stamp_error, "outgoing error status stamp failed"); - } - self.statuses - .update_status(&message.message_id, ClaimStatus::Error); - } - } - - async fn verify_outgoing(&self, message: &CoinageSendMessage) -> Result<(), String> { - let existing = self.plans.plan(&message.memo_key).await?; - match &existing { - // Finished on a prior run: report only. - Some(plan) if plan.status == ClaimPlanStatus::Finished => { - self.statuses.update_status( - &message.message_id, - ClaimStatus::Finished { - claimed_amount: plan.claimed_amount.unwrap_or(plan.total_value), - }, - ); - return Ok(()); - } - Some(plan) if plan.status == ClaimPlanStatus::Detected => { - self.statuses - .update_status(&message.message_id, ClaimStatus::Sent); - self.verifier - .await_claim_on_chain(&message.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) - .await?; - } - other => { - if other.is_none() { - self.plans - .save(&ClaimPlan { - memo_key: message.memo_key, - message_id: Some(message.message_id.clone()), - entries: Vec::new(), - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Processing, - claimed_amount: None, - total_value: message.total_value, - markers: crate::claim_plan::ClaimMarkers::default(), - }) - .await?; - } - self.statuses - .update_status(&message.message_id, ClaimStatus::Detecting); - match self - .verifier - .await_send_or_claimed(&message.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) - .await? - { - SendConfirmation::OnChain => { - self.plans - .update_status(&message.memo_key, ClaimPlanStatus::Detected, None) - .await?; - self.statuses - .update_status(&message.message_id, ClaimStatus::Sent); - self.verifier - .await_claim_on_chain(&message.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) - .await?; - } - // Consumed before the watch saw them — the recipient - // already claimed; terminal. - SendConfirmation::AlreadyClaimed => {} - } - } - } - self.plans - .update_status( - &message.memo_key, - ClaimPlanStatus::Finished, - Some(message.total_value), - ) - .await?; - self.statuses.update_status( - &message.message_id, - ClaimStatus::Finished { - claimed_amount: message.total_value, - }, - ); - Ok(()) - } + /// `statuses` must be the same store injected into `orchestrator`, so + /// incoming and outgoing pushes land on one per-message channel. + pub fn new( + orchestrator: Arc, + plans: Arc, + verifier: Arc, + statuses: Arc, + spawner: crate::Spawner, + ) -> Self { + Self { + orchestrator, + plans, + verifier, + statuses, + registry: Arc::new(ActiveTaskRegistry::new(Arc::clone(&spawner))), + spawner, + loops: Mutex::new(Vec::new()), + } + } + + pub fn registry(&self) -> Arc { + Arc::clone(&self.registry) + } + + pub async fn start( + self: &Arc, + incoming: mpsc::Receiver, + outgoing: mpsc::Receiver, + ) -> Result<(), String> { + self.orchestrator.restore_persisted_statuses().await?; + let mut loops = self.loops.lock(); + loops.push(self.spawn_loop(incoming, Direction::Incoming)); + loops.push(self.spawn_loop(outgoing, Direction::Outgoing)); + Ok(()) + } + + pub fn throttle(&self) { + for handle in self.loops.lock().drain(..) { + handle.abort(); + } + self.registry.cancel_all(); + } + + fn spawn_loop( + self: &Arc, + mut messages: mpsc::Receiver, + direction: Direction, + ) -> AbortHandle { + let service = Arc::clone(self); + crate::tasks::spawn_abortable(&self.spawner, async move { + while let Some(message) = messages.recv().await { + service.dispatch(message, direction); + } + }) + } + + fn dispatch(self: &Arc, message: CoinageSendMessage, direction: Direction) { + if matches!(self.statuses.status(&message.message_id), Some(ClaimStatus::Finished { .. })) { + return; + } + let service = Arc::clone(self); + let id = message.message_id.clone(); + self.registry.try_start(&id, async move { + match direction { + Direction::Incoming => service.run_incoming(message).await, + Direction::Outgoing => service.run_outgoing(message).await, + } + }); + } + + async fn run_incoming(&self, message: CoinageSendMessage) { + let outcome = self + .orchestrator + .claim_incoming(IncomingClaim { + memo_key: message.memo_key, + message_id: message.message_id.clone(), + total_value: message.total_value, + }) + .await; + match outcome { + Ok(claimed) => { + info!(message_id = message.message_id, claimed, "incoming coinage send claimed") + }, + Err(ClaimError::AlreadyClaiming) => { + info!(message_id = message.message_id, "claim already in flight for this memo"); + }, + Err(ClaimError::Failed(error)) => { + warn!(error, message_id = message.message_id, "incoming claim failed"); + }, + } + } + + async fn run_outgoing(&self, message: CoinageSendMessage) { + if let Err(error) = self.verify_outgoing(&message).await { + warn!(error, message_id = message.message_id, "outgoing send verification failed"); + if let Err(stamp_error) = + self.plans.update_status(&message.memo_key, ClaimPlanStatus::Error, None).await + { + warn!(stamp_error, "outgoing error status stamp failed"); + } + self.statuses.update_status(&message.message_id, ClaimStatus::Error); + } + } + + async fn verify_outgoing(&self, message: &CoinageSendMessage) -> Result<(), String> { + let existing = self.plans.plan(&message.memo_key).await?; + match &existing { + // Finished on a prior run: report only. + Some(plan) if plan.status == ClaimPlanStatus::Finished => { + self.statuses.update_status( + &message.message_id, + ClaimStatus::Finished { + claimed_amount: plan.claimed_amount.unwrap_or(plan.total_value), + }, + ); + return Ok(()); + }, + Some(plan) if plan.status == ClaimPlanStatus::Detected => { + self.statuses.update_status(&message.message_id, ClaimStatus::Sent); + self.verifier + .await_claim_on_chain(&message.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) + .await?; + }, + other => { + if other.is_none() { + self.plans + .save(&ClaimPlan { + memo_key: message.memo_key, + message_id: Some(message.message_id.clone()), + entries: Vec::new(), + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Processing, + claimed_amount: None, + total_value: message.total_value, + markers: crate::claim_plan::ClaimMarkers::default(), + }) + .await?; + } + self.statuses.update_status(&message.message_id, ClaimStatus::Detecting); + match self + .verifier + .await_send_or_claimed(&message.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) + .await? + { + SendConfirmation::OnChain => { + self.plans + .update_status(&message.memo_key, ClaimPlanStatus::Detected, None) + .await?; + self.statuses.update_status(&message.message_id, ClaimStatus::Sent); + self.verifier + .await_claim_on_chain(&message.memo_key, SEND_VERIFY_BLOCK_TIMEOUT) + .await?; + }, + // Consumed before the watch saw them — the recipient + // already claimed; terminal. + SendConfirmation::AlreadyClaimed => {}, + } + }, + } + self.plans + .update_status(&message.memo_key, ClaimPlanStatus::Finished, Some(message.total_value)) + .await?; + self.statuses.update_status( + &message.message_id, + ClaimStatus::Finished { claimed_amount: message.total_value }, + ); + Ok(()) + } } #[derive(Clone, Copy)] enum Direction { - Incoming, - Outgoing, + Incoming, + Outgoing, } #[cfg(test)] mod tests { - use std::collections::HashMap; - use std::sync::atomic::{AtomicUsize, Ordering}; - - use async_trait::async_trait; - - use super::*; - use crate::claim::ClaimExecutor; - use crate::claim_plan::CodableClaimPlanEntry; - use crate::denomination::DenominationBreakdownContext; - - fn ctx() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 10, - max_exponent: 4, - min_exponent: 0, - precision: 10, - } - } - - #[derive(Default)] - struct MemPlans { - plans: Mutex>, - } - - #[async_trait] - impl ClaimPlanStore for MemPlans { - async fn save(&self, plan: &ClaimPlan) -> Result<(), String> { - self.plans.lock().insert(plan.memo_key, plan.clone()); - Ok(()) - } - async fn plan(&self, memo_key: &[u8; 32]) -> Result, String> { - Ok(self.plans.lock().get(memo_key).cloned()) - } - async fn load_all(&self) -> Result, String> { - Ok(self.plans.lock().values().cloned().collect()) - } - async fn update_status( - &self, - memo_key: &[u8; 32], - status: ClaimPlanStatus, - claimed_amount: Option, - ) -> Result<(), String> { - let mut plans = self.plans.lock(); - let plan = plans.get_mut(memo_key).ok_or("plan not found")?; - plan.status = status; - plan.claimed_amount = claimed_amount; - Ok(()) - } - async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String> { - self.plans.lock().remove(memo_key); - Ok(()) - } - } - - struct ScriptedVerifier { - plans: Arc, - send_or_claimed: Result, - claim_outcome: Result<(), String>, - send_or_claimed_calls: AtomicUsize, - claim_calls: AtomicUsize, - } - - impl ScriptedVerifier { - fn new( - plans: Arc, - send_or_claimed: Result, - claim_outcome: Result<(), String>, - ) -> Arc { - Arc::new(Self { - plans, - send_or_claimed, - claim_outcome, - send_or_claimed_calls: AtomicUsize::new(0), - claim_calls: AtomicUsize::new(0), - }) - } - } - - #[async_trait] - impl TransferSendVerifying for ScriptedVerifier { - async fn await_send_on_chain( - &self, - _memo_key: &[u8; 32], - _block_timeout: u32, - ) -> Result<(), String> { - Ok(()) - } - async fn await_claim_on_chain( - &self, - _memo_key: &[u8; 32], - block_timeout: u32, - ) -> Result<(), String> { - assert_eq!(block_timeout, 100, "COINM-024"); - self.claim_calls.fetch_add(1, Ordering::SeqCst); - self.claim_outcome.clone() - } - async fn await_send_or_claimed( - &self, - memo_key: &[u8; 32], - block_timeout: u32, - ) -> Result { - assert_eq!(block_timeout, 100, "COINM-024"); - self.send_or_claimed_calls.fetch_add(1, Ordering::SeqCst); - assert!( - self.plans.plan(memo_key).await.unwrap().is_some(), - "the .processing placeholder must exist before the send race (COINA-016)" - ); - self.send_or_claimed.clone() - } - } - - struct NoopExecutor; - - #[async_trait] - impl ClaimExecutor for NoopExecutor { - async fn claim( - &self, - _memo_key: &[u8; 32], - _message_id: &str, - ) -> Result, String> { - Ok(vec![CodableClaimPlanEntry { - entry_index: 0, - exponent: 0, - derivation_index: 1, - }]) - } - } - - fn service( - plans: Arc, - verifier: Arc, - ) -> (Arc, Arc) { - let statuses = Arc::new(ClaimStatusStore::default()); - let orchestrator = Arc::new(ClaimOrchestrator::new( - Arc::clone(&plans) as Arc, - Arc::clone(&verifier) as Arc, - Arc::new(NoopExecutor), - Arc::clone(&statuses), - ctx(), - )); - ( - Arc::new(TransferRecipientService::new( - orchestrator, - plans, - verifier, - Arc::clone(&statuses), - crate::test_spawner(), - )), - statuses, - ) - } - - fn message() -> CoinageSendMessage { - CoinageSendMessage { - message_id: "m1".into(), - memo_key: [7; 32], - total_value: 990, - } - } - - fn detected_plan() -> ClaimPlan { - ClaimPlan { - memo_key: [7; 32], - message_id: Some("m1".into()), - entries: Vec::new(), - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Detected, - claimed_amount: None, - total_value: 990, - markers: crate::claim_plan::ClaimMarkers::default(), - } - } - - async fn settle(statuses: &ClaimStatusStore, id: &str) -> ClaimStatus { - for _ in 0..1_000 { - if let Some(status) = statuses.status(id) - && status.is_terminal() - { - return status; - } - tokio::task::yield_now().await; - } - panic!("status never became terminal"); - } - - #[tokio::test] - async fn detected_plan_jumps_to_await_claim() { - let plans = Arc::new(MemPlans::default()); - plans.save(&detected_plan()).await.unwrap(); - let verifier = - ScriptedVerifier::new(Arc::clone(&plans), Ok(SendConfirmation::OnChain), Ok(())); - let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); - - service.run_outgoing(message()).await; - assert_eq!( - settle(&statuses, "m1").await, - ClaimStatus::Finished { - claimed_amount: 990 - } - ); - assert_eq!(verifier.send_or_claimed_calls.load(Ordering::SeqCst), 0); - assert_eq!(verifier.claim_calls.load(Ordering::SeqCst), 1); - let plan = plans.plan(&[7; 32]).await.unwrap().unwrap(); - assert_eq!(plan.status, ClaimPlanStatus::Finished); - assert_eq!(plan.claimed_amount, Some(990)); - } - - #[tokio::test] - async fn fresh_outgoing_send_walks_the_full_path() { - let plans = Arc::new(MemPlans::default()); - let verifier = - ScriptedVerifier::new(Arc::clone(&plans), Ok(SendConfirmation::OnChain), Ok(())); - let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); - - service.run_outgoing(message()).await; - assert_eq!( - settle(&statuses, "m1").await, - ClaimStatus::Finished { - claimed_amount: 990 - } - ); - assert_eq!(verifier.send_or_claimed_calls.load(Ordering::SeqCst), 1); - assert_eq!(verifier.claim_calls.load(Ordering::SeqCst), 1); - } - - /// `AlreadyClaimed`: the coins were consumed before the watch — the - /// claim await is skipped entirely and the send finishes. - #[tokio::test] - async fn already_claimed_short_circuits_the_claim_await() { - let plans = Arc::new(MemPlans::default()); - let verifier = ScriptedVerifier::new( - Arc::clone(&plans), - Ok(SendConfirmation::AlreadyClaimed), - Ok(()), - ); - let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); - - service.run_outgoing(message()).await; - assert_eq!( - settle(&statuses, "m1").await, - ClaimStatus::Finished { - claimed_amount: 990 - } - ); - assert_eq!(verifier.claim_calls.load(Ordering::SeqCst), 0); - } - - #[tokio::test] - async fn timeout_is_a_terminal_error() { - let plans = Arc::new(MemPlans::default()); - let verifier = ScriptedVerifier::new( - Arc::clone(&plans), - Err("timeout after 100 blocks".into()), - Ok(()), - ); - let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); - - service.run_outgoing(message()).await; - assert_eq!(settle(&statuses, "m1").await, ClaimStatus::Error); - assert_eq!( - plans.plan(&[7; 32]).await.unwrap().unwrap().status, - ClaimPlanStatus::Error - ); - } - - #[tokio::test] - async fn loops_dedup_and_skip_finished_messages() { - let plans = Arc::new(MemPlans::default()); - let verifier = ScriptedVerifier::new( - Arc::clone(&plans), - Ok(SendConfirmation::AlreadyClaimed), - Ok(()), - ); - let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); - - let (incoming_tx, incoming_rx) = mpsc::channel(8); - let (outgoing_tx, outgoing_rx) = mpsc::channel(8); - service.start(incoming_rx, outgoing_rx).await.unwrap(); - - outgoing_tx.send(message()).await.unwrap(); - outgoing_tx.send(message()).await.unwrap(); - assert_eq!( - settle(&statuses, "m1").await, - ClaimStatus::Finished { - claimed_amount: 990 - } - ); - // Re-emission after finish: skipped by the terminal guard. - outgoing_tx.send(message()).await.unwrap(); - for _ in 0..64 { - tokio::task::yield_now().await; - } - assert_eq!( - verifier.send_or_claimed_calls.load(Ordering::SeqCst), - 1, - "one verification for three emissions" - ); - - // Incoming path delegates to the orchestrator. - incoming_tx - .send(CoinageSendMessage { - message_id: "m2".into(), - memo_key: [8; 32], - total_value: 10, - }) - .await - .unwrap(); - assert_eq!( - settle(&statuses, "m2").await, - ClaimStatus::Finished { claimed_amount: 10 } - ); - service.throttle(); - } - - /// `throttle` stops the loops: messages sent afterwards are never - /// processed. - #[tokio::test] - async fn throttle_stops_the_subscription_loops() { - let plans = Arc::new(MemPlans::default()); - let verifier = ScriptedVerifier::new( - Arc::clone(&plans), - Ok(SendConfirmation::AlreadyClaimed), - Ok(()), - ); - let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); - let (_incoming_tx, incoming_rx) = mpsc::channel::(8); - let (outgoing_tx, outgoing_rx) = mpsc::channel(8); - service.start(incoming_rx, outgoing_rx).await.unwrap(); - service.throttle(); - - outgoing_tx.send(message()).await.unwrap(); - for _ in 0..64 { - tokio::task::yield_now().await; - } - assert_eq!(statuses.status("m1"), None, "loop is dead after throttle"); - } + use std::{ + collections::HashMap, + sync::atomic::{AtomicUsize, Ordering}, + }; + + use async_trait::async_trait; + + use super::*; + use crate::{ + claim::ClaimExecutor, claim_plan::CodableClaimPlanEntry, + denomination::DenominationBreakdownContext, + }; + + fn ctx() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 10, + max_exponent: 4, + min_exponent: 0, + precision: 10, + } + } + + #[derive(Default)] + struct MemPlans { + plans: Mutex>, + } + + #[async_trait] + impl ClaimPlanStore for MemPlans { + async fn save(&self, plan: &ClaimPlan) -> Result<(), String> { + self.plans.lock().insert(plan.memo_key, plan.clone()); + Ok(()) + } + async fn plan(&self, memo_key: &[u8; 32]) -> Result, String> { + Ok(self.plans.lock().get(memo_key).cloned()) + } + async fn load_all(&self) -> Result, String> { + Ok(self.plans.lock().values().cloned().collect()) + } + async fn update_status( + &self, + memo_key: &[u8; 32], + status: ClaimPlanStatus, + claimed_amount: Option, + ) -> Result<(), String> { + let mut plans = self.plans.lock(); + let plan = plans.get_mut(memo_key).ok_or("plan not found")?; + plan.status = status; + plan.claimed_amount = claimed_amount; + Ok(()) + } + async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String> { + self.plans.lock().remove(memo_key); + Ok(()) + } + } + + struct ScriptedVerifier { + plans: Arc, + send_or_claimed: Result, + claim_outcome: Result<(), String>, + send_or_claimed_calls: AtomicUsize, + claim_calls: AtomicUsize, + } + + impl ScriptedVerifier { + fn new( + plans: Arc, + send_or_claimed: Result, + claim_outcome: Result<(), String>, + ) -> Arc { + Arc::new(Self { + plans, + send_or_claimed, + claim_outcome, + send_or_claimed_calls: AtomicUsize::new(0), + claim_calls: AtomicUsize::new(0), + }) + } + } + + #[async_trait] + impl TransferSendVerifying for ScriptedVerifier { + async fn await_send_on_chain( + &self, + _memo_key: &[u8; 32], + _block_timeout: u32, + ) -> Result<(), String> { + Ok(()) + } + async fn await_claim_on_chain( + &self, + _memo_key: &[u8; 32], + block_timeout: u32, + ) -> Result<(), String> { + assert_eq!(block_timeout, 100, "COINM-024"); + self.claim_calls.fetch_add(1, Ordering::SeqCst); + self.claim_outcome.clone() + } + async fn await_send_or_claimed( + &self, + memo_key: &[u8; 32], + block_timeout: u32, + ) -> Result { + assert_eq!(block_timeout, 100, "COINM-024"); + self.send_or_claimed_calls.fetch_add(1, Ordering::SeqCst); + assert!( + self.plans.plan(memo_key).await.unwrap().is_some(), + "the .processing placeholder must exist before the send race (COINA-016)" + ); + self.send_or_claimed.clone() + } + } + + struct NoopExecutor; + + #[async_trait] + impl ClaimExecutor for NoopExecutor { + async fn claim( + &self, + _memo_key: &[u8; 32], + _message_id: &str, + ) -> Result, String> { + Ok(vec![CodableClaimPlanEntry { entry_index: 0, exponent: 0, derivation_index: 1 }]) + } + } + + fn service( + plans: Arc, + verifier: Arc, + ) -> (Arc, Arc) { + let statuses = Arc::new(ClaimStatusStore::default()); + let orchestrator = Arc::new(ClaimOrchestrator::new( + Arc::clone(&plans) as Arc, + Arc::clone(&verifier) as Arc, + Arc::new(NoopExecutor), + Arc::clone(&statuses), + ctx(), + )); + ( + Arc::new(TransferRecipientService::new( + orchestrator, + plans, + verifier, + Arc::clone(&statuses), + crate::test_spawner(), + )), + statuses, + ) + } + + fn message() -> CoinageSendMessage { + CoinageSendMessage { message_id: "m1".into(), memo_key: [7; 32], total_value: 990 } + } + + fn detected_plan() -> ClaimPlan { + ClaimPlan { + memo_key: [7; 32], + message_id: Some("m1".into()), + entries: Vec::new(), + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Detected, + claimed_amount: None, + total_value: 990, + markers: crate::claim_plan::ClaimMarkers::default(), + } + } + + async fn settle(statuses: &ClaimStatusStore, id: &str) -> ClaimStatus { + for _ in 0..1_000 { + if let Some(status) = statuses.status(id) && + status.is_terminal() + { + return status; + } + tokio::task::yield_now().await; + } + panic!("status never became terminal"); + } + + #[tokio::test] + async fn detected_plan_jumps_to_await_claim() { + let plans = Arc::new(MemPlans::default()); + plans.save(&detected_plan()).await.unwrap(); + let verifier = + ScriptedVerifier::new(Arc::clone(&plans), Ok(SendConfirmation::OnChain), Ok(())); + let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); + + service.run_outgoing(message()).await; + assert_eq!(settle(&statuses, "m1").await, ClaimStatus::Finished { claimed_amount: 990 }); + assert_eq!(verifier.send_or_claimed_calls.load(Ordering::SeqCst), 0); + assert_eq!(verifier.claim_calls.load(Ordering::SeqCst), 1); + let plan = plans.plan(&[7; 32]).await.unwrap().unwrap(); + assert_eq!(plan.status, ClaimPlanStatus::Finished); + assert_eq!(plan.claimed_amount, Some(990)); + } + + #[tokio::test] + async fn fresh_outgoing_send_walks_the_full_path() { + let plans = Arc::new(MemPlans::default()); + let verifier = + ScriptedVerifier::new(Arc::clone(&plans), Ok(SendConfirmation::OnChain), Ok(())); + let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); + + service.run_outgoing(message()).await; + assert_eq!(settle(&statuses, "m1").await, ClaimStatus::Finished { claimed_amount: 990 }); + assert_eq!(verifier.send_or_claimed_calls.load(Ordering::SeqCst), 1); + assert_eq!(verifier.claim_calls.load(Ordering::SeqCst), 1); + } + + /// `AlreadyClaimed`: the coins were consumed before the watch — the + /// claim await is skipped entirely and the send finishes. + #[tokio::test] + async fn already_claimed_short_circuits_the_claim_await() { + let plans = Arc::new(MemPlans::default()); + let verifier = + ScriptedVerifier::new(Arc::clone(&plans), Ok(SendConfirmation::AlreadyClaimed), Ok(())); + let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); + + service.run_outgoing(message()).await; + assert_eq!(settle(&statuses, "m1").await, ClaimStatus::Finished { claimed_amount: 990 }); + assert_eq!(verifier.claim_calls.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn timeout_is_a_terminal_error() { + let plans = Arc::new(MemPlans::default()); + let verifier = ScriptedVerifier::new( + Arc::clone(&plans), + Err("timeout after 100 blocks".into()), + Ok(()), + ); + let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); + + service.run_outgoing(message()).await; + assert_eq!(settle(&statuses, "m1").await, ClaimStatus::Error); + assert_eq!(plans.plan(&[7; 32]).await.unwrap().unwrap().status, ClaimPlanStatus::Error); + } + + #[tokio::test] + async fn loops_dedup_and_skip_finished_messages() { + let plans = Arc::new(MemPlans::default()); + let verifier = + ScriptedVerifier::new(Arc::clone(&plans), Ok(SendConfirmation::AlreadyClaimed), Ok(())); + let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); + + let (incoming_tx, incoming_rx) = mpsc::channel(8); + let (outgoing_tx, outgoing_rx) = mpsc::channel(8); + service.start(incoming_rx, outgoing_rx).await.unwrap(); + + outgoing_tx.send(message()).await.unwrap(); + outgoing_tx.send(message()).await.unwrap(); + assert_eq!(settle(&statuses, "m1").await, ClaimStatus::Finished { claimed_amount: 990 }); + // Re-emission after finish: skipped by the terminal guard. + outgoing_tx.send(message()).await.unwrap(); + for _ in 0..64 { + tokio::task::yield_now().await; + } + assert_eq!( + verifier.send_or_claimed_calls.load(Ordering::SeqCst), + 1, + "one verification for three emissions" + ); + + // Incoming path delegates to the orchestrator. + incoming_tx + .send(CoinageSendMessage { + message_id: "m2".into(), + memo_key: [8; 32], + total_value: 10, + }) + .await + .unwrap(); + assert_eq!(settle(&statuses, "m2").await, ClaimStatus::Finished { claimed_amount: 10 }); + service.throttle(); + } + + /// `throttle` stops the loops: messages sent afterwards are never + /// processed. + #[tokio::test] + async fn throttle_stops_the_subscription_loops() { + let plans = Arc::new(MemPlans::default()); + let verifier = + ScriptedVerifier::new(Arc::clone(&plans), Ok(SendConfirmation::AlreadyClaimed), Ok(())); + let (service, statuses) = service(Arc::clone(&plans), Arc::clone(&verifier)); + let (_incoming_tx, incoming_rx) = mpsc::channel::(8); + let (outgoing_tx, outgoing_rx) = mpsc::channel(8); + service.start(incoming_rx, outgoing_rx).await.unwrap(); + service.throttle(); + + outgoing_tx.send(message()).await.unwrap(); + for _ in 0..64 { + tokio::task::yield_now().await; + } + assert_eq!(statuses.status("m1"), None, "loop is dead after throttle"); + } } diff --git a/rust/crates/truapi-coinage/src/recovery.rs b/rust/crates/truapi-coinage/src/recovery.rs index c7f2773354..61a0d39001 100644 --- a/rust/crates/truapi-coinage/src/recovery.rs +++ b/rust/crates/truapi-coinage/src/recovery.rs @@ -2,1295 +2,1096 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use async_trait::async_trait; use tracing::warn; -use crate::model::{ - Coin, CoinState, Voucher, VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState, +use crate::{ + model::{Coin, CoinState, Voucher, VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}, + repo::{CoinRepository, VoucherRepository}, + wal::{TransferWalEntry, WalOperation, WalStore}, }; -use crate::repo::{CoinRepository, VoucherRepository}; -use crate::wal::{TransferWalEntry, WalOperation, WalStore}; /// The chain-lookup effect. Presence answers are positional (same order /// as the input indices); implementations typically batch these through /// `chain::get_head_storage`. #[async_trait] pub trait RecoveryChainProbe: Send + Sync { - /// Current finalized head number. - async fn finalized_block(&self) -> Result; + /// Current finalized head number. + async fn finalized_block(&self) -> Result; - /// Canonical block hash at a height; `None` when unavailable. - async fn canonical_hash(&self, block_number: u64) -> Result, String>; + /// Canonical block hash at a height; `None` when unavailable. + async fn canonical_hash(&self, block_number: u64) -> Result, String>; - /// Whether each coin derivation index currently has an on-chain - /// `CoinsByOwner` entry. - async fn coins_present(&self, derivation_indices: &[u32]) -> Result, String>; + /// Whether each coin derivation index currently has an on-chain + /// `CoinsByOwner` entry. + async fn coins_present(&self, derivation_indices: &[u32]) -> Result, String>; - /// Exact denomination at the finalized snapshot of this recovery sweep. - /// Responses are positional and must cover every requested index. `None` - /// proves absence; query errors or truncated batches are not absence. - async fn coin_exponents(&self, derivation_indices: &[u32]) -> Result>, String>; + /// Exact denomination at the finalized snapshot of this recovery sweep. + /// Responses are positional and must cover every requested index. `None` + /// proves absence; query errors or truncated batches are not absence. + async fn coin_exponents(&self, derivation_indices: &[u32]) -> Result>, String>; - /// Whether each voucher derivation index is currently present - /// on-chain (in a recycler / member set). - async fn vouchers_present(&self, derivation_indices: &[u32]) -> Result, String>; + /// Whether each voucher derivation index is currently present + /// on-chain (in a recycler / member set). + async fn vouchers_present(&self, derivation_indices: &[u32]) -> Result, String>; } /// One sweep's outcome. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct RecoveryReport { - /// Entries whose extrinsic landed (outputs materialized). - pub landed: usize, - /// Entries resolved by input consumption without visible outputs. - pub inputs_consumed: usize, - /// Entries dead (expired / forked / never broadcast) — inputs - /// reverted. - pub reverted: usize, - /// Entries left journaled for the next sweep. - pub still_pending: usize, - pub orphans_restored: usize, - pub orphans_deleted: usize, + /// Entries whose extrinsic landed (outputs materialized). + pub landed: usize, + /// Entries resolved by input consumption without visible outputs. + pub inputs_consumed: usize, + /// Entries dead (expired / forked / never broadcast) — inputs + /// reverted. + pub reverted: usize, + /// Entries left journaled for the next sweep. + pub still_pending: usize, + pub orphans_restored: usize, + pub orphans_deleted: usize, } pub struct TransferRecoveryService { - wal: Arc, - coins: Arc, - vouchers: Arc, - probe: Arc, + wal: Arc, + coins: Arc, + vouchers: Arc, + probe: Arc, } impl TransferRecoveryService { - pub fn new( - wal: Arc, - coins: Arc, - vouchers: Arc, - probe: Arc, - ) -> Self { - Self { - wal, - coins, - vouchers, - probe, - } - } + pub fn new( + wal: Arc, + coins: Arc, + vouchers: Arc, + probe: Arc, + ) -> Self { + Self { wal, coins, vouchers, probe } + } - /// One recovery pass: resolve every WAL entry, then sweep orphans. - /// Never guesses a terminal state for money in flight — an entry - /// stays pending until the chain proves it landed or died. - pub async fn recover(&self) -> Result { - let entries = self.wal.load_all().await?; - let finalized = self.probe.finalized_block().await?; - let mut report = RecoveryReport::default(); - let parents = entries - .iter() - .filter(|entry| entry.operation.is_transfer_receipt()) - .map(|entry| (entry.entry_id.as_str(), entry.operation)) - .collect::>(); + /// One recovery pass: resolve every WAL entry, then sweep orphans. + /// Never guesses a terminal state for money in flight — an entry + /// stays pending until the chain proves it landed or died. + pub async fn recover(&self) -> Result { + let entries = self.wal.load_all().await?; + let finalized = self.probe.finalized_block().await?; + let mut report = RecoveryReport::default(); + let parents = entries + .iter() + .filter(|entry| entry.operation.is_transfer_receipt()) + .map(|entry| (entry.entry_id.as_str(), entry.operation)) + .collect::>(); - for entry in &entries { - let parent = entry.operation_parent_id(); - let parent_state = parent.as_deref().and_then(|id| parents.get(id)).copied(); - match self.resolve_entry(entry, finalized, parent_state).await { - Ok(Resolution::Landed) => report.landed += 1, - Ok(Resolution::InputsConsumed) => report.inputs_consumed += 1, - Ok(Resolution::Reverted) => report.reverted += 1, - Ok(Resolution::StillPending) => report.still_pending += 1, - Ok(Resolution::Receipt) => {} - Err(error) => { - warn!( - error, - entry_id = entry.entry_id, - "wal recovery probe failed" - ); - report.still_pending += 1; - } - } - } + for entry in &entries { + let parent = entry.operation_parent_id(); + let parent_state = parent.as_deref().and_then(|id| parents.get(id)).copied(); + match self.resolve_entry(entry, finalized, parent_state).await { + Ok(Resolution::Landed) => report.landed += 1, + Ok(Resolution::InputsConsumed) => report.inputs_consumed += 1, + Ok(Resolution::Reverted) => report.reverted += 1, + Ok(Resolution::StillPending) => report.still_pending += 1, + Ok(Resolution::Receipt) => {}, + Err(error) => { + warn!(error, entry_id = entry.entry_id, "wal recovery probe failed"); + report.still_pending += 1; + }, + } + } - let remaining = self.wal.load_all().await?; - for parent in remaining - .iter() - .filter(|entry| entry.operation == WalOperation::TransferAccepted) - { - if !remaining.iter().any(|entry| { - entry.entry_id != parent.entry_id - && entry.operation_parent_id().as_deref() == Some(parent.entry_id.as_str()) - }) { - let mut completed = parent.clone(); - completed.operation = WalOperation::TransferCompleted; - self.wal.save(&completed).await?; - } - } - let (protected_coins, protected_vouchers) = referenced_indices(&remaining); + let remaining = self.wal.load_all().await?; + for parent in remaining + .iter() + .filter(|entry| entry.operation == WalOperation::TransferAccepted) + { + if !remaining.iter().any(|entry| { + entry.entry_id != parent.entry_id && + entry.operation_parent_id().as_deref() == Some(parent.entry_id.as_str()) + }) { + let mut completed = parent.clone(); + completed.operation = WalOperation::TransferCompleted; + self.wal.save(&completed).await?; + } + } + let (protected_coins, protected_vouchers) = referenced_indices(&remaining); - for coin in self.coins.list().await? { - let orphaned = matches!( - coin.state, - CoinState::PendingTransfer | CoinState::Recycling - ) && !protected_coins.contains(&coin.derivation_index); - if orphaned { - self.coins - .set_state(coin.derivation_index, CoinState::Available) - .await?; - report.orphans_restored += 1; - } - } - for voucher in self.vouchers.list().await? { - if protected_vouchers.contains(&voucher.derivation_index) { - continue; - } - match voucher.local_state { - VoucherLocalState::PendingTransfer => { - self.vouchers - .set_local_state(voucher.derivation_index, VoucherLocalState::Available) - .await?; - report.orphans_restored += 1; - } - VoucherLocalState::PendingOnboarding => { - self.vouchers.remove(voucher.derivation_index).await?; - report.orphans_deleted += 1; - } - _ => {} - } - } - Ok(report) - } + for coin in self.coins.list().await? { + let orphaned = matches!(coin.state, CoinState::PendingTransfer | CoinState::Recycling) && + !protected_coins.contains(&coin.derivation_index); + if orphaned { + self.coins.set_state(coin.derivation_index, CoinState::Available).await?; + report.orphans_restored += 1; + } + } + for voucher in self.vouchers.list().await? { + if protected_vouchers.contains(&voucher.derivation_index) { + continue; + } + match voucher.local_state { + VoucherLocalState::PendingTransfer => { + self.vouchers + .set_local_state(voucher.derivation_index, VoucherLocalState::Available) + .await?; + report.orphans_restored += 1; + }, + VoucherLocalState::PendingOnboarding => { + self.vouchers.remove(voucher.derivation_index).await?; + report.orphans_deleted += 1; + }, + _ => {}, + } + } + Ok(report) + } - async fn resolve_entry( - &self, - entry: &TransferWalEntry, - finalized: u64, - parent_state: Option, - ) -> Result { - if entry.operation.is_transfer_receipt() { - // Receipts preserve idempotency after children disappear. Prepared - // is deliberately not interpreted as accepted or rejected. - return Ok(Resolution::Receipt); - } - let correlated = entry.operation_parent_id().is_some(); - if correlated { - match parent_state { - Some(WalOperation::TransferRejected) - if matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) => - { - self.revert_inputs(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::Reverted); - } - Some(WalOperation::TransferAccepted) => {} - // Missing/ambiguous parent evidence must never unlock inputs. - _ => return Ok(Resolution::StillPending), - } - } - let dead = match entry.checkpoint { - crate::wal::CheckpointBlock::Pending => true, - crate::wal::CheckpointBlock::Known { number, .. } => { - let canonical = self.probe.canonical_hash(number).await?; - entry.is_forked(canonical.as_ref()) || entry.is_expired(finalized) - } - }; + async fn resolve_entry( + &self, + entry: &TransferWalEntry, + finalized: u64, + parent_state: Option, + ) -> Result { + if entry.operation.is_transfer_receipt() { + // Receipts preserve idempotency after children disappear. Prepared + // is deliberately not interpreted as accepted or rejected. + return Ok(Resolution::Receipt); + } + let correlated = entry.operation_parent_id().is_some(); + if correlated { + match parent_state { + Some(WalOperation::TransferRejected) + if matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) => + { + self.revert_inputs(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::Reverted); + }, + Some(WalOperation::TransferAccepted) => {}, + // Missing/ambiguous parent evidence must never unlock inputs. + _ => return Ok(Resolution::StillPending), + } + } + let dead = match entry.checkpoint { + crate::wal::CheckpointBlock::Pending => true, + crate::wal::CheckpointBlock::Known { number, .. } => { + let canonical = self.probe.canonical_hash(number).await?; + entry.is_forked(canonical.as_ref()) || entry.is_expired(finalized) + }, + }; - match entry.operation { - // A handed-off expanded secret never expires. The recipient - // may claim it long after an extrinsic mortality window, so - // presence always remains reserved and only all-input absence - // is terminal. - WalOperation::SecretHandoff => { - if correlated || self.inputs_consumed(entry).await? { - self.retire_inputs(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::InputsConsumed); - } - Ok(Resolution::StillPending) - } - WalOperation::IntoCoins | WalOperation::Split => { - if !matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) { - let output_indices: Vec = entry - .payload - .output_coins - .iter() - .map(|c| c.derivation_index) - .collect(); - let outputs = if correlated { - let exponents = self.probe.coin_exponents(&output_indices).await?; - if exponents.len() != output_indices.len() { - return Err("coin recovery probe returned an incomplete batch".into()); - } - if exponents.iter().zip(&entry.payload.output_coins).any( - |(actual, expected)| { - actual.is_some_and(|exponent| exponent != expected.exponent) - }, - ) { - return Err( - "recovered output denomination differs from the approved plan" - .into(), - ); - } - exponents - .into_iter() - .map(|exponent| exponent.is_some()) - .collect::>() - } else { - self.probe.coins_present(&output_indices).await? - }; - if outputs.len() != output_indices.len() { - return Err("coin recovery probe returned an incomplete batch".into()); - } - let landed = if correlated { - !outputs.is_empty() && outputs.iter().all(|present| *present) - } else { - outputs.iter().any(|present| *present) - }; - if correlated - && outputs.iter().any(|present| *present) - && (!landed || !self.inputs_consumed(entry).await?) - { - // Partial/mixed evidence cannot certify this allocation - // and must never authorize rebroadcast after mortality. - return Ok(Resolution::StillPending); - } - if landed { - // Landed: materialize outputs, retire inputs. - for (reference, present) in entry.payload.output_coins.iter().zip(&outputs) - { - if *present { - let destination = - entry.payload.destination_coins.iter().any(|coin| { - coin.derivation_index == reference.derivation_index - }); - self.coins - .upsert(&Coin { - exponent: reference.exponent, - derivation_index: reference.derivation_index, - age: None, - state: if destination { - CoinState::Spent - } else { - CoinState::Available - }, - }) - .await?; - } - } - self.retire_transfer_inputs(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::Landed); - } - if self.inputs_consumed(entry).await? { - if correlated { - // Consumption alone does not prove this operation - // produced its promised outputs. Retain the receipt - // and checkpoint rather than reporting completion. - return Ok(Resolution::StillPending); - } - self.retire_transfer_inputs(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::InputsConsumed); - } - } - if dead { - if correlated { - // Keep the SAME allocated outputs and input reservation. - // Only explicit host resume may recreate the extrinsic. - // Mixed input presence is ambiguous, not permission to - // spend the remaining inputs in a second transaction. - if matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) - || self.inputs_present(entry).await? - { - self.wal - .update_checkpoint( - &entry.entry_id, - crate::wal::CheckpointBlock::Pending, - ) - .await?; - } - return Ok(Resolution::StillPending); - } - self.revert_inputs(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::Reverted); - } - Ok(Resolution::StillPending) - } - WalOperation::IntoExternalAsset => { - if !matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) - && self.inputs_consumed(entry).await? - { - self.retire_inputs(entry).await?; - self.confirm_surplus_vouchers(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::InputsConsumed); - } - if dead { - self.revert_inputs(entry).await?; - self.delete_surplus_vouchers(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::Reverted); - } - Ok(Resolution::StillPending) - } - WalOperation::RecycleIntoVoucher => { - if !matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) - && self.inputs_consumed(entry).await? - { - self.retire_inputs(entry).await?; - self.confirm_surplus_vouchers(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::Landed); - } - if dead { - self.revert_inputs(entry).await?; - self.delete_surplus_vouchers(entry).await?; - self.wal.delete(&entry.entry_id).await?; - return Ok(Resolution::Reverted); - } - Ok(Resolution::StillPending) - } - WalOperation::TransferPrepared - | WalOperation::TransferAccepted - | WalOperation::TransferCompleted - | WalOperation::TransferRejected => Ok(Resolution::Receipt), - } - } + match entry.operation { + // A handed-off expanded secret never expires. The recipient + // may claim it long after an extrinsic mortality window, so + // presence always remains reserved and only all-input absence + // is terminal. + WalOperation::SecretHandoff => { + if correlated || self.inputs_consumed(entry).await? { + self.retire_inputs(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::InputsConsumed); + } + Ok(Resolution::StillPending) + }, + WalOperation::IntoCoins | WalOperation::Split => { + if !matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) { + let output_indices: Vec = + entry.payload.output_coins.iter().map(|c| c.derivation_index).collect(); + let outputs = if correlated { + let exponents = self.probe.coin_exponents(&output_indices).await?; + if exponents.len() != output_indices.len() { + return Err("coin recovery probe returned an incomplete batch".into()); + } + if exponents.iter().zip(&entry.payload.output_coins).any( + |(actual, expected)| { + actual.is_some_and(|exponent| exponent != expected.exponent) + }, + ) { + return Err( + "recovered output denomination differs from the approved plan" + .into(), + ); + } + exponents.into_iter().map(|exponent| exponent.is_some()).collect::>() + } else { + self.probe.coins_present(&output_indices).await? + }; + if outputs.len() != output_indices.len() { + return Err("coin recovery probe returned an incomplete batch".into()); + } + let landed = if correlated { + !outputs.is_empty() && outputs.iter().all(|present| *present) + } else { + outputs.iter().any(|present| *present) + }; + if correlated && + outputs.iter().any(|present| *present) && + (!landed || !self.inputs_consumed(entry).await?) + { + // Partial/mixed evidence cannot certify this allocation + // and must never authorize rebroadcast after mortality. + return Ok(Resolution::StillPending); + } + if landed { + // Landed: materialize outputs, retire inputs. + for (reference, present) in entry.payload.output_coins.iter().zip(&outputs) + { + if *present { + let destination = + entry.payload.destination_coins.iter().any(|coin| { + coin.derivation_index == reference.derivation_index + }); + self.coins + .upsert(&Coin { + exponent: reference.exponent, + derivation_index: reference.derivation_index, + age: None, + state: if destination { + CoinState::Spent + } else { + CoinState::Available + }, + }) + .await?; + } + } + self.retire_transfer_inputs(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::Landed); + } + if self.inputs_consumed(entry).await? { + if correlated { + // Consumption alone does not prove this operation + // produced its promised outputs. Retain the receipt + // and checkpoint rather than reporting completion. + return Ok(Resolution::StillPending); + } + self.retire_transfer_inputs(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::InputsConsumed); + } + } + if dead { + if correlated { + // Keep the SAME allocated outputs and input reservation. + // Only explicit host resume may recreate the extrinsic. + // Mixed input presence is ambiguous, not permission to + // spend the remaining inputs in a second transaction. + if matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) || + self.inputs_present(entry).await? + { + self.wal + .update_checkpoint( + &entry.entry_id, + crate::wal::CheckpointBlock::Pending, + ) + .await?; + } + return Ok(Resolution::StillPending); + } + self.revert_inputs(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::Reverted); + } + Ok(Resolution::StillPending) + }, + WalOperation::IntoExternalAsset => { + if !matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) && + self.inputs_consumed(entry).await? + { + self.retire_inputs(entry).await?; + self.confirm_surplus_vouchers(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::InputsConsumed); + } + if dead { + self.revert_inputs(entry).await?; + self.delete_surplus_vouchers(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::Reverted); + } + Ok(Resolution::StillPending) + }, + WalOperation::RecycleIntoVoucher => { + if !matches!(entry.checkpoint, crate::wal::CheckpointBlock::Pending) && + self.inputs_consumed(entry).await? + { + self.retire_inputs(entry).await?; + self.confirm_surplus_vouchers(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::Landed); + } + if dead { + self.revert_inputs(entry).await?; + self.delete_surplus_vouchers(entry).await?; + self.wal.delete(&entry.entry_id).await?; + return Ok(Resolution::Reverted); + } + Ok(Resolution::StillPending) + }, + WalOperation::TransferPrepared | + WalOperation::TransferAccepted | + WalOperation::TransferCompleted | + WalOperation::TransferRejected => Ok(Resolution::Receipt), + } + } - async fn inputs_consumed(&self, entry: &TransferWalEntry) -> Result { - let coin_indices: Vec = entry - .payload - .input_coins - .iter() - .map(|c| c.derivation_index) - .collect(); - let voucher_indices: Vec = entry - .payload - .input_vouchers - .iter() - .map(|v| v.derivation_index) - .collect(); - if coin_indices.is_empty() && voucher_indices.is_empty() { - return Ok(false); - } - let coins = self.probe.coins_present(&coin_indices).await?; - let vouchers = self.probe.vouchers_present(&voucher_indices).await?; - if coins.len() != coin_indices.len() || vouchers.len() != voucher_indices.len() { - return Err("input recovery probe returned an incomplete batch".into()); - } - Ok(coins.iter().all(|present| !present) && vouchers.iter().all(|present| !present)) - } + async fn inputs_consumed(&self, entry: &TransferWalEntry) -> Result { + let coin_indices: Vec = + entry.payload.input_coins.iter().map(|c| c.derivation_index).collect(); + let voucher_indices: Vec = + entry.payload.input_vouchers.iter().map(|v| v.derivation_index).collect(); + if coin_indices.is_empty() && voucher_indices.is_empty() { + return Ok(false); + } + let coins = self.probe.coins_present(&coin_indices).await?; + let vouchers = self.probe.vouchers_present(&voucher_indices).await?; + if coins.len() != coin_indices.len() || vouchers.len() != voucher_indices.len() { + return Err("input recovery probe returned an incomplete batch".into()); + } + Ok(coins.iter().all(|present| !present) && vouchers.iter().all(|present| !present)) + } - async fn inputs_present(&self, entry: &TransferWalEntry) -> Result { - let coin_indices = entry - .payload - .input_coins - .iter() - .map(|coin| coin.derivation_index) - .collect::>(); - let voucher_indices = entry - .payload - .input_vouchers - .iter() - .map(|voucher| voucher.derivation_index) - .collect::>(); - let coins = self.probe.coins_present(&coin_indices).await?; - let vouchers = self.probe.vouchers_present(&voucher_indices).await?; - if coins.len() != coin_indices.len() || vouchers.len() != voucher_indices.len() { - return Err("input recovery probe returned an incomplete batch".into()); - } - Ok(coins.iter().all(|present| *present) && vouchers.iter().all(|present| *present)) - } + async fn inputs_present(&self, entry: &TransferWalEntry) -> Result { + let coin_indices = entry + .payload + .input_coins + .iter() + .map(|coin| coin.derivation_index) + .collect::>(); + let voucher_indices = entry + .payload + .input_vouchers + .iter() + .map(|voucher| voucher.derivation_index) + .collect::>(); + let coins = self.probe.coins_present(&coin_indices).await?; + let vouchers = self.probe.vouchers_present(&voucher_indices).await?; + if coins.len() != coin_indices.len() || vouchers.len() != voucher_indices.len() { + return Err("input recovery probe returned an incomplete batch".into()); + } + Ok(coins.iter().all(|present| *present) && vouchers.iter().all(|present| *present)) + } - async fn retire_inputs(&self, entry: &TransferWalEntry) -> Result<(), String> { - for input in &entry.payload.input_coins { - self.coins - .set_state(input.derivation_index, CoinState::Spent) - .await?; - } - for input in &entry.payload.input_vouchers { - self.vouchers - .set_local_state(input.derivation_index, VoucherLocalState::Spent) - .await?; - } - Ok(()) - } + async fn retire_inputs(&self, entry: &TransferWalEntry) -> Result<(), String> { + for input in &entry.payload.input_coins { + self.coins.set_state(input.derivation_index, CoinState::Spent).await?; + } + for input in &entry.payload.input_vouchers { + self.vouchers + .set_local_state(input.derivation_index, VoucherLocalState::Spent) + .await?; + } + Ok(()) + } - /// Split/unload parity: consumed vouchers are removed from the local - /// purse rather than retained as spent tombstones. Destination outputs - /// remain spent rows so sync/monitoring can observe their lifecycle. - async fn retire_transfer_inputs(&self, entry: &TransferWalEntry) -> Result<(), String> { - for input in &entry.payload.input_coins { - self.coins - .set_state(input.derivation_index, CoinState::Spent) - .await?; - } - for input in &entry.payload.input_vouchers { - self.vouchers.remove(input.derivation_index).await?; - } - Ok(()) - } + /// Split/unload parity: consumed vouchers are removed from the local + /// purse rather than retained as spent tombstones. Destination outputs + /// remain spent rows so sync/monitoring can observe their lifecycle. + async fn retire_transfer_inputs(&self, entry: &TransferWalEntry) -> Result<(), String> { + for input in &entry.payload.input_coins { + self.coins.set_state(input.derivation_index, CoinState::Spent).await?; + } + for input in &entry.payload.input_vouchers { + self.vouchers.remove(input.derivation_index).await?; + } + Ok(()) + } - async fn revert_inputs(&self, entry: &TransferWalEntry) -> Result<(), String> { - for input in &entry.payload.input_coins { - self.coins - .set_state(input.derivation_index, CoinState::Available) - .await?; - } - for input in &entry.payload.input_vouchers { - self.vouchers - .set_local_state(input.derivation_index, VoucherLocalState::Available) - .await?; - } - Ok(()) - } + async fn revert_inputs(&self, entry: &TransferWalEntry) -> Result<(), String> { + for input in &entry.payload.input_coins { + self.coins.set_state(input.derivation_index, CoinState::Available).await?; + } + for input in &entry.payload.input_vouchers { + self.vouchers + .set_local_state(input.derivation_index, VoucherLocalState::Available) + .await?; + } + Ok(()) + } - async fn confirm_surplus_vouchers(&self, entry: &TransferWalEntry) -> Result<(), String> { - let indices: Vec = entry - .payload - .output_vouchers - .iter() - .map(|v| v.derivation_index) - .collect(); - if indices.is_empty() { - return Ok(()); - } - let present = self.probe.vouchers_present(&indices).await?; - let known: HashSet = self - .vouchers - .list() - .await? - .into_iter() - .map(|v| v.derivation_index) - .collect(); - for (reference, present) in entry.payload.output_vouchers.iter().zip(&present) { - if !*present { - continue; - } - if known.contains(&reference.derivation_index) { - self.vouchers - .set_local_state(reference.derivation_index, VoucherLocalState::Available) - .await?; - } else { - // Materialize a minimal record; the voucher location - // service reconciles remote state and readiness - self.vouchers - .upsert(&Voucher { - exponent: reference.exponent, - derivation_index: reference.derivation_index, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: VoucherRemoteState::Unlocated, - local_state: VoucherLocalState::Available, - privacy: VoucherPrivacyLevel::Degraded, - }) - .await?; - } - } - Ok(()) - } + async fn confirm_surplus_vouchers(&self, entry: &TransferWalEntry) -> Result<(), String> { + let indices: Vec = + entry.payload.output_vouchers.iter().map(|v| v.derivation_index).collect(); + if indices.is_empty() { + return Ok(()); + } + let present = self.probe.vouchers_present(&indices).await?; + let known: HashSet = + self.vouchers.list().await?.into_iter().map(|v| v.derivation_index).collect(); + for (reference, present) in entry.payload.output_vouchers.iter().zip(&present) { + if !*present { + continue; + } + if known.contains(&reference.derivation_index) { + self.vouchers + .set_local_state(reference.derivation_index, VoucherLocalState::Available) + .await?; + } else { + // Materialize a minimal record; the voucher location + // service reconciles remote state and readiness + self.vouchers + .upsert(&Voucher { + exponent: reference.exponent, + derivation_index: reference.derivation_index, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: VoucherRemoteState::Unlocated, + local_state: VoucherLocalState::Available, + privacy: VoucherPrivacyLevel::Degraded, + }) + .await?; + } + } + Ok(()) + } - async fn delete_surplus_vouchers(&self, entry: &TransferWalEntry) -> Result<(), String> { - for output in &entry.payload.output_vouchers { - self.vouchers.remove(output.derivation_index).await?; - } - Ok(()) - } + async fn delete_surplus_vouchers(&self, entry: &TransferWalEntry) -> Result<(), String> { + for output in &entry.payload.output_vouchers { + self.vouchers.remove(output.derivation_index).await?; + } + Ok(()) + } } enum Resolution { - Landed, - InputsConsumed, - Reverted, - StillPending, - Receipt, + Landed, + InputsConsumed, + Reverted, + StillPending, + Receipt, } /// The coin/voucher indices any journaled entry still references. fn referenced_indices(entries: &[TransferWalEntry]) -> (HashSet, HashSet) { - let mut coins = HashSet::new(); - let mut vouchers = HashSet::new(); - for entry in entries { - coins.extend(entry.payload.input_coins.iter().map(|c| c.derivation_index)); - vouchers.extend( - entry - .payload - .input_vouchers - .iter() - .map(|v| v.derivation_index), - ); - vouchers.extend( - entry - .payload - .output_vouchers - .iter() - .map(|v| v.derivation_index), - ); - } - (coins, vouchers) + let mut coins = HashSet::new(); + let mut vouchers = HashSet::new(); + for entry in entries { + coins.extend(entry.payload.input_coins.iter().map(|c| c.derivation_index)); + vouchers.extend(entry.payload.input_vouchers.iter().map(|v| v.derivation_index)); + vouchers.extend(entry.payload.output_vouchers.iter().map(|v| v.derivation_index)); + } + (coins, vouchers) } #[cfg(test)] mod tests { - use parking_lot::Mutex; + use parking_lot::Mutex; - use super::*; - use crate::repo::{InMemoryCoinRepository, InMemoryVoucherRepository}; - use crate::wal::{CheckpointBlock, WalCoinRef, WalPayload}; + use super::*; + use crate::{ + repo::{InMemoryCoinRepository, InMemoryVoucherRepository}, + wal::{CheckpointBlock, WalCoinRef, WalPayload}, + }; - /// In-memory WAL store for the sweep tests. - #[derive(Default)] - struct MemWal { - entries: Mutex>, - } + /// In-memory WAL store for the sweep tests. + #[derive(Default)] + struct MemWal { + entries: Mutex>, + } - #[async_trait] - impl WalStore for MemWal { - async fn save(&self, entry: &TransferWalEntry) -> Result<(), String> { - let mut entries = self.entries.lock(); - entries.retain(|existing| existing.entry_id != entry.entry_id); - entries.push(entry.clone()); - Ok(()) - } - async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String> { - let mut stored = self.entries.lock(); - stored.retain(|existing| { - !entries - .iter() - .any(|entry| entry.entry_id == existing.entry_id) - }); - stored.extend_from_slice(entries); - Ok(()) - } - async fn update_checkpoint( - &self, - entry_id: &str, - checkpoint: CheckpointBlock, - ) -> Result<(), String> { - let mut entries = self.entries.lock(); - let entry = entries - .iter_mut() - .find(|e| e.entry_id == entry_id) - .ok_or("wal entry not found")?; - entry.checkpoint = checkpoint; - Ok(()) - } - async fn load_all(&self) -> Result, String> { - Ok(self.entries.lock().clone()) - } - async fn delete(&self, entry_id: &str) -> Result<(), String> { - self.entries.lock().retain(|e| e.entry_id != entry_id); - Ok(()) - } - } + #[async_trait] + impl WalStore for MemWal { + async fn save(&self, entry: &TransferWalEntry) -> Result<(), String> { + let mut entries = self.entries.lock(); + entries.retain(|existing| existing.entry_id != entry.entry_id); + entries.push(entry.clone()); + Ok(()) + } + async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String> { + let mut stored = self.entries.lock(); + stored.retain(|existing| { + !entries.iter().any(|entry| entry.entry_id == existing.entry_id) + }); + stored.extend_from_slice(entries); + Ok(()) + } + async fn update_checkpoint( + &self, + entry_id: &str, + checkpoint: CheckpointBlock, + ) -> Result<(), String> { + let mut entries = self.entries.lock(); + let entry = entries + .iter_mut() + .find(|e| e.entry_id == entry_id) + .ok_or("wal entry not found")?; + entry.checkpoint = checkpoint; + Ok(()) + } + async fn load_all(&self) -> Result, String> { + Ok(self.entries.lock().clone()) + } + async fn delete(&self, entry_id: &str) -> Result<(), String> { + self.entries.lock().retain(|e| e.entry_id != entry_id); + Ok(()) + } + } - struct MockProbe { - finalized: u64, - canonical: Option<[u8; 32]>, - coins_on_chain: HashSet, - vouchers_on_chain: HashSet, - output_exponents: HashMap, - } + struct MockProbe { + finalized: u64, + canonical: Option<[u8; 32]>, + coins_on_chain: HashSet, + vouchers_on_chain: HashSet, + output_exponents: HashMap, + } - impl Default for MockProbe { - fn default() -> Self { - Self { - finalized: 100, - canonical: Some([1; 32]), - coins_on_chain: HashSet::new(), - vouchers_on_chain: HashSet::new(), - output_exponents: HashMap::new(), - } - } - } + impl Default for MockProbe { + fn default() -> Self { + Self { + finalized: 100, + canonical: Some([1; 32]), + coins_on_chain: HashSet::new(), + vouchers_on_chain: HashSet::new(), + output_exponents: HashMap::new(), + } + } + } - #[async_trait] - impl RecoveryChainProbe for MockProbe { - async fn finalized_block(&self) -> Result { - Ok(self.finalized) - } - async fn canonical_hash(&self, _block_number: u64) -> Result, String> { - Ok(self.canonical) - } - async fn coins_present(&self, indices: &[u32]) -> Result, String> { - Ok(indices - .iter() - .map(|i| self.coins_on_chain.contains(i)) - .collect()) - } - async fn coin_exponents(&self, indices: &[u32]) -> Result>, String> { - Ok(indices - .iter() - .map(|index| self.output_exponents.get(index).copied()) - .collect()) - } - async fn vouchers_present(&self, indices: &[u32]) -> Result, String> { - Ok(indices - .iter() - .map(|i| self.vouchers_on_chain.contains(i)) - .collect()) - } - } + #[async_trait] + impl RecoveryChainProbe for MockProbe { + async fn finalized_block(&self) -> Result { + Ok(self.finalized) + } + async fn canonical_hash(&self, _block_number: u64) -> Result, String> { + Ok(self.canonical) + } + async fn coins_present(&self, indices: &[u32]) -> Result, String> { + Ok(indices.iter().map(|i| self.coins_on_chain.contains(i)).collect()) + } + async fn coin_exponents(&self, indices: &[u32]) -> Result>, String> { + Ok(indices.iter().map(|index| self.output_exponents.get(index).copied()).collect()) + } + async fn vouchers_present(&self, indices: &[u32]) -> Result, String> { + Ok(indices.iter().map(|i| self.vouchers_on_chain.contains(i)).collect()) + } + } - fn coin(index: u32, state: CoinState) -> Coin { - Coin { - exponent: 1, - derivation_index: index, - age: Some(1), - state, - } - } + fn coin(index: u32, state: CoinState) -> Coin { + Coin { exponent: 1, derivation_index: index, age: Some(1), state } + } - fn service( - wal: Arc, - coins: Arc, - vouchers: Arc, - probe: MockProbe, - ) -> TransferRecoveryService { - TransferRecoveryService::new(wal, coins, vouchers, Arc::new(probe)) - } + fn service( + wal: Arc, + coins: Arc, + vouchers: Arc, + probe: MockProbe, + ) -> TransferRecoveryService { + TransferRecoveryService::new(wal, coins, vouchers, Arc::new(probe)) + } - fn into_coins_entry(checkpoint: CheckpointBlock) -> TransferWalEntry { - TransferWalEntry { - entry_id: "e1".into(), - operation: WalOperation::IntoCoins, - payload: WalPayload { - input_coins: vec![WalCoinRef { - derivation_index: 1, - exponent: 1, - }], - input_vouchers: vec![], - output_coins: vec![WalCoinRef { - derivation_index: 50, - exponent: 0, - }], - output_vouchers: vec![], - destination_coins: vec![], - }, - checkpoint, - created_at_ms: 0, - } - } + fn into_coins_entry(checkpoint: CheckpointBlock) -> TransferWalEntry { + TransferWalEntry { + entry_id: "e1".into(), + operation: WalOperation::IntoCoins, + payload: WalPayload { + input_coins: vec![WalCoinRef { derivation_index: 1, exponent: 1 }], + input_vouchers: vec![], + output_coins: vec![WalCoinRef { derivation_index: 50, exponent: 0 }], + output_vouchers: vec![], + destination_coins: vec![], + }, + checkpoint, + created_at_ms: 0, + } + } - async fn coin_state(repo: &InMemoryCoinRepository, index: u32) -> CoinState { - repo.list() - .await - .unwrap() - .into_iter() - .find(|c| c.derivation_index == index) - .unwrap() - .state - } + async fn coin_state(repo: &InMemoryCoinRepository, index: u32) -> CoinState { + repo.list() + .await + .unwrap() + .into_iter() + .find(|c| c.derivation_index == index) + .unwrap() + .state + } - /// A `Pending` checkpoint means the extrinsic never left the device: - /// the input coin reverts to `.available` and the entry is dropped. - #[tokio::test] - async fn crash_between_wal_write_and_broadcast_reverts_inputs() { - let wal = Arc::new(MemWal::default()); - wal.save(&into_coins_entry(CheckpointBlock::Pending)) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let vouchers = Arc::new(InMemoryVoucherRepository::default()); - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::clone(&vouchers), - MockProbe::default(), - ); + /// A `Pending` checkpoint means the extrinsic never left the device: + /// the input coin reverts to `.available` and the entry is dropped. + #[tokio::test] + async fn crash_between_wal_write_and_broadcast_reverts_inputs() { + let wal = Arc::new(MemWal::default()); + wal.save(&into_coins_entry(CheckpointBlock::Pending)).await.unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let vouchers = Arc::new(InMemoryVoucherRepository::default()); + let service = service( + Arc::clone(&wal), + Arc::clone(&coins), + Arc::clone(&vouchers), + MockProbe::default(), + ); - let report = service.recover().await.unwrap(); - assert_eq!(report.reverted, 1); - assert_eq!(coin_state(&coins, 1).await, CoinState::Available); - assert!(wal.load_all().await.unwrap().is_empty(), "entry retired"); - } + let report = service.recover().await.unwrap(); + assert_eq!(report.reverted, 1); + assert_eq!(coin_state(&coins, 1).await, CoinState::Available); + assert!(wal.load_all().await.unwrap().is_empty(), "entry retired"); + } - #[tokio::test] - async fn into_coins_landed_materializes_outputs_and_retires_inputs() { - let wal = Arc::new(MemWal::default()); - wal.save(&into_coins_entry(CheckpointBlock::Known { - number: 90, - hash: [1; 32], - })) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let vouchers = Arc::new(InMemoryVoucherRepository::default()); - let probe = MockProbe { - coins_on_chain: HashSet::from([50]), - ..MockProbe::default() - }; - let service = service(Arc::clone(&wal), Arc::clone(&coins), vouchers, probe); + #[tokio::test] + async fn into_coins_landed_materializes_outputs_and_retires_inputs() { + let wal = Arc::new(MemWal::default()); + wal.save(&into_coins_entry(CheckpointBlock::Known { number: 90, hash: [1; 32] })) + .await + .unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let vouchers = Arc::new(InMemoryVoucherRepository::default()); + let probe = MockProbe { coins_on_chain: HashSet::from([50]), ..MockProbe::default() }; + let service = service(Arc::clone(&wal), Arc::clone(&coins), vouchers, probe); - let report = service.recover().await.unwrap(); - assert_eq!(report.landed, 1); - assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); - let listed = coins.list().await.unwrap(); - let output = listed.iter().find(|c| c.derivation_index == 50).unwrap(); - assert_eq!(output.state, CoinState::Available); - assert_eq!(output.age, None, "age unknown until first sync"); - assert!(wal.load_all().await.unwrap().is_empty()); - } + let report = service.recover().await.unwrap(); + assert_eq!(report.landed, 1); + assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); + let listed = coins.list().await.unwrap(); + let output = listed.iter().find(|c| c.derivation_index == 50).unwrap(); + assert_eq!(output.state, CoinState::Available); + assert_eq!(output.age, None, "age unknown until first sync"); + assert!(wal.load_all().await.unwrap().is_empty()); + } - #[tokio::test] - async fn unload_recovery_removes_consumed_voucher_and_keeps_destination_spent() { - let wal = Arc::new(MemWal::default()); - wal.save(&TransferWalEntry { - entry_id: "unload".into(), - operation: WalOperation::IntoCoins, - payload: WalPayload { - input_coins: vec![], - input_vouchers: vec![WalCoinRef { - derivation_index: 10, - exponent: 2, - }], - output_coins: vec![WalCoinRef { - derivation_index: 50, - exponent: 2, - }], - output_vouchers: vec![], - destination_coins: vec![WalCoinRef { - derivation_index: 50, - exponent: 2, - }], - }, - checkpoint: CheckpointBlock::Known { - number: 90, - hash: [1; 32], - }, - created_at_ms: 0, - }) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::default()); - let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([Voucher { - exponent: 2, - derivation_index: 10, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: VoucherRemoteState::InRecycler { recycler_index: 1 }, - local_state: VoucherLocalState::PendingTransfer, - privacy: VoucherPrivacyLevel::Full, - }])); - let probe = MockProbe { - coins_on_chain: HashSet::from([50]), - ..MockProbe::default() - }; - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::clone(&vouchers), - probe, - ); - let report = service.recover().await.unwrap(); - assert_eq!(report.landed, 1); - assert!(vouchers.list().await.unwrap().is_empty()); - assert_eq!(coin_state(&coins, 50).await, CoinState::Spent); - assert!(wal.load_all().await.unwrap().is_empty()); - } + #[tokio::test] + async fn unload_recovery_removes_consumed_voucher_and_keeps_destination_spent() { + let wal = Arc::new(MemWal::default()); + wal.save(&TransferWalEntry { + entry_id: "unload".into(), + operation: WalOperation::IntoCoins, + payload: WalPayload { + input_coins: vec![], + input_vouchers: vec![WalCoinRef { derivation_index: 10, exponent: 2 }], + output_coins: vec![WalCoinRef { derivation_index: 50, exponent: 2 }], + output_vouchers: vec![], + destination_coins: vec![WalCoinRef { derivation_index: 50, exponent: 2 }], + }, + checkpoint: CheckpointBlock::Known { number: 90, hash: [1; 32] }, + created_at_ms: 0, + }) + .await + .unwrap(); + let coins = Arc::new(InMemoryCoinRepository::default()); + let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([Voucher { + exponent: 2, + derivation_index: 10, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: VoucherRemoteState::InRecycler { recycler_index: 1 }, + local_state: VoucherLocalState::PendingTransfer, + privacy: VoucherPrivacyLevel::Full, + }])); + let probe = MockProbe { coins_on_chain: HashSet::from([50]), ..MockProbe::default() }; + let service = service(Arc::clone(&wal), Arc::clone(&coins), Arc::clone(&vouchers), probe); + let report = service.recover().await.unwrap(); + assert_eq!(report.landed, 1); + assert!(vouchers.list().await.unwrap().is_empty()); + assert_eq!(coin_state(&coins, 50).await, CoinState::Spent); + assert!(wal.load_all().await.unwrap().is_empty()); + } - #[tokio::test] - async fn forked_checkpoint_reverts_immediately() { - let wal = Arc::new(MemWal::default()); - wal.save(&into_coins_entry(CheckpointBlock::Known { - number: 90, - hash: [9; 32], // stored hash ≠ canonical [1; 32] - })) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let probe = MockProbe { - // Input still on-chain (not consumed), output absent, - // finalized 100 < 90 + 300 (not expired) — ONLY the fork - // can resolve this entry. - coins_on_chain: HashSet::from([1]), - ..MockProbe::default() - }; - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::new(InMemoryVoucherRepository::default()), - probe, - ); + #[tokio::test] + async fn forked_checkpoint_reverts_immediately() { + let wal = Arc::new(MemWal::default()); + wal.save(&into_coins_entry(CheckpointBlock::Known { + number: 90, + hash: [9; 32], // stored hash ≠ canonical [1; 32] + })) + .await + .unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let probe = MockProbe { + // Input still on-chain (not consumed), output absent, + // finalized 100 < 90 + 300 (not expired) — ONLY the fork + // can resolve this entry. + coins_on_chain: HashSet::from([1]), + ..MockProbe::default() + }; + let service = service( + Arc::clone(&wal), + Arc::clone(&coins), + Arc::new(InMemoryVoucherRepository::default()), + probe, + ); - let report = service.recover().await.unwrap(); - assert_eq!(report.reverted, 1); - assert_eq!(coin_state(&coins, 1).await, CoinState::Available); - } + let report = service.recover().await.unwrap(); + assert_eq!(report.reverted, 1); + assert_eq!(coin_state(&coins, 1).await, CoinState::Available); + } - #[tokio::test] - async fn unresolved_entry_stays_pending() { - let wal = Arc::new(MemWal::default()); - wal.save(&into_coins_entry(CheckpointBlock::Known { - number: 90, - hash: [1; 32], - })) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let probe = MockProbe { - // Input still on-chain, output absent, not expired. - coins_on_chain: HashSet::from([1]), - ..MockProbe::default() - }; - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::new(InMemoryVoucherRepository::default()), - probe, - ); + #[tokio::test] + async fn unresolved_entry_stays_pending() { + let wal = Arc::new(MemWal::default()); + wal.save(&into_coins_entry(CheckpointBlock::Known { number: 90, hash: [1; 32] })) + .await + .unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let probe = MockProbe { + // Input still on-chain, output absent, not expired. + coins_on_chain: HashSet::from([1]), + ..MockProbe::default() + }; + let service = service( + Arc::clone(&wal), + Arc::clone(&coins), + Arc::new(InMemoryVoucherRepository::default()), + probe, + ); - let report = service.recover().await.unwrap(); - assert_eq!(report.still_pending, 1); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - assert_eq!(wal.load_all().await.unwrap().len(), 1); - } + let report = service.recover().await.unwrap(); + assert_eq!(report.still_pending, 1); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + assert_eq!(wal.load_all().await.unwrap().len(), 1); + } - #[tokio::test] - async fn expired_entry_reverts_inputs() { - let wal = Arc::new(MemWal::default()); - wal.save(&into_coins_entry(CheckpointBlock::Known { - number: 90, - hash: [1; 32], - })) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let probe = MockProbe { - finalized: 391, // > 90 + 300 - coins_on_chain: HashSet::from([1]), - ..MockProbe::default() - }; - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::new(InMemoryVoucherRepository::default()), - probe, - ); - let report = service.recover().await.unwrap(); - assert_eq!(report.reverted, 1); - assert_eq!(coin_state(&coins, 1).await, CoinState::Available); - } + #[tokio::test] + async fn expired_entry_reverts_inputs() { + let wal = Arc::new(MemWal::default()); + wal.save(&into_coins_entry(CheckpointBlock::Known { number: 90, hash: [1; 32] })) + .await + .unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let probe = MockProbe { + finalized: 391, // > 90 + 300 + coins_on_chain: HashSet::from([1]), + ..MockProbe::default() + }; + let service = service( + Arc::clone(&wal), + Arc::clone(&coins), + Arc::new(InMemoryVoucherRepository::default()), + probe, + ); + let report = service.recover().await.unwrap(); + assert_eq!(report.reverted, 1); + assert_eq!(coin_state(&coins, 1).await, CoinState::Available); + } - #[tokio::test] - async fn recycle_into_voucher_confirms_the_surplus_voucher() { - use crate::model::{VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}; - let wal = Arc::new(MemWal::default()); - wal.save(&TransferWalEntry { - entry_id: "r1".into(), - operation: WalOperation::RecycleIntoVoucher, - payload: WalPayload { - input_coins: vec![WalCoinRef { - derivation_index: 1, - exponent: 1, - }], - input_vouchers: vec![], - output_coins: vec![], - output_vouchers: vec![WalCoinRef { - derivation_index: 70, - exponent: 1, - }], - destination_coins: vec![], - }, - checkpoint: CheckpointBlock::Known { - number: 90, - hash: [1; 32], - }, - created_at_ms: 0, - }) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::Recycling, - )])); - let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([Voucher { - exponent: 1, - derivation_index: 70, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: VoucherRemoteState::Onboarding, - local_state: VoucherLocalState::PendingOnboarding, - privacy: VoucherPrivacyLevel::Full, - }])); - let probe = MockProbe { - vouchers_on_chain: HashSet::from([70]), - // Input coin 1 absent → consumed. - ..MockProbe::default() - }; - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::clone(&vouchers), - probe, - ); + #[tokio::test] + async fn recycle_into_voucher_confirms_the_surplus_voucher() { + use crate::model::{VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}; + let wal = Arc::new(MemWal::default()); + wal.save(&TransferWalEntry { + entry_id: "r1".into(), + operation: WalOperation::RecycleIntoVoucher, + payload: WalPayload { + input_coins: vec![WalCoinRef { derivation_index: 1, exponent: 1 }], + input_vouchers: vec![], + output_coins: vec![], + output_vouchers: vec![WalCoinRef { derivation_index: 70, exponent: 1 }], + destination_coins: vec![], + }, + checkpoint: CheckpointBlock::Known { number: 90, hash: [1; 32] }, + created_at_ms: 0, + }) + .await + .unwrap(); + let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::Recycling)])); + let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([Voucher { + exponent: 1, + derivation_index: 70, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: VoucherRemoteState::Onboarding, + local_state: VoucherLocalState::PendingOnboarding, + privacy: VoucherPrivacyLevel::Full, + }])); + let probe = MockProbe { + vouchers_on_chain: HashSet::from([70]), + // Input coin 1 absent → consumed. + ..MockProbe::default() + }; + let service = service(Arc::clone(&wal), Arc::clone(&coins), Arc::clone(&vouchers), probe); - let report = service.recover().await.unwrap(); - assert_eq!(report.landed, 1); - assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); - assert_eq!( - vouchers.list().await.unwrap()[0].local_state, - VoucherLocalState::Available - ); - } + let report = service.recover().await.unwrap(); + assert_eq!(report.landed, 1); + assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); + assert_eq!(vouchers.list().await.unwrap()[0].local_state, VoucherLocalState::Available); + } - #[tokio::test] - async fn orphaned_pending_assets_are_restored_or_deleted() { - use crate::model::{VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}; - let coins = Arc::new(InMemoryCoinRepository::with_coins([ - coin(1, CoinState::PendingTransfer), - coin(2, CoinState::Recycling), - coin(3, CoinState::Spent), - ])); - let orphan_voucher = |index, local_state| Voucher { - exponent: 0, - derivation_index: index, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: VoucherRemoteState::Unlocated, - local_state, - privacy: VoucherPrivacyLevel::Full, - }; - let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([ - orphan_voucher(10, VoucherLocalState::PendingTransfer), - orphan_voucher(11, VoucherLocalState::PendingOnboarding), - ])); - let service = service( - Arc::new(MemWal::default()), - Arc::clone(&coins), - Arc::clone(&vouchers), - MockProbe::default(), - ); + #[tokio::test] + async fn orphaned_pending_assets_are_restored_or_deleted() { + use crate::model::{VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}; + let coins = Arc::new(InMemoryCoinRepository::with_coins([ + coin(1, CoinState::PendingTransfer), + coin(2, CoinState::Recycling), + coin(3, CoinState::Spent), + ])); + let orphan_voucher = |index, local_state| Voucher { + exponent: 0, + derivation_index: index, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: VoucherRemoteState::Unlocated, + local_state, + privacy: VoucherPrivacyLevel::Full, + }; + let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([ + orphan_voucher(10, VoucherLocalState::PendingTransfer), + orphan_voucher(11, VoucherLocalState::PendingOnboarding), + ])); + let service = service( + Arc::new(MemWal::default()), + Arc::clone(&coins), + Arc::clone(&vouchers), + MockProbe::default(), + ); - let report = service.recover().await.unwrap(); - assert_eq!(report.orphans_restored, 3, "two coins + one voucher"); - assert_eq!(report.orphans_deleted, 1, "pending-onboarding voucher"); - assert_eq!(coin_state(&coins, 1).await, CoinState::Available); - assert_eq!(coin_state(&coins, 2).await, CoinState::Available); - assert_eq!( - coin_state(&coins, 3).await, - CoinState::Spent, - "spent untouched" - ); - let listed = vouchers.list().await.unwrap(); - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].derivation_index, 10); - assert_eq!(listed[0].local_state, VoucherLocalState::Available); - } + let report = service.recover().await.unwrap(); + assert_eq!(report.orphans_restored, 3, "two coins + one voucher"); + assert_eq!(report.orphans_deleted, 1, "pending-onboarding voucher"); + assert_eq!(coin_state(&coins, 1).await, CoinState::Available); + assert_eq!(coin_state(&coins, 2).await, CoinState::Available); + assert_eq!(coin_state(&coins, 3).await, CoinState::Spent, "spent untouched"); + let listed = vouchers.list().await.unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].derivation_index, 10); + assert_eq!(listed[0].local_state, VoucherLocalState::Available); + } - /// A journaled still-pending entry PROTECTS its assets from the - /// orphan sweep. - #[tokio::test] - async fn journaled_assets_are_not_swept_as_orphans() { - let wal = Arc::new(MemWal::default()); - wal.save(&into_coins_entry(CheckpointBlock::Known { - number: 90, - hash: [1; 32], - })) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let probe = MockProbe { - coins_on_chain: HashSet::from([1]), // unresolved - ..MockProbe::default() - }; - let service = service( - wal, - Arc::clone(&coins), - Arc::new(InMemoryVoucherRepository::default()), - probe, - ); - let report = service.recover().await.unwrap(); - assert_eq!(report.orphans_restored, 0); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - } + /// A journaled still-pending entry PROTECTS its assets from the + /// orphan sweep. + #[tokio::test] + async fn journaled_assets_are_not_swept_as_orphans() { + let wal = Arc::new(MemWal::default()); + wal.save(&into_coins_entry(CheckpointBlock::Known { number: 90, hash: [1; 32] })) + .await + .unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let probe = MockProbe { + coins_on_chain: HashSet::from([1]), // unresolved + ..MockProbe::default() + }; + let service = + service(wal, Arc::clone(&coins), Arc::new(InMemoryVoucherRepository::default()), probe); + let report = service.recover().await.unwrap(); + assert_eq!(report.orphans_restored, 0); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + } - /// Expanded secrets have no mortality. Even a very old pending - /// checkpoint remains protected while its coin is present. - #[tokio::test] - async fn secret_handoff_never_mortality_reverts_a_present_coin() { - let wal = Arc::new(MemWal::default()); - wal.save(&TransferWalEntry { - entry_id: "secret-1".into(), - operation: WalOperation::SecretHandoff, - payload: WalPayload { - input_coins: vec![WalCoinRef { - derivation_index: 1, - exponent: 1, - }], - ..WalPayload::default() - }, - checkpoint: CheckpointBlock::Pending, - created_at_ms: 0, - }) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::new(InMemoryVoucherRepository::default()), - MockProbe { - finalized: u64::MAX, - coins_on_chain: HashSet::from([1]), - ..MockProbe::default() - }, - ); + /// Expanded secrets have no mortality. Even a very old pending + /// checkpoint remains protected while its coin is present. + #[tokio::test] + async fn secret_handoff_never_mortality_reverts_a_present_coin() { + let wal = Arc::new(MemWal::default()); + wal.save(&TransferWalEntry { + entry_id: "secret-1".into(), + operation: WalOperation::SecretHandoff, + payload: WalPayload { + input_coins: vec![WalCoinRef { derivation_index: 1, exponent: 1 }], + ..WalPayload::default() + }, + checkpoint: CheckpointBlock::Pending, + created_at_ms: 0, + }) + .await + .unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let service = service( + Arc::clone(&wal), + Arc::clone(&coins), + Arc::new(InMemoryVoucherRepository::default()), + MockProbe { + finalized: u64::MAX, + coins_on_chain: HashSet::from([1]), + ..MockProbe::default() + }, + ); - let report = service.recover().await.unwrap(); - assert_eq!(report.still_pending, 1); - assert_eq!(report.reverted, 0); - assert_eq!(report.orphans_restored, 0); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - assert_eq!(wal.load_all().await.unwrap().len(), 1); - } + let report = service.recover().await.unwrap(); + assert_eq!(report.still_pending, 1); + assert_eq!(report.reverted, 0); + assert_eq!(report.orphans_restored, 0); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + assert_eq!(wal.load_all().await.unwrap().len(), 1); + } - /// Chain absence is the sole terminal proof for an out-of-band - /// secret handoff. - #[tokio::test] - async fn secret_handoff_absence_retires_inputs_and_journal() { - let wal = Arc::new(MemWal::default()); - wal.save(&TransferWalEntry { - entry_id: "secret-2".into(), - operation: WalOperation::SecretHandoff, - payload: WalPayload { - input_coins: vec![WalCoinRef { - derivation_index: 1, - exponent: 1, - }], - ..WalPayload::default() - }, - checkpoint: CheckpointBlock::Pending, - created_at_ms: 0, - }) - .await - .unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let service = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::new(InMemoryVoucherRepository::default()), - MockProbe::default(), - ); + /// Chain absence is the sole terminal proof for an out-of-band + /// secret handoff. + #[tokio::test] + async fn secret_handoff_absence_retires_inputs_and_journal() { + let wal = Arc::new(MemWal::default()); + wal.save(&TransferWalEntry { + entry_id: "secret-2".into(), + operation: WalOperation::SecretHandoff, + payload: WalPayload { + input_coins: vec![WalCoinRef { derivation_index: 1, exponent: 1 }], + ..WalPayload::default() + }, + checkpoint: CheckpointBlock::Pending, + created_at_ms: 0, + }) + .await + .unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let service = service( + Arc::clone(&wal), + Arc::clone(&coins), + Arc::new(InMemoryVoucherRepository::default()), + MockProbe::default(), + ); - let report = service.recover().await.unwrap(); - assert_eq!(report.inputs_consumed, 1); - assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); - assert!(wal.load_all().await.unwrap().is_empty()); - } - async fn operation_fixture( - state: WalOperation, - checkpoint: CheckpointBlock, - probe: MockProbe, - ) -> ( - TransferRecoveryService, - Arc, - Arc, - ) { - let mut child = into_coins_entry(checkpoint); - child.entry_id = crate::wal::operation_entry_id("host-payment", "split"); - child.operation = WalOperation::Split; - child.payload.output_coins.push(WalCoinRef { - derivation_index: 51, - exponent: 0, - }); - child.payload.destination_coins = child.payload.output_coins.clone(); - let parent = TransferWalEntry { - entry_id: crate::wal::operation_entry_id("host-payment", "parent"), - operation: state, - payload: WalPayload { - output_coins: child.payload.destination_coins.clone(), - ..WalPayload::default() - }, - checkpoint: CheckpointBlock::Pending, - created_at_ms: 0, - }; - let wal = Arc::new(MemWal::default()); - wal.save_all(&[parent, child]).await.unwrap(); - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin( - 1, - CoinState::PendingTransfer, - )])); - let recovery = service( - Arc::clone(&wal), - Arc::clone(&coins), - Arc::new(InMemoryVoucherRepository::default()), - probe, - ); - (recovery, wal, coins) - } + let report = service.recover().await.unwrap(); + assert_eq!(report.inputs_consumed, 1); + assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); + assert!(wal.load_all().await.unwrap().is_empty()); + } + async fn operation_fixture( + state: WalOperation, + checkpoint: CheckpointBlock, + probe: MockProbe, + ) -> (TransferRecoveryService, Arc, Arc) { + let mut child = into_coins_entry(checkpoint); + child.entry_id = crate::wal::operation_entry_id("host-payment", "split"); + child.operation = WalOperation::Split; + child + .payload + .output_coins + .push(WalCoinRef { derivation_index: 51, exponent: 0 }); + child.payload.destination_coins = child.payload.output_coins.clone(); + let parent = TransferWalEntry { + entry_id: crate::wal::operation_entry_id("host-payment", "parent"), + operation: state, + payload: WalPayload { + output_coins: child.payload.destination_coins.clone(), + ..WalPayload::default() + }, + checkpoint: CheckpointBlock::Pending, + created_at_ms: 0, + }; + let wal = Arc::new(MemWal::default()); + wal.save_all(&[parent, child]).await.unwrap(); + let coins = + Arc::new(InMemoryCoinRepository::with_coins([coin(1, CoinState::PendingTransfer)])); + let recovery = service( + Arc::clone(&wal), + Arc::clone(&coins), + Arc::new(InMemoryVoucherRepository::default()), + probe, + ); + (recovery, wal, coins) + } - #[tokio::test] - async fn prepared_transport_ambiguity_never_releases_a_pending_chain_input() { - let (service, wal, coins) = operation_fixture( - WalOperation::TransferPrepared, - CheckpointBlock::Pending, - MockProbe { - finalized: 10_000, - ..MockProbe::default() - }, - ) - .await; - let report = service.recover().await.unwrap(); - assert_eq!(report.reverted, 0); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - let rows = wal.load_operation("host-payment").await.unwrap(); - assert!( - rows.iter() - .any(|entry| entry.operation == WalOperation::TransferPrepared) - ); - assert!( - rows.iter() - .any(|entry| entry.operation == WalOperation::Split) - ); - } + #[tokio::test] + async fn prepared_transport_ambiguity_never_releases_a_pending_chain_input() { + let (service, wal, coins) = operation_fixture( + WalOperation::TransferPrepared, + CheckpointBlock::Pending, + MockProbe { finalized: 10_000, ..MockProbe::default() }, + ) + .await; + let report = service.recover().await.unwrap(); + assert_eq!(report.reverted, 0); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + let rows = wal.load_operation("host-payment").await.unwrap(); + assert!(rows.iter().any(|entry| entry.operation == WalOperation::TransferPrepared)); + assert!(rows.iter().any(|entry| entry.operation == WalOperation::Split)); + } - #[tokio::test] - async fn expired_accepted_plan_is_resumeable_without_unlocking_or_reallocating() { - let (service, wal, coins) = operation_fixture( - WalOperation::TransferAccepted, - CheckpointBlock::Known { - number: 1, - hash: [1; 32], - }, - MockProbe { - finalized: 1_000, - coins_on_chain: HashSet::from([1]), - ..MockProbe::default() - }, - ) - .await; - let original = wal - .load_operation("host-payment") - .await - .unwrap() - .into_iter() - .find(|entry| entry.operation == WalOperation::Split) - .unwrap(); - service.recover().await.unwrap(); - service.recover().await.unwrap(); - let restored = wal - .load_operation("host-payment") - .await - .unwrap() - .into_iter() - .find(|entry| entry.operation == WalOperation::Split) - .unwrap(); - assert_eq!(restored.entry_id, original.entry_id); - assert_eq!(restored.payload, original.payload); - assert_eq!(restored.checkpoint, CheckpointBlock::Pending); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - } + #[tokio::test] + async fn expired_accepted_plan_is_resumeable_without_unlocking_or_reallocating() { + let (service, wal, coins) = operation_fixture( + WalOperation::TransferAccepted, + CheckpointBlock::Known { number: 1, hash: [1; 32] }, + MockProbe { + finalized: 1_000, + coins_on_chain: HashSet::from([1]), + ..MockProbe::default() + }, + ) + .await; + let original = wal + .load_operation("host-payment") + .await + .unwrap() + .into_iter() + .find(|entry| entry.operation == WalOperation::Split) + .unwrap(); + service.recover().await.unwrap(); + service.recover().await.unwrap(); + let restored = wal + .load_operation("host-payment") + .await + .unwrap() + .into_iter() + .find(|entry| entry.operation == WalOperation::Split) + .unwrap(); + assert_eq!(restored.entry_id, original.entry_id); + assert_eq!(restored.payload, original.payload); + assert_eq!(restored.checkpoint, CheckpointBlock::Pending); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + } - #[tokio::test] - async fn consumed_inputs_without_output_evidence_cannot_complete_an_operation() { - let checkpoint = CheckpointBlock::Known { - number: 1, - hash: [1; 32], - }; - let (service, wal, coins) = operation_fixture( - WalOperation::TransferAccepted, - checkpoint, - MockProbe { - finalized: 1_000, - ..MockProbe::default() - }, - ) - .await; - service.recover().await.unwrap(); - let rows = wal.load_operation("host-payment").await.unwrap(); - assert!( - rows.iter() - .any(|entry| entry.operation == WalOperation::TransferAccepted) - ); - let child = rows - .iter() - .find(|entry| entry.operation == WalOperation::Split) - .unwrap(); - assert_eq!(child.checkpoint, checkpoint); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - } + #[tokio::test] + async fn consumed_inputs_without_output_evidence_cannot_complete_an_operation() { + let checkpoint = CheckpointBlock::Known { number: 1, hash: [1; 32] }; + let (service, wal, coins) = operation_fixture( + WalOperation::TransferAccepted, + checkpoint, + MockProbe { finalized: 1_000, ..MockProbe::default() }, + ) + .await; + service.recover().await.unwrap(); + let rows = wal.load_operation("host-payment").await.unwrap(); + assert!(rows.iter().any(|entry| entry.operation == WalOperation::TransferAccepted)); + let child = rows.iter().find(|entry| entry.operation == WalOperation::Split).unwrap(); + assert_eq!(child.checkpoint, checkpoint); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + } - #[tokio::test] - async fn landed_operation_keeps_its_receipt_after_repeated_recovery() { - let (service, wal, coins) = operation_fixture( - WalOperation::TransferAccepted, - CheckpointBlock::Known { - number: 1, - hash: [1; 32], - }, - MockProbe { - coins_on_chain: HashSet::from([50, 51]), - output_exponents: HashMap::from([(50, 0), (51, 0)]), - ..MockProbe::default() - }, - ) - .await; - service.recover().await.unwrap(); - service.recover().await.unwrap(); - assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); - assert_eq!(coin_state(&coins, 50).await, CoinState::Spent); - let rows = wal.load_operation("host-payment").await.unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].operation, WalOperation::TransferCompleted); - assert_eq!(rows[0].payload.output_coins[0].derivation_index, 50); - } + #[tokio::test] + async fn landed_operation_keeps_its_receipt_after_repeated_recovery() { + let (service, wal, coins) = operation_fixture( + WalOperation::TransferAccepted, + CheckpointBlock::Known { number: 1, hash: [1; 32] }, + MockProbe { + coins_on_chain: HashSet::from([50, 51]), + output_exponents: HashMap::from([(50, 0), (51, 0)]), + ..MockProbe::default() + }, + ) + .await; + service.recover().await.unwrap(); + service.recover().await.unwrap(); + assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); + assert_eq!(coin_state(&coins, 50).await, CoinState::Spent); + let rows = wal.load_operation("host-payment").await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].operation, WalOperation::TransferCompleted); + assert_eq!(rows[0].payload.output_coins[0].derivation_index, 50); + } - #[tokio::test] - async fn partial_or_wrong_output_evidence_cannot_complete_or_rebroadcast() { - for outputs in [HashMap::from([(50, 0)]), HashMap::from([(50, 0), (51, 4)])] { - let checkpoint = CheckpointBlock::Known { - number: 1, - hash: [1; 32], - }; - let (service, wal, coins) = operation_fixture( - WalOperation::TransferAccepted, - checkpoint, - MockProbe { - finalized: 1_000, - coins_on_chain: HashSet::from([1, 50, 51]), - output_exponents: outputs, - ..MockProbe::default() - }, - ) - .await; - service.recover().await.unwrap(); - let rows = wal.load_operation("host-payment").await.unwrap(); - assert!( - rows.iter() - .any(|entry| entry.operation == WalOperation::TransferAccepted) - ); - assert_eq!( - rows.iter() - .find(|entry| entry.operation == WalOperation::Split) - .unwrap() - .checkpoint, - checkpoint - ); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - } - } + #[tokio::test] + async fn partial_or_wrong_output_evidence_cannot_complete_or_rebroadcast() { + for outputs in [HashMap::from([(50, 0)]), HashMap::from([(50, 0), (51, 4)])] { + let checkpoint = CheckpointBlock::Known { number: 1, hash: [1; 32] }; + let (service, wal, coins) = operation_fixture( + WalOperation::TransferAccepted, + checkpoint, + MockProbe { + finalized: 1_000, + coins_on_chain: HashSet::from([1, 50, 51]), + output_exponents: outputs, + ..MockProbe::default() + }, + ) + .await; + service.recover().await.unwrap(); + let rows = wal.load_operation("host-payment").await.unwrap(); + assert!(rows.iter().any(|entry| entry.operation == WalOperation::TransferAccepted)); + assert_eq!( + rows.iter() + .find(|entry| entry.operation == WalOperation::Split) + .unwrap() + .checkpoint, + checkpoint + ); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + } + } } diff --git a/rust/crates/truapi-coinage/src/repo.rs b/rust/crates/truapi-coinage/src/repo.rs index 4f992363c3..7a66296741 100644 --- a/rust/crates/truapi-coinage/src/repo.rs +++ b/rust/crates/truapi-coinage/src/repo.rs @@ -21,40 +21,40 @@ use crate::model::{Coin, CoinState, Voucher, VoucherLocalState, VoucherRemoteSta /// Local coin persistence effect. #[async_trait] pub trait CoinRepository: Send + Sync { - async fn list(&self) -> Result, String>; + async fn list(&self) -> Result, String>; - /// Insert or replace by `derivation_index`. - async fn upsert(&self, coin: &Coin) -> Result<(), String>; + /// Insert or replace by `derivation_index`. + async fn upsert(&self, coin: &Coin) -> Result<(), String>; - /// Moves one coin's state; unknown index is an error (a recovery - /// sweep must never silently miss). - async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String>; + /// Moves one coin's state; unknown index is an error (a recovery + /// sweep must never silently miss). + async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String>; - async fn remove(&self, derivation_index: u32) -> Result<(), String>; + async fn remove(&self, derivation_index: u32) -> Result<(), String>; } /// Local voucher persistence effect. #[async_trait] pub trait VoucherRepository: Send + Sync { - async fn list(&self) -> Result, String>; + async fn list(&self) -> Result, String>; - async fn upsert(&self, voucher: &Voucher) -> Result<(), String>; + async fn upsert(&self, voucher: &Voucher) -> Result<(), String>; - async fn set_local_state( - &self, - derivation_index: u32, - state: VoucherLocalState, - ) -> Result<(), String>; + async fn set_local_state( + &self, + derivation_index: u32, + state: VoucherLocalState, + ) -> Result<(), String>; - /// Updates only the chain-location projection. Unknown indices are - /// errors so a subscription cannot silently lose a mapper request. - async fn set_remote_state( - &self, - derivation_index: u32, - state: VoucherRemoteState, - ) -> Result<(), String>; + /// Updates only the chain-location projection. Unknown indices are + /// errors so a subscription cannot silently lose a mapper request. + async fn set_remote_state( + &self, + derivation_index: u32, + state: VoucherRemoteState, + ) -> Result<(), String>; - async fn remove(&self, derivation_index: u32) -> Result<(), String>; + async fn remove(&self, derivation_index: u32) -> Result<(), String>; } /// Optional persistence fast path for one logical strategy/group commit. @@ -63,509 +63,443 @@ pub trait VoucherRepository: Send + Sync { /// the repository fallback. #[async_trait] pub trait TransferStateCommitter: Send + Sync { - async fn reserve(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String>; + async fn reserve(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String>; - async fn revert(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String>; + async fn revert(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String>; - async fn commit( - &self, - spent_coins: &[u32], - spent_vouchers: &[u32], - change: &[Coin], - destination: &[Coin], - ) -> Result<(), String>; + async fn commit( + &self, + spent_coins: &[u32], + spent_vouchers: &[u32], + change: &[Coin], + destination: &[Coin], + ) -> Result<(), String>; } /// Mutex-guarded in-memory [`CoinRepository`]. #[derive(Default)] pub struct InMemoryCoinRepository { - coins: Mutex>, + coins: Mutex>, } impl InMemoryCoinRepository { - pub fn with_coins(coins: impl IntoIterator) -> Self { - Self { - coins: Mutex::new(coins.into_iter().map(|c| (c.derivation_index, c)).collect()), - } - } + pub fn with_coins(coins: impl IntoIterator) -> Self { + Self { coins: Mutex::new(coins.into_iter().map(|c| (c.derivation_index, c)).collect()) } + } } #[async_trait] impl CoinRepository for InMemoryCoinRepository { - async fn list(&self) -> Result, String> { - let mut coins: Vec = self.coins.lock().values().cloned().collect(); - coins.sort_by_key(|c| c.derivation_index); - Ok(coins) - } - - async fn upsert(&self, coin: &Coin) -> Result<(), String> { - self.coins - .lock() - .insert(coin.derivation_index, coin.clone()); - Ok(()) - } - - async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String> { - match self.coins.lock().get_mut(&derivation_index) { - Some(coin) => { - coin.state = state; - Ok(()) - } - None => Err(format!("coin {derivation_index} not found")), - } - } - - async fn remove(&self, derivation_index: u32) -> Result<(), String> { - self.coins.lock().remove(&derivation_index); - Ok(()) - } + async fn list(&self) -> Result, String> { + let mut coins: Vec = self.coins.lock().values().cloned().collect(); + coins.sort_by_key(|c| c.derivation_index); + Ok(coins) + } + + async fn upsert(&self, coin: &Coin) -> Result<(), String> { + self.coins.lock().insert(coin.derivation_index, coin.clone()); + Ok(()) + } + + async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String> { + match self.coins.lock().get_mut(&derivation_index) { + Some(coin) => { + coin.state = state; + Ok(()) + }, + None => Err(format!("coin {derivation_index} not found")), + } + } + + async fn remove(&self, derivation_index: u32) -> Result<(), String> { + self.coins.lock().remove(&derivation_index); + Ok(()) + } } /// Mutex-guarded in-memory [`VoucherRepository`]. #[derive(Default)] pub struct InMemoryVoucherRepository { - vouchers: Mutex>, + vouchers: Mutex>, } impl InMemoryVoucherRepository { - pub fn with_vouchers(vouchers: impl IntoIterator) -> Self { - Self { - vouchers: Mutex::new( - vouchers - .into_iter() - .map(|v| (v.derivation_index, v)) - .collect(), - ), - } - } + pub fn with_vouchers(vouchers: impl IntoIterator) -> Self { + Self { + vouchers: Mutex::new(vouchers.into_iter().map(|v| (v.derivation_index, v)).collect()), + } + } } #[async_trait] impl VoucherRepository for InMemoryVoucherRepository { - async fn list(&self) -> Result, String> { - let mut vouchers: Vec = self.vouchers.lock().values().cloned().collect(); - vouchers.sort_by_key(|v| v.derivation_index); - Ok(vouchers) - } - - async fn upsert(&self, voucher: &Voucher) -> Result<(), String> { - self.vouchers - .lock() - .insert(voucher.derivation_index, voucher.clone()); - Ok(()) - } - - async fn set_local_state( - &self, - derivation_index: u32, - state: VoucherLocalState, - ) -> Result<(), String> { - match self.vouchers.lock().get_mut(&derivation_index) { - Some(voucher) => { - voucher.local_state = state; - Ok(()) - } - None => Err(format!("voucher {derivation_index} not found")), - } - } - - async fn set_remote_state( - &self, - derivation_index: u32, - state: VoucherRemoteState, - ) -> Result<(), String> { - match self.vouchers.lock().get_mut(&derivation_index) { - Some(voucher) => { - voucher.remote_state = state; - Ok(()) - } - None => Err(format!("voucher {derivation_index} not found")), - } - } - - async fn remove(&self, derivation_index: u32) -> Result<(), String> { - self.vouchers.lock().remove(&derivation_index); - Ok(()) - } + async fn list(&self) -> Result, String> { + let mut vouchers: Vec = self.vouchers.lock().values().cloned().collect(); + vouchers.sort_by_key(|v| v.derivation_index); + Ok(vouchers) + } + + async fn upsert(&self, voucher: &Voucher) -> Result<(), String> { + self.vouchers.lock().insert(voucher.derivation_index, voucher.clone()); + Ok(()) + } + + async fn set_local_state( + &self, + derivation_index: u32, + state: VoucherLocalState, + ) -> Result<(), String> { + match self.vouchers.lock().get_mut(&derivation_index) { + Some(voucher) => { + voucher.local_state = state; + Ok(()) + }, + None => Err(format!("voucher {derivation_index} not found")), + } + } + + async fn set_remote_state( + &self, + derivation_index: u32, + state: VoucherRemoteState, + ) -> Result<(), String> { + match self.vouchers.lock().get_mut(&derivation_index) { + Some(voucher) => { + voucher.remote_state = state; + Ok(()) + }, + None => Err(format!("voucher {derivation_index} not found")), + } + } + + async fn remove(&self, derivation_index: u32) -> Result<(), String> { + self.vouchers.lock().remove(&derivation_index); + Ok(()) + } } use std::sync::Arc; /// The reserve → process / revert lifecycle around one transfer /// -/// - [`reserve`](Self::reserve) marks inputs `PendingTransfer` BEFORE the -/// strategy runs — a process death here is caught by orphan recovery; -/// - [`process`](Self::process) retires spent inputs, removing them from -/// the pending sets before the first await; if a later `set_state` call -/// fails, the removed ids are re-appended so `revert` can still find -/// them; -/// - [`revert`](Self::revert) restores everything still pending back to -/// `Available`. +/// - [`reserve`](Self::reserve) marks inputs `PendingTransfer` BEFORE the strategy runs — a process +/// death here is caught by orphan recovery; +/// - [`process`](Self::process) retires spent inputs, removing them from the pending sets before +/// the first await; if a later `set_state` call fails, the removed ids are re-appended so +/// `revert` can still find them; +/// - [`revert`](Self::revert) restores everything still pending back to `Available`. pub struct TransferContext { - coins: Arc, - vouchers: Arc, - pending_coins: Mutex>, - pending_vouchers: Mutex>, - committer: Option>, + coins: Arc, + vouchers: Arc, + pending_coins: Mutex>, + pending_vouchers: Mutex>, + committer: Option>, } impl TransferContext { - pub fn new(coins: Arc, vouchers: Arc) -> Self { - Self { - coins, - vouchers, - pending_coins: Mutex::new(Vec::new()), - pending_vouchers: Mutex::new(Vec::new()), - committer: None, - } - } - - pub fn with_committer(mut self, committer: Arc) -> Self { - self.committer = Some(committer); - self - } - - pub async fn reserve(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String> { - if let Some(committer) = &self.committer { - committer.reserve(coins, vouchers).await?; - self.pending_coins.lock().extend_from_slice(coins); - self.pending_vouchers.lock().extend_from_slice(vouchers); - return Ok(()); - } - let mut reserved_coins = Vec::new(); - for &index in coins { - if let Err(error) = self - .coins - .set_state(index, CoinState::PendingTransfer) - .await - { - for reserved in reserved_coins { - let _ = self.coins.set_state(reserved, CoinState::Available).await; - } - self.pending_coins.lock().clear(); - return Err(error); - } - reserved_coins.push(index); - self.pending_coins.lock().push(index); - } - let mut reserved_vouchers = Vec::new(); - for &index in vouchers { - if let Err(error) = self - .vouchers - .set_local_state(index, VoucherLocalState::PendingTransfer) - .await - { - for reserved in reserved_vouchers { - let _ = self - .vouchers - .set_local_state(reserved, VoucherLocalState::Available) - .await; - } - for reserved in reserved_coins { - let _ = self.coins.set_state(reserved, CoinState::Available).await; - } - self.pending_coins.lock().clear(); - self.pending_vouchers.lock().clear(); - return Err(error); - } - reserved_vouchers.push(index); - self.pending_vouchers.lock().push(index); - } - Ok(()) - } - - pub async fn process(&self, spent_coins: &[u32], spent_vouchers: &[u32]) -> Result<(), String> { - let removed_coins: Vec = { - let mut pending = self.pending_coins.lock(); - let removed = pending - .iter() - .copied() - .filter(|index| spent_coins.contains(index)) - .collect(); - pending.retain(|index| !spent_coins.contains(index)); - removed - }; - let removed_vouchers: Vec = { - let mut pending = self.pending_vouchers.lock(); - let removed = pending - .iter() - .copied() - .filter(|index| spent_vouchers.contains(index)) - .collect(); - pending.retain(|index| !spent_vouchers.contains(index)); - removed - }; - - let restore = |this: &Self| { - this.pending_coins.lock().extend_from_slice(&removed_coins); - this.pending_vouchers - .lock() - .extend_from_slice(&removed_vouchers); - }; - for &index in spent_coins { - if let Err(error) = self.coins.set_state(index, CoinState::Spent).await { - restore(self); - return Err(error); - } - } - for &index in spent_vouchers { - if let Err(error) = self - .vouchers - .set_local_state(index, VoucherLocalState::Spent) - .await - { - restore(self); - return Err(error); - } - } - Ok(()) - } - - pub async fn process_outputs( - &self, - spent_coins: &[u32], - spent_vouchers: &[u32], - change: &[Coin], - destination: &[Coin], - ) -> Result<(), String> { - let removed_coins: Vec = { - let mut pending = self.pending_coins.lock(); - let removed = pending - .iter() - .copied() - .filter(|index| spent_coins.contains(index)) - .collect(); - pending.retain(|index| !spent_coins.contains(index)); - removed - }; - let removed_vouchers: Vec = { - let mut pending = self.pending_vouchers.lock(); - let removed = pending - .iter() - .copied() - .filter(|index| spent_vouchers.contains(index)) - .collect(); - pending.retain(|index| !spent_vouchers.contains(index)); - removed - }; - let restore = |this: &Self| { - this.pending_coins.lock().extend_from_slice(&removed_coins); - this.pending_vouchers - .lock() - .extend_from_slice(&removed_vouchers); - }; - - let commit = async { - if let Some(committer) = &self.committer { - return committer - .commit(spent_coins, spent_vouchers, change, destination) - .await; - } - for coin in change { - let mut coin = coin.clone(); - coin.state = CoinState::Available; - self.coins.upsert(&coin).await?; - } - for coin in destination { - let mut coin = coin.clone(); - coin.state = CoinState::Spent; - self.coins.upsert(&coin).await?; - } - for &index in spent_coins { - self.coins.set_state(index, CoinState::Spent).await?; - } - for &index in spent_vouchers { - self.vouchers.remove(index).await?; - } - Ok::<(), String>(()) - } - .await; - if let Err(error) = commit { - restore(self); - return Err(error); - } - Ok(()) - } - - /// Restores only the supplied still-pending inputs. Used after a - /// definitive pre-broadcast failure so another recycler group with a - /// known checkpoint remains reserved for recovery. - pub async fn revert_inputs(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String> { - let coins = { - let mut pending = self.pending_coins.lock(); - let selected = pending - .iter() - .copied() - .filter(|index| coins.contains(index)) - .collect::>(); - pending.retain(|index| !coins.contains(index)); - selected - }; - let vouchers = { - let mut pending = self.pending_vouchers.lock(); - let selected = pending - .iter() - .copied() - .filter(|index| vouchers.contains(index)) - .collect::>(); - pending.retain(|index| !vouchers.contains(index)); - selected - }; - if let Some(committer) = &self.committer { - if let Err(error) = committer.revert(&coins, &vouchers).await { - self.pending_coins.lock().extend_from_slice(&coins); - self.pending_vouchers.lock().extend_from_slice(&vouchers); - return Err(error); - } - return Ok(()); - } - for index in coins { - self.coins.set_state(index, CoinState::Available).await?; - } - for index in vouchers { - self.vouchers - .set_local_state(index, VoucherLocalState::Available) - .await?; - } - Ok(()) - } - - pub async fn revert(&self) -> Result<(), String> { - let coins: Vec = std::mem::take(&mut *self.pending_coins.lock()); - let vouchers: Vec = std::mem::take(&mut *self.pending_vouchers.lock()); - if let Some(committer) = &self.committer { - if let Err(error) = committer.revert(&coins, &vouchers).await { - self.pending_coins.lock().extend_from_slice(&coins); - self.pending_vouchers.lock().extend_from_slice(&vouchers); - return Err(error); - } - return Ok(()); - } - for index in coins { - self.coins.set_state(index, CoinState::Available).await?; - } - for index in vouchers { - self.vouchers - .set_local_state(index, VoucherLocalState::Available) - .await?; - } - Ok(()) - } + pub fn new(coins: Arc, vouchers: Arc) -> Self { + Self { + coins, + vouchers, + pending_coins: Mutex::new(Vec::new()), + pending_vouchers: Mutex::new(Vec::new()), + committer: None, + } + } + + pub fn with_committer(mut self, committer: Arc) -> Self { + self.committer = Some(committer); + self + } + + pub async fn reserve(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String> { + if let Some(committer) = &self.committer { + committer.reserve(coins, vouchers).await?; + self.pending_coins.lock().extend_from_slice(coins); + self.pending_vouchers.lock().extend_from_slice(vouchers); + return Ok(()); + } + let mut reserved_coins = Vec::new(); + for &index in coins { + if let Err(error) = self.coins.set_state(index, CoinState::PendingTransfer).await { + for reserved in reserved_coins { + let _ = self.coins.set_state(reserved, CoinState::Available).await; + } + self.pending_coins.lock().clear(); + return Err(error); + } + reserved_coins.push(index); + self.pending_coins.lock().push(index); + } + let mut reserved_vouchers = Vec::new(); + for &index in vouchers { + if let Err(error) = + self.vouchers.set_local_state(index, VoucherLocalState::PendingTransfer).await + { + for reserved in reserved_vouchers { + let _ = + self.vouchers.set_local_state(reserved, VoucherLocalState::Available).await; + } + for reserved in reserved_coins { + let _ = self.coins.set_state(reserved, CoinState::Available).await; + } + self.pending_coins.lock().clear(); + self.pending_vouchers.lock().clear(); + return Err(error); + } + reserved_vouchers.push(index); + self.pending_vouchers.lock().push(index); + } + Ok(()) + } + + pub async fn process(&self, spent_coins: &[u32], spent_vouchers: &[u32]) -> Result<(), String> { + let removed_coins: Vec = { + let mut pending = self.pending_coins.lock(); + let removed = + pending.iter().copied().filter(|index| spent_coins.contains(index)).collect(); + pending.retain(|index| !spent_coins.contains(index)); + removed + }; + let removed_vouchers: Vec = { + let mut pending = self.pending_vouchers.lock(); + let removed = + pending.iter().copied().filter(|index| spent_vouchers.contains(index)).collect(); + pending.retain(|index| !spent_vouchers.contains(index)); + removed + }; + + let restore = |this: &Self| { + this.pending_coins.lock().extend_from_slice(&removed_coins); + this.pending_vouchers.lock().extend_from_slice(&removed_vouchers); + }; + for &index in spent_coins { + if let Err(error) = self.coins.set_state(index, CoinState::Spent).await { + restore(self); + return Err(error); + } + } + for &index in spent_vouchers { + if let Err(error) = self.vouchers.set_local_state(index, VoucherLocalState::Spent).await + { + restore(self); + return Err(error); + } + } + Ok(()) + } + + pub async fn process_outputs( + &self, + spent_coins: &[u32], + spent_vouchers: &[u32], + change: &[Coin], + destination: &[Coin], + ) -> Result<(), String> { + let removed_coins: Vec = { + let mut pending = self.pending_coins.lock(); + let removed = + pending.iter().copied().filter(|index| spent_coins.contains(index)).collect(); + pending.retain(|index| !spent_coins.contains(index)); + removed + }; + let removed_vouchers: Vec = { + let mut pending = self.pending_vouchers.lock(); + let removed = + pending.iter().copied().filter(|index| spent_vouchers.contains(index)).collect(); + pending.retain(|index| !spent_vouchers.contains(index)); + removed + }; + let restore = |this: &Self| { + this.pending_coins.lock().extend_from_slice(&removed_coins); + this.pending_vouchers.lock().extend_from_slice(&removed_vouchers); + }; + + let commit = async { + if let Some(committer) = &self.committer { + return committer.commit(spent_coins, spent_vouchers, change, destination).await; + } + for coin in change { + let mut coin = coin.clone(); + coin.state = CoinState::Available; + self.coins.upsert(&coin).await?; + } + for coin in destination { + let mut coin = coin.clone(); + coin.state = CoinState::Spent; + self.coins.upsert(&coin).await?; + } + for &index in spent_coins { + self.coins.set_state(index, CoinState::Spent).await?; + } + for &index in spent_vouchers { + self.vouchers.remove(index).await?; + } + Ok::<(), String>(()) + } + .await; + if let Err(error) = commit { + restore(self); + return Err(error); + } + Ok(()) + } + + /// Restores only the supplied still-pending inputs. Used after a + /// definitive pre-broadcast failure so another recycler group with a + /// known checkpoint remains reserved for recovery. + pub async fn revert_inputs(&self, coins: &[u32], vouchers: &[u32]) -> Result<(), String> { + let coins = { + let mut pending = self.pending_coins.lock(); + let selected = pending + .iter() + .copied() + .filter(|index| coins.contains(index)) + .collect::>(); + pending.retain(|index| !coins.contains(index)); + selected + }; + let vouchers = { + let mut pending = self.pending_vouchers.lock(); + let selected = pending + .iter() + .copied() + .filter(|index| vouchers.contains(index)) + .collect::>(); + pending.retain(|index| !vouchers.contains(index)); + selected + }; + if let Some(committer) = &self.committer { + if let Err(error) = committer.revert(&coins, &vouchers).await { + self.pending_coins.lock().extend_from_slice(&coins); + self.pending_vouchers.lock().extend_from_slice(&vouchers); + return Err(error); + } + return Ok(()); + } + for index in coins { + self.coins.set_state(index, CoinState::Available).await?; + } + for index in vouchers { + self.vouchers.set_local_state(index, VoucherLocalState::Available).await?; + } + Ok(()) + } + + pub async fn revert(&self) -> Result<(), String> { + let coins: Vec = std::mem::take(&mut *self.pending_coins.lock()); + let vouchers: Vec = std::mem::take(&mut *self.pending_vouchers.lock()); + if let Some(committer) = &self.committer { + if let Err(error) = committer.revert(&coins, &vouchers).await { + self.pending_coins.lock().extend_from_slice(&coins); + self.pending_vouchers.lock().extend_from_slice(&vouchers); + return Err(error); + } + return Ok(()); + } + for index in coins { + self.coins.set_state(index, CoinState::Available).await?; + } + for index in vouchers { + self.vouchers.set_local_state(index, VoucherLocalState::Available).await?; + } + Ok(()) + } } #[cfg(test)] mod tests { - use super::*; - use crate::model::{VoucherPrivacyLevel, VoucherRemoteState}; - - fn coin(index: u32) -> Coin { - Coin { - exponent: 0, - derivation_index: index, - age: Some(1), - state: CoinState::Available, - } - } - - fn voucher(index: u32) -> Voucher { - Voucher { - exponent: 0, - derivation_index: index, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: VoucherRemoteState::InRecycler { recycler_index: 0 }, - local_state: VoucherLocalState::Available, - privacy: VoucherPrivacyLevel::Full, - } - } - - async fn coin_state(repo: &InMemoryCoinRepository, index: u32) -> CoinState { - repo.list() - .await - .unwrap() - .into_iter() - .find(|c| c.derivation_index == index) - .unwrap() - .state - } - - #[tokio::test] - async fn reserve_process_revert_lifecycle() { - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1), coin(2)])); - let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([voucher(10)])); - let context = TransferContext::new( - Arc::clone(&coins) as Arc<_>, - Arc::clone(&vouchers) as Arc<_>, - ); - - context.reserve(&[1, 2], &[10]).await.unwrap(); - assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); - assert_eq!(coin_state(&coins, 2).await, CoinState::PendingTransfer); - - // One coin is processed (spent); the rest reverts. - context.process(&[1], &[]).await.unwrap(); - context.revert().await.unwrap(); - - assert_eq!( - coin_state(&coins, 1).await, - CoinState::Spent, - "processed stays spent" - ); - assert_eq!( - coin_state(&coins, 2).await, - CoinState::Available, - "unprocessed reverts" - ); - assert_eq!( - vouchers.list().await.unwrap()[0].local_state, - VoucherLocalState::Available, - "unprocessed voucher reverts" - ); - } - - #[tokio::test] - async fn failed_process_keeps_items_revertable() { - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1)])); - let vouchers = Arc::new(InMemoryVoucherRepository::default()); - let context = TransferContext::new(Arc::clone(&coins) as Arc<_>, vouchers); - - context.reserve(&[1], &[]).await.unwrap(); - // Index 99 does not exist — set_state fails mid-process. - assert!(context.process(&[99], &[]).await.is_err()); - context.revert().await.unwrap(); - assert_eq!(coin_state(&coins, 1).await, CoinState::Available); - } - - #[tokio::test] - async fn double_revert_is_a_no_op() { - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1)])); - let vouchers = Arc::new(InMemoryVoucherRepository::default()); - let context = TransferContext::new(Arc::clone(&coins) as Arc<_>, vouchers); - context.reserve(&[1], &[]).await.unwrap(); - context.revert().await.unwrap(); - context.revert().await.unwrap(); - assert_eq!(coin_state(&coins, 1).await, CoinState::Available); - } - - #[tokio::test] - async fn process_outputs_persists_change_spends_destination_and_deletes_vouchers() { - let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1)])); - let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([voucher(10)])); - let context = TransferContext::new( - Arc::clone(&coins) as Arc<_>, - Arc::clone(&vouchers) as Arc<_>, - ); - context.reserve(&[1], &[10]).await.unwrap(); - context - .process_outputs(&[1], &[10], &[coin(2)], &[coin(3)]) - .await - .unwrap(); - - assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); - assert_eq!(coin_state(&coins, 2).await, CoinState::Available); - assert_eq!(coin_state(&coins, 3).await, CoinState::Spent); - assert!(vouchers.list().await.unwrap().is_empty()); - context.revert().await.unwrap(); - assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); - } + use super::*; + use crate::model::{VoucherPrivacyLevel, VoucherRemoteState}; + + fn coin(index: u32) -> Coin { + Coin { exponent: 0, derivation_index: index, age: Some(1), state: CoinState::Available } + } + + fn voucher(index: u32) -> Voucher { + Voucher { + exponent: 0, + derivation_index: index, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: VoucherRemoteState::InRecycler { recycler_index: 0 }, + local_state: VoucherLocalState::Available, + privacy: VoucherPrivacyLevel::Full, + } + } + + async fn coin_state(repo: &InMemoryCoinRepository, index: u32) -> CoinState { + repo.list() + .await + .unwrap() + .into_iter() + .find(|c| c.derivation_index == index) + .unwrap() + .state + } + + #[tokio::test] + async fn reserve_process_revert_lifecycle() { + let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1), coin(2)])); + let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([voucher(10)])); + let context = + TransferContext::new(Arc::clone(&coins) as Arc<_>, Arc::clone(&vouchers) as Arc<_>); + + context.reserve(&[1, 2], &[10]).await.unwrap(); + assert_eq!(coin_state(&coins, 1).await, CoinState::PendingTransfer); + assert_eq!(coin_state(&coins, 2).await, CoinState::PendingTransfer); + + // One coin is processed (spent); the rest reverts. + context.process(&[1], &[]).await.unwrap(); + context.revert().await.unwrap(); + + assert_eq!(coin_state(&coins, 1).await, CoinState::Spent, "processed stays spent"); + assert_eq!(coin_state(&coins, 2).await, CoinState::Available, "unprocessed reverts"); + assert_eq!( + vouchers.list().await.unwrap()[0].local_state, + VoucherLocalState::Available, + "unprocessed voucher reverts" + ); + } + + #[tokio::test] + async fn failed_process_keeps_items_revertable() { + let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1)])); + let vouchers = Arc::new(InMemoryVoucherRepository::default()); + let context = TransferContext::new(Arc::clone(&coins) as Arc<_>, vouchers); + + context.reserve(&[1], &[]).await.unwrap(); + // Index 99 does not exist — set_state fails mid-process. + assert!(context.process(&[99], &[]).await.is_err()); + context.revert().await.unwrap(); + assert_eq!(coin_state(&coins, 1).await, CoinState::Available); + } + + #[tokio::test] + async fn double_revert_is_a_no_op() { + let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1)])); + let vouchers = Arc::new(InMemoryVoucherRepository::default()); + let context = TransferContext::new(Arc::clone(&coins) as Arc<_>, vouchers); + context.reserve(&[1], &[]).await.unwrap(); + context.revert().await.unwrap(); + context.revert().await.unwrap(); + assert_eq!(coin_state(&coins, 1).await, CoinState::Available); + } + + #[tokio::test] + async fn process_outputs_persists_change_spends_destination_and_deletes_vouchers() { + let coins = Arc::new(InMemoryCoinRepository::with_coins([coin(1)])); + let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers([voucher(10)])); + let context = + TransferContext::new(Arc::clone(&coins) as Arc<_>, Arc::clone(&vouchers) as Arc<_>); + context.reserve(&[1], &[10]).await.unwrap(); + context.process_outputs(&[1], &[10], &[coin(2)], &[coin(3)]).await.unwrap(); + + assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); + assert_eq!(coin_state(&coins, 2).await, CoinState::Available); + assert_eq!(coin_state(&coins, 3).await, CoinState::Spent); + assert!(vouchers.list().await.unwrap().is_empty()); + context.revert().await.unwrap(); + assert_eq!(coin_state(&coins, 1).await, CoinState::Spent); + } } diff --git a/rust/crates/truapi-coinage/src/ring_proof.rs b/rust/crates/truapi-coinage/src/ring_proof.rs index a9f033254a..d819f48d62 100644 --- a/rust/crates/truapi-coinage/src/ring_proof.rs +++ b/rust/crates/truapi-coinage/src/ring_proof.rs @@ -15,8 +15,8 @@ pub const RING_VRF_PROOF_LEN: usize = 785; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PersonOriginKind { - Full, - Lite, + Full, + Lite, } /// One finalized ring snapshot. The exponent is the on-chain @@ -26,83 +26,83 @@ pub enum PersonOriginKind { /// (spec 1000032) requires it inside every proof-bearing extension. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RingProofParams { - pub ring_exponent: u8, - pub ring_index: u32, - pub ring_revision: u32, - pub ring_members: Vec<[u8; 32]>, + pub ring_exponent: u8, + pub ring_index: u32, + pub ring_revision: u32, + pub ring_members: Vec<[u8; 32]>, } /// One distinct free unload-token slot selected for a recycler group. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ResolvedUnloadToken { - pub period: u32, - pub counter: u32, + pub period: u32, + pub counter: u32, } impl ResolvedUnloadToken { - /// `coinftk || period(le u32) || counter(le u32)`. - pub fn context(self) -> Vec { - let mut context = Vec::with_capacity(FREE_UNLOAD_TOKEN_CONTEXT_PREFIX.len() + 8); - context.extend_from_slice(FREE_UNLOAD_TOKEN_CONTEXT_PREFIX); - context.extend_from_slice(&self.period.to_le_bytes()); - context.extend_from_slice(&self.counter.to_le_bytes()); - context - } + /// `coinftk || period(le u32) || counter(le u32)`. + pub fn context(self) -> Vec { + let mut context = Vec::with_capacity(FREE_UNLOAD_TOKEN_CONTEXT_PREFIX.len() + 8); + context.extend_from_slice(FREE_UNLOAD_TOKEN_CONTEXT_PREFIX); + context.extend_from_slice(&self.period.to_le_bytes()); + context.extend_from_slice(&self.counter.to_le_bytes()); + context + } } /// Everything the proof signer needs after the transaction builder has /// produced the inherited implication. #[derive(Debug, Clone, PartialEq, Eq)] pub struct UnloadProofRequest { - pub recycler: RecyclerKey, - pub voucher_derivation_indices: Vec, - pub recycler_ring: RingProofParams, - pub person_origin: PersonOriginKind, - pub people_ring: RingProofParams, - pub token: ResolvedUnloadToken, - pub inherited_implication: Vec, + pub recycler: RecyclerKey, + pub voucher_derivation_indices: Vec, + pub recycler_ring: RingProofParams, + pub person_origin: PersonOriginKind, + pub people_ring: RingProofParams, + pub token: ResolvedUnloadToken, + pub inherited_implication: Vec, } /// The complete proof-bearing `AsCoinage` payload plus the aliases carried by /// the unload call itself. #[derive(Debug, Clone, PartialEq, Eq)] pub struct UnloadTokenProof { - pub person_origin: PersonOriginKind, - pub people_proof: Vec, - pub people_ring_index: u32, - pub people_ring_revision: u32, - pub period: u32, - pub counter: u32, - pub aliases: Vec<[u8; 32]>, - pub alias_proofs: Vec>, + pub person_origin: PersonOriginKind, + pub people_proof: Vec, + pub people_ring_index: u32, + pub people_ring_revision: u32, + pub period: u32, + pub counter: u32, + pub aliases: Vec<[u8; 32]>, + pub alias_proofs: Vec>, } impl UnloadTokenProof { - /// SCALE-ready `AsCoinage(Some(…))` value for installation into the - /// prepared transaction extension. - pub fn as_coinage_extension(&self) -> crate::tx_extensions::AsCoinage { - use crate::tx_extensions::{AsCoinage, CoinagePeopleProof}; + /// SCALE-ready `AsCoinage(Some(…))` value for installation into the + /// prepared transaction extension. + pub fn as_coinage_extension(&self) -> crate::tx_extensions::AsCoinage { + use crate::tx_extensions::{AsCoinage, CoinagePeopleProof}; - let proof = CoinagePeopleProof { - proof: self.people_proof.clone(), - ring: self.people_ring_index, - revision: self.people_ring_revision, - }; - match self.person_origin { - PersonOriginKind::Full => AsCoinage::unload_token_people( - proof, - self.period, - self.counter, - self.alias_proofs.clone(), - ), - PersonOriginKind::Lite => AsCoinage::unload_token_lite_people( - proof, - self.period, - self.counter, - self.alias_proofs.clone(), - ), - } - } + let proof = CoinagePeopleProof { + proof: self.people_proof.clone(), + ring: self.people_ring_index, + revision: self.people_ring_revision, + }; + match self.person_origin { + PersonOriginKind::Full => AsCoinage::unload_token_people( + proof, + self.period, + self.counter, + self.alias_proofs.clone(), + ), + PersonOriginKind::Lite => AsCoinage::unload_token_lite_people( + proof, + self.period, + self.counter, + self.alias_proofs.clone(), + ), + } + } } /// A fail-closed proof construction error. Every variant carries a @@ -111,23 +111,23 @@ impl UnloadTokenProof { /// missing crypto support. #[derive(Debug, Clone, PartialEq, Eq)] pub enum RingProofError { - EmptyVoucherGroup, - RecyclerMismatch, - EmptyRing(&'static str), - Proof(String), + EmptyVoucherGroup, + RecyclerMismatch, + EmptyRing(&'static str), + Proof(String), } impl std::fmt::Display for RingProofError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::EmptyVoucherGroup => f.write_str("cannot prove an empty voucher group"), - Self::RecyclerMismatch => { - f.write_str("recycler proof parameters do not match the voucher group") - } - Self::EmptyRing(label) => write!(f, "{label} ring has no included members"), - Self::Proof(message) => f.write_str(message), - } - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::EmptyVoucherGroup => f.write_str("cannot prove an empty voucher group"), + Self::RecyclerMismatch => { + f.write_str("recycler proof parameters do not match the voucher group") + }, + Self::EmptyRing(label) => write!(f, "{label} ring has no included members"), + Self::Proof(message) => f.write_str(message), + } + } } impl std::error::Error for RingProofError {} @@ -138,158 +138,146 @@ impl std::error::Error for RingProofError {} /// methods are intentionally synchronous: once those inputs and the /// implication exist, proof generation is local CPU work only. pub trait RingProofProvider: Send + Sync { - /// Derives the public aliases needed to build the unload call. Aliases do - /// not depend on the transaction implication, so this is the first half of - /// the submitter's two-step flow. - fn unload_aliases( - &self, - voucher_derivation_indices: &[u32], - ) -> Result, RingProofError>; + /// Derives the public aliases needed to build the unload call. Aliases do + /// not depend on the transaction implication, so this is the first half of + /// the submitter's two-step flow. + fn unload_aliases( + &self, + voucher_derivation_indices: &[u32], + ) -> Result, RingProofError>; - /// Creates the proof-bearing extension after the aliases are in the call - /// and the resulting inherited implication has been derived. - fn unload_proof( - &self, - request: &UnloadProofRequest, - ) -> Result; + /// Creates the proof-bearing extension after the aliases are in the call + /// and the resulting inherited implication has been derived. + fn unload_proof( + &self, + request: &UnloadProofRequest, + ) -> Result; } /// The production local signer. Root entropy is retained only in zeroizing /// memory and no derived secret appears in the returned payload. pub struct BandersnatchRingProofProvider { - vouchers: crate::keys::VoucherKeypairFactory, - crypto: std::sync::Arc, - people: std::sync::Arc, + vouchers: crate::keys::VoucherKeypairFactory, + crypto: std::sync::Arc, + people: std::sync::Arc, } impl BandersnatchRingProofProvider { - pub fn new( - entropy: &[u8], - crypto: std::sync::Arc, - people: std::sync::Arc, - ) -> Self { - Self { - vouchers: crate::keys::VoucherKeypairFactory::new(entropy), - crypto, - people, - } - } + pub fn new( + entropy: &[u8], + crypto: std::sync::Arc, + people: std::sync::Arc, + ) -> Self { + Self { vouchers: crate::keys::VoucherKeypairFactory::new(entropy), crypto, people } + } } impl RingProofProvider for BandersnatchRingProofProvider { - fn unload_aliases( - &self, - voucher_derivation_indices: &[u32], - ) -> Result, RingProofError> { - if voucher_derivation_indices.is_empty() { - return Err(RingProofError::EmptyVoucherGroup); - } - let vouchers = &self.vouchers; - voucher_derivation_indices - .iter() - .map(|index| { - vouchers - .alias(*index, RECYCLER_ALIAS_CONTEXT, self.crypto.as_ref()) - .map_err(RingProofError::Proof) - }) - .collect() - } + fn unload_aliases( + &self, + voucher_derivation_indices: &[u32], + ) -> Result, RingProofError> { + if voucher_derivation_indices.is_empty() { + return Err(RingProofError::EmptyVoucherGroup); + } + let vouchers = &self.vouchers; + voucher_derivation_indices + .iter() + .map(|index| { + vouchers + .alias(*index, RECYCLER_ALIAS_CONTEXT, self.crypto.as_ref()) + .map_err(RingProofError::Proof) + }) + .collect() + } - fn unload_proof( - &self, - request: &UnloadProofRequest, - ) -> Result { - if request.voucher_derivation_indices.is_empty() { - return Err(RingProofError::EmptyVoucherGroup); - } - if request.recycler_ring.ring_index != request.recycler.index { - return Err(RingProofError::RecyclerMismatch); - } - if request.recycler_ring.ring_members.is_empty() { - return Err(RingProofError::EmptyRing("recycler")); - } - if request.people_ring.ring_members.is_empty() { - return Err(RingProofError::EmptyRing("People")); - } + fn unload_proof( + &self, + request: &UnloadProofRequest, + ) -> Result { + if request.voucher_derivation_indices.is_empty() { + return Err(RingProofError::EmptyVoucherGroup); + } + if request.recycler_ring.ring_index != request.recycler.index { + return Err(RingProofError::RecyclerMismatch); + } + if request.recycler_ring.ring_members.is_empty() { + return Err(RingProofError::EmptyRing("recycler")); + } + if request.people_ring.ring_members.is_empty() { + return Err(RingProofError::EmptyRing("People")); + } - let alias_message = blake2b_256(&request.inherited_implication); - let vouchers = &self.vouchers; - let aliases = self.unload_aliases(&request.voucher_derivation_indices)?; - let mut alias_proofs = Vec::with_capacity(request.voucher_derivation_indices.len()); - for index in &request.voucher_derivation_indices { - alias_proofs.push( - vouchers - .ring_vrf_proof( - *index, - request.recycler_ring.ring_exponent, - &request.recycler_ring.ring_members, - RECYCLER_ALIAS_CONTEXT, - &alias_message, - self.crypto.as_ref(), - ) - .map_err(RingProofError::Proof)?, - ); - } + let alias_message = blake2b_256(&request.inherited_implication); + let vouchers = &self.vouchers; + let aliases = self.unload_aliases(&request.voucher_derivation_indices)?; + let mut alias_proofs = Vec::with_capacity(request.voucher_derivation_indices.len()); + for index in &request.voucher_derivation_indices { + alias_proofs.push( + vouchers + .ring_vrf_proof( + *index, + request.recycler_ring.ring_exponent, + &request.recycler_ring.ring_members, + RECYCLER_ALIAS_CONTEXT, + &alias_message, + self.crypto.as_ref(), + ) + .map_err(RingProofError::Proof)?, + ); + } - let mut people_payload = alias_proofs.encode(); - people_payload.extend_from_slice(&request.inherited_implication); - let people_message = blake2b_256(&people_payload); - let people_proof = self - .people - .ring_vrf_proof( - request.person_origin, - &request.people_ring, - &request.token.context(), - &people_message, - ) - .map_err(RingProofError::Proof)?; - if alias_proofs - .iter() - .any(|proof| proof.len() != RING_VRF_PROOF_LEN) - || people_proof.len() != RING_VRF_PROOF_LEN - { - return Err(RingProofError::Proof( - "Bandersnatch proof has an invalid length".into(), - )); - } + let mut people_payload = alias_proofs.encode(); + people_payload.extend_from_slice(&request.inherited_implication); + let people_message = blake2b_256(&people_payload); + let people_proof = self + .people + .ring_vrf_proof( + request.person_origin, + &request.people_ring, + &request.token.context(), + &people_message, + ) + .map_err(RingProofError::Proof)?; + if alias_proofs.iter().any(|proof| proof.len() != RING_VRF_PROOF_LEN) || + people_proof.len() != RING_VRF_PROOF_LEN + { + return Err(RingProofError::Proof("Bandersnatch proof has an invalid length".into())); + } - debug_assert!( - alias_proofs - .iter() - .all(|proof| proof.len() == RING_VRF_PROOF_LEN) - ); - debug_assert_eq!(people_proof.len(), RING_VRF_PROOF_LEN); - Ok(UnloadTokenProof { - person_origin: request.person_origin, - people_proof, - people_ring_index: request.people_ring.ring_index, - people_ring_revision: request.people_ring.ring_revision, - period: request.token.period, - counter: request.token.counter, - aliases, - alias_proofs, - }) - } + debug_assert!(alias_proofs.iter().all(|proof| proof.len() == RING_VRF_PROOF_LEN)); + debug_assert_eq!(people_proof.len(), RING_VRF_PROOF_LEN); + Ok(UnloadTokenProof { + person_origin: request.person_origin, + people_proof, + people_ring_index: request.people_ring.ring_index, + people_ring_revision: request.people_ring.ring_revision, + period: request.token.period, + counter: request.token.counter, + aliases, + alias_proofs, + }) + } } fn blake2b_256(message: &[u8]) -> [u8; 32] { - blake2b_simd::Params::new() - .hash_length(32) - .hash(message) - .as_bytes() - .try_into() - .expect("BLAKE2b-256 returns 32 bytes") + blake2b_simd::Params::new() + .hash_length(32) + .hash(message) + .as_bytes() + .try_into() + .expect("BLAKE2b-256 returns 32 bytes") } /// Authority-owned People signer. The adapter chooses the deployed full/lite /// identity derivation for its network; Coinage never exports that identity. pub trait PersonRingProofSigner: Send + Sync { - /// Sign the exact ring/context/implication supplied by the unload builder. - fn ring_vrf_proof( - &self, - origin: PersonOriginKind, - ring: &RingProofParams, - context: &[u8], - message: &[u8], - ) -> Result, String>; + /// Sign the exact ring/context/implication supplied by the unload builder. + fn ring_vrf_proof( + &self, + origin: PersonOriginKind, + ring: &RingProofParams, + context: &[u8], + message: &[u8], + ) -> Result, String>; } diff --git a/rust/crates/truapi-coinage/src/secret_claim.rs b/rust/crates/truapi-coinage/src/secret_claim.rs index 9ad55b5a84..04009f6752 100644 --- a/rust/crates/truapi-coinage/src/secret_claim.rs +++ b/rust/crates/truapi-coinage/src/secret_claim.rs @@ -3,50 +3,49 @@ // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. //! Chain-backed claiming of externally supplied Coinage secrets. -//! [`ExternalMemoClaiming`] is the secret-preserving claim effect. This module implements that effect without ever projecting a -//! secret through FFI: +//! [`ExternalMemoClaiming`] is the secret-preserving claim effect. This module implements that +//! effect without ever projecting a secret through FFI: //! 1. validate every expanded sr25519 secret and reject duplicate sources; -//! 2. read the live Coinage denomination context and source/destination -//! state in ordered batches; +//! 2. read the live Coinage denomination context and source/destination state in ordered batches; //! 3. allocate one session-derived destination with the same denomination; -//! 4. treat a destination present on-chain while its source is absent as -//! already complete; the inverse is safe to retry. Both present is a -//! recipient collision and both absent is ambiguous, so both cases fail -//! closed; -//! 5. submit one `Coinage.transfer` per source under its own `AsCoin` -//! origin; and +//! 4. treat a destination present on-chain while its source is absent as already complete; the +//! inverse is safe to retry. Both present is a recipient collision and both absent is ambiguous, +//! so both cases fail closed; +//! 5. submit one `Coinage.transfer` per source under its own `AsCoin` origin; and //! 6. save only destinations whose finalized on-chain value was verified. -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use async_trait::async_trait; use tokio::sync::Mutex; -use crate::COIN_MAX_AGE; -use crate::allocator::CoinAllocator; -use crate::claim_plan::{ - ClaimMarkers, ClaimPlan, ClaimPlanStatus, ClaimPlanStore, CodableClaimPlanEntry, +use crate::{ + COIN_MAX_AGE, + allocator::CoinAllocator, + claim_plan::{ClaimMarkers, ClaimPlan, ClaimPlanStatus, ClaimPlanStore, CodableClaimPlanEntry}, + constants::SEND_VERIFY_BLOCK_TIMEOUT, + denomination::DenominationBreakdownContext, + keys::CoinKeypairFactory, + memo::{MemoEntry, TransferMemo}, + model::{Coin, CoinState}, + repo::CoinRepository, + sync::OnChainCoin, }; -use crate::constants::SEND_VERIFY_BLOCK_TIMEOUT; -use crate::denomination::DenominationBreakdownContext; -use crate::keys::CoinKeypairFactory; -use crate::memo::{MemoEntry, TransferMemo}; -use crate::model::{Coin, CoinState}; -use crate::repo::CoinRepository; -use crate::sync::OnChainCoin; type SecretSource = Option<(MemoEntry, [u8; 32])>; /// One source-coin transfer. This type intentionally has no `Debug` /// implementation: `source_secret` is seed-phrase-tier material. pub struct ExternalCoinTransferRequest { - pub source_secret: MemoEntry, - pub source_public: [u8; 32], - pub recipient: [u8; 32], - pub exponent: i16, - pub asset_unit: u128, - pub amount_planks: u128, + pub source_secret: MemoEntry, + pub source_public: [u8; 32], + pub recipient: [u8; 32], + pub exponent: i16, + pub asset_unit: u128, + pub amount_planks: u128, } /// The chain edge used by [`ExternalSecretClaimService`]. @@ -56,19 +55,19 @@ pub struct ExternalCoinTransferRequest { /// observed with the requested exponent. #[async_trait] pub trait ExternalCoinTransferBackend: Send + Sync { - async fn denomination_context(&self) -> Result; - - /// Ordered `Coinage.CoinsByOwner` batch. - async fn fetch_coins( - &self, - public_keys: &[[u8; 32]], - ) -> Result>, String>; - - /// Consumes the raw secret and returns the finalized destination row. - async fn submit_transfer( - &self, - request: ExternalCoinTransferRequest, - ) -> Result; + async fn denomination_context(&self) -> Result; + + /// Ordered `Coinage.CoinsByOwner` batch. + async fn fetch_coins( + &self, + public_keys: &[[u8; 32]], + ) -> Result>, String>; + + /// Consumes the raw secret and returns the finalized destination row. + async fn submit_transfer( + &self, + request: ExternalCoinTransferRequest, + ) -> Result; } /// Session-scoped recipient for W3S/external Coinage secrets. @@ -76,1794 +75,1482 @@ pub trait ExternalCoinTransferBackend: Send + Sync { /// destination key factory owns no FFI-visible surface and zeroizes its root /// material on drop. pub struct ExternalSecretClaimService { - key_factory: Arc, - allocator: Arc, - coins: Arc, - plans: Arc, - backend: Arc, - operation: Mutex<()>, + key_factory: Arc, + allocator: Arc, + coins: Arc, + plans: Arc, + backend: Arc, + operation: Mutex<()>, } impl ExternalSecretClaimService { - pub fn new( - root_entropy: &[u8], - allocator: Arc, - coins: Arc, - plans: Arc, - backend: Arc, - ) -> Self { - Self { - key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), - allocator, - coins, - plans, - backend, - operation: Mutex::new(()), - } - } - - pub async fn await_memo_sources_on_chain(&self, memo: &TransferMemo) -> Result<(), String> { - self.await_memo_sources_on_chain_with( - memo, - SEND_VERIFY_BLOCK_TIMEOUT, - std::time::Duration::from_secs(6), - ) - .await - } - - /// Timeout-parameterized body of [`Self::await_memo_sources_on_chain`] - /// (attempt count ≙ finalized blocks, interval ≙ block time). - pub async fn await_memo_sources_on_chain_with( - &self, - memo: &TransferMemo, - attempts: u32, - interval: std::time::Duration, - ) -> Result<(), String> { - if memo.entries.is_empty() { - return Err("external coin claim requires at least one secret".into()); - } - let mut publics = Vec::with_capacity(memo.entries.len()); - for (index, entry) in memo.entries.iter().enumerate() { - let public = schnorrkel::SecretKey::from_bytes(&entry.0) - .map_err(|error| format!("external coin secret {index} is invalid: {error}"))? - .to_public() - .to_bytes(); - publics.push(public); - } - for attempt in 0..attempts.max(1) { - if attempt > 0 { - crate::timer::sleep(interval).await; - } - let rows = - fetch_exact(self.backend.as_ref(), &publics, "external send detection").await?; - if rows.iter().all(Option::is_some) { - return Ok(()); - } - } - Err(format!( - "external send not detected within {} blocks", - attempts.max(1) - )) - } - - /// Validate and persist the complete destination plan without submitting - /// any transaction. Hosts call this before acknowledging custody of a memo. - pub async fn prepare_memo( - &self, - memo: &TransferMemo, - message_id: String, - ) -> Result { - let _operation = self.operation.lock().await; - self.prepare_locked(memo, message_id).await - } - - async fn prepare_locked( - &self, - memo: &TransferMemo, - message_id: String, - ) -> Result { - if memo.entries.is_empty() { - return Err("external coin claim requires at least one secret".into()); - } - let memo_key = memo.identifier(); - - // A Finished plan is authoritative: this memo was claimed on a - // prior run. Report the stored amount instead of re-executing — - // the claimed coins may since have been spent or recycled, so - // re-verification against live chain state can no longer prove - // anything and must not overwrite the terminal outcome. - let existing = self.plans.plan(&memo_key).await?; - if let Some(plan) = &existing - && plan.status == ClaimPlanStatus::Finished - { - if plan.memo_key != memo_key - || plan.total_value != memo.total_value - || plan.claimed_amount != Some(memo.total_value) - || plan.entries.len() != memo.entries.len() - { - return Err("finished external coin claim does not match its memo".into()); - } - return Ok(plan.clone()); - } - - let context = self.backend.denomination_context().await?; - validate_context(&context)?; - - let total_value = memo.total_value; - let sources = source_entries(memo.entries.clone())?; - let plan = match existing { - Some(plan) => { - validate_existing_plan( - &plan, - &memo_key, - &message_id, - total_value, - sources.len(), - &context, - )?; - plan - } - None => { - let source_public = sources - .iter() - .map(|source| source.as_ref().expect("source installed").1) - .collect::>(); - let source_rows = fetch_exact( - self.backend.as_ref(), - &source_public, - "external source coin query", - ) - .await?; - let mut exponents = Vec::with_capacity(source_rows.len()); - let mut computed_total = 0u128; - for (index, row) in source_rows.into_iter().enumerate() { - let row = row.ok_or_else(|| { - format!("external source coin {index} is no longer on-chain") - })?; - validate_exponent(row.exponent, &context)?; - computed_total = computed_total - .checked_add(context.value_in_planks(row.exponent)) - .ok_or_else(|| "external coin claim total exceeds u128".to_string())?; - exponents.push(row.exponent); - } - if computed_total != total_value { - return Err(format!( - "external coin claim amount mismatch: memo {total_value}, chain {computed_total}" - )); - } - - let plan = self - .allocate_plan( - memo_key, - message_id.clone(), - total_value, - &source_public, - &exponents, - ) - .await?; - self.plans.save(&plan).await?; - plan - } - }; - - Ok(plan) - } - - async fn claim(&self, mut memo: TransferMemo, message_id: String) -> Result { - let _operation = self.operation.lock().await; - let plan = self.prepare_locked(&memo, message_id).await?; - if plan.status == ClaimPlanStatus::Finished { - return credited(&plan); - } - let memo_key = plan.memo_key; - let context = self.backend.denomination_context().await?; - validate_context(&context)?; - let mut sources = source_entries(std::mem::take(&mut memo.entries))?; - let outcome = self.execute_plan(&plan, &context, &mut sources).await; - match outcome { - Ok(claimed) => { - self.plans - .update_status(&memo_key, ClaimPlanStatus::Finished, Some(claimed)) - .await?; - let finished = - self.plans.plan(&memo_key).await?.ok_or_else(|| { - "finished external coin claim plan disappeared".to_string() - })?; - credited(&finished) - } - Err(error) => { - let confirmed = self - .plans - .plan(&memo_key) - .await? - .and_then(|plan| plan.claimed_amount); - if let Err(status_error) = self - .plans - .update_status(&memo_key, ClaimPlanStatus::Error, confirmed) - .await - { - tracing::warn!( - %status_error, - "external coin claim error status could not be persisted" - ); - } - Err(error) - } - } - } - - async fn allocate_plan( - &self, - memo_key: [u8; 32], - message_id: String, - total_value: u128, - source_public: &[[u8; 32]], - exponents: &[i16], - ) -> Result { - let mut entries = Vec::with_capacity(exponents.len()); - let mut recipients = Vec::with_capacity(exponents.len()); - let source_set = source_public.iter().copied().collect::>(); - let mut recipient_set = HashSet::with_capacity(exponents.len()); - - for (entry_index, exponent) in exponents.iter().copied().enumerate() { - let entry_index = i16::try_from(entry_index) - .map_err(|_| "external coin claim has too many entries".to_string())?; - let destination = self.allocator.allocate(exponent).await?; - let recipient = self.key_factory.public_key(destination.derivation_index)?; - if recipient == [0; 32] - || source_set.contains(&recipient) - || !recipient_set.insert(recipient) - { - return Err("external coin claim destination key collision".into()); - } - recipients.push(recipient); - entries.push(CodableClaimPlanEntry { - entry_index, - exponent, - derivation_index: destination.derivation_index, - }); - } - - let destination_rows = fetch_exact( - self.backend.as_ref(), - &recipients, - "external destination collision query", - ) - .await?; - if destination_rows.iter().any(Option::is_some) { - return Err("external coin claim destination already exists on-chain".into()); - } - - Ok(ClaimPlan { - memo_key, - message_id: Some(message_id), - entries, - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Processing, - claimed_amount: None, - total_value, - markers: ClaimMarkers::default(), - }) - } - - /// Persist the plan's markers, and with `claimed` its processed prefix, in - /// one write so a forfeit and its prefix advance never separate. - async fn save_markers( - &self, - memo_key: &[u8; 32], - markers: &ClaimMarkers, - claimed: Option, - ) -> Result<(), String> { - let mut current = self - .plans - .plan(memo_key) - .await? - .ok_or_else(|| "external coin claim plan disappeared".to_string())?; - current.markers = markers.clone(); - if let Some(claimed) = claimed { - current.status = ClaimPlanStatus::Processing; - current.claimed_amount = Some(claimed); - } - self.plans.save(¤t).await - } - - async fn execute_plan( - &self, - plan: &ClaimPlan, - context: &DenominationBreakdownContext, - sources: &mut [SecretSource], - ) -> Result { - let entries = ordered_plan_entries(plan, sources.len())?; - let source_public = sources - .iter() - .map(|source| source.as_ref().expect("validated source").1) - .collect::>(); - let recipients = entries - .iter() - .map(|entry| self.key_factory.public_key(entry.derivation_index)) - .collect::, _>>()?; - validate_recipients(&source_public, &recipients)?; - - let mut all_keys = source_public.clone(); - all_keys.extend_from_slice(&recipients); - let mut rows = fetch_exact( - self.backend.as_ref(), - &all_keys, - "external claim recovery query", - ) - .await?; - let destination_rows = rows.split_off(source_public.len()); - let source_rows = rows; - let local_states = self - .coins - .list() - .await? - .into_iter() - .map(|coin| (coin.derivation_index, coin.state)) - .collect::>(); - - let mut markers = plan.markers.clone(); - let mut claimed = 0u128; - for (position, entry) in entries.into_iter().enumerate() { - validate_exponent(entry.exponent, context)?; - let expected_amount = context.value_in_planks(entry.exponent); - claimed = claimed - .checked_add(expected_amount) - .ok_or_else(|| "external coin claim total exceeds u128".to_string())?; - // Each sequential prefix was durably recorded only after exact - // finalized destination verification. Missing both keys without - // that evidence is ambiguous, never proof of a successful claim. - if claimed <= plan.claimed_amount.unwrap_or(0) { - continue; - } - let source = source_rows[position]; - let destination = destination_rows[position]; - let landed = match (source, destination) { - (None, Some(destination)) => { - if destination.exponent != entry.exponent { - return Err(format!( - "external claim destination {position} denomination mismatch: expected {}, found {}", - entry.exponent, destination.exponent - )); - } - destination - } - (Some(source), None) => { - if source.exponent != entry.exponent { - return Err(format!( - "external claim source {position} denomination changed: expected {}, found {}", - entry.exponent, source.exponent - )); - } - // Record the submission before it can reach the chain, so a - // transfer that lands unobserved is never read as a spend. - if !markers.submitted.contains(&entry.entry_index) { - markers.submitted.push(entry.entry_index); - self.save_markers(&plan.memo_key, &markers, None).await?; - } - let (source_secret, source_public) = sources[position] - .take() - .expect("validated source entry consumed once"); - let recipient = recipients[position]; - self.backend - .submit_transfer(ExternalCoinTransferRequest { - source_secret, - source_public, - recipient, - exponent: entry.exponent, - asset_unit: context.asset_unit, - amount_planks: expected_amount, - }) - .await? - } - (Some(_), Some(_)) => { - return Err( - "external claim destination collision: source remains unconsumed".into(), - ); - } - // Finalized absence of an entry this wallet never submitted is - // proof the source was spent elsewhere: forfeit it and continue. - (None, None) if !markers.submitted.contains(&entry.entry_index) => { - markers.forfeited.push(entry.entry_index); - markers.forfeited_value = markers - .forfeited_value - .checked_add(expected_amount) - .ok_or_else(|| "external coin claim total exceeds u128".to_string())?; - self.save_markers(&plan.memo_key, &markers, Some(claimed)) - .await?; - continue; - } - (None, None) => { - return Err("external claim source and destination are both absent without finalized evidence".into()); - } - }; - if landed.exponent != entry.exponent { - return Err(format!( - "external claim finalized destination {position} denomination mismatch: expected {}, found {}", - entry.exponent, landed.exponent - )); - } - let state = local_states - .get(&entry.derivation_index) - .copied() - .unwrap_or(CoinState::Available); - self.coins - .upsert(&Coin { - exponent: entry.exponent, - derivation_index: entry.derivation_index, - age: Some(landed.age), - state, - }) - .await?; - self.plans - .update_status(&plan.memo_key, ClaimPlanStatus::Processing, Some(claimed)) - .await?; - } - if claimed != plan.total_value { - return Err(format!( - "external coin claim plan amount mismatch: plan {}, entries {claimed}", - plan.total_value - )); - } - Ok(claimed) - } + pub fn new( + root_entropy: &[u8], + allocator: Arc, + coins: Arc, + plans: Arc, + backend: Arc, + ) -> Self { + Self { + key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), + allocator, + coins, + plans, + backend, + operation: Mutex::new(()), + } + } + + pub async fn await_memo_sources_on_chain(&self, memo: &TransferMemo) -> Result<(), String> { + self.await_memo_sources_on_chain_with( + memo, + SEND_VERIFY_BLOCK_TIMEOUT, + std::time::Duration::from_secs(6), + ) + .await + } + + /// Timeout-parameterized body of [`Self::await_memo_sources_on_chain`] + /// (attempt count ≙ finalized blocks, interval ≙ block time). + pub async fn await_memo_sources_on_chain_with( + &self, + memo: &TransferMemo, + attempts: u32, + interval: std::time::Duration, + ) -> Result<(), String> { + if memo.entries.is_empty() { + return Err("external coin claim requires at least one secret".into()); + } + let mut publics = Vec::with_capacity(memo.entries.len()); + for (index, entry) in memo.entries.iter().enumerate() { + let public = schnorrkel::SecretKey::from_bytes(&entry.0) + .map_err(|error| format!("external coin secret {index} is invalid: {error}"))? + .to_public() + .to_bytes(); + publics.push(public); + } + for attempt in 0..attempts.max(1) { + if attempt > 0 { + crate::timer::sleep(interval).await; + } + let rows = + fetch_exact(self.backend.as_ref(), &publics, "external send detection").await?; + if rows.iter().all(Option::is_some) { + return Ok(()); + } + } + Err(format!("external send not detected within {} blocks", attempts.max(1))) + } + + /// Validate and persist the complete destination plan without submitting + /// any transaction. Hosts call this before acknowledging custody of a memo. + pub async fn prepare_memo( + &self, + memo: &TransferMemo, + message_id: String, + ) -> Result { + let _operation = self.operation.lock().await; + self.prepare_locked(memo, message_id).await + } + + async fn prepare_locked( + &self, + memo: &TransferMemo, + message_id: String, + ) -> Result { + if memo.entries.is_empty() { + return Err("external coin claim requires at least one secret".into()); + } + let memo_key = memo.identifier(); + + // A Finished plan is authoritative: this memo was claimed on a + // prior run. Report the stored amount instead of re-executing — + // the claimed coins may since have been spent or recycled, so + // re-verification against live chain state can no longer prove + // anything and must not overwrite the terminal outcome. + let existing = self.plans.plan(&memo_key).await?; + if let Some(plan) = &existing && + plan.status == ClaimPlanStatus::Finished + { + if plan.memo_key != memo_key || + plan.total_value != memo.total_value || + plan.claimed_amount != Some(memo.total_value) || + plan.entries.len() != memo.entries.len() + { + return Err("finished external coin claim does not match its memo".into()); + } + return Ok(plan.clone()); + } + + let context = self.backend.denomination_context().await?; + validate_context(&context)?; + + let total_value = memo.total_value; + let sources = source_entries(memo.entries.clone())?; + let plan = match existing { + Some(plan) => { + validate_existing_plan( + &plan, + &memo_key, + &message_id, + total_value, + sources.len(), + &context, + )?; + plan + }, + None => { + let source_public = sources + .iter() + .map(|source| source.as_ref().expect("source installed").1) + .collect::>(); + let source_rows = fetch_exact( + self.backend.as_ref(), + &source_public, + "external source coin query", + ) + .await?; + let mut exponents = Vec::with_capacity(source_rows.len()); + let mut computed_total = 0u128; + for (index, row) in source_rows.into_iter().enumerate() { + let row = row.ok_or_else(|| { + format!("external source coin {index} is no longer on-chain") + })?; + validate_exponent(row.exponent, &context)?; + computed_total = computed_total + .checked_add(context.value_in_planks(row.exponent)) + .ok_or_else(|| "external coin claim total exceeds u128".to_string())?; + exponents.push(row.exponent); + } + if computed_total != total_value { + return Err(format!( + "external coin claim amount mismatch: memo {total_value}, chain {computed_total}" + )); + } + + let plan = self + .allocate_plan( + memo_key, + message_id.clone(), + total_value, + &source_public, + &exponents, + ) + .await?; + self.plans.save(&plan).await?; + plan + }, + }; + + Ok(plan) + } + + async fn claim(&self, mut memo: TransferMemo, message_id: String) -> Result { + let _operation = self.operation.lock().await; + let plan = self.prepare_locked(&memo, message_id).await?; + if plan.status == ClaimPlanStatus::Finished { + return credited(&plan); + } + let memo_key = plan.memo_key; + let context = self.backend.denomination_context().await?; + validate_context(&context)?; + let mut sources = source_entries(std::mem::take(&mut memo.entries))?; + let outcome = self.execute_plan(&plan, &context, &mut sources).await; + match outcome { + Ok(claimed) => { + self.plans + .update_status(&memo_key, ClaimPlanStatus::Finished, Some(claimed)) + .await?; + let finished = + self.plans.plan(&memo_key).await?.ok_or_else(|| { + "finished external coin claim plan disappeared".to_string() + })?; + credited(&finished) + }, + Err(error) => { + let confirmed = + self.plans.plan(&memo_key).await?.and_then(|plan| plan.claimed_amount); + if let Err(status_error) = + self.plans.update_status(&memo_key, ClaimPlanStatus::Error, confirmed).await + { + tracing::warn!( + %status_error, + "external coin claim error status could not be persisted" + ); + } + Err(error) + }, + } + } + + async fn allocate_plan( + &self, + memo_key: [u8; 32], + message_id: String, + total_value: u128, + source_public: &[[u8; 32]], + exponents: &[i16], + ) -> Result { + let mut entries = Vec::with_capacity(exponents.len()); + let mut recipients = Vec::with_capacity(exponents.len()); + let source_set = source_public.iter().copied().collect::>(); + let mut recipient_set = HashSet::with_capacity(exponents.len()); + + for (entry_index, exponent) in exponents.iter().copied().enumerate() { + let entry_index = i16::try_from(entry_index) + .map_err(|_| "external coin claim has too many entries".to_string())?; + let destination = self.allocator.allocate(exponent).await?; + let recipient = self.key_factory.public_key(destination.derivation_index)?; + if recipient == [0; 32] || + source_set.contains(&recipient) || + !recipient_set.insert(recipient) + { + return Err("external coin claim destination key collision".into()); + } + recipients.push(recipient); + entries.push(CodableClaimPlanEntry { + entry_index, + exponent, + derivation_index: destination.derivation_index, + }); + } + + let destination_rows = + fetch_exact(self.backend.as_ref(), &recipients, "external destination collision query") + .await?; + if destination_rows.iter().any(Option::is_some) { + return Err("external coin claim destination already exists on-chain".into()); + } + + Ok(ClaimPlan { + memo_key, + message_id: Some(message_id), + entries, + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Processing, + claimed_amount: None, + total_value, + markers: ClaimMarkers::default(), + }) + } + + /// Persist the plan's markers, and with `claimed` its processed prefix, in + /// one write so a forfeit and its prefix advance never separate. + async fn save_markers( + &self, + memo_key: &[u8; 32], + markers: &ClaimMarkers, + claimed: Option, + ) -> Result<(), String> { + let mut current = self + .plans + .plan(memo_key) + .await? + .ok_or_else(|| "external coin claim plan disappeared".to_string())?; + current.markers = markers.clone(); + if let Some(claimed) = claimed { + current.status = ClaimPlanStatus::Processing; + current.claimed_amount = Some(claimed); + } + self.plans.save(¤t).await + } + + async fn execute_plan( + &self, + plan: &ClaimPlan, + context: &DenominationBreakdownContext, + sources: &mut [SecretSource], + ) -> Result { + let entries = ordered_plan_entries(plan, sources.len())?; + let source_public = sources + .iter() + .map(|source| source.as_ref().expect("validated source").1) + .collect::>(); + let recipients = entries + .iter() + .map(|entry| self.key_factory.public_key(entry.derivation_index)) + .collect::, _>>()?; + validate_recipients(&source_public, &recipients)?; + + let mut all_keys = source_public.clone(); + all_keys.extend_from_slice(&recipients); + let mut rows = + fetch_exact(self.backend.as_ref(), &all_keys, "external claim recovery query").await?; + let destination_rows = rows.split_off(source_public.len()); + let source_rows = rows; + let local_states = self + .coins + .list() + .await? + .into_iter() + .map(|coin| (coin.derivation_index, coin.state)) + .collect::>(); + + let mut markers = plan.markers.clone(); + let mut claimed = 0u128; + for (position, entry) in entries.into_iter().enumerate() { + validate_exponent(entry.exponent, context)?; + let expected_amount = context.value_in_planks(entry.exponent); + claimed = claimed + .checked_add(expected_amount) + .ok_or_else(|| "external coin claim total exceeds u128".to_string())?; + // Each sequential prefix was durably recorded only after exact + // finalized destination verification. Missing both keys without + // that evidence is ambiguous, never proof of a successful claim. + if claimed <= plan.claimed_amount.unwrap_or(0) { + continue; + } + let source = source_rows[position]; + let destination = destination_rows[position]; + let landed = match (source, destination) { + (None, Some(destination)) => { + if destination.exponent != entry.exponent { + return Err(format!( + "external claim destination {position} denomination mismatch: expected {}, found {}", + entry.exponent, destination.exponent + )); + } + destination + }, + (Some(source), None) => { + if source.exponent != entry.exponent { + return Err(format!( + "external claim source {position} denomination changed: expected {}, found {}", + entry.exponent, source.exponent + )); + } + // Record the submission before it can reach the chain, so a + // transfer that lands unobserved is never read as a spend. + if !markers.submitted.contains(&entry.entry_index) { + markers.submitted.push(entry.entry_index); + self.save_markers(&plan.memo_key, &markers, None).await?; + } + let (source_secret, source_public) = + sources[position].take().expect("validated source entry consumed once"); + let recipient = recipients[position]; + self.backend + .submit_transfer(ExternalCoinTransferRequest { + source_secret, + source_public, + recipient, + exponent: entry.exponent, + asset_unit: context.asset_unit, + amount_planks: expected_amount, + }) + .await? + }, + (Some(_), Some(_)) => { + return Err( + "external claim destination collision: source remains unconsumed".into() + ); + }, + // Finalized absence of an entry this wallet never submitted is + // proof the source was spent elsewhere: forfeit it and continue. + (None, None) if !markers.submitted.contains(&entry.entry_index) => { + markers.forfeited.push(entry.entry_index); + markers.forfeited_value = markers + .forfeited_value + .checked_add(expected_amount) + .ok_or_else(|| "external coin claim total exceeds u128".to_string())?; + self.save_markers(&plan.memo_key, &markers, Some(claimed)).await?; + continue; + }, + (None, None) => { + return Err("external claim source and destination are both absent without finalized evidence".into()); + }, + }; + if landed.exponent != entry.exponent { + return Err(format!( + "external claim finalized destination {position} denomination mismatch: expected {}, found {}", + entry.exponent, landed.exponent + )); + } + let state = local_states + .get(&entry.derivation_index) + .copied() + .unwrap_or(CoinState::Available); + self.coins + .upsert(&Coin { + exponent: entry.exponent, + derivation_index: entry.derivation_index, + age: Some(landed.age), + state, + }) + .await?; + self.plans + .update_status(&plan.memo_key, ClaimPlanStatus::Processing, Some(claimed)) + .await?; + } + if claimed != plan.total_value { + return Err(format!( + "external coin claim plan amount mismatch: plan {}, entries {claimed}", + plan.total_value + )); + } + Ok(claimed) + } } #[async_trait] impl ExternalMemoClaiming for ExternalSecretClaimService { - async fn claim_external_memo( - &self, - memo: TransferMemo, - message_id: String, - ) -> Result { - self.claim(memo, message_id).await - } + async fn claim_external_memo( + &self, + memo: TransferMemo, + message_id: String, + ) -> Result { + self.claim(memo, message_id).await + } } /// Exact result of one local spent-coin recovery pass. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct SpentCoinTransferRecoveryReport { - /// Present max-age coins restored locally plus younger coins moved to - /// fresh destinations. - pub recovered_count: u32, - pub recovered_planks: u128, - /// Subset restored locally because `Coinage.transfer` would reject a - /// coin at or beyond `COIN_MAX_AGE`. - pub restored_max_age_count: u32, - /// Subset claimed through finalized `Coinage.transfer` extrinsics. - pub transferred_count: u32, + /// Present max-age coins restored locally plus younger coins moved to + /// fresh destinations. + pub recovered_count: u32, + pub recovered_planks: u128, + /// Subset restored locally because `Coinage.transfer` would reject a + /// coin at or beyond `COIN_MAX_AGE`. + pub restored_max_age_count: u32, + /// Subset claimed through finalized `Coinage.transfer` extrinsics. + pub transferred_count: u32, } pub struct SpentCoinTransferRecoveryService { - key_factory: Arc, - coins: Arc, - backend: Arc, - claimer: Arc, - operation: Mutex<()>, + key_factory: Arc, + coins: Arc, + backend: Arc, + claimer: Arc, + operation: Mutex<()>, } impl SpentCoinTransferRecoveryService { - pub fn new( - root_entropy: &[u8], - coins: Arc, - backend: Arc, - claimer: Arc, - ) -> Self { - Self { - key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), - coins, - backend, - claimer, - operation: Mutex::new(()), - } - } - - pub async fn recover( - &self, - spent: Vec, - ) -> Result { - let _operation = self.operation.lock().await; - if spent.is_empty() { - return Ok(SpentCoinTransferRecoveryReport::default()); - } - let mut indices = HashSet::with_capacity(spent.len()); - for coin in &spent { - if coin.state != CoinState::Spent { - return Err(format!( - "spent recovery received non-spent coin {}", - coin.derivation_index - )); - } - if !indices.insert(coin.derivation_index) { - return Err(format!( - "spent recovery coin {} is duplicated", - coin.derivation_index - )); - } - } - - let context = self.backend.denomination_context().await?; - validate_context(&context)?; - let public_keys = spent - .iter() - .map(|coin| self.key_factory.public_key(coin.derivation_index)) - .collect::, _>>()?; - let rows = fetch_exact( - self.backend.as_ref(), - &public_keys, - "spent Coinage recovery query", - ) - .await?; - - let mut report = SpentCoinTransferRecoveryReport::default(); - let mut transfer_entries = Vec::new(); - let mut transfer_total = 0u128; - for (coin, row) in spent.into_iter().zip(rows) { - let Some(row) = row else { - continue; - }; - validate_exponent(row.exponent, &context)?; - if row.exponent != coin.exponent { - return Err(format!( - "spent coin {} denomination mismatch: local {}, chain {}", - coin.derivation_index, coin.exponent, row.exponent - )); - } - let value = context.value_in_planks(row.exponent); - if row.age >= COIN_MAX_AGE { - self.coins - .upsert(&Coin { - exponent: row.exponent, - derivation_index: coin.derivation_index, - age: Some(row.age), - state: CoinState::Available, - }) - .await?; - report.recovered_count = report.recovered_count.saturating_add(1); - report.restored_max_age_count = report.restored_max_age_count.saturating_add(1); - report.recovered_planks = report - .recovered_planks - .checked_add(value) - .ok_or_else(|| "spent Coinage recovery total exceeds u128".to_string())?; - } else { - transfer_entries.push(MemoEntry( - self.key_factory.secret_bytes(coin.derivation_index)?, - )); - transfer_total = transfer_total - .checked_add(value) - .ok_or_else(|| "spent Coinage transfer total exceeds u128".to_string())?; - report.transferred_count = report.transferred_count.saturating_add(1); - } - } - - if !transfer_entries.is_empty() { - let memo = TransferMemo { - entries: transfer_entries, - total_value: transfer_total, - }; - let memo_key = memo.identifier(); - self.claimer - .claim_external_memo(memo, external_claim_message_id(&memo_key)) - .await?; - report.recovered_count = report - .recovered_count - .checked_add(report.transferred_count) - .ok_or_else(|| "spent Coinage recovered count exceeds u32".to_string())?; - report.recovered_planks = report - .recovered_planks - .checked_add(transfer_total) - .ok_or_else(|| "spent Coinage recovery total exceeds u128".to_string())?; - } - Ok(report) - } + pub fn new( + root_entropy: &[u8], + coins: Arc, + backend: Arc, + claimer: Arc, + ) -> Self { + Self { + key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), + coins, + backend, + claimer, + operation: Mutex::new(()), + } + } + + pub async fn recover( + &self, + spent: Vec, + ) -> Result { + let _operation = self.operation.lock().await; + if spent.is_empty() { + return Ok(SpentCoinTransferRecoveryReport::default()); + } + let mut indices = HashSet::with_capacity(spent.len()); + for coin in &spent { + if coin.state != CoinState::Spent { + return Err(format!( + "spent recovery received non-spent coin {}", + coin.derivation_index + )); + } + if !indices.insert(coin.derivation_index) { + return Err(format!("spent recovery coin {} is duplicated", coin.derivation_index)); + } + } + + let context = self.backend.denomination_context().await?; + validate_context(&context)?; + let public_keys = spent + .iter() + .map(|coin| self.key_factory.public_key(coin.derivation_index)) + .collect::, _>>()?; + let rows = fetch_exact(self.backend.as_ref(), &public_keys, "spent Coinage recovery query") + .await?; + + let mut report = SpentCoinTransferRecoveryReport::default(); + let mut transfer_entries = Vec::new(); + let mut transfer_total = 0u128; + for (coin, row) in spent.into_iter().zip(rows) { + let Some(row) = row else { + continue; + }; + validate_exponent(row.exponent, &context)?; + if row.exponent != coin.exponent { + return Err(format!( + "spent coin {} denomination mismatch: local {}, chain {}", + coin.derivation_index, coin.exponent, row.exponent + )); + } + let value = context.value_in_planks(row.exponent); + if row.age >= COIN_MAX_AGE { + self.coins + .upsert(&Coin { + exponent: row.exponent, + derivation_index: coin.derivation_index, + age: Some(row.age), + state: CoinState::Available, + }) + .await?; + report.recovered_count = report.recovered_count.saturating_add(1); + report.restored_max_age_count = report.restored_max_age_count.saturating_add(1); + report.recovered_planks = report + .recovered_planks + .checked_add(value) + .ok_or_else(|| "spent Coinage recovery total exceeds u128".to_string())?; + } else { + transfer_entries + .push(MemoEntry(self.key_factory.secret_bytes(coin.derivation_index)?)); + transfer_total = transfer_total + .checked_add(value) + .ok_or_else(|| "spent Coinage transfer total exceeds u128".to_string())?; + report.transferred_count = report.transferred_count.saturating_add(1); + } + } + + if !transfer_entries.is_empty() { + let memo = TransferMemo { entries: transfer_entries, total_value: transfer_total }; + let memo_key = memo.identifier(); + self.claimer + .claim_external_memo(memo, external_claim_message_id(&memo_key)) + .await?; + report.recovered_count = + report + .recovered_count + .checked_add(report.transferred_count) + .ok_or_else(|| "spent Coinage recovered count exceeds u32".to_string())?; + report.recovered_planks = report + .recovered_planks + .checked_add(transfer_total) + .ok_or_else(|| "spent Coinage recovery total exceeds u128".to_string())?; + } + Ok(report) + } } #[async_trait] impl SpentCoinsRecovering for SpentCoinTransferRecoveryService { - async fn recover_spent_coins(&self, spent: Vec) -> Result { - self.recover(spent) - .await - .map(|report| report.recovered_planks) - } + async fn recover_spent_coins(&self, spent: Vec) -> Result { + self.recover(spent).await.map(|report| report.recovered_planks) + } } /// The only accepted external-claim id. It is public for host composition /// and tests, but contains no secret material. pub fn external_claim_message_id(memo_key: &[u8; 32]) -> String { - format!("w3s-coins-{}", hex::encode(memo_key)) + format!("w3s-coins-{}", hex::encode(memo_key)) } fn source_entries(entries: Vec) -> Result, String> { - let mut seen = HashSet::with_capacity(entries.len()); - entries - .into_iter() - .enumerate() - .map(|(index, entry)| { - let secret = schnorrkel::SecretKey::from_bytes(&entry.0) - .map_err(|error| format!("external coin secret {index} is invalid: {error}"))?; - let public = secret.to_public().to_bytes(); - if !seen.insert(public) { - return Err(format!("external coin source {index} is duplicated")); - } - Ok(Some((entry, public))) - }) - .collect() + let mut seen = HashSet::with_capacity(entries.len()); + entries + .into_iter() + .enumerate() + .map(|(index, entry)| { + let secret = schnorrkel::SecretKey::from_bytes(&entry.0) + .map_err(|error| format!("external coin secret {index} is invalid: {error}"))?; + let public = secret.to_public().to_bytes(); + if !seen.insert(public) { + return Err(format!("external coin source {index} is duplicated")); + } + Ok(Some((entry, public))) + }) + .collect() } fn validate_context(context: &DenominationBreakdownContext) -> Result<(), String> { - if context.asset_unit == 0 { - return Err("Coinage asset unit must be non-zero".into()); - } - if context.max_exponent < context.min_exponent { - return Err("Coinage denomination range is inverted".into()); - } - Ok(()) + if context.asset_unit == 0 { + return Err("Coinage asset unit must be non-zero".into()); + } + if context.max_exponent < context.min_exponent { + return Err("Coinage denomination range is inverted".into()); + } + Ok(()) } fn validate_exponent(exponent: i16, context: &DenominationBreakdownContext) -> Result<(), String> { - if exponent < context.min_exponent || exponent > context.max_exponent { - return Err(format!( - "Coinage exponent {exponent} is outside {}..={}", - context.min_exponent, context.max_exponent - )); - } - // The live pallet's transfer preserves its signed i8 `value`. - i8::try_from(exponent) - .map(|_| ()) - .map_err(|_| format!("Coinage exponent {exponent} does not fit the runtime i8")) + if exponent < context.min_exponent || exponent > context.max_exponent { + return Err(format!( + "Coinage exponent {exponent} is outside {}..={}", + context.min_exponent, context.max_exponent + )); + } + // The live pallet's transfer preserves its signed i8 `value`. + i8::try_from(exponent) + .map(|_| ()) + .map_err(|_| format!("Coinage exponent {exponent} does not fit the runtime i8")) } fn validate_existing_plan( - plan: &ClaimPlan, - memo_key: &[u8; 32], - message_id: &str, - total_value: u128, - entry_count: usize, - context: &DenominationBreakdownContext, + plan: &ClaimPlan, + memo_key: &[u8; 32], + message_id: &str, + total_value: u128, + entry_count: usize, + context: &DenominationBreakdownContext, ) -> Result<(), String> { - // Plans written before chat claims switched to chat message ids carry - // the memo-derived external id; accept either spelling. - let message_id_matches = plan.message_id.as_deref() == Some(message_id) - || plan.message_id.as_deref() == Some(external_claim_message_id(memo_key).as_str()); - if plan.memo_key != *memo_key || !message_id_matches || plan.total_value != total_value { - return Err("persisted external coin claim plan does not match its memo".into()); - } - if plan.entries.len() != entry_count { - return Err(format!( - "persisted external coin claim plan has {} entries; expected {entry_count}", - plan.entries.len() - )); - } - let entries = ordered_plan_entries(plan, entry_count)?; - let mut total = 0u128; - let confirmed = plan.claimed_amount.unwrap_or(0); - let mut confirmed_boundary = confirmed == 0; - let mut forfeited_value = 0u128; - for entry in entries { - validate_exponent(entry.exponent, context)?; - let value = context.value_in_planks(entry.exponent); - total = total - .checked_add(value) - .ok_or_else(|| "external coin claim plan total exceeds u128".to_string())?; - confirmed_boundary |= confirmed == total; - if plan.markers.forfeited.contains(&entry.entry_index) { - // A forfeit is recorded together with the prefix that passes it. - if total > confirmed { - return Err("persisted external claim forfeit lies beyond its progress".into()); - } - forfeited_value = forfeited_value - .checked_add(value) - .ok_or_else(|| "external coin claim plan total exceeds u128".to_string())?; - } - } - if forfeited_value != plan.markers.forfeited_value { - return Err("persisted external claim forfeits do not match their value".into()); - } - if total != total_value { - return Err(format!( - "persisted external coin claim amount mismatch: memo {total_value}, plan {total}" - )); - } - if !confirmed_boundary { - return Err("persisted external claim progress is not a finalized entry boundary".into()); - } - Ok(()) + // Plans written before chat claims switched to chat message ids carry + // the memo-derived external id; accept either spelling. + let message_id_matches = plan.message_id.as_deref() == Some(message_id) || + plan.message_id.as_deref() == Some(external_claim_message_id(memo_key).as_str()); + if plan.memo_key != *memo_key || !message_id_matches || plan.total_value != total_value { + return Err("persisted external coin claim plan does not match its memo".into()); + } + if plan.entries.len() != entry_count { + return Err(format!( + "persisted external coin claim plan has {} entries; expected {entry_count}", + plan.entries.len() + )); + } + let entries = ordered_plan_entries(plan, entry_count)?; + let mut total = 0u128; + let confirmed = plan.claimed_amount.unwrap_or(0); + let mut confirmed_boundary = confirmed == 0; + let mut forfeited_value = 0u128; + for entry in entries { + validate_exponent(entry.exponent, context)?; + let value = context.value_in_planks(entry.exponent); + total = total + .checked_add(value) + .ok_or_else(|| "external coin claim plan total exceeds u128".to_string())?; + confirmed_boundary |= confirmed == total; + if plan.markers.forfeited.contains(&entry.entry_index) { + // A forfeit is recorded together with the prefix that passes it. + if total > confirmed { + return Err("persisted external claim forfeit lies beyond its progress".into()); + } + forfeited_value = forfeited_value + .checked_add(value) + .ok_or_else(|| "external coin claim plan total exceeds u128".to_string())?; + } + } + if forfeited_value != plan.markers.forfeited_value { + return Err("persisted external claim forfeits do not match their value".into()); + } + if total != total_value { + return Err(format!( + "persisted external coin claim amount mismatch: memo {total_value}, plan {total}" + )); + } + if !confirmed_boundary { + return Err("persisted external claim progress is not a finalized entry boundary".into()); + } + Ok(()) } /// The credited value of a finished plan, never its forfeited entries. fn credited(plan: &ClaimPlan) -> Result { - plan.credited_amount() - .ok_or_else(|| "external coin claim credit exceeds its processed prefix".to_string()) + plan.credited_amount() + .ok_or_else(|| "external coin claim credit exceeds its processed prefix".to_string()) } fn ordered_plan_entries( - plan: &ClaimPlan, - entry_count: usize, + plan: &ClaimPlan, + entry_count: usize, ) -> Result, String> { - let mut ordered = vec![None; entry_count]; - for entry in &plan.entries { - let index = usize::try_from(entry.entry_index) - .map_err(|_| "external coin claim plan has a negative entry index".to_string())?; - let slot = ordered.get_mut(index).ok_or_else(|| { - format!("external coin claim plan entry index {index} is out of bounds") - })?; - if slot.replace(*entry).is_some() { - return Err(format!( - "external coin claim plan entry index {index} is duplicated" - )); - } - } - ordered - .into_iter() - .enumerate() - .map(|(index, entry)| { - entry.ok_or_else(|| format!("external coin claim plan entry index {index} is missing")) - }) - .collect() + let mut ordered = vec![None; entry_count]; + for entry in &plan.entries { + let index = usize::try_from(entry.entry_index) + .map_err(|_| "external coin claim plan has a negative entry index".to_string())?; + let slot = ordered.get_mut(index).ok_or_else(|| { + format!("external coin claim plan entry index {index} is out of bounds") + })?; + if slot.replace(*entry).is_some() { + return Err(format!("external coin claim plan entry index {index} is duplicated")); + } + } + ordered + .into_iter() + .enumerate() + .map(|(index, entry)| { + entry.ok_or_else(|| format!("external coin claim plan entry index {index} is missing")) + }) + .collect() } fn validate_recipients(sources: &[[u8; 32]], recipients: &[[u8; 32]]) -> Result<(), String> { - if sources.len() != recipients.len() { - return Err("external coin source/recipient count mismatch".into()); - } - let source_set = sources.iter().copied().collect::>(); - let mut recipient_set = HashSet::with_capacity(recipients.len()); - for recipient in recipients { - if *recipient == [0; 32] - || source_set.contains(recipient) - || !recipient_set.insert(*recipient) - { - return Err("external coin claim recipient key collision".into()); - } - } - Ok(()) + if sources.len() != recipients.len() { + return Err("external coin source/recipient count mismatch".into()); + } + let source_set = sources.iter().copied().collect::>(); + let mut recipient_set = HashSet::with_capacity(recipients.len()); + for recipient in recipients { + if *recipient == [0; 32] || + source_set.contains(recipient) || + !recipient_set.insert(*recipient) + { + return Err("external coin claim recipient key collision".into()); + } + } + Ok(()) } async fn fetch_exact( - backend: &dyn ExternalCoinTransferBackend, - keys: &[[u8; 32]], - label: &str, + backend: &dyn ExternalCoinTransferBackend, + keys: &[[u8; 32]], + label: &str, ) -> Result>, String> { - let rows = backend.fetch_coins(keys).await?; - if rows.len() != keys.len() { - return Err(format!( - "{label} returned {} values for {} keys", - rows.len(), - keys.len() - )); - } - Ok(rows) + let rows = backend.fetch_coins(keys).await?; + if rows.len() != keys.len() { + return Err(format!("{label} returned {} values for {} keys", rows.len(), keys.len())); + } + Ok(rows) } /// Secret-preserving claim operation; implementations do not expose memo bytes /// through a product or transport API. #[async_trait] pub trait ExternalMemoClaiming: Send + Sync { - /// Execute or resume a durable memo-keyed claim into this wallet. - async fn claim_external_memo( - &self, - memo: TransferMemo, - message_id: String, - ) -> Result; + /// Execute or resume a durable memo-keyed claim into this wallet. + async fn claim_external_memo( + &self, + memo: TransferMemo, + message_id: String, + ) -> Result; } /// Recover locally spent coins whose finalized on-chain value remains owned. #[async_trait] pub trait SpentCoinsRecovering: Send + Sync { - /// Reconcile and recover the supplied spent inventory. - async fn recover_spent_coins(&self, spent: Vec) -> Result; + /// Reconcile and recover the supplied spent inventory. + async fn recover_spent_coins(&self, spent: Vec) -> Result; } #[cfg(test)] mod tests { - use parking_lot::Mutex as StdMutex; - - use super::*; - use crate::index_store::InMemoryCoinageIndexStore; - use crate::repo::InMemoryCoinRepository; - - fn context() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 10, - max_exponent: 4, - min_exponent: 0, - precision: 2, - } - } - - fn expanded_secret(seed: u8) -> MemoEntry { - MemoEntry( - schnorrkel::MiniSecretKey::from_bytes(&[seed; 32]) - .unwrap() - .expand(schnorrkel::ExpansionMode::Ed25519) - .to_bytes(), - ) - } - - fn public(entry: &MemoEntry) -> [u8; 32] { - schnorrkel::SecretKey::from_bytes(&entry.0) - .unwrap() - .to_public() - .to_bytes() - } - - #[derive(Default)] - struct MemoryPlans(StdMutex>); - - #[async_trait] - impl ClaimPlanStore for MemoryPlans { - async fn save(&self, plan: &ClaimPlan) -> Result<(), String> { - self.0.lock().insert(plan.memo_key, plan.clone()); - Ok(()) - } - - async fn plan(&self, memo_key: &[u8; 32]) -> Result, String> { - Ok(self.0.lock().get(memo_key).cloned()) - } - - async fn load_all(&self) -> Result, String> { - Ok(self.0.lock().values().cloned().collect()) - } - - async fn update_status( - &self, - memo_key: &[u8; 32], - status: ClaimPlanStatus, - claimed_amount: Option, - ) -> Result<(), String> { - let mut plans = self.0.lock(); - let plan = plans - .get_mut(memo_key) - .ok_or_else(|| "claim plan is missing".to_string())?; - plan.status = status; - plan.claimed_amount = claimed_amount; - Ok(()) - } - - async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String> { - self.0.lock().remove(memo_key); - Ok(()) - } - } - - #[derive(Debug, Clone, PartialEq, Eq)] - struct RecordedTransfer { - source: [u8; 32], - recipient: [u8; 32], - exponent: i16, - asset_unit: u128, - amount_planks: u128, - } - - struct MockBackend { - context: DenominationBreakdownContext, - state: StdMutex>, - transfers: StdMutex>, - plans: Arc, - expected_plan: StdMutex>, - /// Consume the source but report no outcome, like a transfer whose - /// finality this wallet has not yet observed. - lose_transfers: StdMutex, - } - - #[async_trait] - impl ExternalCoinTransferBackend for MockBackend { - async fn denomination_context(&self) -> Result { - Ok(self.context.clone()) - } - - async fn fetch_coins( - &self, - public_keys: &[[u8; 32]], - ) -> Result>, String> { - let state = self.state.lock(); - Ok(public_keys - .iter() - .map(|public| state.get(public).copied()) - .collect()) - } - - async fn submit_transfer( - &self, - request: ExternalCoinTransferRequest, - ) -> Result { - if let Some(expected_plan) = *self.expected_plan.lock() { - assert!( - self.plans.0.lock().contains_key(&expected_plan), - "claim plan must be durable before the first transfer" - ); - } - let derived = public(&request.source_secret); - assert_eq!(derived, request.source_public); - let mut state = self.state.lock(); - let source = state - .remove(&request.source_public) - .ok_or_else(|| "source disappeared".to_string())?; - assert_eq!(source.exponent, request.exponent); - if *self.lose_transfers.lock() { - return Err("transfer outcome not yet observed".into()); - } - assert!(!state.contains_key(&request.recipient)); - let landed = OnChainCoin { - exponent: request.exponent, - age: 0, - }; - state.insert(request.recipient, landed); - self.transfers.lock().push(RecordedTransfer { - source: request.source_public, - recipient: request.recipient, - exponent: request.exponent, - asset_unit: request.asset_unit, - amount_planks: request.amount_planks, - }); - Ok(landed) - } - } - - struct Rig { - service: Arc, - plans: Arc, - coins: Arc, - backend: Arc, - } - - fn rig(source_rows: impl IntoIterator) -> Rig { - let plans = Arc::new(MemoryPlans::default()); - let coins = Arc::new(InMemoryCoinRepository::default()); - let backend = Arc::new(MockBackend { - context: context(), - state: StdMutex::new(source_rows.into_iter().collect()), - transfers: StdMutex::new(Vec::new()), - plans: Arc::clone(&plans), - expected_plan: StdMutex::new(None), - lose_transfers: StdMutex::new(false), - }); - let service = Arc::new(ExternalSecretClaimService::new( - &[0x44; 16], - Arc::new(CoinAllocator::new(Arc::new( - InMemoryCoinageIndexStore::default(), - ))), - Arc::clone(&coins) as Arc<_>, - Arc::clone(&plans) as Arc<_>, - Arc::clone(&backend) as Arc<_>, - )); - Rig { - service, - plans, - coins, - backend, - } - } - - #[tokio::test] - async fn await_memo_sources_waits_until_all_sources_land() { - let entry_a = expanded_secret(1); - let entry_b = expanded_secret(2); - let coin = OnChainCoin { - exponent: 1, - age: 0, - }; - // Only A is on-chain at start; B lands while the wait is polling. - let rig = rig([(public(&entry_a), coin)]); - let waiter = { - let service = Arc::clone(&rig.service); - let memo = TransferMemo { - entries: vec![entry_a.clone(), entry_b.clone()], - total_value: 20, - }; - tokio::spawn(async move { - service - .await_memo_sources_on_chain_with( - &memo, - 200, - std::time::Duration::from_millis(2), - ) - .await - }) - }; - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - rig.backend.state.lock().insert(public(&entry_b), coin); - waiter - .await - .unwrap() - .expect("resolves once every source landed"); - - // A memo whose sources never land times out into an error. - let missing = TransferMemo { - entries: vec![expanded_secret(3)], - total_value: 10, - }; - let outcome = rig - .service - .await_memo_sources_on_chain_with(&missing, 3, std::time::Duration::from_millis(1)) - .await; - assert!(outcome.unwrap_err().contains("not detected")); - } - - #[tokio::test] - async fn claim_persists_plan_before_exact_denominated_transfers() { - let first = expanded_secret(1); - let second = expanded_secret(2); - let memo = TransferMemo { - entries: vec![first.clone(), second.clone()], - total_value: 60, - }; - let memo_key = memo.identifier(); - let rig = rig([ - ( - public(&first), - OnChainCoin { - exponent: 1, - age: 7, - }, - ), - ( - public(&second), - OnChainCoin { - exponent: 2, - age: 9, - }, - ), - ]); - *rig.backend.expected_plan.lock() = Some(memo_key); - - rig.service - .claim_external_memo(memo, external_claim_message_id(&memo_key)) - .await - .unwrap(); - - let transfers = rig.backend.transfers.lock().clone(); - assert_eq!(transfers.len(), 2); - assert_eq!( - transfers - .iter() - .map(|transfer| ( - transfer.exponent, - transfer.asset_unit, - transfer.amount_planks, - )) - .collect::>(), - [(1, 10, 20), (2, 10, 40)] - ); - let plan = rig.plans.0.lock().get(&memo_key).unwrap().clone(); - assert_eq!(plan.status, ClaimPlanStatus::Finished); - assert_eq!(plan.claimed_amount, Some(60)); - assert_eq!(plan.entries.len(), 2); - let coins = rig.coins.list().await.unwrap(); - assert_eq!(coins.len(), 2); - assert!(coins.iter().all(|coin| coin.state == CoinState::Available)); - } - - #[tokio::test] - async fn amount_mismatch_never_allocates_or_submits() { - let source = expanded_secret(3); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 21, - }; - let memo_key = memo.identifier(); - let rig = rig([( - public(&source), - OnChainCoin { - exponent: 1, - age: 0, - }, - )]); - - let error = rig - .service - .claim_external_memo(memo, external_claim_message_id(&memo_key)) - .await - .unwrap_err(); - assert!(error.contains("amount mismatch")); - assert!(rig.plans.0.lock().is_empty()); - assert!(rig.backend.transfers.lock().is_empty()); - } - - #[tokio::test] - async fn duplicate_source_fails_before_chain_mutation() { - let source = expanded_secret(4); - let duplicate = TransferMemo { - entries: vec![source.clone(), source.clone()], - total_value: 40, - }; - let duplicate_key = duplicate.identifier(); - let rig = rig([( - public(&source), - OnChainCoin { - exponent: 1, - age: 0, - }, - )]); - assert!( - rig.service - .claim_external_memo(duplicate, external_claim_message_id(&duplicate_key)) - .await - .unwrap_err() - .contains("duplicated") - ); - assert!(rig.backend.transfers.lock().is_empty()); - } - - /// Chat claims pass the chat row's message id; it must be accepted and - /// recorded on the plan so startup hydration restores the status under - /// the id the chat UI actually reads. - #[tokio::test] - async fn chat_message_id_is_accepted_and_persisted_on_the_plan() { - let source = expanded_secret(5); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let memo_key = memo.identifier(); - let rig = rig([( - public(&source), - OnChainCoin { - exponent: 1, - age: 0, - }, - )]); - - let claimed = rig - .service - .claim_external_memo(memo, "chat-message-1".into()) - .await - .unwrap(); - assert_eq!(claimed, 20); - let plan = rig.plans.0.lock().get(&memo_key).unwrap().clone(); - assert_eq!(plan.message_id.as_deref(), Some("chat-message-1")); - assert_eq!(plan.status, ClaimPlanStatus::Finished); - } - - #[tokio::test] - async fn existing_landed_destination_recovers_without_resubmission() { - let source = expanded_secret(6); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let memo_key = memo.identifier(); - let rig = rig([]); - let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); - rig.backend.state.lock().insert( - recipient, - OnChainCoin { - exponent: 1, - age: 3, - }, - ); - rig.plans.0.lock().insert( - memo_key, - ClaimPlan { - memo_key, - message_id: Some(external_claim_message_id(&memo_key)), - entries: vec![CodableClaimPlanEntry { - entry_index: 0, - exponent: 1, - derivation_index: 0, - }], - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Error, - claimed_amount: None, - total_value: 20, - markers: ClaimMarkers::default(), - }, - ); - - rig.service - .claim_external_memo(memo, external_claim_message_id(&memo_key)) - .await - .unwrap(); - assert!(rig.backend.transfers.lock().is_empty()); - let coins = rig.coins.list().await.unwrap(); - assert_eq!(coins.len(), 1); - assert_eq!(coins[0].age, Some(3)); - assert_eq!( - rig.plans.0.lock().get(&memo_key).unwrap().status, - ClaimPlanStatus::Finished - ); - } - - #[tokio::test] - async fn prepared_claim_is_durable_without_spending_and_survives_restart() { - let source = expanded_secret(8); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let key = memo.identifier(); - let rig = rig([( - public(&source), - OnChainCoin { - exponent: 1, - age: 2, - }, - )]); - let plan = rig - .service - .prepare_memo(&memo, external_claim_message_id(&key)) - .await - .unwrap(); - assert!(rig.backend.transfers.lock().is_empty()); - assert_eq!(rig.plans.plan(&key).await.unwrap(), Some(plan.clone())); - let restarted = ExternalSecretClaimService::new( - &[0x44; 16], - Arc::new(CoinAllocator::new(Arc::new( - InMemoryCoinageIndexStore::default(), - ))), - rig.coins.clone(), - rig.plans.clone(), - rig.backend.clone(), - ); - assert_eq!( - restarted - .prepare_memo(&memo, external_claim_message_id(&key)) - .await - .unwrap(), - plan - ); - assert_eq!( - restarted - .claim_external_memo( - TransferMemo { - entries: memo.entries.clone(), - total_value: 20 - }, - external_claim_message_id(&key), - ) - .await - .unwrap(), - 20 - ); - rig.backend.state.lock().clear(); - assert_eq!( - restarted - .claim_external_memo(memo, external_claim_message_id(&key)) - .await - .unwrap(), - 20 - ); - assert_eq!(rig.backend.transfers.lock().len(), 1); - } - - #[tokio::test] - async fn source_spent_elsewhere_after_planning_finishes_with_zero_credit() { - let source = expanded_secret(9); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let key = memo.identifier(); - let rig = rig([( - public(&source), - OnChainCoin { - exponent: 1, - age: 2, - }, - )]); - rig.service - .prepare_memo(&memo, external_claim_message_id(&key)) - .await - .unwrap(); - // The sender spends the source before this wallet submits anything. - rig.backend.state.lock().clear(); - assert_eq!( - rig.service - .claim_external_memo( - TransferMemo { - entries: memo.entries.clone(), - total_value: 20 - }, - external_claim_message_id(&key) - ) - .await - .unwrap(), - 0 - ); - let plan = rig.plans.plan(&key).await.unwrap().unwrap(); - assert_eq!(plan.status, ClaimPlanStatus::Finished); - assert_eq!(plan.claimed_amount, Some(20)); - assert_eq!(plan.markers.forfeited, vec![0]); - assert_eq!(plan.credited_amount(), Some(0)); - assert!(rig.backend.transfers.lock().is_empty()); - assert!(rig.coins.list().await.unwrap().is_empty()); - // The terminal outcome is stable across retries. - assert_eq!( - rig.service - .claim_external_memo(memo, external_claim_message_id(&key)) - .await - .unwrap(), - 0 - ); - } - - #[tokio::test] - async fn one_source_spent_elsewhere_credits_only_what_landed() { - let first = expanded_secret(21); - let second = expanded_secret(22); - let memo = TransferMemo { - entries: vec![first.clone(), second.clone()], - total_value: 60, - }; - let key = memo.identifier(); - let rig = rig([ - ( - public(&first), - OnChainCoin { - exponent: 1, - age: 2, - }, - ), - ( - public(&second), - OnChainCoin { - exponent: 2, - age: 2, - }, - ), - ]); - rig.service - .prepare_memo(&memo, external_claim_message_id(&key)) - .await - .unwrap(); - rig.backend.state.lock().remove(&public(&second)); - assert_eq!( - rig.service - .claim_external_memo(memo, external_claim_message_id(&key)) - .await - .unwrap(), - 20 - ); - let plan = rig.plans.plan(&key).await.unwrap().unwrap(); - assert_eq!(plan.status, ClaimPlanStatus::Finished); - assert_eq!(plan.markers.submitted, vec![0]); - assert_eq!(plan.markers.forfeited, vec![1]); - assert_eq!(plan.markers.forfeited_value, 40); - assert_eq!(plan.credited_amount(), Some(20)); - assert_eq!(rig.coins.list().await.unwrap().len(), 1); - } - - #[tokio::test] - async fn unobserved_own_transfer_stays_ambiguous_across_restart() { - let source = expanded_secret(23); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let key = memo.identifier(); - let rig = rig([( - public(&source), - OnChainCoin { - exponent: 1, - age: 2, - }, - )]); - *rig.backend.lose_transfers.lock() = true; - assert!( - rig.service - .claim_external_memo( - TransferMemo { - entries: memo.entries.clone(), - total_value: 20 - }, - external_claim_message_id(&key) - ) - .await - .is_err() - ); - let plan = rig.plans.plan(&key).await.unwrap().unwrap(); - assert_eq!(plan.markers.submitted, vec![0]); - assert!(plan.markers.forfeited.is_empty()); - // Source consumed, destination unobserved: never a forfeit, even after - // a restart reads the durable marker back. - let restarted = ExternalSecretClaimService::new( - &[0x44; 16], - Arc::new(CoinAllocator::new(Arc::new( - InMemoryCoinageIndexStore::default(), - ))), - rig.coins.clone(), - rig.plans.clone(), - rig.backend.clone(), - ); - assert!( - restarted - .claim_external_memo(memo, external_claim_message_id(&key)) - .await - .is_err() - ); - let plan = rig.plans.plan(&key).await.unwrap().unwrap(); - assert_ne!(plan.status, ClaimPlanStatus::Finished); - assert_eq!(plan.markers.submitted, vec![0]); - assert!(plan.markers.forfeited.is_empty()); - assert_eq!(plan.claimed_amount, None); - } - - #[tokio::test] - async fn absent_source_before_planning_records_nothing() { - let source = expanded_secret(25); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let key = memo.identifier(); - // Unfunded and spent-elsewhere look the same before any observation. - let rig = rig(std::iter::empty()); - assert!( - rig.service - .claim_external_memo(memo, external_claim_message_id(&key)) - .await - .is_err() - ); - assert!(rig.plans.plan(&key).await.unwrap().is_none()); - } - - #[tokio::test] - async fn partial_finalized_prefix_survives_spent_destination_and_retry() { - let first = expanded_secret(14); - let second = expanded_secret(15); - let memo = TransferMemo { - entries: vec![first.clone(), second.clone()], - total_value: 60, - }; - let key = memo.identifier(); - let rig = rig([ - ( - public(&first), - OnChainCoin { - exponent: 1, - age: 2, - }, - ), - ( - public(&second), - OnChainCoin { - exponent: 2, - age: 2, - }, - ), - ]); - let plan = rig - .service - .prepare_memo(&memo, external_claim_message_id(&key)) - .await - .unwrap(); - let destination = CoinKeypairFactory::new(&[0x44; 16]) - .public_key(plan.entries[0].derivation_index) - .unwrap(); - // Entry 1's transfer was submitted but not yet observed, so its - // absence stays ambiguous rather than a forfeit. - let mut submitted = plan.clone(); - submitted.markers.submitted = vec![1]; - rig.plans.save(&submitted).await.unwrap(); - { - let mut state = rig.backend.state.lock(); - state.remove(&public(&first)); - state.remove(&public(&second)); - state.insert( - destination, - OnChainCoin { - exponent: 1, - age: 0, - }, - ); - } - assert!( - rig.service - .claim_external_memo( - TransferMemo { - entries: memo.entries.clone(), - total_value: 60 - }, - external_claim_message_id(&key), - ) - .await - .is_err() - ); - assert_eq!( - rig.plans.plan(&key).await.unwrap().unwrap().claimed_amount, - Some(20) - ); - { - let mut state = rig.backend.state.lock(); - state.remove(&destination); - state.insert( - public(&second), - OnChainCoin { - exponent: 2, - age: 2, - }, - ); - } - let restarted = ExternalSecretClaimService::new( - &[0x44; 16], - Arc::new(CoinAllocator::new(Arc::new( - InMemoryCoinageIndexStore::default(), - ))), - rig.coins.clone(), - rig.plans.clone(), - rig.backend.clone(), - ); - assert_eq!( - restarted - .claim_external_memo(memo, external_claim_message_id(&key)) - .await - .unwrap(), - 60 - ); - assert_eq!( - rig.backend - .transfers - .lock() - .iter() - .map(|transfer| transfer.source) - .collect::>(), - vec![public(&second)] - ); - assert_eq!( - rig.plans.plan(&key).await.unwrap().unwrap().status, - ClaimPlanStatus::Finished - ); - } - - /// At one finalized snapshot, both keys present is a destination collision, - /// not proof this memo's source was transferred. - #[tokio::test] - async fn landed_destination_with_unconsumed_source_never_clears() { - let source = expanded_secret(10); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let memo_key = memo.identifier(); - let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); - let rig = rig([ - ( - public(&source), - OnChainCoin { - exponent: 1, - age: 2, - }, - ), - ( - recipient, - OnChainCoin { - exponent: 1, - age: 5, - }, - ), - ]); - rig.plans.0.lock().insert( - memo_key, - ClaimPlan { - memo_key, - message_id: Some("chat-message-1".into()), - entries: vec![CodableClaimPlanEntry { - entry_index: 0, - exponent: 1, - derivation_index: 0, - }], - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Processing, - claimed_amount: None, - total_value: 20, - markers: ClaimMarkers::default(), - }, - ); - - assert!( - rig.service - .claim_external_memo(memo, "chat-message-1".into()) - .await - .is_err() - ); - assert!(rig.backend.transfers.lock().is_empty()); - assert!(rig.coins.list().await.unwrap().is_empty()); - assert_eq!( - rig.plans - .plan(&memo_key) - .await - .unwrap() - .unwrap() - .claimed_amount, - None - ); - } - - /// A plan persisted before chat claims carried chat message ids keeps - /// working when the claim now arrives under the chat row's id. - #[tokio::test] - async fn legacy_external_id_plan_accepts_the_chat_message_id() { - let source = expanded_secret(11); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let memo_key = memo.identifier(); - let rig = rig([]); - let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); - rig.backend.state.lock().insert( - recipient, - OnChainCoin { - exponent: 1, - age: 3, - }, - ); - rig.plans.0.lock().insert( - memo_key, - ClaimPlan { - memo_key, - message_id: Some(external_claim_message_id(&memo_key)), - entries: vec![CodableClaimPlanEntry { - entry_index: 0, - exponent: 1, - derivation_index: 0, - }], - outgoing_public_keys: Vec::new(), - detection_anchor: None, - status: ClaimPlanStatus::Error, - claimed_amount: None, - total_value: 20, - markers: ClaimMarkers::default(), - }, - ); - - let claimed = rig - .service - .claim_external_memo(memo, "chat-message-1".into()) - .await - .unwrap(); - assert_eq!(claimed, 20); - assert_eq!( - rig.plans.0.lock().get(&memo_key).unwrap().status, - ClaimPlanStatus::Finished, - "a persisted error heals once the destination is proven" - ); - } - - #[tokio::test] - async fn source_and_recipient_presence_collision_fails_closed() { - let source = expanded_secret(7); - let memo = TransferMemo { - entries: vec![source.clone()], - total_value: 20, - }; - let memo_key = memo.identifier(); - let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); - let rig = rig([ - ( - public(&source), - OnChainCoin { - exponent: 1, - age: 0, - }, - ), - ( - recipient, - OnChainCoin { - exponent: 1, - age: 0, - }, - ), - ]); - - let error = rig - .service - .claim_external_memo(memo, external_claim_message_id(&memo_key)) - .await - .unwrap_err(); - assert!(error.contains("destination already exists")); - assert!(rig.backend.transfers.lock().is_empty()); - assert!(rig.plans.0.lock().is_empty()); - } - - #[tokio::test] - async fn spent_recovery_restores_max_age_and_reuses_the_claim_transfer_lane() { - let factory = CoinKeypairFactory::new(&[0x44; 16]); - let max_age = Coin { - exponent: 1, - derivation_index: 3, - age: Some(1), - state: CoinState::Spent, - }; - let transferable = Coin { - exponent: 2, - derivation_index: 4, - age: Some(1), - state: CoinState::Spent, - }; - let absent = Coin { - exponent: 0, - derivation_index: 5, - age: Some(1), - state: CoinState::Spent, - }; - let rig = rig([ - ( - factory.public_key(max_age.derivation_index).unwrap(), - OnChainCoin { - exponent: max_age.exponent, - age: COIN_MAX_AGE, - }, - ), - ( - factory.public_key(transferable.derivation_index).unwrap(), - OnChainCoin { - exponent: transferable.exponent, - age: COIN_MAX_AGE - 1, - }, - ), - ]); - for coin in [&max_age, &transferable, &absent] { - rig.coins.upsert(coin).await.unwrap(); - } - let recovery = SpentCoinTransferRecoveryService::new( - &[0x44; 16], - Arc::clone(&rig.coins) as Arc<_>, - Arc::clone(&rig.backend) as Arc<_>, - Arc::clone(&rig.service), - ); - - let report = recovery - .recover(vec![max_age.clone(), transferable.clone(), absent]) - .await - .unwrap(); - assert_eq!( - report, - SpentCoinTransferRecoveryReport { - recovered_count: 2, - recovered_planks: 60, - restored_max_age_count: 1, - transferred_count: 1, - } - ); - assert_eq!(rig.backend.transfers.lock().len(), 1); - let coins = rig.coins.list().await.unwrap(); - assert_eq!( - coins - .iter() - .find(|coin| coin.derivation_index == max_age.derivation_index) - .unwrap() - .state, - CoinState::Available - ); - assert_eq!( - coins - .iter() - .find(|coin| coin.derivation_index == transferable.derivation_index) - .unwrap() - .state, - CoinState::Spent - ); - assert!( - coins.iter().any(|coin| coin.derivation_index == 0 - && coin.exponent == transferable.exponent - && coin.state == CoinState::Available), - "the younger source lands in the allocator's fresh destination" - ); - } - - #[tokio::test] - async fn spent_recovery_rejects_non_spent_inputs_before_querying() { - let rig = rig([]); - let recovery = SpentCoinTransferRecoveryService::new( - &[0x44; 16], - Arc::clone(&rig.coins) as Arc<_>, - Arc::clone(&rig.backend) as Arc<_>, - Arc::clone(&rig.service), - ); - let error = recovery - .recover(vec![Coin { - exponent: 0, - derivation_index: 0, - age: Some(0), - state: CoinState::Available, - }]) - .await - .unwrap_err(); - assert!(error.contains("non-spent")); - assert!(rig.backend.transfers.lock().is_empty()); - } + use parking_lot::Mutex as StdMutex; + + use super::*; + use crate::{index_store::InMemoryCoinageIndexStore, repo::InMemoryCoinRepository}; + + fn context() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 10, + max_exponent: 4, + min_exponent: 0, + precision: 2, + } + } + + fn expanded_secret(seed: u8) -> MemoEntry { + MemoEntry( + schnorrkel::MiniSecretKey::from_bytes(&[seed; 32]) + .unwrap() + .expand(schnorrkel::ExpansionMode::Ed25519) + .to_bytes(), + ) + } + + fn public(entry: &MemoEntry) -> [u8; 32] { + schnorrkel::SecretKey::from_bytes(&entry.0).unwrap().to_public().to_bytes() + } + + #[derive(Default)] + struct MemoryPlans(StdMutex>); + + #[async_trait] + impl ClaimPlanStore for MemoryPlans { + async fn save(&self, plan: &ClaimPlan) -> Result<(), String> { + self.0.lock().insert(plan.memo_key, plan.clone()); + Ok(()) + } + + async fn plan(&self, memo_key: &[u8; 32]) -> Result, String> { + Ok(self.0.lock().get(memo_key).cloned()) + } + + async fn load_all(&self) -> Result, String> { + Ok(self.0.lock().values().cloned().collect()) + } + + async fn update_status( + &self, + memo_key: &[u8; 32], + status: ClaimPlanStatus, + claimed_amount: Option, + ) -> Result<(), String> { + let mut plans = self.0.lock(); + let plan = + plans.get_mut(memo_key).ok_or_else(|| "claim plan is missing".to_string())?; + plan.status = status; + plan.claimed_amount = claimed_amount; + Ok(()) + } + + async fn remove(&self, memo_key: &[u8; 32]) -> Result<(), String> { + self.0.lock().remove(memo_key); + Ok(()) + } + } + + #[derive(Debug, Clone, PartialEq, Eq)] + struct RecordedTransfer { + source: [u8; 32], + recipient: [u8; 32], + exponent: i16, + asset_unit: u128, + amount_planks: u128, + } + + struct MockBackend { + context: DenominationBreakdownContext, + state: StdMutex>, + transfers: StdMutex>, + plans: Arc, + expected_plan: StdMutex>, + /// Consume the source but report no outcome, like a transfer whose + /// finality this wallet has not yet observed. + lose_transfers: StdMutex, + } + + #[async_trait] + impl ExternalCoinTransferBackend for MockBackend { + async fn denomination_context(&self) -> Result { + Ok(self.context.clone()) + } + + async fn fetch_coins( + &self, + public_keys: &[[u8; 32]], + ) -> Result>, String> { + let state = self.state.lock(); + Ok(public_keys.iter().map(|public| state.get(public).copied()).collect()) + } + + async fn submit_transfer( + &self, + request: ExternalCoinTransferRequest, + ) -> Result { + if let Some(expected_plan) = *self.expected_plan.lock() { + assert!( + self.plans.0.lock().contains_key(&expected_plan), + "claim plan must be durable before the first transfer" + ); + } + let derived = public(&request.source_secret); + assert_eq!(derived, request.source_public); + let mut state = self.state.lock(); + let source = state + .remove(&request.source_public) + .ok_or_else(|| "source disappeared".to_string())?; + assert_eq!(source.exponent, request.exponent); + if *self.lose_transfers.lock() { + return Err("transfer outcome not yet observed".into()); + } + assert!(!state.contains_key(&request.recipient)); + let landed = OnChainCoin { exponent: request.exponent, age: 0 }; + state.insert(request.recipient, landed); + self.transfers.lock().push(RecordedTransfer { + source: request.source_public, + recipient: request.recipient, + exponent: request.exponent, + asset_unit: request.asset_unit, + amount_planks: request.amount_planks, + }); + Ok(landed) + } + } + + struct Rig { + service: Arc, + plans: Arc, + coins: Arc, + backend: Arc, + } + + fn rig(source_rows: impl IntoIterator) -> Rig { + let plans = Arc::new(MemoryPlans::default()); + let coins = Arc::new(InMemoryCoinRepository::default()); + let backend = Arc::new(MockBackend { + context: context(), + state: StdMutex::new(source_rows.into_iter().collect()), + transfers: StdMutex::new(Vec::new()), + plans: Arc::clone(&plans), + expected_plan: StdMutex::new(None), + lose_transfers: StdMutex::new(false), + }); + let service = Arc::new(ExternalSecretClaimService::new( + &[0x44; 16], + Arc::new(CoinAllocator::new(Arc::new(InMemoryCoinageIndexStore::default()))), + Arc::clone(&coins) as Arc<_>, + Arc::clone(&plans) as Arc<_>, + Arc::clone(&backend) as Arc<_>, + )); + Rig { service, plans, coins, backend } + } + + #[tokio::test] + async fn await_memo_sources_waits_until_all_sources_land() { + let entry_a = expanded_secret(1); + let entry_b = expanded_secret(2); + let coin = OnChainCoin { exponent: 1, age: 0 }; + // Only A is on-chain at start; B lands while the wait is polling. + let rig = rig([(public(&entry_a), coin)]); + let waiter = { + let service = Arc::clone(&rig.service); + let memo = + TransferMemo { entries: vec![entry_a.clone(), entry_b.clone()], total_value: 20 }; + tokio::spawn(async move { + service + .await_memo_sources_on_chain_with( + &memo, + 200, + std::time::Duration::from_millis(2), + ) + .await + }) + }; + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + rig.backend.state.lock().insert(public(&entry_b), coin); + waiter.await.unwrap().expect("resolves once every source landed"); + + // A memo whose sources never land times out into an error. + let missing = TransferMemo { entries: vec![expanded_secret(3)], total_value: 10 }; + let outcome = rig + .service + .await_memo_sources_on_chain_with(&missing, 3, std::time::Duration::from_millis(1)) + .await; + assert!(outcome.unwrap_err().contains("not detected")); + } + + #[tokio::test] + async fn claim_persists_plan_before_exact_denominated_transfers() { + let first = expanded_secret(1); + let second = expanded_secret(2); + let memo = TransferMemo { entries: vec![first.clone(), second.clone()], total_value: 60 }; + let memo_key = memo.identifier(); + let rig = rig([ + (public(&first), OnChainCoin { exponent: 1, age: 7 }), + (public(&second), OnChainCoin { exponent: 2, age: 9 }), + ]); + *rig.backend.expected_plan.lock() = Some(memo_key); + + rig.service + .claim_external_memo(memo, external_claim_message_id(&memo_key)) + .await + .unwrap(); + + let transfers = rig.backend.transfers.lock().clone(); + assert_eq!(transfers.len(), 2); + assert_eq!( + transfers + .iter() + .map(|transfer| (transfer.exponent, transfer.asset_unit, transfer.amount_planks,)) + .collect::>(), + [(1, 10, 20), (2, 10, 40)] + ); + let plan = rig.plans.0.lock().get(&memo_key).unwrap().clone(); + assert_eq!(plan.status, ClaimPlanStatus::Finished); + assert_eq!(plan.claimed_amount, Some(60)); + assert_eq!(plan.entries.len(), 2); + let coins = rig.coins.list().await.unwrap(); + assert_eq!(coins.len(), 2); + assert!(coins.iter().all(|coin| coin.state == CoinState::Available)); + } + + #[tokio::test] + async fn amount_mismatch_never_allocates_or_submits() { + let source = expanded_secret(3); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 21 }; + let memo_key = memo.identifier(); + let rig = rig([(public(&source), OnChainCoin { exponent: 1, age: 0 })]); + + let error = rig + .service + .claim_external_memo(memo, external_claim_message_id(&memo_key)) + .await + .unwrap_err(); + assert!(error.contains("amount mismatch")); + assert!(rig.plans.0.lock().is_empty()); + assert!(rig.backend.transfers.lock().is_empty()); + } + + #[tokio::test] + async fn duplicate_source_fails_before_chain_mutation() { + let source = expanded_secret(4); + let duplicate = + TransferMemo { entries: vec![source.clone(), source.clone()], total_value: 40 }; + let duplicate_key = duplicate.identifier(); + let rig = rig([(public(&source), OnChainCoin { exponent: 1, age: 0 })]); + assert!( + rig.service + .claim_external_memo(duplicate, external_claim_message_id(&duplicate_key)) + .await + .unwrap_err() + .contains("duplicated") + ); + assert!(rig.backend.transfers.lock().is_empty()); + } + + /// Chat claims pass the chat row's message id; it must be accepted and + /// recorded on the plan so startup hydration restores the status under + /// the id the chat UI actually reads. + #[tokio::test] + async fn chat_message_id_is_accepted_and_persisted_on_the_plan() { + let source = expanded_secret(5); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let memo_key = memo.identifier(); + let rig = rig([(public(&source), OnChainCoin { exponent: 1, age: 0 })]); + + let claimed = rig.service.claim_external_memo(memo, "chat-message-1".into()).await.unwrap(); + assert_eq!(claimed, 20); + let plan = rig.plans.0.lock().get(&memo_key).unwrap().clone(); + assert_eq!(plan.message_id.as_deref(), Some("chat-message-1")); + assert_eq!(plan.status, ClaimPlanStatus::Finished); + } + + #[tokio::test] + async fn existing_landed_destination_recovers_without_resubmission() { + let source = expanded_secret(6); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let memo_key = memo.identifier(); + let rig = rig([]); + let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); + rig.backend.state.lock().insert(recipient, OnChainCoin { exponent: 1, age: 3 }); + rig.plans.0.lock().insert( + memo_key, + ClaimPlan { + memo_key, + message_id: Some(external_claim_message_id(&memo_key)), + entries: vec![CodableClaimPlanEntry { + entry_index: 0, + exponent: 1, + derivation_index: 0, + }], + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Error, + claimed_amount: None, + total_value: 20, + markers: ClaimMarkers::default(), + }, + ); + + rig.service + .claim_external_memo(memo, external_claim_message_id(&memo_key)) + .await + .unwrap(); + assert!(rig.backend.transfers.lock().is_empty()); + let coins = rig.coins.list().await.unwrap(); + assert_eq!(coins.len(), 1); + assert_eq!(coins[0].age, Some(3)); + assert_eq!(rig.plans.0.lock().get(&memo_key).unwrap().status, ClaimPlanStatus::Finished); + } + + #[tokio::test] + async fn prepared_claim_is_durable_without_spending_and_survives_restart() { + let source = expanded_secret(8); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let key = memo.identifier(); + let rig = rig([(public(&source), OnChainCoin { exponent: 1, age: 2 })]); + let plan = rig.service.prepare_memo(&memo, external_claim_message_id(&key)).await.unwrap(); + assert!(rig.backend.transfers.lock().is_empty()); + assert_eq!(rig.plans.plan(&key).await.unwrap(), Some(plan.clone())); + let restarted = ExternalSecretClaimService::new( + &[0x44; 16], + Arc::new(CoinAllocator::new(Arc::new(InMemoryCoinageIndexStore::default()))), + rig.coins.clone(), + rig.plans.clone(), + rig.backend.clone(), + ); + assert_eq!( + restarted.prepare_memo(&memo, external_claim_message_id(&key)).await.unwrap(), + plan + ); + assert_eq!( + restarted + .claim_external_memo( + TransferMemo { entries: memo.entries.clone(), total_value: 20 }, + external_claim_message_id(&key), + ) + .await + .unwrap(), + 20 + ); + rig.backend.state.lock().clear(); + assert_eq!( + restarted + .claim_external_memo(memo, external_claim_message_id(&key)) + .await + .unwrap(), + 20 + ); + assert_eq!(rig.backend.transfers.lock().len(), 1); + } + + #[tokio::test] + async fn source_spent_elsewhere_after_planning_finishes_with_zero_credit() { + let source = expanded_secret(9); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let key = memo.identifier(); + let rig = rig([(public(&source), OnChainCoin { exponent: 1, age: 2 })]); + rig.service.prepare_memo(&memo, external_claim_message_id(&key)).await.unwrap(); + // The sender spends the source before this wallet submits anything. + rig.backend.state.lock().clear(); + assert_eq!( + rig.service + .claim_external_memo( + TransferMemo { entries: memo.entries.clone(), total_value: 20 }, + external_claim_message_id(&key) + ) + .await + .unwrap(), + 0 + ); + let plan = rig.plans.plan(&key).await.unwrap().unwrap(); + assert_eq!(plan.status, ClaimPlanStatus::Finished); + assert_eq!(plan.claimed_amount, Some(20)); + assert_eq!(plan.markers.forfeited, vec![0]); + assert_eq!(plan.credited_amount(), Some(0)); + assert!(rig.backend.transfers.lock().is_empty()); + assert!(rig.coins.list().await.unwrap().is_empty()); + // The terminal outcome is stable across retries. + assert_eq!( + rig.service + .claim_external_memo(memo, external_claim_message_id(&key)) + .await + .unwrap(), + 0 + ); + } + + #[tokio::test] + async fn one_source_spent_elsewhere_credits_only_what_landed() { + let first = expanded_secret(21); + let second = expanded_secret(22); + let memo = TransferMemo { entries: vec![first.clone(), second.clone()], total_value: 60 }; + let key = memo.identifier(); + let rig = rig([ + (public(&first), OnChainCoin { exponent: 1, age: 2 }), + (public(&second), OnChainCoin { exponent: 2, age: 2 }), + ]); + rig.service.prepare_memo(&memo, external_claim_message_id(&key)).await.unwrap(); + rig.backend.state.lock().remove(&public(&second)); + assert_eq!( + rig.service + .claim_external_memo(memo, external_claim_message_id(&key)) + .await + .unwrap(), + 20 + ); + let plan = rig.plans.plan(&key).await.unwrap().unwrap(); + assert_eq!(plan.status, ClaimPlanStatus::Finished); + assert_eq!(plan.markers.submitted, vec![0]); + assert_eq!(plan.markers.forfeited, vec![1]); + assert_eq!(plan.markers.forfeited_value, 40); + assert_eq!(plan.credited_amount(), Some(20)); + assert_eq!(rig.coins.list().await.unwrap().len(), 1); + } + + #[tokio::test] + async fn unobserved_own_transfer_stays_ambiguous_across_restart() { + let source = expanded_secret(23); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let key = memo.identifier(); + let rig = rig([(public(&source), OnChainCoin { exponent: 1, age: 2 })]); + *rig.backend.lose_transfers.lock() = true; + assert!( + rig.service + .claim_external_memo( + TransferMemo { entries: memo.entries.clone(), total_value: 20 }, + external_claim_message_id(&key) + ) + .await + .is_err() + ); + let plan = rig.plans.plan(&key).await.unwrap().unwrap(); + assert_eq!(plan.markers.submitted, vec![0]); + assert!(plan.markers.forfeited.is_empty()); + // Source consumed, destination unobserved: never a forfeit, even after + // a restart reads the durable marker back. + let restarted = ExternalSecretClaimService::new( + &[0x44; 16], + Arc::new(CoinAllocator::new(Arc::new(InMemoryCoinageIndexStore::default()))), + rig.coins.clone(), + rig.plans.clone(), + rig.backend.clone(), + ); + assert!( + restarted + .claim_external_memo(memo, external_claim_message_id(&key)) + .await + .is_err() + ); + let plan = rig.plans.plan(&key).await.unwrap().unwrap(); + assert_ne!(plan.status, ClaimPlanStatus::Finished); + assert_eq!(plan.markers.submitted, vec![0]); + assert!(plan.markers.forfeited.is_empty()); + assert_eq!(plan.claimed_amount, None); + } + + #[tokio::test] + async fn absent_source_before_planning_records_nothing() { + let source = expanded_secret(25); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let key = memo.identifier(); + // Unfunded and spent-elsewhere look the same before any observation. + let rig = rig(std::iter::empty()); + assert!( + rig.service + .claim_external_memo(memo, external_claim_message_id(&key)) + .await + .is_err() + ); + assert!(rig.plans.plan(&key).await.unwrap().is_none()); + } + + #[tokio::test] + async fn partial_finalized_prefix_survives_spent_destination_and_retry() { + let first = expanded_secret(14); + let second = expanded_secret(15); + let memo = TransferMemo { entries: vec![first.clone(), second.clone()], total_value: 60 }; + let key = memo.identifier(); + let rig = rig([ + (public(&first), OnChainCoin { exponent: 1, age: 2 }), + (public(&second), OnChainCoin { exponent: 2, age: 2 }), + ]); + let plan = rig.service.prepare_memo(&memo, external_claim_message_id(&key)).await.unwrap(); + let destination = CoinKeypairFactory::new(&[0x44; 16]) + .public_key(plan.entries[0].derivation_index) + .unwrap(); + // Entry 1's transfer was submitted but not yet observed, so its + // absence stays ambiguous rather than a forfeit. + let mut submitted = plan.clone(); + submitted.markers.submitted = vec![1]; + rig.plans.save(&submitted).await.unwrap(); + { + let mut state = rig.backend.state.lock(); + state.remove(&public(&first)); + state.remove(&public(&second)); + state.insert(destination, OnChainCoin { exponent: 1, age: 0 }); + } + assert!( + rig.service + .claim_external_memo( + TransferMemo { entries: memo.entries.clone(), total_value: 60 }, + external_claim_message_id(&key), + ) + .await + .is_err() + ); + assert_eq!(rig.plans.plan(&key).await.unwrap().unwrap().claimed_amount, Some(20)); + { + let mut state = rig.backend.state.lock(); + state.remove(&destination); + state.insert(public(&second), OnChainCoin { exponent: 2, age: 2 }); + } + let restarted = ExternalSecretClaimService::new( + &[0x44; 16], + Arc::new(CoinAllocator::new(Arc::new(InMemoryCoinageIndexStore::default()))), + rig.coins.clone(), + rig.plans.clone(), + rig.backend.clone(), + ); + assert_eq!( + restarted + .claim_external_memo(memo, external_claim_message_id(&key)) + .await + .unwrap(), + 60 + ); + assert_eq!( + rig.backend + .transfers + .lock() + .iter() + .map(|transfer| transfer.source) + .collect::>(), + vec![public(&second)] + ); + assert_eq!(rig.plans.plan(&key).await.unwrap().unwrap().status, ClaimPlanStatus::Finished); + } + + /// At one finalized snapshot, both keys present is a destination collision, + /// not proof this memo's source was transferred. + #[tokio::test] + async fn landed_destination_with_unconsumed_source_never_clears() { + let source = expanded_secret(10); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let memo_key = memo.identifier(); + let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); + let rig = rig([ + (public(&source), OnChainCoin { exponent: 1, age: 2 }), + (recipient, OnChainCoin { exponent: 1, age: 5 }), + ]); + rig.plans.0.lock().insert( + memo_key, + ClaimPlan { + memo_key, + message_id: Some("chat-message-1".into()), + entries: vec![CodableClaimPlanEntry { + entry_index: 0, + exponent: 1, + derivation_index: 0, + }], + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Processing, + claimed_amount: None, + total_value: 20, + markers: ClaimMarkers::default(), + }, + ); + + assert!(rig.service.claim_external_memo(memo, "chat-message-1".into()).await.is_err()); + assert!(rig.backend.transfers.lock().is_empty()); + assert!(rig.coins.list().await.unwrap().is_empty()); + assert_eq!(rig.plans.plan(&memo_key).await.unwrap().unwrap().claimed_amount, None); + } + + /// A plan persisted before chat claims carried chat message ids keeps + /// working when the claim now arrives under the chat row's id. + #[tokio::test] + async fn legacy_external_id_plan_accepts_the_chat_message_id() { + let source = expanded_secret(11); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let memo_key = memo.identifier(); + let rig = rig([]); + let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); + rig.backend.state.lock().insert(recipient, OnChainCoin { exponent: 1, age: 3 }); + rig.plans.0.lock().insert( + memo_key, + ClaimPlan { + memo_key, + message_id: Some(external_claim_message_id(&memo_key)), + entries: vec![CodableClaimPlanEntry { + entry_index: 0, + exponent: 1, + derivation_index: 0, + }], + outgoing_public_keys: Vec::new(), + detection_anchor: None, + status: ClaimPlanStatus::Error, + claimed_amount: None, + total_value: 20, + markers: ClaimMarkers::default(), + }, + ); + + let claimed = rig.service.claim_external_memo(memo, "chat-message-1".into()).await.unwrap(); + assert_eq!(claimed, 20); + assert_eq!( + rig.plans.0.lock().get(&memo_key).unwrap().status, + ClaimPlanStatus::Finished, + "a persisted error heals once the destination is proven" + ); + } + + #[tokio::test] + async fn source_and_recipient_presence_collision_fails_closed() { + let source = expanded_secret(7); + let memo = TransferMemo { entries: vec![source.clone()], total_value: 20 }; + let memo_key = memo.identifier(); + let recipient = CoinKeypairFactory::new(&[0x44; 16]).public_key(0).unwrap(); + let rig = rig([ + (public(&source), OnChainCoin { exponent: 1, age: 0 }), + (recipient, OnChainCoin { exponent: 1, age: 0 }), + ]); + + let error = rig + .service + .claim_external_memo(memo, external_claim_message_id(&memo_key)) + .await + .unwrap_err(); + assert!(error.contains("destination already exists")); + assert!(rig.backend.transfers.lock().is_empty()); + assert!(rig.plans.0.lock().is_empty()); + } + + #[tokio::test] + async fn spent_recovery_restores_max_age_and_reuses_the_claim_transfer_lane() { + let factory = CoinKeypairFactory::new(&[0x44; 16]); + let max_age = + Coin { exponent: 1, derivation_index: 3, age: Some(1), state: CoinState::Spent }; + let transferable = + Coin { exponent: 2, derivation_index: 4, age: Some(1), state: CoinState::Spent }; + let absent = + Coin { exponent: 0, derivation_index: 5, age: Some(1), state: CoinState::Spent }; + let rig = rig([ + ( + factory.public_key(max_age.derivation_index).unwrap(), + OnChainCoin { exponent: max_age.exponent, age: COIN_MAX_AGE }, + ), + ( + factory.public_key(transferable.derivation_index).unwrap(), + OnChainCoin { exponent: transferable.exponent, age: COIN_MAX_AGE - 1 }, + ), + ]); + for coin in [&max_age, &transferable, &absent] { + rig.coins.upsert(coin).await.unwrap(); + } + let recovery = SpentCoinTransferRecoveryService::new( + &[0x44; 16], + Arc::clone(&rig.coins) as Arc<_>, + Arc::clone(&rig.backend) as Arc<_>, + Arc::clone(&rig.service), + ); + + let report = recovery + .recover(vec![max_age.clone(), transferable.clone(), absent]) + .await + .unwrap(); + assert_eq!( + report, + SpentCoinTransferRecoveryReport { + recovered_count: 2, + recovered_planks: 60, + restored_max_age_count: 1, + transferred_count: 1, + } + ); + assert_eq!(rig.backend.transfers.lock().len(), 1); + let coins = rig.coins.list().await.unwrap(); + assert_eq!( + coins + .iter() + .find(|coin| coin.derivation_index == max_age.derivation_index) + .unwrap() + .state, + CoinState::Available + ); + assert_eq!( + coins + .iter() + .find(|coin| coin.derivation_index == transferable.derivation_index) + .unwrap() + .state, + CoinState::Spent + ); + assert!( + coins.iter().any(|coin| coin.derivation_index == 0 && + coin.exponent == transferable.exponent && + coin.state == CoinState::Available), + "the younger source lands in the allocator's fresh destination" + ); + } + + #[tokio::test] + async fn spent_recovery_rejects_non_spent_inputs_before_querying() { + let rig = rig([]); + let recovery = SpentCoinTransferRecoveryService::new( + &[0x44; 16], + Arc::clone(&rig.coins) as Arc<_>, + Arc::clone(&rig.backend) as Arc<_>, + Arc::clone(&rig.service), + ); + let error = recovery + .recover(vec![Coin { + exponent: 0, + derivation_index: 0, + age: Some(0), + state: CoinState::Available, + }]) + .await + .unwrap_err(); + assert!(error.contains("non-spent")); + assert!(rig.backend.transfers.lock().is_empty()); + } } diff --git a/rust/crates/truapi-coinage/src/selection.rs b/rust/crates/truapi-coinage/src/selection.rs index 990a32c2af..e5d278c038 100644 --- a/rust/crates/truapi-coinage/src/selection.rs +++ b/rust/crates/truapi-coinage/src/selection.rs @@ -2,60 +2,62 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use crate::denomination::{Denomination, DenominationBreakdownContext}; -use crate::model::{Coin, EffectivePrivacy, Voucher, VoucherRemoteState}; +use crate::{ + denomination::{Denomination, DenominationBreakdownContext}, + model::{Coin, EffectivePrivacy, Voucher, VoucherRemoteState}, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PrivacyLevel { - Full, - Degraded, + Full, + Degraded, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum CoinSelectionError { - ZeroAmount, - EmptyWallet, - /// The amount does not decompose exactly into denominations at this - /// context's granularity (below `min_exponent`). - AmountNotRepresentable { - remainder: u128, - }, - /// Vouchers exist but none are ready — distinct from - /// `InsufficientFunds` so the UI can show "wait for maturity" - NoReadyVouchers, - TooManyVouchersInGroup { - count: usize, - max: usize, - }, - InsufficientFunds, + ZeroAmount, + EmptyWallet, + /// The amount does not decompose exactly into denominations at this + /// context's granularity (below `min_exponent`). + AmountNotRepresentable { + remainder: u128, + }, + /// Vouchers exist but none are ready — distinct from + /// `InsufficientFunds` so the UI can show "wait for maturity" + NoReadyVouchers, + TooManyVouchersInGroup { + count: usize, + max: usize, + }, + InsufficientFunds, } impl std::fmt::Display for CoinSelectionError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - CoinSelectionError::ZeroAmount => write!(f, "amount must be greater than zero"), - CoinSelectionError::EmptyWallet => write!(f, "no coins or vouchers available"), - CoinSelectionError::AmountNotRepresentable { remainder } => { - write!( - f, - "amount not representable ({remainder} planks below the smallest denomination)" - ) - } - CoinSelectionError::NoReadyVouchers => write!(f, "vouchers are not ready yet"), - CoinSelectionError::TooManyVouchersInGroup { count, max } => { - write!(f, "recycler group holds {count} vouchers, maximum {max}") - } - CoinSelectionError::InsufficientFunds => write!(f, "insufficient funds"), - } - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + CoinSelectionError::ZeroAmount => write!(f, "amount must be greater than zero"), + CoinSelectionError::EmptyWallet => write!(f, "no coins or vouchers available"), + CoinSelectionError::AmountNotRepresentable { remainder } => { + write!( + f, + "amount not representable ({remainder} planks below the smallest denomination)" + ) + }, + CoinSelectionError::NoReadyVouchers => write!(f, "vouchers are not ready yet"), + CoinSelectionError::TooManyVouchersInGroup { count, max } => { + write!(f, "recycler group holds {count} vouchers, maximum {max}") + }, + CoinSelectionError::InsufficientFunds => write!(f, "insufficient funds"), + } + } } impl std::error::Error for CoinSelectionError {} #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RecyclerKey { - pub exponent: i16, - pub index: u32, + pub exponent: i16, + pub index: u32, } /// One unload group: all selected vouchers of one recycler, with the @@ -63,849 +65,742 @@ pub struct RecyclerKey { /// combined value always equals the group's total voucher input. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VoucherGroup { - pub recycler: RecyclerKey, - pub vouchers: Vec, - pub recipient_denominations: Vec, - pub change_denominations: Vec, + pub recycler: RecyclerKey, + pub vouchers: Vec, + pub recipient_denominations: Vec, + pub change_denominations: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum TransferStrategy { - /// Whole coins pass to the recipient via the memo; nothing on-chain. - ExactMatch { coins: Vec }, - /// `partial_coins` pass whole; `split_coin` is split into - /// `target_denominations` (recipient) + `change_denominations` - /// (sender), signed with the coin's own key (AsCoin origin). - Split { - partial_coins: Vec, - split_coin: Coin, - target_denominations: Vec, - change_denominations: Vec, - }, - /// `coins` pass whole; each group is one - /// `UnloadRecyclerIntoCoins` extrinsic (Ring-VRF origin). - UnloadIntoCoins { - coins: Vec, - groups: Vec, - }, + /// Whole coins pass to the recipient via the memo; nothing on-chain. + ExactMatch { coins: Vec }, + /// `partial_coins` pass whole; `split_coin` is split into + /// `target_denominations` (recipient) + `change_denominations` + /// (sender), signed with the coin's own key (AsCoin origin). + Split { + partial_coins: Vec, + split_coin: Coin, + target_denominations: Vec, + change_denominations: Vec, + }, + /// `coins` pass whole; each group is one + /// `UnloadRecyclerIntoCoins` extrinsic (Ring-VRF origin). + UnloadIntoCoins { coins: Vec, groups: Vec }, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct CoinSelectionResult { - pub strategy: TransferStrategy, - pub privacy_level: PrivacyLevel, + pub strategy: TransferStrategy, + pub privacy_level: PrivacyLevel, } pub fn find_exact_match( - amount: u128, - coins: &[Coin], - context: &DenominationBreakdownContext, + amount: u128, + coins: &[Coin], + context: &DenominationBreakdownContext, ) -> Option> { - let (selected, remaining) = greedy_take(amount, coins, context); - (remaining == 0).then_some(selected) + let (selected, remaining) = greedy_take(amount, coins, context); + (remaining == 0).then_some(selected) } /// Greedy largest-first pass: takes coins whose value fits the remaining /// amount; returns the take and what is left uncovered. fn greedy_take( - amount: u128, - coins: &[Coin], - context: &DenominationBreakdownContext, + amount: u128, + coins: &[Coin], + context: &DenominationBreakdownContext, ) -> (Vec, u128) { - let mut pool: Vec<&Coin> = coins.iter().filter(|c| c.is_selectable()).collect(); - pool.sort_by(|a, b| { - b.exponent - .cmp(&a.exponent) - .then(b.age.unwrap_or(-1).cmp(&a.age.unwrap_or(-1))) - .then(a.derivation_index.cmp(&b.derivation_index)) - }); - let mut remaining = amount; - let mut selected = Vec::new(); - for coin in pool { - let value = context.value_in_planks(coin.exponent); - if value <= remaining { - remaining -= value; - selected.push(coin.clone()); - } - } - (selected, remaining) + let mut pool: Vec<&Coin> = coins.iter().filter(|c| c.is_selectable()).collect(); + pool.sort_by(|a, b| { + b.exponent + .cmp(&a.exponent) + .then(b.age.unwrap_or(-1).cmp(&a.age.unwrap_or(-1))) + .then(a.derivation_index.cmp(&b.derivation_index)) + }); + let mut remaining = amount; + let mut selected = Vec::new(); + for coin in pool { + let value = context.value_in_planks(coin.exponent); + if value <= remaining { + remaining -= value; + selected.push(coin.clone()); + } + } + (selected, remaining) } pub struct CoinSelector { - context: DenominationBreakdownContext, - max_consolidation: usize, + context: DenominationBreakdownContext, + max_consolidation: usize, } impl CoinSelector { - pub fn new(context: DenominationBreakdownContext, max_consolidation: usize) -> Self { - Self { - context, - max_consolidation, - } - } - - /// Runs the three strategies in priority order. `now_ms` drives - /// voucher effective-privacy evaluation. - pub fn select( - &self, - amount: u128, - coins: &[Coin], - vouchers: &[Voucher], - now_ms: i64, - ) -> Result { - if amount == 0 { - return Err(CoinSelectionError::ZeroAmount); - } - let unloadable: Vec<&Voucher> = vouchers.iter().filter(|v| v.is_unloadable()).collect(); - let any_available_coin = coins - .iter() - .any(|c| c.state == crate::model::CoinState::Available); - if !any_available_coin && unloadable.is_empty() { - return Err(CoinSelectionError::EmptyWallet); - } - let amount_breakdown = self.context.breakdown(amount); - if !amount_breakdown.is_exact() { - return Err(CoinSelectionError::AmountNotRepresentable { - remainder: amount_breakdown.remainder, - }); - } - - if let Some(selected) = find_exact_match(amount, coins, &self.context) { - return Ok(CoinSelectionResult { - strategy: TransferStrategy::ExactMatch { coins: selected }, - privacy_level: PrivacyLevel::Full, - }); - } - - if let Some(result) = self.try_split_coin(amount, coins) { - return Ok(CoinSelectionResult { - strategy: result, - privacy_level: PrivacyLevel::Full, - }); - } - - let full_pool: Vec<&Voucher> = unloadable - .iter() - .copied() - .filter(|v| v.privacy == crate::model::VoucherPrivacyLevel::Full) - .collect(); - if let Some(strategy) = self.try_unload(amount, coins, &full_pool)? { - let privacy_level = strategy_privacy(&strategy, now_ms); - return Ok(CoinSelectionResult { - strategy, - privacy_level, - }); - } - - if unloadable.len() > full_pool.len() - && let Some(strategy) = self.try_unload(amount, coins, &unloadable)? - { - let privacy_level = strategy_privacy(&strategy, now_ms); - return Ok(CoinSelectionResult { - strategy, - privacy_level, - }); - } - - if !unloadable.is_empty() && full_pool.is_empty() { - return Err(CoinSelectionError::NoReadyVouchers); - } - Err(CoinSelectionError::InsufficientFunds) - } - - fn try_split_coin(&self, amount: u128, coins: &[Coin]) -> Option { - let mut selectable = coins - .iter() - .filter(|c| c.is_selectable()) - .cloned() - .collect::>(); - let sufficient = selectable - .iter() - .filter(|coin| self.context.value_in_planks(coin.exponent) > amount) - .min_by_key(|coin| { - ( - self.context.value_in_planks(coin.exponent), - coin.derivation_index, - ) - }) - .cloned(); - if let Some(split_coin) = sufficient { - return Some(self.split_strategy(Vec::new(), split_coin, amount)); - } - - selectable.sort_by(|a, b| { - b.exponent - .cmp(&a.exponent) - .then(a.derivation_index.cmp(&b.derivation_index)) - }); - let mut partial = Vec::new(); - let mut accumulated = 0u128; - for coin in selectable { - let value = self.context.value_in_planks(coin.exponent); - let next = accumulated.saturating_add(value); - if next < amount { - partial.push(coin); - accumulated = next; - continue; - } - return Some(self.split_strategy(partial, coin, amount - accumulated)); - } - None - } - - fn split_strategy( - &self, - partial: Vec, - split_coin: Coin, - remaining: u128, - ) -> TransferStrategy { - let coin_value = self.context.value_in_planks(split_coin.exponent); - let target = self.context.breakdown(remaining); - let change = self.context.breakdown(coin_value - remaining); - debug_assert!( - target.is_exact() && change.is_exact(), - "powers of two split exactly" - ); - TransferStrategy::Split { - partial_coins: partial, - split_coin, - target_denominations: target.denominations, - change_denominations: change.denominations, - } - } - - fn try_unload( - &self, - amount: u128, - coins: &[Coin], - pool: &[&Voucher], - ) -> Result, CoinSelectionError> { - if pool.is_empty() { - return Ok(None); - } - let (partial, needed) = greedy_take(amount, coins, &self.context); - debug_assert!(needed > 0); - - let chosen: Vec<&Voucher> = match pool - .iter() - .filter(|v| self.context.value_in_planks(v.exponent) >= needed) - .min_by_key(|v| (self.context.value_in_planks(v.exponent), v.derivation_index)) - { - Some(single) => vec![single], - None => { - // Greedy largest-first accumulation until covered. - let mut sorted: Vec<&Voucher> = pool.to_vec(); - sorted.sort_by(|a, b| { - b.exponent - .cmp(&a.exponent) - .then(a.derivation_index.cmp(&b.derivation_index)) - }); - let mut sum = 0u128; - let mut chosen = Vec::new(); - for voucher in sorted { - if sum >= needed { - break; - } - sum = sum.saturating_add(self.context.value_in_planks(voucher.exponent)); - chosen.push(voucher); - } - if sum < needed { - return Ok(None); - } - chosen - } - }; - - let mut groups: Vec<(RecyclerKey, Vec)> = Vec::new(); - for voucher in chosen { - let VoucherRemoteState::InRecycler { recycler_index } = voucher.remote_state else { - // is_unloadable filtered already; defensive. - continue; - }; - let key = RecyclerKey { - exponent: voucher.exponent, - index: recycler_index, - }; - match groups.iter_mut().find(|(k, _)| *k == key) { - Some((_, members)) => members.push(voucher.clone()), - None => groups.push((key, vec![voucher.clone()])), - } - } - - groups.sort_by(|(left, _), (right, _)| { - right - .exponent - .cmp(&left.exponent) - .then(left.index.cmp(&right.index)) - }); - - let mut needed_left = needed; - let mut allocated = Vec::with_capacity(groups.len()); - for (recycler, members) in groups { - if members.len() >= self.max_consolidation { - return Err(CoinSelectionError::TooManyVouchersInGroup { - count: members.len(), - max: self.max_consolidation, - }); - } - let input: u128 = members.iter().fold(0u128, |acc, v| { - acc.saturating_add(self.context.value_in_planks(v.exponent)) - }); - let recipient_amount = needed_left.min(input); - needed_left -= recipient_amount; - let recipient = self.context.breakdown(recipient_amount); - let change = self.context.breakdown(input - recipient_amount); - debug_assert!(recipient.is_exact() && change.is_exact()); - allocated.push(VoucherGroup { - recycler, - vouchers: members, - recipient_denominations: recipient.denominations, - change_denominations: change.denominations, - }); - } - debug_assert_eq!(needed_left, 0); - Ok(Some(TransferStrategy::UnloadIntoCoins { - coins: partial, - groups: allocated, - })) - } + pub fn new(context: DenominationBreakdownContext, max_consolidation: usize) -> Self { + Self { context, max_consolidation } + } + + /// Runs the three strategies in priority order. `now_ms` drives + /// voucher effective-privacy evaluation. + pub fn select( + &self, + amount: u128, + coins: &[Coin], + vouchers: &[Voucher], + now_ms: i64, + ) -> Result { + if amount == 0 { + return Err(CoinSelectionError::ZeroAmount); + } + let unloadable: Vec<&Voucher> = vouchers.iter().filter(|v| v.is_unloadable()).collect(); + let any_available_coin = + coins.iter().any(|c| c.state == crate::model::CoinState::Available); + if !any_available_coin && unloadable.is_empty() { + return Err(CoinSelectionError::EmptyWallet); + } + let amount_breakdown = self.context.breakdown(amount); + if !amount_breakdown.is_exact() { + return Err(CoinSelectionError::AmountNotRepresentable { + remainder: amount_breakdown.remainder, + }); + } + + if let Some(selected) = find_exact_match(amount, coins, &self.context) { + return Ok(CoinSelectionResult { + strategy: TransferStrategy::ExactMatch { coins: selected }, + privacy_level: PrivacyLevel::Full, + }); + } + + if let Some(result) = self.try_split_coin(amount, coins) { + return Ok(CoinSelectionResult { strategy: result, privacy_level: PrivacyLevel::Full }); + } + + let full_pool: Vec<&Voucher> = unloadable + .iter() + .copied() + .filter(|v| v.privacy == crate::model::VoucherPrivacyLevel::Full) + .collect(); + if let Some(strategy) = self.try_unload(amount, coins, &full_pool)? { + let privacy_level = strategy_privacy(&strategy, now_ms); + return Ok(CoinSelectionResult { strategy, privacy_level }); + } + + if unloadable.len() > full_pool.len() && + let Some(strategy) = self.try_unload(amount, coins, &unloadable)? + { + let privacy_level = strategy_privacy(&strategy, now_ms); + return Ok(CoinSelectionResult { strategy, privacy_level }); + } + + if !unloadable.is_empty() && full_pool.is_empty() { + return Err(CoinSelectionError::NoReadyVouchers); + } + Err(CoinSelectionError::InsufficientFunds) + } + + fn try_split_coin(&self, amount: u128, coins: &[Coin]) -> Option { + let mut selectable = + coins.iter().filter(|c| c.is_selectable()).cloned().collect::>(); + let sufficient = selectable + .iter() + .filter(|coin| self.context.value_in_planks(coin.exponent) > amount) + .min_by_key(|coin| (self.context.value_in_planks(coin.exponent), coin.derivation_index)) + .cloned(); + if let Some(split_coin) = sufficient { + return Some(self.split_strategy(Vec::new(), split_coin, amount)); + } + + selectable.sort_by(|a, b| { + b.exponent.cmp(&a.exponent).then(a.derivation_index.cmp(&b.derivation_index)) + }); + let mut partial = Vec::new(); + let mut accumulated = 0u128; + for coin in selectable { + let value = self.context.value_in_planks(coin.exponent); + let next = accumulated.saturating_add(value); + if next < amount { + partial.push(coin); + accumulated = next; + continue; + } + return Some(self.split_strategy(partial, coin, amount - accumulated)); + } + None + } + + fn split_strategy( + &self, + partial: Vec, + split_coin: Coin, + remaining: u128, + ) -> TransferStrategy { + let coin_value = self.context.value_in_planks(split_coin.exponent); + let target = self.context.breakdown(remaining); + let change = self.context.breakdown(coin_value - remaining); + debug_assert!(target.is_exact() && change.is_exact(), "powers of two split exactly"); + TransferStrategy::Split { + partial_coins: partial, + split_coin, + target_denominations: target.denominations, + change_denominations: change.denominations, + } + } + + fn try_unload( + &self, + amount: u128, + coins: &[Coin], + pool: &[&Voucher], + ) -> Result, CoinSelectionError> { + if pool.is_empty() { + return Ok(None); + } + let (partial, needed) = greedy_take(amount, coins, &self.context); + debug_assert!(needed > 0); + + let chosen: Vec<&Voucher> = match pool + .iter() + .filter(|v| self.context.value_in_planks(v.exponent) >= needed) + .min_by_key(|v| (self.context.value_in_planks(v.exponent), v.derivation_index)) + { + Some(single) => vec![single], + None => { + // Greedy largest-first accumulation until covered. + let mut sorted: Vec<&Voucher> = pool.to_vec(); + sorted.sort_by(|a, b| { + b.exponent.cmp(&a.exponent).then(a.derivation_index.cmp(&b.derivation_index)) + }); + let mut sum = 0u128; + let mut chosen = Vec::new(); + for voucher in sorted { + if sum >= needed { + break; + } + sum = sum.saturating_add(self.context.value_in_planks(voucher.exponent)); + chosen.push(voucher); + } + if sum < needed { + return Ok(None); + } + chosen + }, + }; + + let mut groups: Vec<(RecyclerKey, Vec)> = Vec::new(); + for voucher in chosen { + let VoucherRemoteState::InRecycler { recycler_index } = voucher.remote_state else { + // is_unloadable filtered already; defensive. + continue; + }; + let key = RecyclerKey { exponent: voucher.exponent, index: recycler_index }; + match groups.iter_mut().find(|(k, _)| *k == key) { + Some((_, members)) => members.push(voucher.clone()), + None => groups.push((key, vec![voucher.clone()])), + } + } + + groups.sort_by(|(left, _), (right, _)| { + right.exponent.cmp(&left.exponent).then(left.index.cmp(&right.index)) + }); + + let mut needed_left = needed; + let mut allocated = Vec::with_capacity(groups.len()); + for (recycler, members) in groups { + if members.len() >= self.max_consolidation { + return Err(CoinSelectionError::TooManyVouchersInGroup { + count: members.len(), + max: self.max_consolidation, + }); + } + let input: u128 = members + .iter() + .fold(0u128, |acc, v| acc.saturating_add(self.context.value_in_planks(v.exponent))); + let recipient_amount = needed_left.min(input); + needed_left -= recipient_amount; + let recipient = self.context.breakdown(recipient_amount); + let change = self.context.breakdown(input - recipient_amount); + debug_assert!(recipient.is_exact() && change.is_exact()); + allocated.push(VoucherGroup { + recycler, + vouchers: members, + recipient_denominations: recipient.denominations, + change_denominations: change.denominations, + }); + } + debug_assert_eq!(needed_left, 0); + Ok(Some(TransferStrategy::UnloadIntoCoins { coins: partial, groups: allocated })) + } } fn strategy_privacy(strategy: &TransferStrategy, now_ms: i64) -> PrivacyLevel { - match strategy { - TransferStrategy::UnloadIntoCoins { groups, .. } - if groups - .iter() - .flat_map(|group| &group.vouchers) - .any(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Degraded) => - { - PrivacyLevel::Degraded - } - _ => PrivacyLevel::Full, - } + match strategy { + TransferStrategy::UnloadIntoCoins { groups, .. } + if groups + .iter() + .flat_map(|group| &group.vouchers) + .any(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Degraded) => + { + PrivacyLevel::Degraded + }, + _ => PrivacyLevel::Full, + } } #[cfg(test)] mod tests { - use super::*; - use crate::model::{CoinState, VoucherLocalState, VoucherPrivacyLevel}; - - /// Unit 10, exponents 0..=4 → coin values 10..160. - fn ctx() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 10, - max_exponent: 4, - min_exponent: 0, - precision: 10, - } - } - - fn selector() -> CoinSelector { - CoinSelector::new(ctx(), 8) - } - - fn coin(index: u32, exponent: i16, age: Option) -> Coin { - Coin { - exponent, - derivation_index: index, - age, - state: CoinState::Available, - } - } - - fn voucher( - index: u32, - exponent: i16, - recycler: u32, - privacy: VoucherPrivacyLevel, - ready_at_ms: i64, - ) -> Voucher { - Voucher { - exponent, - derivation_index: index, - allocated_at_ms: 0, - ready_at_ms, - remote_state: VoucherRemoteState::InRecycler { - recycler_index: recycler, - }, - local_state: VoucherLocalState::Available, - privacy, - } - } - - fn full_voucher(index: u32, exponent: i16) -> Voucher { - voucher(index, exponent, 0, VoucherPrivacyLevel::Full, 0) - } - - const NOW: i64 = 1_000_000; - - #[test] - fn zero_amount_is_rejected() { - assert_eq!( - selector().select(0, &[coin(1, 0, None)], &[], NOW), - Err(CoinSelectionError::ZeroAmount) - ); - } - - #[test] - fn empty_wallet_is_rejected() { - assert_eq!( - selector().select(10, &[], &[], NOW), - Err(CoinSelectionError::EmptyWallet) - ); - // A wallet of only spent coins is empty too. - let spent = Coin { - state: CoinState::Spent, - ..coin(1, 4, None) - }; - assert_eq!( - selector().select(10, &[spent], &[], NOW), - Err(CoinSelectionError::EmptyWallet) - ); - } - - #[test] - fn sub_denomination_amount_is_rejected() { - assert_eq!( - selector().select(15, &[coin(1, 4, None)], &[], NOW), - Err(CoinSelectionError::AmountNotRepresentable { remainder: 5 }) - ); - } - - #[test] - fn exact_match_selects_minimum_coins_largest_first() { - let coins = [ - coin(1, 0, None), - coin(2, 1, None), - coin(3, 2, None), - coin(4, 4, None), - ]; - // 230 = 160 + 40 + 20 + 10 — all four; 200 = 160 + 40. - let result = selector().select(200, &coins, &[], NOW).unwrap(); - let TransferStrategy::ExactMatch { coins: selected } = result.strategy else { - panic!("expected exact match"); - }; - assert_eq!( - selected - .iter() - .map(|c| c.derivation_index) - .collect::>(), - [4, 3] - ); - assert_eq!(result.privacy_level, PrivacyLevel::Full); - } - - #[test] - fn exact_match_prefers_older_coins_within_a_denomination() { - let coins = [coin(1, 0, Some(2)), coin(2, 0, Some(9)), coin(3, 0, None)]; - let result = selector().select(10, &coins, &[], NOW).unwrap(); - let TransferStrategy::ExactMatch { coins: selected } = result.strategy else { - panic!("expected exact match"); - }; - assert_eq!(selected[0].derivation_index, 2, "age 9 spends before age 2"); - } - - #[test] - fn expiring_coins_never_enter_selection() { - let coins = [coin(1, 0, Some(14)), coin(2, 0, Some(13))]; - // 20 would need both — the expiring one is invisible. - assert_eq!( - selector().select(20, &coins, &[], NOW), - Err(CoinSelectionError::InsufficientFunds) - ); - // 10 matches with the young coin only. - let result = selector().select(10, &coins, &[], NOW).unwrap(); - let TransferStrategy::ExactMatch { coins: selected } = result.strategy else { - panic!("expected exact match"); - }; - assert_eq!(selected[0].derivation_index, 2); - } - - #[test] - fn find_exact_match_returns_none_when_no_exact_subset_exists() { - assert!(find_exact_match(30, &[coin(1, 2, None)], &ctx()).is_none()); - assert!(find_exact_match(30, &[coin(1, 1, None), coin(2, 0, None)], &ctx()).is_some()); - } - - #[test] - fn split_picks_smallest_coin_larger_than_the_remainder() { - // Amount 30: no exact match from {160, 80}; split the 80? No — - // smallest coin larger than 30 is 80 (overshoot 50) vs 160 - // (overshoot 130) → split coin 2 (exp 3). - let coins = [coin(1, 4, None), coin(2, 3, None)]; - let result = selector().select(30, &coins, &[], NOW).unwrap(); - let TransferStrategy::Split { - partial_coins, - split_coin, - target_denominations, - change_denominations, - } = result.strategy - else { - panic!("expected split"); - }; - assert!(partial_coins.is_empty()); - assert_eq!(split_coin.derivation_index, 2); - // target 30 = 20 + 10; change 50 = 40 + 10. - assert_eq!( - target_denominations, - [Denomination { exponent: 1 }, Denomination { exponent: 0 }] - ); - assert_eq!( - change_denominations, - [Denomination { exponent: 2 }, Denomination { exponent: 0 }] - ); - // Split invariant: partial + target == amount; target + change == coin. - assert_eq!(ctx().total_value(&target_denominations), 30); - assert_eq!(ctx().total_value(&change_denominations), 50); - } - - /// Smaller whole coins must not be added when one coin can fund the full - /// split. - #[test] - fn split_uses_one_smallest_coin_larger_than_the_whole_request() { - let coins = [ - coin(1, 4, None), // 160 - coin(2, 2, None), // 40 - coin(3, 0, None), // 10 - ]; - let result = selector().select(30, &coins, &[], NOW).unwrap(); - let TransferStrategy::Split { - partial_coins, - split_coin, - .. - } = result.strategy - else { - panic!("expected split"); - }; - assert!(partial_coins.is_empty()); - assert_eq!(split_coin.derivation_index, 2); - } - - #[test] - fn split_takes_a_partial_contribution_first() { - // Amount 50: greedy takes the 40 (exp 2), remainder 10 needs a - // split of the 20 (exp 1) into 10 + 10. - let coins = [coin(1, 2, None), coin(2, 1, None)]; - let result = selector().select(50, &coins, &[], NOW).unwrap(); - let TransferStrategy::Split { - partial_coins, - split_coin, - target_denominations, - change_denominations, - } = result.strategy - else { - panic!("expected split"); - }; - assert_eq!(partial_coins[0].derivation_index, 1); - assert_eq!(split_coin.derivation_index, 2); - assert_eq!(ctx().total_value(&target_denominations), 10); - assert_eq!(ctx().total_value(&change_denominations), 10); - } - - #[test] - fn unload_prefers_single_smallest_sufficient_voucher() { - let coins: [Coin; 0] = []; - let vouchers = [full_voucher(1, 4), full_voucher(2, 2), full_voucher(3, 3)]; - // Need 40: the exp-2 voucher (value 40) is the minimal cover — - // not the 80, not the 160, not a combination. - let result = selector().select(40, &coins, &vouchers, NOW).unwrap(); - let TransferStrategy::UnloadIntoCoins { - coins: partial, - groups, - } = result.strategy - else { - panic!("expected unload"); - }; - assert!(partial.is_empty()); - assert_eq!(groups.len(), 1); - assert_eq!(groups[0].vouchers[0].derivation_index, 2); - assert_eq!(ctx().total_value(&groups[0].recipient_denominations), 40); - assert!(groups[0].change_denominations.is_empty()); - assert_eq!(result.privacy_level, PrivacyLevel::Full); - } - - #[test] - fn unload_groups_by_recycler_and_balances_output_to_input() { - let vouchers = [ - voucher(1, 2, 7, VoucherPrivacyLevel::Full, 0), // 40, recycler (2,7) - voucher(2, 2, 9, VoucherPrivacyLevel::Full, 0), // 40, recycler (2,9) - ]; - // Need 60 → both vouchers (no single is sufficient): group (2,7) - // gives 40 to the recipient, group (2,9) gives 20 + 20 change. - let result = selector().select(60, &[], &vouchers, NOW).unwrap(); - let TransferStrategy::UnloadIntoCoins { groups, .. } = result.strategy else { - panic!("expected unload"); - }; - assert_eq!(groups.len(), 2); - for group in &groups { - let input: u128 = group - .vouchers - .iter() - .map(|v| ctx().value_in_planks(v.exponent)) - .sum(); - let output = ctx().total_value(&group.recipient_denominations) - + ctx().total_value(&group.change_denominations); - assert_eq!(input, output, "pallet invariant: group output == input"); - } - let recipient_total: u128 = groups - .iter() - .map(|g| ctx().total_value(&g.recipient_denominations)) - .sum(); - assert_eq!(recipient_total, 60); - } - - #[test] - fn unload_groups_are_ordered_by_descending_exponent() { - let vouchers = [ - voucher(1, 0, 7, VoucherPrivacyLevel::Full, 0), // 10 - voucher(2, 2, 9, VoucherPrivacyLevel::Full, 0), // 40 - ]; - let result = selector().select(50, &[], &vouchers, NOW).unwrap(); - let TransferStrategy::UnloadIntoCoins { groups, .. } = result.strategy else { - panic!("expected unload"); - }; - assert_eq!( - groups - .iter() - .map(|group| group.recycler.exponent) - .collect::>(), - [2, 0] - ); - } - - #[test] - fn unload_uses_partial_coins_before_vouchers() { - let coins = [coin(1, 1, None)]; // 20 - let vouchers = [full_voucher(10, 2)]; // 40 - // Need 60 = coin 20 + voucher 40. - let result = selector().select(60, &coins, &vouchers, NOW).unwrap(); - let TransferStrategy::UnloadIntoCoins { - coins: partial, - groups, - } = result.strategy - else { - panic!("expected unload"); - }; - assert_eq!(partial[0].derivation_index, 1); - assert_eq!(groups[0].vouchers[0].derivation_index, 10); - } - - #[test] - fn degraded_fallback_triggers_when_full_privacy_is_insufficient() { - let vouchers = [ - full_voucher(1, 1), // 20 full - voucher(2, 2, 0, VoucherPrivacyLevel::Degraded, 0), // 40 degraded - ]; - // 20 is coverable full-privacy → Full. - let result = selector().select(20, &[], &vouchers, NOW).unwrap(); - assert_eq!(result.privacy_level, PrivacyLevel::Full); - // 60 needs the degraded voucher too → Degraded. - let result = selector().select(60, &[], &vouchers, NOW).unwrap(); - assert_eq!(result.privacy_level, PrivacyLevel::Degraded); - } - - #[test] - fn not_yet_ready_full_voucher_counts_as_degraded() { - let vouchers = [voucher(1, 1, 0, VoucherPrivacyLevel::Full, NOW + 1)]; - let result = selector().select(20, &[], &vouchers, NOW).unwrap(); - assert_eq!(result.privacy_level, PrivacyLevel::Degraded); - } - - #[test] - fn no_ready_vouchers_error_when_pool_is_all_unready() { - let vouchers = [voucher(1, 0, 0, VoucherPrivacyLevel::Degraded, 0)]; // 10 - assert_eq!( - selector().select(160, &[], &vouchers, NOW), - Err(CoinSelectionError::NoReadyVouchers) - ); - } - - #[test] - fn too_many_vouchers_in_group_is_a_hard_stop() { - let tight = CoinSelector::new(ctx(), 2); - let vouchers: Vec = (0..3).map(|i| full_voucher(i, 0)).collect(); // 3 × 10, one recycler - assert_eq!( - tight.select(30, &[], &vouchers, NOW), - Err(CoinSelectionError::TooManyVouchersInGroup { count: 3, max: 2 }) - ); - } - - #[test] - fn voucher_group_equal_to_max_is_rejected_like_ios_v2() { - let tight = CoinSelector::new(ctx(), 2); - let vouchers = [full_voucher(1, 0), full_voucher(2, 0)]; - assert_eq!( - tight.select(20, &[], &vouchers, NOW), - Err(CoinSelectionError::TooManyVouchersInGroup { count: 2, max: 2 }) - ); - } - - #[test] - fn insufficient_funds_when_everything_together_cannot_cover() { - let coins = [coin(1, 0, None)]; - let vouchers = [full_voucher(2, 0)]; - assert_eq!( - selector().select(160, &coins, &vouchers, NOW), - Err(CoinSelectionError::InsufficientFunds) - ); - } - - /// Deterministic pseudo-random sweep: every outcome upholds the value - /// invariants, and all three strategy paths are exercised. - #[test] - fn random_sweep_covers_all_strategies_and_holds_invariants() { - use rand::rngs::StdRng; - use rand::{Rng, SeedableRng}; - let mut rng = StdRng::seed_from_u64(0x_C01_A6E); - let context = ctx(); - let selector = selector(); - let (mut exact, mut split, mut unload) = (0, 0, 0); - - for _ in 0..300 { - let coins: Vec = (0..rng.gen_range(0..6)) - .map(|i| { - coin( - i, - rng.gen_range(0..=4), - if rng.gen_bool(0.3) { - None - } else { - Some(rng.gen_range(0..16)) - }, - ) - }) - .collect(); - let vouchers: Vec = (0..rng.gen_range(0..5)) - .map(|i| { - voucher( - 100 + i, - rng.gen_range(0..=4), - rng.gen_range(0..3), - if rng.gen_bool(0.7) { - VoucherPrivacyLevel::Full - } else { - VoucherPrivacyLevel::Degraded - }, - if rng.gen_bool(0.8) { 0 } else { NOW + 1 }, - ) - }) - .collect(); - let amount = u128::from(rng.gen_range(1..60u32)) * 10; - - let first = selector.select(amount, &coins, &vouchers, NOW); - assert_eq!( - first, - selector.select(amount, &coins, &vouchers, NOW), - "identical snapshots must select deterministically" - ); - - match first { - Ok(result) => match result.strategy { - TransferStrategy::ExactMatch { coins: selected } => { - let unique: std::collections::HashSet<_> = - selected.iter().map(|coin| coin.derivation_index).collect(); - assert_eq!(unique.len(), selected.len(), "coin inputs are unique"); - exact += 1; - let total: u128 = selected - .iter() - .map(|c| context.value_in_planks(c.exponent)) - .sum(); - assert_eq!(total, amount); - assert!(selected.iter().all(|c| c.is_selectable())); - } - TransferStrategy::Split { - partial_coins, - split_coin, - target_denominations, - change_denominations, - } => { - split += 1; - let mut unique: std::collections::HashSet<_> = partial_coins - .iter() - .map(|coin| coin.derivation_index) - .collect(); - assert!( - unique.insert(split_coin.derivation_index), - "the split coin cannot also be a partial input" - ); - assert!(partial_coins.iter().all(Coin::is_selectable)); - assert!(split_coin.is_selectable()); - let partial: u128 = partial_coins - .iter() - .map(|c| context.value_in_planks(c.exponent)) - .sum(); - assert_eq!( - partial + context.total_value(&target_denominations), - amount, - "partial + split target == amount" - ); - assert_eq!( - context.total_value(&target_denominations) - + context.total_value(&change_denominations), - context.value_in_planks(split_coin.exponent), - "split conserves the coin's value" - ); - } - TransferStrategy::UnloadIntoCoins { - coins: partial, - groups, - } => { - unload += 1; - let unique_coins: std::collections::HashSet<_> = - partial.iter().map(|coin| coin.derivation_index).collect(); - assert_eq!(unique_coins.len(), partial.len(), "coin inputs are unique"); - assert!(partial.iter().all(Coin::is_selectable)); - let mut unique_vouchers = std::collections::HashSet::new(); - let partial: u128 = partial - .iter() - .map(|c| context.value_in_planks(c.exponent)) - .sum(); - let recipient: u128 = groups - .iter() - .map(|g| context.total_value(&g.recipient_denominations)) - .sum(); - assert_eq!(partial + recipient, amount, "unload covers exactly"); - for group in &groups { - let input: u128 = group - .vouchers - .iter() - .map(|v| context.value_in_planks(v.exponent)) - .sum(); - assert_eq!( - input, - context.total_value(&group.recipient_denominations) - + context.total_value(&group.change_denominations) - ); - assert!( - group.vouchers.len() < 8, - "reference max-consolidation check is strict" - ); - assert!(group.vouchers.iter().all(Voucher::is_unloadable)); - assert!( - group.vouchers.iter().all(|voucher| { - unique_vouchers.insert(voucher.derivation_index) - }), - "voucher inputs are unique across recycler groups" - ); - } - } - }, - Err(error) => { - assert!( - matches!( - error, - CoinSelectionError::EmptyWallet - | CoinSelectionError::InsufficientFunds - | CoinSelectionError::NoReadyVouchers - | CoinSelectionError::TooManyVouchersInGroup { .. } - ), - "unexpected error class: {error:?}" - ); - } - } - } - assert!(exact > 10, "exact-match path exercised ({exact})"); - assert!(split > 10, "split path exercised ({split})"); - assert!(unload > 10, "unload path exercised ({unload})"); - } + use super::*; + use crate::model::{CoinState, VoucherLocalState, VoucherPrivacyLevel}; + + /// Unit 10, exponents 0..=4 → coin values 10..160. + fn ctx() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 10, + max_exponent: 4, + min_exponent: 0, + precision: 10, + } + } + + fn selector() -> CoinSelector { + CoinSelector::new(ctx(), 8) + } + + fn coin(index: u32, exponent: i16, age: Option) -> Coin { + Coin { exponent, derivation_index: index, age, state: CoinState::Available } + } + + fn voucher( + index: u32, + exponent: i16, + recycler: u32, + privacy: VoucherPrivacyLevel, + ready_at_ms: i64, + ) -> Voucher { + Voucher { + exponent, + derivation_index: index, + allocated_at_ms: 0, + ready_at_ms, + remote_state: VoucherRemoteState::InRecycler { recycler_index: recycler }, + local_state: VoucherLocalState::Available, + privacy, + } + } + + fn full_voucher(index: u32, exponent: i16) -> Voucher { + voucher(index, exponent, 0, VoucherPrivacyLevel::Full, 0) + } + + const NOW: i64 = 1_000_000; + + #[test] + fn zero_amount_is_rejected() { + assert_eq!( + selector().select(0, &[coin(1, 0, None)], &[], NOW), + Err(CoinSelectionError::ZeroAmount) + ); + } + + #[test] + fn empty_wallet_is_rejected() { + assert_eq!(selector().select(10, &[], &[], NOW), Err(CoinSelectionError::EmptyWallet)); + // A wallet of only spent coins is empty too. + let spent = Coin { state: CoinState::Spent, ..coin(1, 4, None) }; + assert_eq!(selector().select(10, &[spent], &[], NOW), Err(CoinSelectionError::EmptyWallet)); + } + + #[test] + fn sub_denomination_amount_is_rejected() { + assert_eq!( + selector().select(15, &[coin(1, 4, None)], &[], NOW), + Err(CoinSelectionError::AmountNotRepresentable { remainder: 5 }) + ); + } + + #[test] + fn exact_match_selects_minimum_coins_largest_first() { + let coins = [coin(1, 0, None), coin(2, 1, None), coin(3, 2, None), coin(4, 4, None)]; + // 230 = 160 + 40 + 20 + 10 — all four; 200 = 160 + 40. + let result = selector().select(200, &coins, &[], NOW).unwrap(); + let TransferStrategy::ExactMatch { coins: selected } = result.strategy else { + panic!("expected exact match"); + }; + assert_eq!(selected.iter().map(|c| c.derivation_index).collect::>(), [4, 3]); + assert_eq!(result.privacy_level, PrivacyLevel::Full); + } + + #[test] + fn exact_match_prefers_older_coins_within_a_denomination() { + let coins = [coin(1, 0, Some(2)), coin(2, 0, Some(9)), coin(3, 0, None)]; + let result = selector().select(10, &coins, &[], NOW).unwrap(); + let TransferStrategy::ExactMatch { coins: selected } = result.strategy else { + panic!("expected exact match"); + }; + assert_eq!(selected[0].derivation_index, 2, "age 9 spends before age 2"); + } + + #[test] + fn expiring_coins_never_enter_selection() { + let coins = [coin(1, 0, Some(14)), coin(2, 0, Some(13))]; + // 20 would need both — the expiring one is invisible. + assert_eq!( + selector().select(20, &coins, &[], NOW), + Err(CoinSelectionError::InsufficientFunds) + ); + // 10 matches with the young coin only. + let result = selector().select(10, &coins, &[], NOW).unwrap(); + let TransferStrategy::ExactMatch { coins: selected } = result.strategy else { + panic!("expected exact match"); + }; + assert_eq!(selected[0].derivation_index, 2); + } + + #[test] + fn find_exact_match_returns_none_when_no_exact_subset_exists() { + assert!(find_exact_match(30, &[coin(1, 2, None)], &ctx()).is_none()); + assert!(find_exact_match(30, &[coin(1, 1, None), coin(2, 0, None)], &ctx()).is_some()); + } + + #[test] + fn split_picks_smallest_coin_larger_than_the_remainder() { + // Amount 30: no exact match from {160, 80}; split the 80? No — + // smallest coin larger than 30 is 80 (overshoot 50) vs 160 + // (overshoot 130) → split coin 2 (exp 3). + let coins = [coin(1, 4, None), coin(2, 3, None)]; + let result = selector().select(30, &coins, &[], NOW).unwrap(); + let TransferStrategy::Split { + partial_coins, + split_coin, + target_denominations, + change_denominations, + } = result.strategy + else { + panic!("expected split"); + }; + assert!(partial_coins.is_empty()); + assert_eq!(split_coin.derivation_index, 2); + // target 30 = 20 + 10; change 50 = 40 + 10. + assert_eq!( + target_denominations, + [Denomination { exponent: 1 }, Denomination { exponent: 0 }] + ); + assert_eq!( + change_denominations, + [Denomination { exponent: 2 }, Denomination { exponent: 0 }] + ); + // Split invariant: partial + target == amount; target + change == coin. + assert_eq!(ctx().total_value(&target_denominations), 30); + assert_eq!(ctx().total_value(&change_denominations), 50); + } + + /// Smaller whole coins must not be added when one coin can fund the full + /// split. + #[test] + fn split_uses_one_smallest_coin_larger_than_the_whole_request() { + let coins = [ + coin(1, 4, None), // 160 + coin(2, 2, None), // 40 + coin(3, 0, None), // 10 + ]; + let result = selector().select(30, &coins, &[], NOW).unwrap(); + let TransferStrategy::Split { partial_coins, split_coin, .. } = result.strategy else { + panic!("expected split"); + }; + assert!(partial_coins.is_empty()); + assert_eq!(split_coin.derivation_index, 2); + } + + #[test] + fn split_takes_a_partial_contribution_first() { + // Amount 50: greedy takes the 40 (exp 2), remainder 10 needs a + // split of the 20 (exp 1) into 10 + 10. + let coins = [coin(1, 2, None), coin(2, 1, None)]; + let result = selector().select(50, &coins, &[], NOW).unwrap(); + let TransferStrategy::Split { + partial_coins, + split_coin, + target_denominations, + change_denominations, + } = result.strategy + else { + panic!("expected split"); + }; + assert_eq!(partial_coins[0].derivation_index, 1); + assert_eq!(split_coin.derivation_index, 2); + assert_eq!(ctx().total_value(&target_denominations), 10); + assert_eq!(ctx().total_value(&change_denominations), 10); + } + + #[test] + fn unload_prefers_single_smallest_sufficient_voucher() { + let coins: [Coin; 0] = []; + let vouchers = [full_voucher(1, 4), full_voucher(2, 2), full_voucher(3, 3)]; + // Need 40: the exp-2 voucher (value 40) is the minimal cover — + // not the 80, not the 160, not a combination. + let result = selector().select(40, &coins, &vouchers, NOW).unwrap(); + let TransferStrategy::UnloadIntoCoins { coins: partial, groups } = result.strategy else { + panic!("expected unload"); + }; + assert!(partial.is_empty()); + assert_eq!(groups.len(), 1); + assert_eq!(groups[0].vouchers[0].derivation_index, 2); + assert_eq!(ctx().total_value(&groups[0].recipient_denominations), 40); + assert!(groups[0].change_denominations.is_empty()); + assert_eq!(result.privacy_level, PrivacyLevel::Full); + } + + #[test] + fn unload_groups_by_recycler_and_balances_output_to_input() { + let vouchers = [ + voucher(1, 2, 7, VoucherPrivacyLevel::Full, 0), // 40, recycler (2,7) + voucher(2, 2, 9, VoucherPrivacyLevel::Full, 0), // 40, recycler (2,9) + ]; + // Need 60 → both vouchers (no single is sufficient): group (2,7) + // gives 40 to the recipient, group (2,9) gives 20 + 20 change. + let result = selector().select(60, &[], &vouchers, NOW).unwrap(); + let TransferStrategy::UnloadIntoCoins { groups, .. } = result.strategy else { + panic!("expected unload"); + }; + assert_eq!(groups.len(), 2); + for group in &groups { + let input: u128 = + group.vouchers.iter().map(|v| ctx().value_in_planks(v.exponent)).sum(); + let output = ctx().total_value(&group.recipient_denominations) + + ctx().total_value(&group.change_denominations); + assert_eq!(input, output, "pallet invariant: group output == input"); + } + let recipient_total: u128 = + groups.iter().map(|g| ctx().total_value(&g.recipient_denominations)).sum(); + assert_eq!(recipient_total, 60); + } + + #[test] + fn unload_groups_are_ordered_by_descending_exponent() { + let vouchers = [ + voucher(1, 0, 7, VoucherPrivacyLevel::Full, 0), // 10 + voucher(2, 2, 9, VoucherPrivacyLevel::Full, 0), // 40 + ]; + let result = selector().select(50, &[], &vouchers, NOW).unwrap(); + let TransferStrategy::UnloadIntoCoins { groups, .. } = result.strategy else { + panic!("expected unload"); + }; + assert_eq!(groups.iter().map(|group| group.recycler.exponent).collect::>(), [2, 0]); + } + + #[test] + fn unload_uses_partial_coins_before_vouchers() { + let coins = [coin(1, 1, None)]; // 20 + let vouchers = [full_voucher(10, 2)]; // 40 + // Need 60 = coin 20 + voucher 40. + let result = selector().select(60, &coins, &vouchers, NOW).unwrap(); + let TransferStrategy::UnloadIntoCoins { coins: partial, groups } = result.strategy else { + panic!("expected unload"); + }; + assert_eq!(partial[0].derivation_index, 1); + assert_eq!(groups[0].vouchers[0].derivation_index, 10); + } + + #[test] + fn degraded_fallback_triggers_when_full_privacy_is_insufficient() { + let vouchers = [ + full_voucher(1, 1), // 20 full + voucher(2, 2, 0, VoucherPrivacyLevel::Degraded, 0), // 40 degraded + ]; + // 20 is coverable full-privacy → Full. + let result = selector().select(20, &[], &vouchers, NOW).unwrap(); + assert_eq!(result.privacy_level, PrivacyLevel::Full); + // 60 needs the degraded voucher too → Degraded. + let result = selector().select(60, &[], &vouchers, NOW).unwrap(); + assert_eq!(result.privacy_level, PrivacyLevel::Degraded); + } + + #[test] + fn not_yet_ready_full_voucher_counts_as_degraded() { + let vouchers = [voucher(1, 1, 0, VoucherPrivacyLevel::Full, NOW + 1)]; + let result = selector().select(20, &[], &vouchers, NOW).unwrap(); + assert_eq!(result.privacy_level, PrivacyLevel::Degraded); + } + + #[test] + fn no_ready_vouchers_error_when_pool_is_all_unready() { + let vouchers = [voucher(1, 0, 0, VoucherPrivacyLevel::Degraded, 0)]; // 10 + assert_eq!( + selector().select(160, &[], &vouchers, NOW), + Err(CoinSelectionError::NoReadyVouchers) + ); + } + + #[test] + fn too_many_vouchers_in_group_is_a_hard_stop() { + let tight = CoinSelector::new(ctx(), 2); + let vouchers: Vec = (0..3).map(|i| full_voucher(i, 0)).collect(); // 3 × 10, one recycler + assert_eq!( + tight.select(30, &[], &vouchers, NOW), + Err(CoinSelectionError::TooManyVouchersInGroup { count: 3, max: 2 }) + ); + } + + #[test] + fn voucher_group_equal_to_max_is_rejected_like_ios_v2() { + let tight = CoinSelector::new(ctx(), 2); + let vouchers = [full_voucher(1, 0), full_voucher(2, 0)]; + assert_eq!( + tight.select(20, &[], &vouchers, NOW), + Err(CoinSelectionError::TooManyVouchersInGroup { count: 2, max: 2 }) + ); + } + + #[test] + fn insufficient_funds_when_everything_together_cannot_cover() { + let coins = [coin(1, 0, None)]; + let vouchers = [full_voucher(2, 0)]; + assert_eq!( + selector().select(160, &coins, &vouchers, NOW), + Err(CoinSelectionError::InsufficientFunds) + ); + } + + /// Deterministic pseudo-random sweep: every outcome upholds the value + /// invariants, and all three strategy paths are exercised. + #[test] + fn random_sweep_covers_all_strategies_and_holds_invariants() { + use rand::{Rng, SeedableRng, rngs::StdRng}; + let mut rng = StdRng::seed_from_u64(0x_C01_A6E); + let context = ctx(); + let selector = selector(); + let (mut exact, mut split, mut unload) = (0, 0, 0); + + for _ in 0..300 { + let coins: Vec = (0..rng.gen_range(0..6)) + .map(|i| { + coin( + i, + rng.gen_range(0..=4), + if rng.gen_bool(0.3) { None } else { Some(rng.gen_range(0..16)) }, + ) + }) + .collect(); + let vouchers: Vec = (0..rng.gen_range(0..5)) + .map(|i| { + voucher( + 100 + i, + rng.gen_range(0..=4), + rng.gen_range(0..3), + if rng.gen_bool(0.7) { + VoucherPrivacyLevel::Full + } else { + VoucherPrivacyLevel::Degraded + }, + if rng.gen_bool(0.8) { 0 } else { NOW + 1 }, + ) + }) + .collect(); + let amount = u128::from(rng.gen_range(1..60u32)) * 10; + + let first = selector.select(amount, &coins, &vouchers, NOW); + assert_eq!( + first, + selector.select(amount, &coins, &vouchers, NOW), + "identical snapshots must select deterministically" + ); + + match first { + Ok(result) => match result.strategy { + TransferStrategy::ExactMatch { coins: selected } => { + let unique: std::collections::HashSet<_> = + selected.iter().map(|coin| coin.derivation_index).collect(); + assert_eq!(unique.len(), selected.len(), "coin inputs are unique"); + exact += 1; + let total: u128 = + selected.iter().map(|c| context.value_in_planks(c.exponent)).sum(); + assert_eq!(total, amount); + assert!(selected.iter().all(|c| c.is_selectable())); + }, + TransferStrategy::Split { + partial_coins, + split_coin, + target_denominations, + change_denominations, + } => { + split += 1; + let mut unique: std::collections::HashSet<_> = + partial_coins.iter().map(|coin| coin.derivation_index).collect(); + assert!( + unique.insert(split_coin.derivation_index), + "the split coin cannot also be a partial input" + ); + assert!(partial_coins.iter().all(Coin::is_selectable)); + assert!(split_coin.is_selectable()); + let partial: u128 = + partial_coins.iter().map(|c| context.value_in_planks(c.exponent)).sum(); + assert_eq!( + partial + context.total_value(&target_denominations), + amount, + "partial + split target == amount" + ); + assert_eq!( + context.total_value(&target_denominations) + + context.total_value(&change_denominations), + context.value_in_planks(split_coin.exponent), + "split conserves the coin's value" + ); + }, + TransferStrategy::UnloadIntoCoins { coins: partial, groups } => { + unload += 1; + let unique_coins: std::collections::HashSet<_> = + partial.iter().map(|coin| coin.derivation_index).collect(); + assert_eq!(unique_coins.len(), partial.len(), "coin inputs are unique"); + assert!(partial.iter().all(Coin::is_selectable)); + let mut unique_vouchers = std::collections::HashSet::new(); + let partial: u128 = + partial.iter().map(|c| context.value_in_planks(c.exponent)).sum(); + let recipient: u128 = groups + .iter() + .map(|g| context.total_value(&g.recipient_denominations)) + .sum(); + assert_eq!(partial + recipient, amount, "unload covers exactly"); + for group in &groups { + let input: u128 = group + .vouchers + .iter() + .map(|v| context.value_in_planks(v.exponent)) + .sum(); + assert_eq!( + input, + context.total_value(&group.recipient_denominations) + + context.total_value(&group.change_denominations) + ); + assert!( + group.vouchers.len() < 8, + "reference max-consolidation check is strict" + ); + assert!(group.vouchers.iter().all(Voucher::is_unloadable)); + assert!( + group.vouchers.iter().all(|voucher| { + unique_vouchers.insert(voucher.derivation_index) + }), + "voucher inputs are unique across recycler groups" + ); + } + }, + }, + Err(error) => { + assert!( + matches!( + error, + CoinSelectionError::EmptyWallet | + CoinSelectionError::InsufficientFunds | + CoinSelectionError::NoReadyVouchers | + CoinSelectionError::TooManyVouchersInGroup { .. } + ), + "unexpected error class: {error:?}" + ); + }, + } + } + assert!(exact > 10, "exact-match path exercised ({exact})"); + assert!(split > 10, "split path exercised ({split})"); + assert!(unload > 10, "unload path exercised ({unload})"); + } } diff --git a/rust/crates/truapi-coinage/src/sync.rs b/rust/crates/truapi-coinage/src/sync.rs index 038fc20fd9..ca69b6d1cf 100644 --- a/rust/crates/truapi-coinage/src/sync.rs +++ b/rust/crates/truapi-coinage/src/sync.rs @@ -2,28 +2,31 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use {parking_lot::Mutex, std::sync::Arc}; +use parking_lot::Mutex; +use std::sync::Arc; use async_trait::async_trait; use futures::future::AbortHandle; use tokio::sync::{mpsc, watch}; use tracing::warn; -use crate::model::{Coin, CoinState, Voucher, VoucherLocalState}; -use crate::repo::{CoinRepository, VoucherRepository}; +use crate::{ + model::{Coin, CoinState, Voucher, VoucherLocalState}, + repo::{CoinRepository, VoucherRepository}, +}; /// One coin's on-chain reading (`CoinsByOwner` decode). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct OnChainCoin { - pub exponent: i16, - pub age: i16, + pub exponent: i16, + pub age: i16, } /// One (possibly partial) emission: `None` means the coin's entry is /// absent on-chain. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct CoinStateUpdate { - pub coins: Vec<(u32, Option)>, + pub coins: Vec<(u32, Option)>, } /// The chain effect: ONE batched storage subscription over the given @@ -31,462 +34,409 @@ pub struct CoinStateUpdate { /// Re-calling replaces the previous subscription. #[async_trait] pub trait CoinStateSubscriber: Send + Sync { - async fn subscribe( - &self, - derivation_indices: Vec, - ) -> Result, String>; + async fn subscribe( + &self, + derivation_indices: Vec, + ) -> Result, String>; } pub struct CoinStateSyncService { - spawner: crate::Spawner, - coins: Arc, - chain: Arc, - subscribed: Mutex>, - task: Mutex>, + spawner: crate::Spawner, + coins: Arc, + chain: Arc, + subscribed: Mutex>, + task: Mutex>, } impl CoinStateSyncService { - pub fn new( - coins: Arc, - chain: Arc, - spawner: crate::Spawner, - ) -> Self { - Self { - coins, - chain, - subscribed: Mutex::new(Vec::new()), - spawner, - task: Mutex::new(None), - } - } - - /// (Re)builds the batch subscription over the monitored set. Call at - /// startup and whenever local coins change; the service also resyncs - /// itself when an applied update shrinks the monitored set. - pub async fn sync(self: &Arc) -> Result<(), String> { - let monitored = self.monitored_indices().await?; - if monitored.is_empty() { - self.stop(); - return Ok(()); - } - *self.subscribed.lock() = monitored.clone(); - let receiver = self.chain.subscribe(monitored).await?; - self.replace_task(receiver); - Ok(()) - } - - pub fn stop(&self) { - if let Some(handle) = self.task.lock().take() { - handle.abort(); - } - self.subscribed.lock().clear(); - } - - async fn monitored_indices(&self) -> Result, String> { - let mut indices: Vec = self - .coins - .list() - .await? - .into_iter() - .filter(|c| c.state != CoinState::Spent && c.age.is_none()) - .map(|c| c.derivation_index) - .collect(); - indices.sort_unstable(); - Ok(indices) - } - - fn replace_task(self: &Arc, mut receiver: mpsc::Receiver) { - let service = Arc::clone(self); - let handle = crate::tasks::spawn_abortable(&self.spawner, async move { - while let Some(update) = receiver.recv().await { - match service.handle_update(update).await { - Ok(true) => { - // The monitored set changed — rebuild. - let service = Arc::clone(&service); - crate::tasks::spawn_abortable(&service.spawner.clone(), async move { - if let Err(error) = service.sync().await { - warn!(error, "coin state resync failed"); - } - }); - return; - } - Ok(false) => {} - Err(error) => warn!(error, "coin state update failed"), - } - } - }); - let previous = self.task.lock().replace(handle); - if let Some(previous) = previous { - previous.abort(); - } - } - - /// Applies one emission; resolves `true` when the monitored set - /// changed (resync needed). - async fn handle_update(&self, update: CoinStateUpdate) -> Result { - let coins = self.coins.list().await?; - for (index, on_chain) in &update.coins { - let Some(coin) = coins - .iter() - .find(|c| c.derivation_index == *index && c.state != CoinState::Spent) - else { - continue; - }; - match on_chain { - Some(reading) => { - if coin.age != Some(reading.age) { - let mut updated = coin.clone(); - updated.age = Some(reading.age); - self.coins.upsert(&updated).await?; - } - } - None => { - if coin.age.is_some() { - self.coins - .set_state(coin.derivation_index, CoinState::Spent) - .await?; - } - } - } - } - let monitored = self.monitored_indices().await?; - Ok(monitored != *self.subscribed.lock()) - } + pub fn new( + coins: Arc, + chain: Arc, + spawner: crate::Spawner, + ) -> Self { + Self { coins, chain, subscribed: Mutex::new(Vec::new()), spawner, task: Mutex::new(None) } + } + + /// (Re)builds the batch subscription over the monitored set. Call at + /// startup and whenever local coins change; the service also resyncs + /// itself when an applied update shrinks the monitored set. + pub async fn sync(self: &Arc) -> Result<(), String> { + let monitored = self.monitored_indices().await?; + if monitored.is_empty() { + self.stop(); + return Ok(()); + } + *self.subscribed.lock() = monitored.clone(); + let receiver = self.chain.subscribe(monitored).await?; + self.replace_task(receiver); + Ok(()) + } + + pub fn stop(&self) { + if let Some(handle) = self.task.lock().take() { + handle.abort(); + } + self.subscribed.lock().clear(); + } + + async fn monitored_indices(&self) -> Result, String> { + let mut indices: Vec = self + .coins + .list() + .await? + .into_iter() + .filter(|c| c.state != CoinState::Spent && c.age.is_none()) + .map(|c| c.derivation_index) + .collect(); + indices.sort_unstable(); + Ok(indices) + } + + fn replace_task(self: &Arc, mut receiver: mpsc::Receiver) { + let service = Arc::clone(self); + let handle = crate::tasks::spawn_abortable(&self.spawner, async move { + while let Some(update) = receiver.recv().await { + match service.handle_update(update).await { + Ok(true) => { + // The monitored set changed — rebuild. + let service = Arc::clone(&service); + crate::tasks::spawn_abortable(&service.spawner.clone(), async move { + if let Err(error) = service.sync().await { + warn!(error, "coin state resync failed"); + } + }); + return; + }, + Ok(false) => {}, + Err(error) => warn!(error, "coin state update failed"), + } + } + }); + let previous = self.task.lock().replace(handle); + if let Some(previous) = previous { + previous.abort(); + } + } + + /// Applies one emission; resolves `true` when the monitored set + /// changed (resync needed). + async fn handle_update(&self, update: CoinStateUpdate) -> Result { + let coins = self.coins.list().await?; + for (index, on_chain) in &update.coins { + let Some(coin) = coins + .iter() + .find(|c| c.derivation_index == *index && c.state != CoinState::Spent) + else { + continue; + }; + match on_chain { + Some(reading) => { + if coin.age != Some(reading.age) { + let mut updated = coin.clone(); + updated.age = Some(reading.age); + self.coins.upsert(&updated).await?; + } + }, + None => { + if coin.age.is_some() { + self.coins.set_state(coin.derivation_index, CoinState::Spent).await?; + } + }, + } + } + let monitored = self.monitored_indices().await?; + Ok(monitored != *self.subscribed.lock()) + } } /// [`CoinRepository`] decorator bumping a watch counter on every /// successful mutation — the reactive change stream consumers re-fetch /// on. pub struct NotifyingCoinRepository { - inner: Arc, - changes: watch::Sender, + inner: Arc, + changes: watch::Sender, } impl NotifyingCoinRepository { - pub fn new(inner: Arc) -> Self { - Self { - inner, - changes: watch::channel(0).0, - } - } - - pub fn subscribe_changes(&self) -> watch::Receiver { - self.changes.subscribe() - } - - fn bump(&self) { - self.changes.send_modify(|generation| *generation += 1); - } - - pub fn notify_changed(&self) { - self.bump(); - } + pub fn new(inner: Arc) -> Self { + Self { inner, changes: watch::channel(0).0 } + } + + pub fn subscribe_changes(&self) -> watch::Receiver { + self.changes.subscribe() + } + + fn bump(&self) { + self.changes.send_modify(|generation| *generation += 1); + } + + pub fn notify_changed(&self) { + self.bump(); + } } #[async_trait] impl CoinRepository for NotifyingCoinRepository { - async fn list(&self) -> Result, String> { - self.inner.list().await - } - async fn upsert(&self, coin: &Coin) -> Result<(), String> { - self.inner.upsert(coin).await?; - self.bump(); - Ok(()) - } - async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String> { - self.inner.set_state(derivation_index, state).await?; - self.bump(); - Ok(()) - } - async fn remove(&self, derivation_index: u32) -> Result<(), String> { - self.inner.remove(derivation_index).await?; - self.bump(); - Ok(()) - } + async fn list(&self) -> Result, String> { + self.inner.list().await + } + async fn upsert(&self, coin: &Coin) -> Result<(), String> { + self.inner.upsert(coin).await?; + self.bump(); + Ok(()) + } + async fn set_state(&self, derivation_index: u32, state: CoinState) -> Result<(), String> { + self.inner.set_state(derivation_index, state).await?; + self.bump(); + Ok(()) + } + async fn remove(&self, derivation_index: u32) -> Result<(), String> { + self.inner.remove(derivation_index).await?; + self.bump(); + Ok(()) + } } /// [`VoucherRepository`] decorator with the same change stream. pub struct NotifyingVoucherRepository { - inner: Arc, - changes: watch::Sender, + inner: Arc, + changes: watch::Sender, } impl NotifyingVoucherRepository { - pub fn new(inner: Arc) -> Self { - Self { - inner, - changes: watch::channel(0).0, - } - } - - pub fn subscribe_changes(&self) -> watch::Receiver { - self.changes.subscribe() - } - - fn bump(&self) { - self.changes.send_modify(|generation| *generation += 1); - } - - pub fn notify_changed(&self) { - self.bump(); - } + pub fn new(inner: Arc) -> Self { + Self { inner, changes: watch::channel(0).0 } + } + + pub fn subscribe_changes(&self) -> watch::Receiver { + self.changes.subscribe() + } + + fn bump(&self) { + self.changes.send_modify(|generation| *generation += 1); + } + + pub fn notify_changed(&self) { + self.bump(); + } } #[async_trait] impl VoucherRepository for NotifyingVoucherRepository { - async fn list(&self) -> Result, String> { - self.inner.list().await - } - async fn upsert(&self, voucher: &Voucher) -> Result<(), String> { - self.inner.upsert(voucher).await?; - self.bump(); - Ok(()) - } - async fn set_local_state( - &self, - derivation_index: u32, - state: VoucherLocalState, - ) -> Result<(), String> { - self.inner.set_local_state(derivation_index, state).await?; - self.bump(); - Ok(()) - } - async fn set_remote_state( - &self, - derivation_index: u32, - state: crate::model::VoucherRemoteState, - ) -> Result<(), String> { - self.inner.set_remote_state(derivation_index, state).await?; - self.bump(); - Ok(()) - } - async fn remove(&self, derivation_index: u32) -> Result<(), String> { - self.inner.remove(derivation_index).await?; - self.bump(); - Ok(()) - } + async fn list(&self) -> Result, String> { + self.inner.list().await + } + async fn upsert(&self, voucher: &Voucher) -> Result<(), String> { + self.inner.upsert(voucher).await?; + self.bump(); + Ok(()) + } + async fn set_local_state( + &self, + derivation_index: u32, + state: VoucherLocalState, + ) -> Result<(), String> { + self.inner.set_local_state(derivation_index, state).await?; + self.bump(); + Ok(()) + } + async fn set_remote_state( + &self, + derivation_index: u32, + state: crate::model::VoucherRemoteState, + ) -> Result<(), String> { + self.inner.set_remote_state(derivation_index, state).await?; + self.bump(); + Ok(()) + } + async fn remove(&self, derivation_index: u32) -> Result<(), String> { + self.inner.remove(derivation_index).await?; + self.bump(); + Ok(()) + } } pub struct CoinageDatabaseDependencyFactory { - coins: Arc, - vouchers: Arc, + coins: Arc, + vouchers: Arc, } impl CoinageDatabaseDependencyFactory { - pub fn new(coins: Arc, vouchers: Arc) -> Self { - Self { - coins: Arc::new(NotifyingCoinRepository::new(coins)), - vouchers: Arc::new(NotifyingVoucherRepository::new(vouchers)), - } - } - - pub fn coin_repository(&self) -> Arc { - Arc::clone(&self.coins) - } - - pub fn voucher_repository(&self) -> Arc { - Arc::clone(&self.vouchers) - } + pub fn new(coins: Arc, vouchers: Arc) -> Self { + Self { + coins: Arc::new(NotifyingCoinRepository::new(coins)), + vouchers: Arc::new(NotifyingVoucherRepository::new(vouchers)), + } + } + + pub fn coin_repository(&self) -> Arc { + Arc::clone(&self.coins) + } + + pub fn voucher_repository(&self) -> Arc { + Arc::clone(&self.vouchers) + } } #[cfg(test)] mod tests { - use super::*; - use crate::repo::{InMemoryCoinRepository, InMemoryVoucherRepository}; - - #[derive(Default)] - struct MockSubscriber { - calls: Mutex>>, - senders: Mutex>>, - } - - impl MockSubscriber { - fn latest_sender(&self) -> mpsc::Sender { - self.senders.lock().last().expect("no subscription").clone() - } - } - - #[async_trait] - impl CoinStateSubscriber for MockSubscriber { - async fn subscribe( - &self, - derivation_indices: Vec, - ) -> Result, String> { - self.calls.lock().push(derivation_indices); - let (tx, rx) = mpsc::channel(8); - self.senders.lock().push(tx); - Ok(rx) - } - } - - fn coin(index: u32, age: Option, state: CoinState) -> Coin { - Coin { - exponent: 1, - derivation_index: index, - age, - state, - } - } - - fn rig( - coins: Vec, - ) -> ( - Arc, - Arc, - Arc, - ) { - let repo = Arc::new(InMemoryCoinRepository::with_coins(coins)); - let subscriber = Arc::new(MockSubscriber::default()); - ( - Arc::new(CoinStateSyncService::new( - Arc::clone(&repo) as Arc, - Arc::clone(&subscriber) as Arc, - crate::test_spawner(), - )), - repo, - subscriber, - ) - } - - async fn read_coin(repo: &InMemoryCoinRepository, index: u32) -> Coin { - repo.list() - .await - .unwrap() - .into_iter() - .find(|c| c.derivation_index == index) - .unwrap() - } - - async fn settle(mut probe: impl AsyncFnMut() -> bool) { - for _ in 0..1_000 { - if probe().await { - return; - } - tokio::task::yield_now().await; - } - panic!("never settled"); - } - - #[tokio::test] - async fn age_lands_and_the_monitored_set_shrinks() { - let (service, repo, subscriber) = rig(vec![ - coin(1, None, CoinState::Available), - coin(2, Some(4), CoinState::Available), // known age — not monitored - coin(3, None, CoinState::Spent), // spent — not monitored - ]); - service.sync().await.unwrap(); - assert_eq!(subscriber.calls.lock().as_slice(), [vec![1]]); - - subscriber - .latest_sender() - .send(CoinStateUpdate { - coins: vec![( - 1, - Some(OnChainCoin { - exponent: 1, - age: 0, - }), - )], - }) - .await - .unwrap(); - settle(async || read_coin(&repo, 1).await.age == Some(0)).await; - // Monitored set now empty → the resync stops the subscription. - settle(async || service.task.lock().is_none()).await; - } - - #[tokio::test] - async fn absence_spends_only_previously_observed_coins() { - let (service, repo, subscriber) = rig(vec![ - coin(1, None, CoinState::Available), - coin(2, None, CoinState::Available), - ]); - service.sync().await.unwrap(); - - // Coin 1 lands with an age… - subscriber - .latest_sender() - .send(CoinStateUpdate { - coins: vec![( - 1, - Some(OnChainCoin { - exponent: 1, - age: 2, - }), - )], - }) - .await - .unwrap(); - settle(async || read_coin(&repo, 1).await.age == Some(2)).await; - settle(async || subscriber.calls.lock().len() == 2).await; - - // …then disappears (claimed by a recipient) while coin 2 is - // still absent because it never landed. - subscriber - .latest_sender() - .send(CoinStateUpdate { - coins: vec![(1, None), (2, None)], - }) - .await - .unwrap(); - settle(async || read_coin(&repo, 1).await.state == CoinState::Spent).await; - let unlanded = read_coin(&repo, 2).await; - assert_eq!( - unlanded.state, - CoinState::Available, - "unknown-age absence is 'not landed yet', never 'spent'" - ); - assert_eq!(unlanded.age, None); - } - - #[tokio::test] - async fn empty_monitored_set_never_subscribes() { - let (service, _repo, subscriber) = rig(vec![coin(1, Some(3), CoinState::Available)]); - service.sync().await.unwrap(); - assert!(subscriber.calls.lock().is_empty()); - assert!(service.task.lock().is_none()); - } - - #[tokio::test] - async fn factory_change_streams_fire_on_mutation() { - let factory = CoinageDatabaseDependencyFactory::new( - Arc::new(InMemoryCoinRepository::default()), - Arc::new(InMemoryVoucherRepository::default()), - ); - let coins = factory.coin_repository(); - let mut coin_changes = coins.subscribe_changes(); - coins - .upsert(&coin(1, None, CoinState::Available)) - .await - .unwrap(); - coin_changes.changed().await.unwrap(); - - let same = factory.coin_repository(); - assert_eq!( - same.list().await.unwrap().len(), - 1, - "same underlying instance" - ); - - let vouchers = factory.voucher_repository(); - let mut voucher_changes = vouchers.subscribe_changes(); - vouchers - .upsert(&Voucher { - exponent: 0, - derivation_index: 1, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: crate::model::VoucherRemoteState::Unlocated, - local_state: VoucherLocalState::Available, - privacy: crate::model::VoucherPrivacyLevel::Degraded, - }) - .await - .unwrap(); - voucher_changes.changed().await.unwrap(); - vouchers - .set_local_state(1, VoucherLocalState::Spent) - .await - .unwrap(); - voucher_changes.changed().await.unwrap(); - } + use super::*; + use crate::repo::{InMemoryCoinRepository, InMemoryVoucherRepository}; + + #[derive(Default)] + struct MockSubscriber { + calls: Mutex>>, + senders: Mutex>>, + } + + impl MockSubscriber { + fn latest_sender(&self) -> mpsc::Sender { + self.senders.lock().last().expect("no subscription").clone() + } + } + + #[async_trait] + impl CoinStateSubscriber for MockSubscriber { + async fn subscribe( + &self, + derivation_indices: Vec, + ) -> Result, String> { + self.calls.lock().push(derivation_indices); + let (tx, rx) = mpsc::channel(8); + self.senders.lock().push(tx); + Ok(rx) + } + } + + fn coin(index: u32, age: Option, state: CoinState) -> Coin { + Coin { exponent: 1, derivation_index: index, age, state } + } + + fn rig( + coins: Vec, + ) -> (Arc, Arc, Arc) { + let repo = Arc::new(InMemoryCoinRepository::with_coins(coins)); + let subscriber = Arc::new(MockSubscriber::default()); + ( + Arc::new(CoinStateSyncService::new( + Arc::clone(&repo) as Arc, + Arc::clone(&subscriber) as Arc, + crate::test_spawner(), + )), + repo, + subscriber, + ) + } + + async fn read_coin(repo: &InMemoryCoinRepository, index: u32) -> Coin { + repo.list() + .await + .unwrap() + .into_iter() + .find(|c| c.derivation_index == index) + .unwrap() + } + + async fn settle(mut probe: impl AsyncFnMut() -> bool) { + for _ in 0..1_000 { + if probe().await { + return; + } + tokio::task::yield_now().await; + } + panic!("never settled"); + } + + #[tokio::test] + async fn age_lands_and_the_monitored_set_shrinks() { + let (service, repo, subscriber) = rig(vec![ + coin(1, None, CoinState::Available), + coin(2, Some(4), CoinState::Available), // known age — not monitored + coin(3, None, CoinState::Spent), // spent — not monitored + ]); + service.sync().await.unwrap(); + assert_eq!(subscriber.calls.lock().as_slice(), [vec![1]]); + + subscriber + .latest_sender() + .send(CoinStateUpdate { coins: vec![(1, Some(OnChainCoin { exponent: 1, age: 0 }))] }) + .await + .unwrap(); + settle(async || read_coin(&repo, 1).await.age == Some(0)).await; + // Monitored set now empty → the resync stops the subscription. + settle(async || service.task.lock().is_none()).await; + } + + #[tokio::test] + async fn absence_spends_only_previously_observed_coins() { + let (service, repo, subscriber) = + rig(vec![coin(1, None, CoinState::Available), coin(2, None, CoinState::Available)]); + service.sync().await.unwrap(); + + // Coin 1 lands with an age… + subscriber + .latest_sender() + .send(CoinStateUpdate { coins: vec![(1, Some(OnChainCoin { exponent: 1, age: 2 }))] }) + .await + .unwrap(); + settle(async || read_coin(&repo, 1).await.age == Some(2)).await; + settle(async || subscriber.calls.lock().len() == 2).await; + + // …then disappears (claimed by a recipient) while coin 2 is + // still absent because it never landed. + subscriber + .latest_sender() + .send(CoinStateUpdate { coins: vec![(1, None), (2, None)] }) + .await + .unwrap(); + settle(async || read_coin(&repo, 1).await.state == CoinState::Spent).await; + let unlanded = read_coin(&repo, 2).await; + assert_eq!( + unlanded.state, + CoinState::Available, + "unknown-age absence is 'not landed yet', never 'spent'" + ); + assert_eq!(unlanded.age, None); + } + + #[tokio::test] + async fn empty_monitored_set_never_subscribes() { + let (service, _repo, subscriber) = rig(vec![coin(1, Some(3), CoinState::Available)]); + service.sync().await.unwrap(); + assert!(subscriber.calls.lock().is_empty()); + assert!(service.task.lock().is_none()); + } + + #[tokio::test] + async fn factory_change_streams_fire_on_mutation() { + let factory = CoinageDatabaseDependencyFactory::new( + Arc::new(InMemoryCoinRepository::default()), + Arc::new(InMemoryVoucherRepository::default()), + ); + let coins = factory.coin_repository(); + let mut coin_changes = coins.subscribe_changes(); + coins.upsert(&coin(1, None, CoinState::Available)).await.unwrap(); + coin_changes.changed().await.unwrap(); + + let same = factory.coin_repository(); + assert_eq!(same.list().await.unwrap().len(), 1, "same underlying instance"); + + let vouchers = factory.voucher_repository(); + let mut voucher_changes = vouchers.subscribe_changes(); + vouchers + .upsert(&Voucher { + exponent: 0, + derivation_index: 1, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: crate::model::VoucherRemoteState::Unlocated, + local_state: VoucherLocalState::Available, + privacy: crate::model::VoucherPrivacyLevel::Degraded, + }) + .await + .unwrap(); + voucher_changes.changed().await.unwrap(); + vouchers.set_local_state(1, VoucherLocalState::Spent).await.unwrap(); + voucher_changes.changed().await.unwrap(); + } } diff --git a/rust/crates/truapi-coinage/src/tasks.rs b/rust/crates/truapi-coinage/src/tasks.rs index 1ef42039f4..f045cd4d08 100644 --- a/rust/crates/truapi-coinage/src/tasks.rs +++ b/rust/crates/truapi-coinage/src/tasks.rs @@ -3,227 +3,209 @@ // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. use futures::future::{AbortHandle, Abortable}; -use std::collections::HashMap; -use std::future::Future; -use {parking_lot::Mutex, std::sync::Arc}; +use parking_lot::Mutex; +use std::{collections::HashMap, future::Future, sync::Arc}; /// Launch a cancellable future on the Host's executor. pub(crate) fn spawn_abortable(spawner: &crate::Spawner, work: F) -> AbortHandle where - F: Future + Send + 'static, + F: Future + Send + 'static, { - let (abort, registration) = AbortHandle::new_pair(); - spawner(Box::pin(async move { - let _ = Abortable::new(work, registration).await; - })); - abort + let (abort, registration) = AbortHandle::new_pair(); + spawner(Box::pin(async move { + let _ = Abortable::new(work, registration).await; + })); + abort } /// Per-message task ownership with cancellation and duplicate suppression. pub struct ActiveTaskRegistry { - spawner: crate::Spawner, - state: Mutex, + spawner: crate::Spawner, + state: Mutex, } #[derive(Default)] struct RegistryState { - next_generation: u64, - tasks: HashMap, + next_generation: u64, + tasks: HashMap, } impl ActiveTaskRegistry { - /// Bind background work to the owning Host executor. - pub fn new(spawner: crate::Spawner) -> Self { - Self { - spawner, - state: Mutex::new(RegistryState::default()), - } - } - - /// Start only if this message does not already have a live task. - pub fn try_start(self: &Arc, message_id: &str, work: F) -> bool - where - F: Future + Send + 'static, - { - let mut state = self.state.lock(); - if state.tasks.contains_key(message_id) { - return false; - } - let generation = state.next_generation; - state.next_generation = generation.checked_add(1).expect("task generation overflow"); - let (abort, registration) = AbortHandle::new_pair(); - let id = message_id.to_owned(); - state.tasks.insert(id.clone(), (generation, abort)); - drop(state); - // Construct outside the future so cancellation before its first poll - // still releases the id. An older cancelled task cannot remove a restart. - let guard = RemoveOnDrop { - registry: Arc::clone(self), - id, - generation, - }; - (self.spawner)(Box::pin( - Abortable::new( - async move { - let _guard = guard; - work.await; - }, - registration, - ) - .map(|_| ()), - )); - true - } - - /// Whether work currently owns this message id. - pub fn is_tracked(&self, message_id: &str) -> bool { - self.state.lock().tasks.contains_key(message_id) - } - - /// Number of live message tasks. - pub fn len(&self) -> usize { - self.state.lock().tasks.len() - } - - /// Whether no message is currently owned. - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Cancel all work and make the message ids available for restart. - pub fn cancel_all(&self) { - let handles: Vec<_> = self - .state - .lock() - .tasks - .drain() - .map(|(_, (_, handle))| handle) - .collect(); - for handle in handles { - handle.abort(); - } - } + /// Bind background work to the owning Host executor. + pub fn new(spawner: crate::Spawner) -> Self { + Self { spawner, state: Mutex::new(RegistryState::default()) } + } + + /// Start only if this message does not already have a live task. + pub fn try_start(self: &Arc, message_id: &str, work: F) -> bool + where + F: Future + Send + 'static, + { + let mut state = self.state.lock(); + if state.tasks.contains_key(message_id) { + return false; + } + let generation = state.next_generation; + state.next_generation = generation.checked_add(1).expect("task generation overflow"); + let (abort, registration) = AbortHandle::new_pair(); + let id = message_id.to_owned(); + state.tasks.insert(id.clone(), (generation, abort)); + drop(state); + // Construct outside the future so cancellation before its first poll + // still releases the id. An older cancelled task cannot remove a restart. + let guard = RemoveOnDrop { registry: Arc::clone(self), id, generation }; + (self.spawner)(Box::pin( + Abortable::new( + async move { + let _guard = guard; + work.await; + }, + registration, + ) + .map(|_| ()), + )); + true + } + + /// Whether work currently owns this message id. + pub fn is_tracked(&self, message_id: &str) -> bool { + self.state.lock().tasks.contains_key(message_id) + } + + /// Number of live message tasks. + pub fn len(&self) -> usize { + self.state.lock().tasks.len() + } + + /// Whether no message is currently owned. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Cancel all work and make the message ids available for restart. + pub fn cancel_all(&self) { + let handles: Vec<_> = + self.state.lock().tasks.drain().map(|(_, (_, handle))| handle).collect(); + for handle in handles { + handle.abort(); + } + } } use futures::FutureExt; struct RemoveOnDrop { - registry: Arc, - id: String, - generation: u64, + registry: Arc, + id: String, + generation: u64, } impl Drop for RemoveOnDrop { - fn drop(&mut self) { - let mut state = self.registry.state.lock(); - if state - .tasks - .get(&self.id) - .is_some_and(|(generation, _)| *generation == self.generation) - { - state.tasks.remove(&self.id); - } - } + fn drop(&mut self) { + let mut state = self.registry.state.lock(); + if state + .tasks + .get(&self.id) + .is_some_and(|(generation, _)| *generation == self.generation) + { + state.tasks.remove(&self.id); + } + } } #[cfg(test)] mod tests { - use std::sync::atomic::{AtomicUsize, Ordering}; - - use tokio::sync::watch; - - use super::*; - - async fn settle(registry: &ActiveTaskRegistry, until: impl Fn(&ActiveTaskRegistry) -> bool) { - for _ in 0..1_000 { - if until(registry) { - return; - } - tokio::task::yield_now().await; - } - panic!("registry never settled"); - } - - #[tokio::test] - async fn duplicate_starts_are_rejected_until_completion() { - let registry = Arc::new(ActiveTaskRegistry::new(crate::test_spawner())); - let (release_tx, release_rx) = watch::channel(false); - let runs = Arc::new(AtomicUsize::new(0)); - - let work = { - let runs = Arc::clone(&runs); - let mut release = release_rx.clone(); - async move { - runs.fetch_add(1, Ordering::SeqCst); - while !*release.borrow() { - if release.changed().await.is_err() { - return; - } - } - } - }; - assert!(registry.try_start("m1", work)); - assert!(registry.is_tracked("m1")); - assert!( - !registry.try_start("m1", async {}), - "in-flight id rejects a second task" - ); - - release_tx.send(true).unwrap(); - settle(®istry, |r| !r.is_tracked("m1")).await; - assert_eq!(runs.load(Ordering::SeqCst), 1, "the duplicate never ran"); - assert!(registry.try_start("m1", async {}), "restart after defer"); - } - - #[tokio::test] - async fn distinct_ids_run_concurrently() { - let registry = Arc::new(ActiveTaskRegistry::new(crate::test_spawner())); - let (_release_tx, release_rx) = watch::channel(false); - for id in ["a", "b", "c"] { - let mut release = release_rx.clone(); - assert!(registry.try_start(id, async move { - let _ = release.changed().await; - })); - } - assert_eq!(registry.len(), 3); - } - - #[tokio::test] - async fn cancel_all_aborts_and_clears() { - let registry = Arc::new(ActiveTaskRegistry::new(crate::test_spawner())); - let completed = Arc::new(AtomicUsize::new(0)); - for id in ["a", "b"] { - let completed = Arc::clone(&completed); - registry.try_start(id, async move { - std::future::pending::<()>().await; - completed.fetch_add(1, Ordering::SeqCst); - }); - } - registry.cancel_all(); - settle(®istry, |r| r.is_empty()).await; - assert_eq!(completed.load(Ordering::SeqCst), 0, "aborted, not run"); - assert!(registry.try_start("a", async {}), "ids are free again"); - } - - #[tokio::test] - async fn cancelled_unpolled_task_cannot_remove_its_replacement() { - let queue = Arc::new(Mutex::new( - Vec::>::new(), - )); - let pending = Arc::clone(&queue); - let registry = Arc::new(ActiveTaskRegistry::new(Arc::new(move |future| { - pending.lock().push(future); - }))); - assert!(registry.try_start("message", std::future::pending())); - registry.cancel_all(); - assert!(registry.try_start("message", std::future::pending())); - let old = queue.lock().remove(0); - old.await; - assert!(registry.is_tracked("message")); - assert!(!registry.try_start("message", async {})); - registry.cancel_all(); - let replacement = queue.lock().remove(0); - replacement.await; - assert!(registry.is_empty()); - } + use std::sync::atomic::{AtomicUsize, Ordering}; + + use tokio::sync::watch; + + use super::*; + + async fn settle(registry: &ActiveTaskRegistry, until: impl Fn(&ActiveTaskRegistry) -> bool) { + for _ in 0..1_000 { + if until(registry) { + return; + } + tokio::task::yield_now().await; + } + panic!("registry never settled"); + } + + #[tokio::test] + async fn duplicate_starts_are_rejected_until_completion() { + let registry = Arc::new(ActiveTaskRegistry::new(crate::test_spawner())); + let (release_tx, release_rx) = watch::channel(false); + let runs = Arc::new(AtomicUsize::new(0)); + + let work = { + let runs = Arc::clone(&runs); + let mut release = release_rx.clone(); + async move { + runs.fetch_add(1, Ordering::SeqCst); + while !*release.borrow() { + if release.changed().await.is_err() { + return; + } + } + } + }; + assert!(registry.try_start("m1", work)); + assert!(registry.is_tracked("m1")); + assert!(!registry.try_start("m1", async {}), "in-flight id rejects a second task"); + + release_tx.send(true).unwrap(); + settle(®istry, |r| !r.is_tracked("m1")).await; + assert_eq!(runs.load(Ordering::SeqCst), 1, "the duplicate never ran"); + assert!(registry.try_start("m1", async {}), "restart after defer"); + } + + #[tokio::test] + async fn distinct_ids_run_concurrently() { + let registry = Arc::new(ActiveTaskRegistry::new(crate::test_spawner())); + let (_release_tx, release_rx) = watch::channel(false); + for id in ["a", "b", "c"] { + let mut release = release_rx.clone(); + assert!(registry.try_start(id, async move { + let _ = release.changed().await; + })); + } + assert_eq!(registry.len(), 3); + } + + #[tokio::test] + async fn cancel_all_aborts_and_clears() { + let registry = Arc::new(ActiveTaskRegistry::new(crate::test_spawner())); + let completed = Arc::new(AtomicUsize::new(0)); + for id in ["a", "b"] { + let completed = Arc::clone(&completed); + registry.try_start(id, async move { + std::future::pending::<()>().await; + completed.fetch_add(1, Ordering::SeqCst); + }); + } + registry.cancel_all(); + settle(®istry, |r| r.is_empty()).await; + assert_eq!(completed.load(Ordering::SeqCst), 0, "aborted, not run"); + assert!(registry.try_start("a", async {}), "ids are free again"); + } + + #[tokio::test] + async fn cancelled_unpolled_task_cannot_remove_its_replacement() { + let queue = Arc::new(Mutex::new(Vec::>::new())); + let pending = Arc::clone(&queue); + let registry = Arc::new(ActiveTaskRegistry::new(Arc::new(move |future| { + pending.lock().push(future); + }))); + assert!(registry.try_start("message", std::future::pending())); + registry.cancel_all(); + assert!(registry.try_start("message", std::future::pending())); + let old = queue.lock().remove(0); + old.await; + assert!(registry.is_tracked("message")); + assert!(!registry.try_start("message", async {})); + registry.cancel_all(); + let replacement = queue.lock().remove(0); + replacement.await; + assert!(registry.is_empty()); + } } diff --git a/rust/crates/truapi-coinage/src/timer.rs b/rust/crates/truapi-coinage/src/timer.rs index 3397625059..70cbbae098 100644 --- a/rust/crates/truapi-coinage/src/timer.rs +++ b/rust/crates/truapi-coinage/src/timer.rs @@ -4,5 +4,5 @@ //! Runtime-independent delays, including browser hosts. pub(crate) async fn sleep(duration: std::time::Duration) { - futures_timer::Delay::new(duration).await; + futures_timer::Delay::new(duration).await; } diff --git a/rust/crates/truapi-coinage/src/transfer_sender.rs b/rust/crates/truapi-coinage/src/transfer_sender.rs index 642982db94..00f84ae664 100644 --- a/rust/crates/truapi-coinage/src/transfer_sender.rs +++ b/rust/crates/truapi-coinage/src/transfer_sender.rs @@ -2,9 +2,8 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use std::collections::HashMap; -use std::future::Future; -use {parking_lot::Mutex, std::sync::Arc}; +use parking_lot::Mutex; +use std::{collections::HashMap, future::Future, sync::Arc}; use async_trait::async_trait; use futures::future::join_all; @@ -12,83 +11,85 @@ use rand::RngCore; use tokio::sync::{Mutex as AsyncMutex, Notify}; use tracing::{error, warn}; -use crate::allocator::CoinAllocator; -use crate::clock::Clock; -use crate::denomination::DenominationBreakdownContext; -use crate::keys::CoinKeypairFactory; -use crate::memo::{MemoEntry, TransferMemo}; -use crate::model::{Coin, CoinState, EffectivePrivacy, Voucher, VoucherRemoteState}; -use crate::repo::{CoinRepository, TransferContext, TransferStateCommitter, VoucherRepository}; -use crate::ring_proof::{PersonOriginKind, ResolvedUnloadToken, RingProofParams}; -use crate::selection::{ - CoinSelectionError, CoinSelectionResult, CoinSelector, PrivacyLevel, RecyclerKey, - TransferStrategy, -}; -use crate::wal::{ - CheckpointBlock, TransferWalEntry, WalCoinRef, WalOperation, WalPayload, WalStore, - operation_entry_id, +use crate::{ + allocator::CoinAllocator, + clock::Clock, + denomination::DenominationBreakdownContext, + keys::CoinKeypairFactory, + memo::{MemoEntry, TransferMemo}, + model::{Coin, CoinState, EffectivePrivacy, Voucher, VoucherRemoteState}, + repo::{CoinRepository, TransferContext, TransferStateCommitter, VoucherRepository}, + ring_proof::{PersonOriginKind, ResolvedUnloadToken, RingProofParams}, + selection::{ + CoinSelectionError, CoinSelectionResult, CoinSelector, PrivacyLevel, RecyclerKey, + TransferStrategy, + }, + wal::{ + CheckpointBlock, TransferWalEntry, WalCoinRef, WalOperation, WalPayload, WalStore, + operation_entry_id, + }, }; const PREVIEW_LIFETIME_MS: i64 = 2 * 60 * 1_000; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TransferPreviewChoice { - Full, - NonDegraded, + Full, + NonDegraded, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TransferPreviewStrategy { - ExactMatch, - Split, - UnloadIntoCoins, + ExactMatch, + Split, + UnloadIntoCoins, } /// Secret-free preview fields suitable for an FFI record. `preview_id` is /// opaque and meaningful only to the session-scoped service that created it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct OpaqueTransferPreview { - pub preview_id: String, - pub session_generation: u64, - pub full_amount: u128, - /// Maximum source value that may leave the purse, in raw planks. - /// Unload bounds conservatively include all selected voucher value. - pub max_debit_amount: u128, - pub non_degraded_amount: u128, - pub is_degraded: bool, - pub strategy: TransferPreviewStrategy, - pub expires_at_ms: i64, + pub preview_id: String, + pub session_generation: u64, + pub full_amount: u128, + /// Maximum source value that may leave the purse, in raw planks. + /// Unload bounds conservatively include all selected voucher value. + pub max_debit_amount: u128, + pub non_degraded_amount: u128, + pub is_degraded: bool, + pub strategy: TransferPreviewStrategy, + pub expires_at_ms: i64, } /// Public-only voucher snapshot for selection diagnostics: exposes selection /// state without exposing any voucher secret key material. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VoucherSelectionDiagnostic { - pub derivation_index: u32, - pub exponent: i16, - pub local_state: crate::model::VoucherLocalState, - pub remote_state: crate::model::VoucherRemoteState, - pub stored_privacy: crate::model::VoucherPrivacyLevel, - pub effective_privacy: EffectivePrivacy, - pub ready_at_ms: i64, + pub derivation_index: u32, + pub exponent: i16, + pub local_state: crate::model::VoucherLocalState, + pub remote_state: crate::model::VoucherRemoteState, + pub stored_privacy: crate::model::VoucherPrivacyLevel, + pub effective_privacy: EffectivePrivacy, + pub ready_at_ms: i64, } pub fn voucher_selection_diagnostics( - vouchers: &[Voucher], - now_ms: i64, + vouchers: &[Voucher], + now_ms: i64, ) -> Vec { - vouchers - .iter() - .map(|voucher| VoucherSelectionDiagnostic { - derivation_index: voucher.derivation_index, - exponent: voucher.exponent, - local_state: voucher.local_state, - remote_state: voucher.remote_state, - stored_privacy: voucher.privacy, - effective_privacy: voucher.effective_privacy(now_ms), - ready_at_ms: voucher.ready_at_ms, - }) - .collect() + vouchers + .iter() + .map(|voucher| VoucherSelectionDiagnostic { + derivation_index: voucher.derivation_index, + exponent: voucher.exponent, + local_state: voucher.local_state, + remote_state: voucher.remote_state, + stored_privacy: voucher.privacy, + effective_privacy: voucher.effective_privacy(now_ms), + ready_at_ms: voucher.ready_at_ms, + }) + .collect() } /// Redacted aggregate emitted when authoritative preview selection fails. @@ -96,146 +97,136 @@ pub fn voucher_selection_diagnostics( /// reveal neither exact balances nor any coin/voucher key. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SelectorSnapshotDiagnostic { - pub selectable_coins: usize, - pub expiring_coins: usize, - pub locked_coins: usize, - pub unloadable_vouchers: usize, - pub locked_vouchers: usize, - pub full_vouchers: usize, - pub degraded_vouchers: usize, - pub selectable_coin_value_digits: usize, - pub unloadable_voucher_value_digits: usize, + pub selectable_coins: usize, + pub expiring_coins: usize, + pub locked_coins: usize, + pub unloadable_vouchers: usize, + pub locked_vouchers: usize, + pub full_vouchers: usize, + pub degraded_vouchers: usize, + pub selectable_coin_value_digits: usize, + pub unloadable_voucher_value_digits: usize, } pub fn selector_snapshot_diagnostic( - coins: &[Coin], - vouchers: &[Voucher], - context: &DenominationBreakdownContext, - now_ms: i64, + coins: &[Coin], + vouchers: &[Voucher], + context: &DenominationBreakdownContext, + now_ms: i64, ) -> SelectorSnapshotDiagnostic { - let selectable_coin_value = coins - .iter() - .filter(|coin| coin.is_selectable()) - .fold(0u128, |sum, coin| { - sum.saturating_add(context.value_in_planks(coin.exponent)) - }); - let unloadable_voucher_value = vouchers - .iter() - .filter(|voucher| voucher.is_unloadable()) - .fold(0u128, |sum, voucher| { - sum.saturating_add(context.value_in_planks(voucher.exponent)) - }); - SelectorSnapshotDiagnostic { - selectable_coins: coins.iter().filter(|coin| coin.is_selectable()).count(), - expiring_coins: coins - .iter() - .filter(|coin| { - coin.state == crate::model::CoinState::Available && coin.is_expiring_soon() - }) - .count(), - locked_coins: coins.iter().filter(|coin| !coin.is_selectable()).count(), - unloadable_vouchers: vouchers - .iter() - .filter(|voucher| voucher.is_unloadable()) - .count(), - locked_vouchers: vouchers - .iter() - .filter(|voucher| !voucher.is_unloadable()) - .count(), - full_vouchers: vouchers - .iter() - .filter(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Full) - .count(), - degraded_vouchers: vouchers - .iter() - .filter(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Degraded) - .count(), - selectable_coin_value_digits: decimal_digits(selectable_coin_value), - unloadable_voucher_value_digits: decimal_digits(unloadable_voucher_value), - } + let selectable_coin_value = coins + .iter() + .filter(|coin| coin.is_selectable()) + .fold(0u128, |sum, coin| sum.saturating_add(context.value_in_planks(coin.exponent))); + let unloadable_voucher_value = vouchers + .iter() + .filter(|voucher| voucher.is_unloadable()) + .fold(0u128, |sum, voucher| sum.saturating_add(context.value_in_planks(voucher.exponent))); + SelectorSnapshotDiagnostic { + selectable_coins: coins.iter().filter(|coin| coin.is_selectable()).count(), + expiring_coins: coins + .iter() + .filter(|coin| { + coin.state == crate::model::CoinState::Available && coin.is_expiring_soon() + }) + .count(), + locked_coins: coins.iter().filter(|coin| !coin.is_selectable()).count(), + unloadable_vouchers: vouchers.iter().filter(|voucher| voucher.is_unloadable()).count(), + locked_vouchers: vouchers.iter().filter(|voucher| !voucher.is_unloadable()).count(), + full_vouchers: vouchers + .iter() + .filter(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Full) + .count(), + degraded_vouchers: vouchers + .iter() + .filter(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Degraded) + .count(), + selectable_coin_value_digits: decimal_digits(selectable_coin_value), + unloadable_voucher_value_digits: decimal_digits(unloadable_voucher_value), + } } fn decimal_digits(value: u128) -> usize { - value.to_string().len() + value.to_string().len() } fn selection_error_kind(error: &CoinSelectionError) -> &'static str { - match error { - CoinSelectionError::ZeroAmount => "zero_amount", - CoinSelectionError::EmptyWallet => "empty_wallet", - CoinSelectionError::AmountNotRepresentable { .. } => "amount_not_representable", - CoinSelectionError::NoReadyVouchers => "vouchers_not_ready", - CoinSelectionError::TooManyVouchersInGroup { .. } => "too_many_vouchers", - CoinSelectionError::InsufficientFunds => "insufficient_funds", - } + match error { + CoinSelectionError::ZeroAmount => "zero_amount", + CoinSelectionError::EmptyWallet => "empty_wallet", + CoinSelectionError::AmountNotRepresentable { .. } => "amount_not_representable", + CoinSelectionError::NoReadyVouchers => "vouchers_not_ready", + CoinSelectionError::TooManyVouchersInGroup { .. } => "too_many_vouchers", + CoinSelectionError::InsufficientFunds => "insufficient_funds", + } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum RegularTransferError { - Selection(CoinSelectionError), - PreviewNotFound, - PreviewExpired, - BalanceChanged, - NonDegradedAmountUnavailable, - OperationNotFound, - InvalidOperationId, - Planning(String), - Reservation(String), - Journal(String), - HandoffRejected, + Selection(CoinSelectionError), + PreviewNotFound, + PreviewExpired, + BalanceChanged, + NonDegradedAmountUnavailable, + OperationNotFound, + InvalidOperationId, + Planning(String), + Reservation(String), + Journal(String), + HandoffRejected, } impl std::fmt::Display for RegularTransferError { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Selection(error) => error.fmt(formatter), - Self::PreviewNotFound => formatter.write_str("transfer preview was not found"), - Self::PreviewExpired => formatter.write_str("transfer preview expired"), - Self::BalanceChanged => { - formatter.write_str("CASH balance changed; preview the payment again") - } - Self::NonDegradedAmountUnavailable => { - formatter.write_str("no non-degraded CASH amount is available") - } - Self::OperationNotFound => formatter.write_str("transfer operation was not found"), - Self::InvalidOperationId => { - formatter.write_str("transfer operation identifier is empty") - } - Self::Planning(error) => write!(formatter, "transfer planning failed: {error}"), - Self::Reservation(error) => write!(formatter, "transfer reservation failed: {error}"), - Self::Journal(error) => write!(formatter, "transfer journal failed: {error}"), - Self::HandoffRejected => { - formatter.write_str("CASH message was rejected before durable acceptance") - } - } - } + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Selection(error) => error.fmt(formatter), + Self::PreviewNotFound => formatter.write_str("transfer preview was not found"), + Self::PreviewExpired => formatter.write_str("transfer preview expired"), + Self::BalanceChanged => { + formatter.write_str("CASH balance changed; preview the payment again") + }, + Self::NonDegradedAmountUnavailable => { + formatter.write_str("no non-degraded CASH amount is available") + }, + Self::OperationNotFound => formatter.write_str("transfer operation was not found"), + Self::InvalidOperationId => { + formatter.write_str("transfer operation identifier is empty") + }, + Self::Planning(error) => write!(formatter, "transfer planning failed: {error}"), + Self::Reservation(error) => write!(formatter, "transfer reservation failed: {error}"), + Self::Journal(error) => write!(formatter, "transfer journal failed: {error}"), + Self::HandoffRejected => { + formatter.write_str("CASH message was rejected before durable acceptance") + }, + } + } } impl std::error::Error for RegularTransferError {} impl From for RegularTransferError { - fn from(value: CoinSelectionError) -> Self { - Self::Selection(value) - } + fn from(value: CoinSelectionError) -> Self { + Self::Selection(value) + } } /// One split submission after recipient/change indices have been allocated. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SplitTransferSubmission { - pub overflow_coin: Coin, - pub recipient_coins: Vec, - pub change_coins: Vec, - pub wal_entry_id: String, + pub overflow_coin: Coin, + pub recipient_coins: Vec, + pub change_coins: Vec, + pub wal_entry_id: String, } /// One unload group before the host resolves the shared finalized state. #[derive(Debug, Clone, PartialEq, Eq)] pub struct UnloadGroupDraft { - pub recycler: RecyclerKey, - pub vouchers: Vec, - pub recipient_coins: Vec, - pub change_coins: Vec, - pub wal_entry_id: String, + pub recycler: RecyclerKey, + pub vouchers: Vec, + pub recipient_coins: Vec, + pub change_coins: Vec, + pub wal_entry_id: String, } /// Chain-origin inputs resolved at one finalized snapshot. Proof bytes are @@ -243,18 +234,18 @@ pub struct UnloadGroupDraft { /// implication exists inside the submitter. #[derive(Debug, Clone, PartialEq, Eq)] pub struct UnloadOriginPreparation { - pub recycler_ring: RingProofParams, - pub person_origin: PersonOriginKind, - pub people_ring: RingProofParams, - pub token: ResolvedUnloadToken, + pub recycler_ring: RingProofParams, + pub person_origin: PersonOriginKind, + pub people_ring: RingProofParams, + pub token: ResolvedUnloadToken, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct PreparedUnloadGroup { - pub draft: UnloadGroupDraft, - pub readiness_block_hash: [u8; 32], - pub recycler_revision: u32, - pub origin: UnloadOriginPreparation, + pub draft: UnloadGroupDraft, + pub readiness_block_hash: [u8; 32], + pub recycler_revision: u32, + pub origin: UnloadOriginPreparation, } /// Production implementations must update the named WAL checkpoint after @@ -264,1729 +255,1557 @@ pub struct PreparedUnloadGroup { /// child WAL even if the recipient consumes an output before the next query. #[async_trait] pub trait RegularTransferSubmitter: Send + Sync { - async fn prepare_unload_groups( - &self, - groups: &[UnloadGroupDraft], - ) -> Result, String>; + async fn prepare_unload_groups( + &self, + groups: &[UnloadGroupDraft], + ) -> Result, String>; - async fn submit_split(&self, submission: &SplitTransferSubmission) -> Result<(), String>; + async fn submit_split(&self, submission: &SplitTransferSubmission) -> Result<(), String>; - async fn submit_unload_group(&self, submission: &PreparedUnloadGroup) -> Result<(), String>; + async fn submit_unload_group(&self, submission: &PreparedUnloadGroup) -> Result<(), String>; } pub struct RegularCoinTransferParts { - /// Executor owned by the active signing authority. - pub spawner: crate::Spawner, - pub coins: Arc, - pub vouchers: Arc, - pub wal: Arc, - pub allocator: Arc, - pub submitter: Arc, - pub denominations: DenominationBreakdownContext, - pub max_consolidation: usize, - pub clock: Arc, - pub session_generation: u64, - pub committer: Option>, + /// Executor owned by the active signing authority. + pub spawner: crate::Spawner, + pub coins: Arc, + pub vouchers: Arc, + pub wal: Arc, + pub allocator: Arc, + pub submitter: Arc, + pub denominations: DenominationBreakdownContext, + pub max_consolidation: usize, + pub clock: Arc, + pub session_generation: u64, + pub committer: Option>, } #[derive(Clone)] struct CachedPreview { - descriptor: OpaqueTransferPreview, - full: CoinSelectionResult, - non_degraded: Option, - coins: Vec, - vouchers: Vec, + descriptor: OpaqueTransferPreview, + full: CoinSelectionResult, + non_degraded: Option, + coins: Vec, + vouchers: Vec, } #[derive(Default)] struct Confirmation { - result: Mutex>>, - notify: Notify, + result: Mutex>>, + notify: Notify, } impl Confirmation { - async fn wait(&self) -> Result<(), RegularTransferError> { - loop { - let notified = self.notify.notified(); - if let Some(result) = self.result.lock().clone() { - return result; - } - notified.await; - } - } - - fn finish(&self, result: Result<(), RegularTransferError>) { - *self.result.lock() = Some(result); - self.notify.notify_waiters(); - } + async fn wait(&self) -> Result<(), RegularTransferError> { + loop { + let notified = self.notify.notified(); + if let Some(result) = self.result.lock().clone() { + return result; + } + notified.await; + } + } + + fn finish(&self, result: Result<(), RegularTransferError>) { + *self.result.lock() = Some(result); + self.notify.notify_waiters(); + } } pub struct RegularCoinTransferService { - spawner: crate::Spawner, - key_factory: Arc, - coins: Arc, - vouchers: Arc, - wal: Arc, - allocator: Arc, - submitter: Arc, - denominations: DenominationBreakdownContext, - max_consolidation: usize, - clock: Arc, - session_generation: u64, - committer: Option>, - previews: AsyncMutex>, - confirmations: AsyncMutex>>, - execution_lock: AsyncMutex<()>, + spawner: crate::Spawner, + key_factory: Arc, + coins: Arc, + vouchers: Arc, + wal: Arc, + allocator: Arc, + submitter: Arc, + denominations: DenominationBreakdownContext, + max_consolidation: usize, + clock: Arc, + session_generation: u64, + committer: Option>, + previews: AsyncMutex>, + confirmations: AsyncMutex>>, + execution_lock: AsyncMutex<()>, } impl RegularCoinTransferService { - pub fn new(root_entropy: &[u8], parts: RegularCoinTransferParts) -> Self { - Self { - key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), - coins: parts.coins, - vouchers: parts.vouchers, - wal: parts.wal, - allocator: parts.allocator, - submitter: parts.submitter, - denominations: parts.denominations, - max_consolidation: parts.max_consolidation.max(1), - clock: parts.clock, - session_generation: parts.session_generation, - committer: parts.committer, - previews: AsyncMutex::new(HashMap::new()), - confirmations: AsyncMutex::new(HashMap::new()), - execution_lock: AsyncMutex::new(()), - spawner: parts.spawner, - } - } - - /// The native send UI speaks whole CASH cents; selection and memo values - /// speak raw chain planks. Keep their only conversion at this service - /// boundary so callers cannot accidentally preview cents as planks. - pub fn cash_cents_to_planks(&self, cents: u128) -> Option { - self.denominations.cash_cents_to_planks(cents) - } - - pub fn cash_cents_from_planks(&self, planks: u128) -> Option { - self.denominations.cash_cents_from_planks(planks) - } - - pub fn planks_per_cash_cent(&self) -> u128 { - self.denominations.asset_unit - } - - pub async fn preview( - &self, - amount: u128, - ) -> Result { - let coins = self - .coins - .list() - .await - .map_err(RegularTransferError::Planning)?; - let vouchers = self - .vouchers - .list() - .await - .map_err(RegularTransferError::Planning)?; - let now_ms = self.clock.now_ms(); - let full = match CoinSelector::new(self.denominations.clone(), self.max_consolidation) - .select(amount, &coins, &vouchers, now_ms) - { - Ok(selection) => selection, - Err(selection_error) => { - let snapshot = - selector_snapshot_diagnostic(&coins, &vouchers, &self.denominations, now_ms); - warn!( - error = selection_error_kind(&selection_error), - strategy = "none", - requested_value_digits = decimal_digits(amount), - selectable_coins = snapshot.selectable_coins, - expiring_coins = snapshot.expiring_coins, - locked_coins = snapshot.locked_coins, - unloadable_vouchers = snapshot.unloadable_vouchers, - locked_vouchers = snapshot.locked_vouchers, - full_vouchers = snapshot.full_vouchers, - degraded_vouchers = snapshot.degraded_vouchers, - selectable_coin_value_digits = snapshot.selectable_coin_value_digits, - unloadable_voucher_value_digits = snapshot.unloadable_voucher_value_digits, - "coinage selector snapshot" - ); - return Err(selection_error.into()); - } - }; - let (non_degraded, non_degraded_amount) = - non_degraded_selection(&full, &self.denominations, now_ms); - let strategy = match full.strategy { - TransferStrategy::ExactMatch { .. } => TransferPreviewStrategy::ExactMatch, - TransferStrategy::Split { .. } => TransferPreviewStrategy::Split, - TransferStrategy::UnloadIntoCoins { .. } => TransferPreviewStrategy::UnloadIntoCoins, - }; - let preview_id = random_id("cash-preview"); - let descriptor = OpaqueTransferPreview { - preview_id: preview_id.clone(), - session_generation: self.session_generation, - full_amount: amount, - max_debit_amount: selection_max_debit(&full, &self.denominations), - non_degraded_amount, - is_degraded: full.privacy_level == PrivacyLevel::Degraded, - strategy, - expires_at_ms: now_ms.saturating_add(PREVIEW_LIFETIME_MS), - }; - let mut previews = self.previews.lock().await; - previews.retain(|_, preview| preview.descriptor.expires_at_ms >= now_ms); - previews.insert( - preview_id, - CachedPreview { - descriptor: descriptor.clone(), - full, - non_degraded, - coins, - vouchers, - }, - ); - Ok(descriptor) - } - - pub async fn preview_descriptor( - &self, - preview_id: &str, - ) -> Result { - let descriptor = match self - .previews - .lock() - .await - .get(preview_id) - .map(|preview| preview.descriptor.clone()) - { - Some(descriptor) => descriptor, - None => { - return Err(RegularTransferError::PreviewNotFound); - } - }; - if self.clock.now_ms() > descriptor.expires_at_ms { - return Err(RegularTransferError::PreviewExpired); - } - Ok(descriptor) - } - - /// Confirms exactly the cached selector result. Calls racing for the same - /// preview join one result; only the first closure can receive the memo. - /// `handoff` may return `Err(())` only if it certifies that no recipient or - /// transport accepted the secret. Ambiguous delivery must retain the WAL - /// by returning `Ok(())` and reporting transport uncertainty separately. - pub async fn confirm( - self: &Arc, - preview_id: &str, - choice: TransferPreviewChoice, - handoff: F, - ) -> Result<(), RegularTransferError> - where - F: FnOnce(TransferMemo) -> Fut + Send + 'static, - Fut: Future> + Send + 'static, - { - let (confirmation, leader) = { - let mut confirmations = self.confirmations.lock().await; - match confirmations.get(preview_id) { - Some(existing) => (Arc::clone(existing), false), - None => { - let confirmation = Arc::new(Confirmation::default()); - confirmations.insert(preview_id.to_owned(), Arc::clone(&confirmation)); - (confirmation, true) - } - } - }; - if leader { - let service = Arc::clone(self); - let preview_id = preview_id.to_owned(); - let running = Arc::clone(&confirmation); - crate::tasks::spawn_abortable(&self.spawner, async move { - let result = service - .confirm_operation(&preview_id, &preview_id, choice, handoff) - .await; - running.finish(result); - }); - } - confirmation.wait().await - } - - /// Confirms a host-owned durable operation. The host must serialize wallet - /// recovery with this call and run it on its cancellation-safe executor. - /// The callback may await durable transport persistence before returning. - /// `Err` from the callback certifies no acceptance; uncertain acceptance - /// must return `Ok` and retain the transport's idempotent operation key. - /// - /// All chain work finishes (or leaves recoverable WAL) before returning. - /// Once transport accepts, chain/persistence failures never become `Err`. - pub async fn confirm_operation( - self: &Arc, - operation_id: &str, - preview_id: &str, - choice: TransferPreviewChoice, - handoff: F, - ) -> Result<(), RegularTransferError> - where - F: FnOnce(TransferMemo) -> Fut + Send, - Fut: Future> + Send, - { - if operation_id.is_empty() { - return Err(RegularTransferError::InvalidOperationId); - } - let _execution = self.execution_lock.lock().await; - let existing = self.operation_wal(operation_id).await?; - if !existing.is_empty() { - return self.resume_entries(existing, handoff).await; - } - let cached = self - .previews - .lock() - .await - .get(preview_id) - .cloned() - .ok_or(RegularTransferError::PreviewNotFound)?; - if self.clock.now_ms() > cached.descriptor.expires_at_ms { - return Err(RegularTransferError::PreviewExpired); - } - let current_coins = self - .coins - .list() - .await - .map_err(RegularTransferError::Planning)?; - let current_vouchers = self - .vouchers - .list() - .await - .map_err(RegularTransferError::Planning)?; - if current_coins != cached.coins || current_vouchers != cached.vouchers { - return Err(RegularTransferError::BalanceChanged); - } - let expected_amount = match choice { - TransferPreviewChoice::Full => cached.descriptor.full_amount, - TransferPreviewChoice::NonDegraded => cached.descriptor.non_degraded_amount, - }; - let result = match choice { - TransferPreviewChoice::Full => cached.full, - TransferPreviewChoice::NonDegraded => cached - .non_degraded - .ok_or(RegularTransferError::NonDegradedAmountUnavailable)?, - }; - let amount = selection_value(&result, &self.denominations); - if amount == 0 - || amount != expected_amount - || selection_max_debit(&result, &self.denominations) - > cached.descriptor.max_debit_amount - { - return Err(RegularTransferError::BalanceChanged); - } - let mut plan = self.create_plan(operation_id, result, amount).await?; - let context = self.transfer_context(); - context - .reserve(&plan.reserved_coins, &plan.reserved_vouchers) - .await - .map_err(RegularTransferError::Reservation)?; - if let Err(error) = self.wal.save_all(&plan.journals).await { - // A failed acknowledgement can still have committed the atomic - // batch. Never partially delete it: restart would lose the plan. - // Recovery restores orphan reservations if no batch committed, - // otherwise the complete Prepared operation remains resumable. - return Err(RegularTransferError::Journal(error)); - } - let mut parent = plan - .journals - .iter() - .find(|entry| entry.operation.is_transfer_receipt()) - .cloned() - .expect("operation plan includes its durable receipt"); - let memo = plan.memo.take().expect("plan memo consumed once"); - if handoff(memo).await.is_err() { - self.reject_operation(&mut parent, &plan.journals).await?; - return Err(RegularTransferError::HandoffRejected); - } - if let Err(error) = self - .finish_accepted(&mut parent, &plan.journals, plan.chain) - .await - { - error!(%error, "accepted CASH operation remains journaled for recovery"); - } - Ok(()) - } - - pub async fn operation_wal( - &self, - operation_id: &str, - ) -> Result, RegularTransferError> { - self.wal - .load_operation(operation_id) - .await - .map_err(RegularTransferError::Journal) - } - - /// Resumes only existing allocations, never selects or debits new inputs. - /// Invoke after recovery and renewed user approval, never from passive - /// reconciliation. For Prepared receipts, `handoff` must resolve/replay the - /// SAME host transport operation, since acceptance may precede a crash. - /// Accepted/Completed receipts never invoke it. Known checkpoints are not - /// broadcast again; recovery must first prove their mortality or fork. - pub async fn resume_operation( - self: &Arc, - operation_id: &str, - handoff: F, - ) -> Result<(), RegularTransferError> - where - F: FnOnce(TransferMemo) -> Fut + Send, - Fut: Future> + Send, - { - let _execution = self.execution_lock.lock().await; - self.resume_entries(self.operation_wal(operation_id).await?, handoff) - .await - } - - async fn resume_entries( - &self, - entries: Vec, - handoff: F, - ) -> Result<(), RegularTransferError> - where - F: FnOnce(TransferMemo) -> Fut + Send, - Fut: Future> + Send, - { - let mut parent = entries - .iter() - .find(|entry| entry.operation.is_transfer_receipt()) - .cloned() - .ok_or(RegularTransferError::OperationNotFound)?; - match parent.operation { - WalOperation::TransferCompleted => return Ok(()), - WalOperation::TransferRejected => { - self.reject_operation(&mut parent, &entries).await?; - return Err(RegularTransferError::HandoffRejected); - } - WalOperation::TransferPrepared => { - let coins = parent - .payload - .output_coins - .iter() - .map(referenced_coin) - .collect::>(); - let amount = coins.iter().fold(0u128, |sum, coin| { - sum.saturating_add(self.denominations.value_in_planks(coin.exponent)) - }); - let memo = self.build_memo(&coins, amount)?; - if handoff(memo).await.is_err() { - self.reject_operation(&mut parent, &entries).await?; - return Err(RegularTransferError::HandoffRejected); - } - } - WalOperation::TransferAccepted => {} - _ => return Err(RegularTransferError::OperationNotFound), - } - // From here the memo may already be owned by the recipient. - let completion = async { - parent.operation = WalOperation::TransferAccepted; - self.wal.save(&parent).await?; - let chain = self.restore_chain_plan(&entries).await?; - self.finish_accepted(&mut parent, &entries, chain).await - } - .await; - if let Err(error) = completion { - error!(%error, "accepted CASH operation remains journaled for recovery"); - } - Ok(()) - } - - fn transfer_context(&self) -> Arc { - let mut context = TransferContext::new(Arc::clone(&self.coins), Arc::clone(&self.vouchers)); - if let Some(committer) = &self.committer { - context = context.with_committer(Arc::clone(committer)); - } - Arc::new(context) - } - - async fn reject_operation( - &self, - parent: &mut TransferWalEntry, - entries: &[TransferWalEntry], - ) -> Result<(), RegularTransferError> { - parent.operation = WalOperation::TransferRejected; - self.wal - .save(parent) - .await - .map_err(RegularTransferError::Journal)?; - for entry in entries - .iter() - .filter(|entry| !entry.operation.is_transfer_receipt()) - { - for input in &entry.payload.input_coins { - self.coins - .set_state(input.derivation_index, CoinState::Available) - .await - .map_err(RegularTransferError::Reservation)?; - } - for input in &entry.payload.input_vouchers { - self.vouchers - .set_local_state( - input.derivation_index, - crate::model::VoucherLocalState::Available, - ) - .await - .map_err(RegularTransferError::Reservation)?; - } - self.wal - .delete(&entry.entry_id) - .await - .map_err(RegularTransferError::Journal)?; - } - Ok(()) - } - - async fn finish_accepted( - &self, - parent: &mut TransferWalEntry, - entries: &[TransferWalEntry], - chain: ChainPlan, - ) -> Result<(), String> { - parent.operation = WalOperation::TransferAccepted; - self.wal.save(parent).await?; - let context = self.transfer_context(); - for entry in entries - .iter() - .filter(|entry| entry.operation == WalOperation::SecretHandoff) - { - let indices = entry - .payload - .input_coins - .iter() - .map(|coin| coin.derivation_index) - .collect::>(); - context.process_outputs(&indices, &[], &[], &[]).await?; - self.wal.delete(&entry.entry_id).await?; - } - self.run_chain_plan(chain, context).await?; - let children_remain = self.wal.load_all().await?.iter().any(|entry| { - entry.entry_id != parent.entry_id - && entry.operation_parent_id().as_deref() == Some(parent.entry_id.as_str()) - }); - if !children_remain { - parent.operation = WalOperation::TransferCompleted; - self.wal.save(parent).await?; - } - Ok(()) - } - - async fn restore_chain_plan(&self, entries: &[TransferWalEntry]) -> Result { - let mut drafts = Vec::new(); - let vouchers = if entries.iter().any(|entry| { - entry.operation == WalOperation::IntoCoins - && entry.checkpoint == CheckpointBlock::Pending - }) { - self.vouchers.list().await? - } else { - Vec::new() - }; - for entry in entries.iter().filter(|entry| { - entry.checkpoint == CheckpointBlock::Pending - && matches!( - entry.operation, - WalOperation::Split | WalOperation::IntoCoins - ) - }) { - let recipient_coins = entry - .payload - .destination_coins - .iter() - .map(referenced_coin) - .collect::>(); - let change_coins = entry - .payload - .output_coins - .iter() - .filter(|coin| !entry.payload.destination_coins.contains(coin)) - .map(referenced_coin) - .collect::>(); - match entry.operation { - WalOperation::Split => { - if entry.payload.input_coins.len() != 1 { - return Err("split journal does not have exactly one input".into()); - } - return Ok(ChainPlan::Split(SplitTransferSubmission { - overflow_coin: referenced_coin(&entry.payload.input_coins[0]), - recipient_coins, - change_coins, - wal_entry_id: entry.entry_id.clone(), - })); - } - WalOperation::IntoCoins => { - let members = entry - .payload - .input_vouchers - .iter() - .map(|reference| { - vouchers - .iter() - .find(|voucher| { - voucher.derivation_index == reference.derivation_index - && voucher.exponent == reference.exponent - }) - .cloned() - .ok_or_else(|| { - "unload journal input is not available locally".to_string() - }) - }) - .collect::, _>>()?; - let first = members.first().ok_or("unload journal has no vouchers")?; - let VoucherRemoteState::InRecycler { recycler_index } = first.remote_state - else { - return Err("unload journal awaits voucher location reconciliation".into()); - }; - let recycler = RecyclerKey { - exponent: first.exponent, - index: recycler_index, - }; - if members.iter().any(|voucher| { - voucher.exponent != recycler.exponent - || voucher.remote_state != first.remote_state - }) { - return Err("unload journal spans multiple recyclers".into()); - } - drafts.push(UnloadGroupDraft { - recycler, - vouchers: members, - recipient_coins, - change_coins, - wal_entry_id: entry.entry_id.clone(), - }); - } - _ => {} - } - } - if drafts.is_empty() { - return Ok(ChainPlan::None); - } - let prepared = self.submitter.prepare_unload_groups(&drafts).await?; - if prepared.len() != drafts.len() - || prepared - .iter() - .zip(&drafts) - .any(|(prepared, draft)| &prepared.draft != draft) - { - return Err("unload recovery changed the durable allocation".into()); - } - Ok(ChainPlan::Unload(prepared)) - } - - async fn create_plan( - &self, - operation_id: &str, - result: CoinSelectionResult, - amount: u128, - ) -> Result { - let mut journals = Vec::new(); - let mut reserved_coins = Vec::new(); - let mut reserved_vouchers = Vec::new(); - let (pass_through, recipient, chain) = match result.strategy { - TransferStrategy::ExactMatch { coins } => { - reserved_coins.extend(coins.iter().map(|coin| coin.derivation_index)); - (coins.clone(), coins, ChainPlan::None) - } - TransferStrategy::Split { - partial_coins, - split_coin, - target_denominations, - change_denominations, - } => { - let recipient = self.allocate_coins(&target_denominations).await?; - let change = self.allocate_coins(&change_denominations).await?; - reserved_coins.extend(partial_coins.iter().map(|coin| coin.derivation_index)); - reserved_coins.push(split_coin.derivation_index); - let wal_entry_id = operation_entry_id(operation_id, "split"); - let submission = SplitTransferSubmission { - overflow_coin: split_coin.clone(), - recipient_coins: recipient.clone(), - change_coins: change.clone(), - wal_entry_id: wal_entry_id.clone(), - }; - journals.push(chain_journal( - wal_entry_id, - WalOperation::Split, - &[split_coin], - &[], - &recipient, - &change, - self.clock.now_ms(), - )); - let mut memo_coins = partial_coins.clone(); - memo_coins.extend(recipient); - (partial_coins, memo_coins, ChainPlan::Split(submission)) - } - TransferStrategy::UnloadIntoCoins { coins, groups } => { - reserved_coins.extend(coins.iter().map(|coin| coin.derivation_index)); - let mut drafts = Vec::with_capacity(groups.len()); - let mut memo_coins = coins.clone(); - for (group_index, group) in groups.into_iter().enumerate() { - let recipient = self.allocate_coins(&group.recipient_denominations).await?; - let change = self.allocate_coins(&group.change_denominations).await?; - reserved_vouchers.extend( - group - .vouchers - .iter() - .map(|voucher| voucher.derivation_index), - ); - memo_coins.extend(recipient.clone()); - drafts.push(UnloadGroupDraft { - recycler: group.recycler, - vouchers: group.vouchers, - recipient_coins: recipient, - change_coins: change, - wal_entry_id: operation_entry_id( - operation_id, - &format!("unload-{group_index}"), - ), - }); - } - let prepared = self - .submitter - .prepare_unload_groups(&drafts) - .await - .map_err(RegularTransferError::Planning)?; - if prepared.len() != drafts.len() - || prepared - .iter() - .zip(&drafts) - .any(|(prepared, draft)| &prepared.draft != draft) - { - return Err(RegularTransferError::Planning( - "unload preparation did not preserve every recycler group".into(), - )); - } - for group in &prepared { - journals.push(chain_journal( - group.draft.wal_entry_id.clone(), - WalOperation::IntoCoins, - &[], - &group.draft.vouchers, - &group.draft.recipient_coins, - &group.draft.change_coins, - self.clock.now_ms(), - )); - } - (coins, memo_coins, ChainPlan::Unload(prepared)) - } - }; - - let memo = self.build_memo(&recipient, amount)?; - if !pass_through.is_empty() { - let id = operation_entry_id(operation_id, "handoff"); - journals.push(TransferWalEntry { - entry_id: id.clone(), - operation: WalOperation::SecretHandoff, - payload: WalPayload { - input_coins: coin_refs(&pass_through), - ..WalPayload::default() - }, - checkpoint: CheckpointBlock::Pending, - created_at_ms: self.clock.now_ms(), - }); - } - journals.push(TransferWalEntry { - entry_id: operation_entry_id(operation_id, "parent"), - operation: WalOperation::TransferPrepared, - payload: WalPayload { - output_coins: coin_refs(&recipient), - ..WalPayload::default() - }, - checkpoint: CheckpointBlock::Pending, - created_at_ms: self.clock.now_ms(), - }); - Ok(TransferPlan { - memo: Some(memo), - reserved_coins, - reserved_vouchers, - journals, - chain, - }) - } - - async fn allocate_coins( - &self, - denominations: &[crate::denomination::Denomination], - ) -> Result, RegularTransferError> { - let mut coins = Vec::with_capacity(denominations.len()); - for denomination in denominations { - coins.push( - self.allocator - .allocate(denomination.exponent) - .await - .map_err(RegularTransferError::Planning)?, - ); - } - Ok(coins) - } - - fn build_memo( - &self, - coins: &[Coin], - expected: u128, - ) -> Result { - let total = coins.iter().fold(0u128, |total, coin| { - total.saturating_add(self.denominations.value_in_planks(coin.exponent)) - }); - if total != expected { - return Err(RegularTransferError::Planning(format!( - "memo value {total} does not equal selected amount {expected}" - ))); - } - let entries = coins - .iter() - .map(|coin| { - self.key_factory - .secret_bytes(coin.derivation_index) - .map(MemoEntry) - .map_err(RegularTransferError::Planning) - }) - .collect::, _>>()?; - Ok(TransferMemo { - entries, - total_value: total, - }) - } - - async fn run_chain_plan( - &self, - chain: ChainPlan, - context: Arc, - ) -> Result<(), String> { - match chain { - ChainPlan::None => Ok(()), - ChainPlan::Split(submission) => match self.submitter.submit_split(&submission).await { - Ok(()) => { - context - .process_outputs( - &[submission.overflow_coin.derivation_index], - &[], - &submission.change_coins, - &submission.recipient_coins, - ) - .await?; - self.wal.delete(&submission.wal_entry_id).await - } - // Even a pre-broadcast failure must retain the fixed outputs: - // their secrets already belong to the recipient. - Err(error) => Err(error), - }, - ChainPlan::Unload(groups) => { - let outcomes = join_all(groups.into_iter().map(|group| { - let submitter = Arc::clone(&self.submitter); - async move { - let result = submitter.submit_unload_group(&group).await; - (group, result) - } - })) - .await; - let mut errors = Vec::new(); - for (group, outcome) in outcomes { - let voucher_ids = group - .draft - .vouchers - .iter() - .map(|voucher| voucher.derivation_index) - .collect::>(); - match outcome { - Ok(()) => { - if let Err(error) = context - .process_outputs( - &[], - &voucher_ids, - &group.draft.change_coins, - &group.draft.recipient_coins, - ) - .await - { - errors.push(error); - continue; - } - if let Err(error) = self.wal.delete(&group.draft.wal_entry_id).await { - errors.push(error); - } - } - Err(error) => errors.push(error), - } - } - if errors.is_empty() { - Ok(()) - } else { - Err(errors.join("; ")) - } - } - } - } + pub fn new(root_entropy: &[u8], parts: RegularCoinTransferParts) -> Self { + Self { + key_factory: Arc::new(CoinKeypairFactory::new(root_entropy)), + coins: parts.coins, + vouchers: parts.vouchers, + wal: parts.wal, + allocator: parts.allocator, + submitter: parts.submitter, + denominations: parts.denominations, + max_consolidation: parts.max_consolidation.max(1), + clock: parts.clock, + session_generation: parts.session_generation, + committer: parts.committer, + previews: AsyncMutex::new(HashMap::new()), + confirmations: AsyncMutex::new(HashMap::new()), + execution_lock: AsyncMutex::new(()), + spawner: parts.spawner, + } + } + + /// The native send UI speaks whole CASH cents; selection and memo values + /// speak raw chain planks. Keep their only conversion at this service + /// boundary so callers cannot accidentally preview cents as planks. + pub fn cash_cents_to_planks(&self, cents: u128) -> Option { + self.denominations.cash_cents_to_planks(cents) + } + + pub fn cash_cents_from_planks(&self, planks: u128) -> Option { + self.denominations.cash_cents_from_planks(planks) + } + + pub fn planks_per_cash_cent(&self) -> u128 { + self.denominations.asset_unit + } + + pub async fn preview( + &self, + amount: u128, + ) -> Result { + let coins = self.coins.list().await.map_err(RegularTransferError::Planning)?; + let vouchers = self.vouchers.list().await.map_err(RegularTransferError::Planning)?; + let now_ms = self.clock.now_ms(); + let full = match CoinSelector::new(self.denominations.clone(), self.max_consolidation) + .select(amount, &coins, &vouchers, now_ms) + { + Ok(selection) => selection, + Err(selection_error) => { + let snapshot = + selector_snapshot_diagnostic(&coins, &vouchers, &self.denominations, now_ms); + warn!( + error = selection_error_kind(&selection_error), + strategy = "none", + requested_value_digits = decimal_digits(amount), + selectable_coins = snapshot.selectable_coins, + expiring_coins = snapshot.expiring_coins, + locked_coins = snapshot.locked_coins, + unloadable_vouchers = snapshot.unloadable_vouchers, + locked_vouchers = snapshot.locked_vouchers, + full_vouchers = snapshot.full_vouchers, + degraded_vouchers = snapshot.degraded_vouchers, + selectable_coin_value_digits = snapshot.selectable_coin_value_digits, + unloadable_voucher_value_digits = snapshot.unloadable_voucher_value_digits, + "coinage selector snapshot" + ); + return Err(selection_error.into()); + }, + }; + let (non_degraded, non_degraded_amount) = + non_degraded_selection(&full, &self.denominations, now_ms); + let strategy = match full.strategy { + TransferStrategy::ExactMatch { .. } => TransferPreviewStrategy::ExactMatch, + TransferStrategy::Split { .. } => TransferPreviewStrategy::Split, + TransferStrategy::UnloadIntoCoins { .. } => TransferPreviewStrategy::UnloadIntoCoins, + }; + let preview_id = random_id("cash-preview"); + let descriptor = OpaqueTransferPreview { + preview_id: preview_id.clone(), + session_generation: self.session_generation, + full_amount: amount, + max_debit_amount: selection_max_debit(&full, &self.denominations), + non_degraded_amount, + is_degraded: full.privacy_level == PrivacyLevel::Degraded, + strategy, + expires_at_ms: now_ms.saturating_add(PREVIEW_LIFETIME_MS), + }; + let mut previews = self.previews.lock().await; + previews.retain(|_, preview| preview.descriptor.expires_at_ms >= now_ms); + previews.insert( + preview_id, + CachedPreview { descriptor: descriptor.clone(), full, non_degraded, coins, vouchers }, + ); + Ok(descriptor) + } + + pub async fn preview_descriptor( + &self, + preview_id: &str, + ) -> Result { + let descriptor = match self + .previews + .lock() + .await + .get(preview_id) + .map(|preview| preview.descriptor.clone()) + { + Some(descriptor) => descriptor, + None => { + return Err(RegularTransferError::PreviewNotFound); + }, + }; + if self.clock.now_ms() > descriptor.expires_at_ms { + return Err(RegularTransferError::PreviewExpired); + } + Ok(descriptor) + } + + /// Confirms exactly the cached selector result. Calls racing for the same + /// preview join one result; only the first closure can receive the memo. + /// `handoff` may return `Err(())` only if it certifies that no recipient or + /// transport accepted the secret. Ambiguous delivery must retain the WAL + /// by returning `Ok(())` and reporting transport uncertainty separately. + pub async fn confirm( + self: &Arc, + preview_id: &str, + choice: TransferPreviewChoice, + handoff: F, + ) -> Result<(), RegularTransferError> + where + F: FnOnce(TransferMemo) -> Fut + Send + 'static, + Fut: Future> + Send + 'static, + { + let (confirmation, leader) = { + let mut confirmations = self.confirmations.lock().await; + match confirmations.get(preview_id) { + Some(existing) => (Arc::clone(existing), false), + None => { + let confirmation = Arc::new(Confirmation::default()); + confirmations.insert(preview_id.to_owned(), Arc::clone(&confirmation)); + (confirmation, true) + }, + } + }; + if leader { + let service = Arc::clone(self); + let preview_id = preview_id.to_owned(); + let running = Arc::clone(&confirmation); + crate::tasks::spawn_abortable(&self.spawner, async move { + let result = + service.confirm_operation(&preview_id, &preview_id, choice, handoff).await; + running.finish(result); + }); + } + confirmation.wait().await + } + + /// Confirms a host-owned durable operation. The host must serialize wallet + /// recovery with this call and run it on its cancellation-safe executor. + /// The callback may await durable transport persistence before returning. + /// `Err` from the callback certifies no acceptance; uncertain acceptance + /// must return `Ok` and retain the transport's idempotent operation key. + /// + /// All chain work finishes (or leaves recoverable WAL) before returning. + /// Once transport accepts, chain/persistence failures never become `Err`. + pub async fn confirm_operation( + self: &Arc, + operation_id: &str, + preview_id: &str, + choice: TransferPreviewChoice, + handoff: F, + ) -> Result<(), RegularTransferError> + where + F: FnOnce(TransferMemo) -> Fut + Send, + Fut: Future> + Send, + { + if operation_id.is_empty() { + return Err(RegularTransferError::InvalidOperationId); + } + let _execution = self.execution_lock.lock().await; + let existing = self.operation_wal(operation_id).await?; + if !existing.is_empty() { + return self.resume_entries(existing, handoff).await; + } + let cached = self + .previews + .lock() + .await + .get(preview_id) + .cloned() + .ok_or(RegularTransferError::PreviewNotFound)?; + if self.clock.now_ms() > cached.descriptor.expires_at_ms { + return Err(RegularTransferError::PreviewExpired); + } + let current_coins = self.coins.list().await.map_err(RegularTransferError::Planning)?; + let current_vouchers = + self.vouchers.list().await.map_err(RegularTransferError::Planning)?; + if current_coins != cached.coins || current_vouchers != cached.vouchers { + return Err(RegularTransferError::BalanceChanged); + } + let expected_amount = match choice { + TransferPreviewChoice::Full => cached.descriptor.full_amount, + TransferPreviewChoice::NonDegraded => cached.descriptor.non_degraded_amount, + }; + let result = match choice { + TransferPreviewChoice::Full => cached.full, + TransferPreviewChoice::NonDegraded => { + cached.non_degraded.ok_or(RegularTransferError::NonDegradedAmountUnavailable)? + }, + }; + let amount = selection_value(&result, &self.denominations); + if amount == 0 || + amount != expected_amount || + selection_max_debit(&result, &self.denominations) > + cached.descriptor.max_debit_amount + { + return Err(RegularTransferError::BalanceChanged); + } + let mut plan = self.create_plan(operation_id, result, amount).await?; + let context = self.transfer_context(); + context + .reserve(&plan.reserved_coins, &plan.reserved_vouchers) + .await + .map_err(RegularTransferError::Reservation)?; + if let Err(error) = self.wal.save_all(&plan.journals).await { + // A failed acknowledgement can still have committed the atomic + // batch. Never partially delete it: restart would lose the plan. + // Recovery restores orphan reservations if no batch committed, + // otherwise the complete Prepared operation remains resumable. + return Err(RegularTransferError::Journal(error)); + } + let mut parent = plan + .journals + .iter() + .find(|entry| entry.operation.is_transfer_receipt()) + .cloned() + .expect("operation plan includes its durable receipt"); + let memo = plan.memo.take().expect("plan memo consumed once"); + if handoff(memo).await.is_err() { + self.reject_operation(&mut parent, &plan.journals).await?; + return Err(RegularTransferError::HandoffRejected); + } + if let Err(error) = self.finish_accepted(&mut parent, &plan.journals, plan.chain).await { + error!(%error, "accepted CASH operation remains journaled for recovery"); + } + Ok(()) + } + + pub async fn operation_wal( + &self, + operation_id: &str, + ) -> Result, RegularTransferError> { + self.wal + .load_operation(operation_id) + .await + .map_err(RegularTransferError::Journal) + } + + /// Resumes only existing allocations, never selects or debits new inputs. + /// Invoke after recovery and renewed user approval, never from passive + /// reconciliation. For Prepared receipts, `handoff` must resolve/replay the + /// SAME host transport operation, since acceptance may precede a crash. + /// Accepted/Completed receipts never invoke it. Known checkpoints are not + /// broadcast again; recovery must first prove their mortality or fork. + pub async fn resume_operation( + self: &Arc, + operation_id: &str, + handoff: F, + ) -> Result<(), RegularTransferError> + where + F: FnOnce(TransferMemo) -> Fut + Send, + Fut: Future> + Send, + { + let _execution = self.execution_lock.lock().await; + self.resume_entries(self.operation_wal(operation_id).await?, handoff).await + } + + async fn resume_entries( + &self, + entries: Vec, + handoff: F, + ) -> Result<(), RegularTransferError> + where + F: FnOnce(TransferMemo) -> Fut + Send, + Fut: Future> + Send, + { + let mut parent = entries + .iter() + .find(|entry| entry.operation.is_transfer_receipt()) + .cloned() + .ok_or(RegularTransferError::OperationNotFound)?; + match parent.operation { + WalOperation::TransferCompleted => return Ok(()), + WalOperation::TransferRejected => { + self.reject_operation(&mut parent, &entries).await?; + return Err(RegularTransferError::HandoffRejected); + }, + WalOperation::TransferPrepared => { + let coins = + parent.payload.output_coins.iter().map(referenced_coin).collect::>(); + let amount = coins.iter().fold(0u128, |sum, coin| { + sum.saturating_add(self.denominations.value_in_planks(coin.exponent)) + }); + let memo = self.build_memo(&coins, amount)?; + if handoff(memo).await.is_err() { + self.reject_operation(&mut parent, &entries).await?; + return Err(RegularTransferError::HandoffRejected); + } + }, + WalOperation::TransferAccepted => {}, + _ => return Err(RegularTransferError::OperationNotFound), + } + // From here the memo may already be owned by the recipient. + let completion = async { + parent.operation = WalOperation::TransferAccepted; + self.wal.save(&parent).await?; + let chain = self.restore_chain_plan(&entries).await?; + self.finish_accepted(&mut parent, &entries, chain).await + } + .await; + if let Err(error) = completion { + error!(%error, "accepted CASH operation remains journaled for recovery"); + } + Ok(()) + } + + fn transfer_context(&self) -> Arc { + let mut context = TransferContext::new(Arc::clone(&self.coins), Arc::clone(&self.vouchers)); + if let Some(committer) = &self.committer { + context = context.with_committer(Arc::clone(committer)); + } + Arc::new(context) + } + + async fn reject_operation( + &self, + parent: &mut TransferWalEntry, + entries: &[TransferWalEntry], + ) -> Result<(), RegularTransferError> { + parent.operation = WalOperation::TransferRejected; + self.wal.save(parent).await.map_err(RegularTransferError::Journal)?; + for entry in entries.iter().filter(|entry| !entry.operation.is_transfer_receipt()) { + for input in &entry.payload.input_coins { + self.coins + .set_state(input.derivation_index, CoinState::Available) + .await + .map_err(RegularTransferError::Reservation)?; + } + for input in &entry.payload.input_vouchers { + self.vouchers + .set_local_state( + input.derivation_index, + crate::model::VoucherLocalState::Available, + ) + .await + .map_err(RegularTransferError::Reservation)?; + } + self.wal.delete(&entry.entry_id).await.map_err(RegularTransferError::Journal)?; + } + Ok(()) + } + + async fn finish_accepted( + &self, + parent: &mut TransferWalEntry, + entries: &[TransferWalEntry], + chain: ChainPlan, + ) -> Result<(), String> { + parent.operation = WalOperation::TransferAccepted; + self.wal.save(parent).await?; + let context = self.transfer_context(); + for entry in entries.iter().filter(|entry| entry.operation == WalOperation::SecretHandoff) { + let indices = entry + .payload + .input_coins + .iter() + .map(|coin| coin.derivation_index) + .collect::>(); + context.process_outputs(&indices, &[], &[], &[]).await?; + self.wal.delete(&entry.entry_id).await?; + } + self.run_chain_plan(chain, context).await?; + let children_remain = self.wal.load_all().await?.iter().any(|entry| { + entry.entry_id != parent.entry_id && + entry.operation_parent_id().as_deref() == Some(parent.entry_id.as_str()) + }); + if !children_remain { + parent.operation = WalOperation::TransferCompleted; + self.wal.save(parent).await?; + } + Ok(()) + } + + async fn restore_chain_plan(&self, entries: &[TransferWalEntry]) -> Result { + let mut drafts = Vec::new(); + let vouchers = if entries.iter().any(|entry| { + entry.operation == WalOperation::IntoCoins && + entry.checkpoint == CheckpointBlock::Pending + }) { + self.vouchers.list().await? + } else { + Vec::new() + }; + for entry in entries.iter().filter(|entry| { + entry.checkpoint == CheckpointBlock::Pending && + matches!(entry.operation, WalOperation::Split | WalOperation::IntoCoins) + }) { + let recipient_coins = + entry.payload.destination_coins.iter().map(referenced_coin).collect::>(); + let change_coins = entry + .payload + .output_coins + .iter() + .filter(|coin| !entry.payload.destination_coins.contains(coin)) + .map(referenced_coin) + .collect::>(); + match entry.operation { + WalOperation::Split => { + if entry.payload.input_coins.len() != 1 { + return Err("split journal does not have exactly one input".into()); + } + return Ok(ChainPlan::Split(SplitTransferSubmission { + overflow_coin: referenced_coin(&entry.payload.input_coins[0]), + recipient_coins, + change_coins, + wal_entry_id: entry.entry_id.clone(), + })); + }, + WalOperation::IntoCoins => { + let members = entry + .payload + .input_vouchers + .iter() + .map(|reference| { + vouchers + .iter() + .find(|voucher| { + voucher.derivation_index == reference.derivation_index && + voucher.exponent == reference.exponent + }) + .cloned() + .ok_or_else(|| { + "unload journal input is not available locally".to_string() + }) + }) + .collect::, _>>()?; + let first = members.first().ok_or("unload journal has no vouchers")?; + let VoucherRemoteState::InRecycler { recycler_index } = first.remote_state + else { + return Err("unload journal awaits voucher location reconciliation".into()); + }; + let recycler = RecyclerKey { exponent: first.exponent, index: recycler_index }; + if members.iter().any(|voucher| { + voucher.exponent != recycler.exponent || + voucher.remote_state != first.remote_state + }) { + return Err("unload journal spans multiple recyclers".into()); + } + drafts.push(UnloadGroupDraft { + recycler, + vouchers: members, + recipient_coins, + change_coins, + wal_entry_id: entry.entry_id.clone(), + }); + }, + _ => {}, + } + } + if drafts.is_empty() { + return Ok(ChainPlan::None); + } + let prepared = self.submitter.prepare_unload_groups(&drafts).await?; + if prepared.len() != drafts.len() || + prepared.iter().zip(&drafts).any(|(prepared, draft)| &prepared.draft != draft) + { + return Err("unload recovery changed the durable allocation".into()); + } + Ok(ChainPlan::Unload(prepared)) + } + + async fn create_plan( + &self, + operation_id: &str, + result: CoinSelectionResult, + amount: u128, + ) -> Result { + let mut journals = Vec::new(); + let mut reserved_coins = Vec::new(); + let mut reserved_vouchers = Vec::new(); + let (pass_through, recipient, chain) = match result.strategy { + TransferStrategy::ExactMatch { coins } => { + reserved_coins.extend(coins.iter().map(|coin| coin.derivation_index)); + (coins.clone(), coins, ChainPlan::None) + }, + TransferStrategy::Split { + partial_coins, + split_coin, + target_denominations, + change_denominations, + } => { + let recipient = self.allocate_coins(&target_denominations).await?; + let change = self.allocate_coins(&change_denominations).await?; + reserved_coins.extend(partial_coins.iter().map(|coin| coin.derivation_index)); + reserved_coins.push(split_coin.derivation_index); + let wal_entry_id = operation_entry_id(operation_id, "split"); + let submission = SplitTransferSubmission { + overflow_coin: split_coin.clone(), + recipient_coins: recipient.clone(), + change_coins: change.clone(), + wal_entry_id: wal_entry_id.clone(), + }; + journals.push(chain_journal( + wal_entry_id, + WalOperation::Split, + &[split_coin], + &[], + &recipient, + &change, + self.clock.now_ms(), + )); + let mut memo_coins = partial_coins.clone(); + memo_coins.extend(recipient); + (partial_coins, memo_coins, ChainPlan::Split(submission)) + }, + TransferStrategy::UnloadIntoCoins { coins, groups } => { + reserved_coins.extend(coins.iter().map(|coin| coin.derivation_index)); + let mut drafts = Vec::with_capacity(groups.len()); + let mut memo_coins = coins.clone(); + for (group_index, group) in groups.into_iter().enumerate() { + let recipient = self.allocate_coins(&group.recipient_denominations).await?; + let change = self.allocate_coins(&group.change_denominations).await?; + reserved_vouchers + .extend(group.vouchers.iter().map(|voucher| voucher.derivation_index)); + memo_coins.extend(recipient.clone()); + drafts.push(UnloadGroupDraft { + recycler: group.recycler, + vouchers: group.vouchers, + recipient_coins: recipient, + change_coins: change, + wal_entry_id: operation_entry_id( + operation_id, + &format!("unload-{group_index}"), + ), + }); + } + let prepared = self + .submitter + .prepare_unload_groups(&drafts) + .await + .map_err(RegularTransferError::Planning)?; + if prepared.len() != drafts.len() || + prepared + .iter() + .zip(&drafts) + .any(|(prepared, draft)| &prepared.draft != draft) + { + return Err(RegularTransferError::Planning( + "unload preparation did not preserve every recycler group".into(), + )); + } + for group in &prepared { + journals.push(chain_journal( + group.draft.wal_entry_id.clone(), + WalOperation::IntoCoins, + &[], + &group.draft.vouchers, + &group.draft.recipient_coins, + &group.draft.change_coins, + self.clock.now_ms(), + )); + } + (coins, memo_coins, ChainPlan::Unload(prepared)) + }, + }; + + let memo = self.build_memo(&recipient, amount)?; + if !pass_through.is_empty() { + let id = operation_entry_id(operation_id, "handoff"); + journals.push(TransferWalEntry { + entry_id: id.clone(), + operation: WalOperation::SecretHandoff, + payload: WalPayload { + input_coins: coin_refs(&pass_through), + ..WalPayload::default() + }, + checkpoint: CheckpointBlock::Pending, + created_at_ms: self.clock.now_ms(), + }); + } + journals.push(TransferWalEntry { + entry_id: operation_entry_id(operation_id, "parent"), + operation: WalOperation::TransferPrepared, + payload: WalPayload { output_coins: coin_refs(&recipient), ..WalPayload::default() }, + checkpoint: CheckpointBlock::Pending, + created_at_ms: self.clock.now_ms(), + }); + Ok(TransferPlan { memo: Some(memo), reserved_coins, reserved_vouchers, journals, chain }) + } + + async fn allocate_coins( + &self, + denominations: &[crate::denomination::Denomination], + ) -> Result, RegularTransferError> { + let mut coins = Vec::with_capacity(denominations.len()); + for denomination in denominations { + coins.push( + self.allocator + .allocate(denomination.exponent) + .await + .map_err(RegularTransferError::Planning)?, + ); + } + Ok(coins) + } + + fn build_memo( + &self, + coins: &[Coin], + expected: u128, + ) -> Result { + let total = coins.iter().fold(0u128, |total, coin| { + total.saturating_add(self.denominations.value_in_planks(coin.exponent)) + }); + if total != expected { + return Err(RegularTransferError::Planning(format!( + "memo value {total} does not equal selected amount {expected}" + ))); + } + let entries = coins + .iter() + .map(|coin| { + self.key_factory + .secret_bytes(coin.derivation_index) + .map(MemoEntry) + .map_err(RegularTransferError::Planning) + }) + .collect::, _>>()?; + Ok(TransferMemo { entries, total_value: total }) + } + + async fn run_chain_plan( + &self, + chain: ChainPlan, + context: Arc, + ) -> Result<(), String> { + match chain { + ChainPlan::None => Ok(()), + ChainPlan::Split(submission) => match self.submitter.submit_split(&submission).await { + Ok(()) => { + context + .process_outputs( + &[submission.overflow_coin.derivation_index], + &[], + &submission.change_coins, + &submission.recipient_coins, + ) + .await?; + self.wal.delete(&submission.wal_entry_id).await + }, + // Even a pre-broadcast failure must retain the fixed outputs: + // their secrets already belong to the recipient. + Err(error) => Err(error), + }, + ChainPlan::Unload(groups) => { + let outcomes = join_all(groups.into_iter().map(|group| { + let submitter = Arc::clone(&self.submitter); + async move { + let result = submitter.submit_unload_group(&group).await; + (group, result) + } + })) + .await; + let mut errors = Vec::new(); + for (group, outcome) in outcomes { + let voucher_ids = group + .draft + .vouchers + .iter() + .map(|voucher| voucher.derivation_index) + .collect::>(); + match outcome { + Ok(()) => { + if let Err(error) = context + .process_outputs( + &[], + &voucher_ids, + &group.draft.change_coins, + &group.draft.recipient_coins, + ) + .await + { + errors.push(error); + continue; + } + if let Err(error) = self.wal.delete(&group.draft.wal_entry_id).await { + errors.push(error); + } + }, + Err(error) => errors.push(error), + } + } + if errors.is_empty() { Ok(()) } else { Err(errors.join("; ")) } + }, + } + } } struct TransferPlan { - memo: Option, - reserved_coins: Vec, - reserved_vouchers: Vec, - journals: Vec, - chain: ChainPlan, + memo: Option, + reserved_coins: Vec, + reserved_vouchers: Vec, + journals: Vec, + chain: ChainPlan, } enum ChainPlan { - None, - Split(SplitTransferSubmission), - Unload(Vec), + None, + Split(SplitTransferSubmission), + Unload(Vec), } fn random_id(prefix: &str) -> String { - let mut bytes = [0u8; 16]; - rand::thread_rng().fill_bytes(&mut bytes); - format!("{prefix}-{}", hex::encode(bytes)) + let mut bytes = [0u8; 16]; + rand::thread_rng().fill_bytes(&mut bytes); + format!("{prefix}-{}", hex::encode(bytes)) } fn coin_refs(coins: &[Coin]) -> Vec { - coins - .iter() - .map(|coin| WalCoinRef { - derivation_index: coin.derivation_index, - exponent: coin.exponent, - }) - .collect() + coins + .iter() + .map(|coin| WalCoinRef { derivation_index: coin.derivation_index, exponent: coin.exponent }) + .collect() } fn voucher_refs(vouchers: &[Voucher]) -> Vec { - vouchers - .iter() - .map(|voucher| WalCoinRef { - derivation_index: voucher.derivation_index, - exponent: voucher.exponent, - }) - .collect() + vouchers + .iter() + .map(|voucher| WalCoinRef { + derivation_index: voucher.derivation_index, + exponent: voucher.exponent, + }) + .collect() } fn referenced_coin(reference: &WalCoinRef) -> Coin { - Coin { - derivation_index: reference.derivation_index, - exponent: reference.exponent, - age: None, - state: CoinState::PendingTransfer, - } + Coin { + derivation_index: reference.derivation_index, + exponent: reference.exponent, + age: None, + state: CoinState::PendingTransfer, + } } fn chain_journal( - entry_id: String, - operation: WalOperation, - input_coins: &[Coin], - input_vouchers: &[Voucher], - destination: &[Coin], - change: &[Coin], - created_at_ms: i64, + entry_id: String, + operation: WalOperation, + input_coins: &[Coin], + input_vouchers: &[Voucher], + destination: &[Coin], + change: &[Coin], + created_at_ms: i64, ) -> TransferWalEntry { - let mut output_coins = coin_refs(destination); - output_coins.extend(coin_refs(change)); - TransferWalEntry { - entry_id, - operation, - payload: WalPayload { - input_coins: coin_refs(input_coins), - input_vouchers: voucher_refs(input_vouchers), - output_coins, - output_vouchers: Vec::new(), - destination_coins: coin_refs(destination), - }, - checkpoint: CheckpointBlock::Pending, - created_at_ms, - } + let mut output_coins = coin_refs(destination); + output_coins.extend(coin_refs(change)); + TransferWalEntry { + entry_id, + operation, + payload: WalPayload { + input_coins: coin_refs(input_coins), + input_vouchers: voucher_refs(input_vouchers), + output_coins, + output_vouchers: Vec::new(), + destination_coins: coin_refs(destination), + }, + checkpoint: CheckpointBlock::Pending, + created_at_ms, + } } fn selection_value(result: &CoinSelectionResult, context: &DenominationBreakdownContext) -> u128 { - match &result.strategy { - TransferStrategy::ExactMatch { coins } => coins.iter().fold(0u128, |sum, coin| { - sum.saturating_add(context.value_in_planks(coin.exponent)) - }), - TransferStrategy::Split { - partial_coins, - target_denominations, - .. - } => partial_coins - .iter() - .fold(0u128, |sum, coin| { - sum.saturating_add(context.value_in_planks(coin.exponent)) - }) - .saturating_add(context.total_value(target_denominations)), - TransferStrategy::UnloadIntoCoins { coins, groups } => groups.iter().fold( - coins.iter().fold(0u128, |sum, coin| { - sum.saturating_add(context.value_in_planks(coin.exponent)) - }), - |sum, group| sum.saturating_add(context.total_value(&group.recipient_denominations)), - ), - } + match &result.strategy { + TransferStrategy::ExactMatch { coins } => coins + .iter() + .fold(0u128, |sum, coin| sum.saturating_add(context.value_in_planks(coin.exponent))), + TransferStrategy::Split { partial_coins, target_denominations, .. } => partial_coins + .iter() + .fold(0u128, |sum, coin| sum.saturating_add(context.value_in_planks(coin.exponent))) + .saturating_add(context.total_value(target_denominations)), + TransferStrategy::UnloadIntoCoins { coins, groups } => groups.iter().fold( + coins.iter().fold(0u128, |sum, coin| { + sum.saturating_add(context.value_in_planks(coin.exponent)) + }), + |sum, group| sum.saturating_add(context.total_value(&group.recipient_denominations)), + ), + } } fn selection_max_debit( - result: &CoinSelectionResult, - context: &DenominationBreakdownContext, + result: &CoinSelectionResult, + context: &DenominationBreakdownContext, ) -> u128 { - match &result.strategy { - TransferStrategy::UnloadIntoCoins { coins, groups } => coins - .iter() - .map(|coin| coin.exponent) - .chain( - groups - .iter() - .flat_map(|group| group.vouchers.iter().map(|voucher| voucher.exponent)), - ) - .fold(0u128, |total, exponent| { - total.saturating_add(context.value_in_planks(exponent)) - }), - // Whole coins and splits retain their planned change exactly. - _ => selection_value(result, context), - } + match &result.strategy { + TransferStrategy::UnloadIntoCoins { coins, groups } => coins + .iter() + .map(|coin| coin.exponent) + .chain( + groups + .iter() + .flat_map(|group| group.vouchers.iter().map(|voucher| voucher.exponent)), + ) + .fold(0u128, |total, exponent| total.saturating_add(context.value_in_planks(exponent))), + // Whole coins and splits retain their planned change exactly. + _ => selection_value(result, context), + } } fn non_degraded_selection( - full: &CoinSelectionResult, - context: &DenominationBreakdownContext, - now_ms: i64, + full: &CoinSelectionResult, + context: &DenominationBreakdownContext, + now_ms: i64, ) -> (Option, u128) { - if full.privacy_level == PrivacyLevel::Full { - return (Some(full.clone()), selection_value(full, context)); - } - let TransferStrategy::UnloadIntoCoins { coins, groups } = &full.strategy else { - return (Some(full.clone()), selection_value(full, context)); - }; - let groups = groups - .iter() - .filter(|group| { - group - .vouchers - .iter() - .all(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Full) - }) - .cloned() - .collect::>(); - let result = CoinSelectionResult { - strategy: if groups.is_empty() { - TransferStrategy::ExactMatch { - coins: coins.clone(), - } - } else { - TransferStrategy::UnloadIntoCoins { - coins: coins.clone(), - groups, - } - }, - privacy_level: PrivacyLevel::Full, - }; - let amount = selection_value(&result, context); - ((amount > 0).then_some(result), amount) + if full.privacy_level == PrivacyLevel::Full { + return (Some(full.clone()), selection_value(full, context)); + } + let TransferStrategy::UnloadIntoCoins { coins, groups } = &full.strategy else { + return (Some(full.clone()), selection_value(full, context)); + }; + let groups = groups + .iter() + .filter(|group| { + group + .vouchers + .iter() + .all(|voucher| voucher.effective_privacy(now_ms) == EffectivePrivacy::Full) + }) + .cloned() + .collect::>(); + let result = CoinSelectionResult { + strategy: if groups.is_empty() { + TransferStrategy::ExactMatch { coins: coins.clone() } + } else { + TransferStrategy::UnloadIntoCoins { coins: coins.clone(), groups } + }, + privacy_level: PrivacyLevel::Full, + }; + let amount = selection_value(&result, context); + ((amount > 0).then_some(result), amount) } #[cfg(test)] mod tests { - use super::*; - use std::collections::HashSet; - - use crate::balance::compute_balance; - use crate::clock::FixedClock; - use crate::index_store::InMemoryCoinageIndexStore; - use crate::model::{CoinState, VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}; - use crate::repo::{InMemoryCoinRepository, InMemoryVoucherRepository}; - - #[derive(Default)] - struct MemWal(Mutex>); - - #[async_trait] - impl WalStore for MemWal { - async fn save(&self, entry: &TransferWalEntry) -> Result<(), String> { - let mut entries = self.0.lock(); - entries.retain(|existing| existing.entry_id != entry.entry_id); - entries.push(entry.clone()); - Ok(()) - } - async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String> { - let mut stored = self.0.lock(); - stored.retain(|existing| { - !entries - .iter() - .any(|entry| entry.entry_id == existing.entry_id) - }); - stored.extend_from_slice(entries); - Ok(()) - } - async fn update_checkpoint( - &self, - entry_id: &str, - checkpoint: CheckpointBlock, - ) -> Result<(), String> { - let mut entries = self.0.lock(); - entries - .iter_mut() - .find(|entry| entry.entry_id == entry_id) - .ok_or_else(|| "missing WAL".to_string())? - .checkpoint = checkpoint; - Ok(()) - } - async fn load_all(&self) -> Result, String> { - Ok(self.0.lock().clone()) - } - async fn delete(&self, entry_id: &str) -> Result<(), String> { - self.0.lock().retain(|entry| entry.entry_id != entry_id); - Ok(()) - } - } - - struct MockSubmitter { - wal: Arc, - fail_unload: HashSet, - } - - #[async_trait] - impl RegularTransferSubmitter for MockSubmitter { - async fn prepare_unload_groups( - &self, - groups: &[UnloadGroupDraft], - ) -> Result, String> { - Ok(groups - .iter() - .cloned() - .map(|draft| PreparedUnloadGroup { - recycler_revision: 1, - readiness_block_hash: [7; 32], - origin: UnloadOriginPreparation { - recycler_ring: RingProofParams { - ring_exponent: 9, - ring_index: draft.recycler.index, - ring_revision: 1, - ring_members: vec![[1; 32]], - }, - person_origin: PersonOriginKind::Lite, - people_ring: RingProofParams { - ring_exponent: 9, - ring_index: 2, - ring_revision: 1, - ring_members: vec![[2; 32]], - }, - token: ResolvedUnloadToken { - period: 3, - counter: draft.recycler.index, - }, - }, - draft, - }) - .collect()) - } - - async fn submit_split(&self, submission: &SplitTransferSubmission) -> Result<(), String> { - self.wal - .update_checkpoint( - &submission.wal_entry_id, - CheckpointBlock::Known { - number: 10, - hash: [9; 32], - }, - ) - .await - } - - async fn submit_unload_group( - &self, - submission: &PreparedUnloadGroup, - ) -> Result<(), String> { - self.wal - .update_checkpoint( - &submission.draft.wal_entry_id, - CheckpointBlock::Known { - number: 10, - hash: [9; 32], - }, - ) - .await?; - if self.fail_unload.contains(&submission.draft.recycler.index) { - Err("scripted ambiguous unload failure".into()) - } else { - Ok(()) - } - } - } - - fn context() -> DenominationBreakdownContext { - DenominationBreakdownContext { - asset_unit: 1, - max_exponent: 10, - min_exponent: 0, - precision: 2, - } - } - - fn voucher(index: u32, exponent: i16, recycler: u32) -> Voucher { - Voucher { - exponent, - derivation_index: index, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: VoucherRemoteState::InRecycler { - recycler_index: recycler, - }, - local_state: VoucherLocalState::Available, - privacy: VoucherPrivacyLevel::Full, - } - } - - #[test] - fn selector_snapshot_is_aggregate_only_and_uses_value_digit_counts() { - let coins = vec![ - Coin { - exponent: 2, - derivation_index: 99, - age: Some(1), - state: CoinState::Available, - }, - Coin { - exponent: 1, - derivation_index: 100, - age: Some(14), - state: CoinState::Available, - }, - Coin { - exponent: 0, - derivation_index: 101, - age: Some(1), - state: CoinState::PendingTransfer, - }, - ]; - let mut ready = voucher(7, 3, 4); - ready.ready_at_ms = 0; - let mut locked = voucher(8, 1, 4); - locked.local_state = VoucherLocalState::PendingTransfer; - locked.privacy = VoucherPrivacyLevel::Degraded; - let diagnostic = selector_snapshot_diagnostic(&coins, &[ready, locked], &context(), 1_000); - assert_eq!(diagnostic.selectable_coins, 1); - assert_eq!(diagnostic.expiring_coins, 1); - assert_eq!(diagnostic.locked_coins, 2); - assert_eq!(diagnostic.unloadable_vouchers, 1); - assert_eq!(diagnostic.locked_vouchers, 1); - assert_eq!(diagnostic.full_vouchers, 1); - assert_eq!(diagnostic.degraded_vouchers, 1); - assert_eq!(diagnostic.selectable_coin_value_digits, 1); // value 4 - assert_eq!(diagnostic.unloadable_voucher_value_digits, 1); // value 8 - } - - fn service( - vouchers: Vec, - fail_unload: HashSet, - ) -> ( - Arc, - Arc, - Arc, - Arc, - ) { - service_with_context(vouchers, fail_unload, context()) - } - - fn service_with_context( - vouchers: Vec, - fail_unload: HashSet, - denominations: DenominationBreakdownContext, - ) -> ( - Arc, - Arc, - Arc, - Arc, - ) { - let coins = Arc::new(InMemoryCoinRepository::default()); - let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers(vouchers)); - let wal = Arc::new(MemWal::default()); - let submitter = Arc::new(MockSubmitter { - wal: Arc::clone(&wal), - fail_unload, - }); - let service = Arc::new(RegularCoinTransferService::new( - &[0x33; 32], - RegularCoinTransferParts { - spawner: crate::test_spawner(), - coins: Arc::clone(&coins) as Arc<_>, - vouchers: Arc::clone(&vouchers) as Arc<_>, - wal: Arc::clone(&wal) as Arc<_>, - allocator: Arc::new(CoinAllocator::new(Arc::new( - InMemoryCoinageIndexStore::default(), - ))), - submitter, - denominations, - max_consolidation: 100, - clock: Arc::new(FixedClock(1_000)), - session_generation: 4, - committer: None, - }, - )); - (service, coins, vouchers, wal) - } - - /// Native amounts stay in CASH cents while the selector stays in raw - /// asset planks. This regression covers real-scale CASH amounts and - /// proves the 10,000x boundary is applied before all three selector - /// strategies run. - #[tokio::test] - async fn native_cash_amounts_preview_at_six_decimal_asset_precision() { - let denominations = DenominationBreakdownContext { - asset_unit: 10_000, - max_exponent: 14, - min_exponent: 0, - precision: 6, - }; - // 2^14 + 2^11 + 2^10 + 2^9 + 2^5 = 20,000 cents = 200 CASH. - let inventory = vec![ - voucher(1, 14, 1), - voucher(2, 11, 2), - voucher(3, 10, 3), - voucher(4, 9, 4), - voucher(5, 5, 5), - ]; - let (service, _, _, _) = service_with_context(inventory, HashSet::new(), denominations); - - for (cash, cents, expected_planks) in [ - (1, 100, 1_000_000), - (10, 1_000, 10_000_000), - (100, 10_000, 100_000_000), - (200, 20_000, 200_000_000), - ] { - let planks = service.cash_cents_to_planks(cents).unwrap(); - assert_eq!(planks, expected_planks, "{cash} CASH conversion"); - let preview = service.preview(planks).await.unwrap(); - assert_eq!(preview.full_amount, expected_planks, "{cash} CASH preview"); - assert_eq!( - service.cash_cents_from_planks(preview.full_amount), - Some(cents), - "{cash} CASH projection" - ); - } - } - - #[tokio::test] - async fn six_voucher_balance_previews_and_confirms_one_cash() { - let inventory = vec![ - voucher(1, 10, 1), // 1024 - voucher(2, 4, 2), // 16 - voucher(3, 4, 3), // 16 - voucher(4, 3, 4), // 8 - voucher(5, 1, 5), // 2 - voucher(6, 1, 6), // 2 - ]; - assert_eq!( - compute_balance(&[], &inventory, &context(), 1_000).total_planks(), - 1_068 - ); - let (service, _coins, vouchers, wal) = service(inventory, HashSet::new()); - let preview = service.preview(100).await.unwrap(); - assert_eq!(preview.strategy, TransferPreviewStrategy::UnloadIntoCoins); - assert_eq!(preview.full_amount, 100); - service - .confirm( - &preview.preview_id, - TransferPreviewChoice::Full, - |memo| async move { - assert_eq!(memo.total_value, 100); - Ok(()) - }, - ) - .await - .unwrap(); - assert_eq!(vouchers.list().await.unwrap().len(), 5); - assert_eq!( - wal.load_operation(&preview.preview_id).await.unwrap()[0].operation, - WalOperation::TransferCompleted - ); - } - - #[tokio::test] - async fn split_persists_change_retires_destination_and_preserves_receipt() { - let coins = Arc::new(InMemoryCoinRepository::with_coins([Coin { - exponent: 3, - derivation_index: 100, - age: Some(1), - state: crate::CoinState::Available, - }])); - let vouchers = Arc::new(InMemoryVoucherRepository::default()); - let wal = Arc::new(MemWal::default()); - let service = Arc::new(RegularCoinTransferService::new( - &[0x33; 32], - RegularCoinTransferParts { - spawner: crate::test_spawner(), - coins: Arc::clone(&coins) as Arc<_>, - vouchers, - wal: Arc::clone(&wal) as Arc<_>, - allocator: Arc::new(CoinAllocator::new(Arc::new( - InMemoryCoinageIndexStore::default(), - ))), - submitter: Arc::new(MockSubmitter { - wal: Arc::clone(&wal), - fail_unload: HashSet::new(), - }), - denominations: context(), - max_consolidation: 100, - clock: Arc::new(FixedClock(1_000)), - session_generation: 4, - committer: None, - }, - )); - let preview = service.preview(3).await.unwrap(); - assert_eq!(preview.strategy, TransferPreviewStrategy::Split); - service - .confirm( - &preview.preview_id, - TransferPreviewChoice::Full, - |memo| async move { - assert_eq!(memo.total_value, 3); - Ok(()) - }, - ) - .await - .unwrap(); - let rows = coins.list().await.unwrap(); - assert_eq!( - rows.iter() - .find(|coin| coin.derivation_index == 100) - .unwrap() - .state, - crate::CoinState::Spent - ); - assert!( - rows.iter() - .any(|coin| coin.state == crate::CoinState::Spent && coin.derivation_index != 100) - ); - assert!( - rows.iter() - .any(|coin| coin.state == crate::CoinState::Available) - ); - assert_eq!( - wal.load_operation(&preview.preview_id).await.unwrap()[0].operation, - WalOperation::TransferCompleted - ); - } - - #[tokio::test] - async fn multi_group_unload_commits_success_and_keeps_ambiguous_group_reserved() { - let (service, _, vouchers, wal) = - service(vec![voucher(1, 1, 1), voucher(2, 0, 2)], HashSet::from([2])); - let preview = service.preview(3).await.unwrap(); - service - .confirm( - &preview.preview_id, - TransferPreviewChoice::Full, - |_| async { Ok(()) }, - ) - .await - .unwrap(); - let remaining = vouchers.list().await.unwrap(); - assert_eq!(remaining.len(), 1); - assert_eq!(remaining[0].derivation_index, 2); - assert_eq!(remaining[0].local_state, VoucherLocalState::PendingTransfer); - let entries = wal.load_operation(&preview.preview_id).await.unwrap(); - assert!( - entries - .iter() - .any(|entry| entry.operation == WalOperation::TransferAccepted) - ); - let unresolved = entries - .iter() - .find(|entry| entry.operation == WalOperation::IntoCoins) - .unwrap(); - assert_eq!(unresolved.payload.input_vouchers[0].derivation_index, 2); - assert!(matches!( - unresolved.checkpoint, - CheckpointBlock::Known { .. } - )); - } - - #[test] - fn spendable_voucher_snapshot_never_returns_false_empty_wallet() { - let inventory = vec![ - voucher(1, 10, 1), - voucher(2, 4, 2), - voucher(3, 4, 3), - voucher(4, 3, 4), - voucher(5, 1, 5), - voucher(6, 1, 6), - ]; - let selector = CoinSelector::new(context(), 100); - for amount in 1..=1_068 { - assert_ne!( - selector.select(amount, &[], &inventory, 1_000), - Err(CoinSelectionError::EmptyWallet), - "false empty wallet at amount {amount}" - ); - } - } - - /// Property sweep for the opaque boundary: confirmation must execute the - /// exact amount retained by preview, across every representable amount in - /// the source voucher. It must never reselect a different total. - #[tokio::test] - async fn preview_to_confirm_preserves_every_representable_amount() { - for amount in 1..=64_u128 { - let (service, _, _, _) = service(vec![voucher(1, 6, 1)], HashSet::new()); - let preview = service.preview(amount).await.unwrap(); - assert_eq!(preview.full_amount, amount); - service - .confirm( - &preview.preview_id, - TransferPreviewChoice::Full, - move |memo| async move { - assert_eq!(memo.total_value, amount); - Ok(()) - }, - ) - .await - .unwrap(); - } - } - - #[tokio::test] - async fn preview_rejects_a_changed_repository_snapshot() { - let inventory = vec![voucher(1, 10, 1)]; - let (service, _coins, vouchers, _) = service(inventory, HashSet::new()); - let preview = service.preview(100).await.unwrap(); - vouchers - .set_local_state(1, VoucherLocalState::PendingTransfer) - .await - .unwrap(); - assert_eq!( - service - .confirm( - &preview.preview_id, - TransferPreviewChoice::Full, - |_| async { Ok(()) } - ) - .await, - Err(RegularTransferError::BalanceChanged) - ); - } - - #[tokio::test] - async fn same_preview_confirmations_are_coalesced() { - let (service, _, _, _) = service(vec![voucher(1, 10, 1)], HashSet::new()); - let preview = service.preview(100).await.unwrap(); - let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let first = { - let service = Arc::clone(&service); - let calls = Arc::clone(&calls); - let id = preview.preview_id.clone(); - tokio::spawn(async move { - service - .confirm(&id, TransferPreviewChoice::Full, move |_| async move { - calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - tokio::task::yield_now().await; - Ok(()) - }) - .await - }) - }; - let second = service.confirm( - &preview.preview_id, - TransferPreviewChoice::Full, - |_| async { panic!("coalesced confirmation must not receive the memo") }, - ); - assert!(first.await.unwrap().is_ok()); - assert!(second.await.is_ok()); - assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); - } - - #[test] - fn diagnostics_contain_only_public_selection_state() { - let fixture = [ - voucher(7, 10, 9), - voucher(8, 4, 9), - voucher(9, 4, 9), - voucher(10, 3, 9), - voucher(11, 1, 9), - voucher(12, 1, 9), - ]; - let rows = voucher_selection_diagnostics(&fixture, 0); - assert_eq!(rows.len(), 6); - assert_eq!(rows[0].derivation_index, 7); - assert_eq!( - rows[0].remote_state, - VoucherRemoteState::InRecycler { recycler_index: 9 } - ); - assert_eq!(rows[0].effective_privacy, EffectivePrivacy::Full); - } - - fn restart(service: &RegularCoinTransferService) -> Arc { - Arc::new(RegularCoinTransferService::new( - &[0x33; 32], - RegularCoinTransferParts { - spawner: crate::test_spawner(), - coins: Arc::clone(&service.coins), - vouchers: Arc::clone(&service.vouchers), - wal: Arc::clone(&service.wal), - allocator: Arc::clone(&service.allocator), - submitter: Arc::clone(&service.submitter), - denominations: service.denominations.clone(), - max_consolidation: service.max_consolidation, - clock: Arc::clone(&service.clock), - session_generation: service.session_generation + 1, - committer: service.committer.clone(), - }, - )) - } - - #[tokio::test] - async fn restart_after_transport_acceptance_replays_same_allocations_once() { - let (service, coins, vouchers, wal) = service(vec![voucher(1, 3, 1)], HashSet::new()); - let preview = service.preview(3).await.unwrap(); - assert_eq!(preview.max_debit_amount, 8); - let (accepted, received) = tokio::sync::oneshot::channel(); - let transfer = { - let service = Arc::clone(&service); - tokio::spawn(async move { - service - .confirm_operation( - "host:payment-1", - &preview.preview_id, - TransferPreviewChoice::Full, - move |memo| async move { - accepted.send(memo.identifier()).unwrap(); - // Transport durably accepted but its acknowledgement - // has not returned when the process disappears. - std::future::pending::>().await - }, - ) - .await - }) - }; - let accepted_identifier = received.await.unwrap(); - let before = wal.load_operation("host:payment-1").await.unwrap(); - assert!( - before - .iter() - .any(|entry| entry.operation == WalOperation::TransferPrepared) - ); - assert!( - before - .iter() - .any(|entry| entry.operation == WalOperation::IntoCoins) - ); - assert_eq!( - vouchers.list().await.unwrap()[0].local_state, - VoucherLocalState::PendingTransfer - ); - transfer.abort(); - let _ = transfer.await; - let restarted = restart(&service); - restarted - .resume_operation("host:payment-1", move |memo| async move { - assert_eq!(memo.identifier(), accepted_identifier); - assert_eq!(memo.total_value, 3); - Ok(()) - }) - .await - .unwrap(); - assert!(vouchers.list().await.unwrap().is_empty()); - let after = coins.list().await.unwrap(); - assert_eq!( - after - .iter() - .filter(|coin| coin.state == CoinState::Available) - .map(|coin| context().value_in_planks(coin.exponent)) - .sum::(), - 5 - ); - let receipt = wal.load_operation("host:payment-1").await.unwrap(); - assert_eq!(receipt.len(), 1); - assert_eq!(receipt[0].operation, WalOperation::TransferCompleted); - assert_eq!( - receipt[0].payload.output_coins, - before - .iter() - .find(|entry| entry.operation == WalOperation::TransferPrepared) - .unwrap() - .payload - .output_coins - ); - restarted - .confirm_operation( - "host:payment-1", - "no-preview-after-restart", - TransferPreviewChoice::Full, - |_| async { panic!("completed operation must not hand off or debit again") }, - ) - .await - .unwrap(); - assert_eq!(coins.list().await.unwrap(), after); - } - - #[tokio::test] - async fn rejected_operation_keeps_identity_but_releases_only_its_inputs() { - let (service, _, vouchers, wal) = service(vec![voucher(1, 3, 1)], HashSet::new()); - let preview = service.preview(3).await.unwrap(); - assert_eq!( - service - .confirm_operation( - "rejected", - &preview.preview_id, - TransferPreviewChoice::Full, - |_| async { Err(()) } - ) - .await, - Err(RegularTransferError::HandoffRejected) - ); - assert_eq!( - vouchers.list().await.unwrap()[0].local_state, - VoucherLocalState::Available - ); - let restarted = restart(&service); - assert_eq!( - restarted - .resume_operation("rejected", |_| async { - panic!("rejected operation identity must not start a new debit") - }) - .await, - Err(RegularTransferError::HandoffRejected) - ); - let entries = wal.load_operation("rejected").await.unwrap(); - assert_eq!(entries.len(), 1); - assert_eq!(entries[0].operation, WalOperation::TransferRejected); - } - - #[tokio::test] - async fn exact_operation_preserves_receipt_without_reexporting_coin_secrets() { - let (service, coins, _, wal) = service(Vec::new(), HashSet::new()); - coins - .upsert(&Coin { - derivation_index: 90, - exponent: 2, - age: Some(1), - state: CoinState::Available, - }) - .await - .unwrap(); - let preview = service.preview(4).await.unwrap(); - let observed = Arc::clone(&wal); - service - .confirm_operation( - "exact", - &preview.preview_id, - TransferPreviewChoice::Full, - move |memo| async move { - let entries = observed.load_operation("exact").await.unwrap(); - let handoff = entries - .iter() - .find(|entry| entry.operation == WalOperation::SecretHandoff) - .unwrap(); - assert_eq!(handoff.payload.input_coins[0].derivation_index, 90); - assert_eq!(memo.total_value, 4); - Ok(()) - }, - ) - .await - .unwrap(); - assert_eq!(coins.list().await.unwrap()[0].state, CoinState::Spent); - restart(&service) - .resume_operation("exact", |_| async { - panic!("accepted exact-coin secret must not be handed out again") - }) - .await - .unwrap(); - assert_eq!( - wal.load_operation("exact").await.unwrap()[0].operation, - WalOperation::TransferCompleted - ); - } + use super::*; + use std::collections::HashSet; + + use crate::{ + balance::compute_balance, + clock::FixedClock, + index_store::InMemoryCoinageIndexStore, + model::{CoinState, VoucherLocalState, VoucherPrivacyLevel, VoucherRemoteState}, + repo::{InMemoryCoinRepository, InMemoryVoucherRepository}, + }; + + #[derive(Default)] + struct MemWal(Mutex>); + + #[async_trait] + impl WalStore for MemWal { + async fn save(&self, entry: &TransferWalEntry) -> Result<(), String> { + let mut entries = self.0.lock(); + entries.retain(|existing| existing.entry_id != entry.entry_id); + entries.push(entry.clone()); + Ok(()) + } + async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String> { + let mut stored = self.0.lock(); + stored.retain(|existing| { + !entries.iter().any(|entry| entry.entry_id == existing.entry_id) + }); + stored.extend_from_slice(entries); + Ok(()) + } + async fn update_checkpoint( + &self, + entry_id: &str, + checkpoint: CheckpointBlock, + ) -> Result<(), String> { + let mut entries = self.0.lock(); + entries + .iter_mut() + .find(|entry| entry.entry_id == entry_id) + .ok_or_else(|| "missing WAL".to_string())? + .checkpoint = checkpoint; + Ok(()) + } + async fn load_all(&self) -> Result, String> { + Ok(self.0.lock().clone()) + } + async fn delete(&self, entry_id: &str) -> Result<(), String> { + self.0.lock().retain(|entry| entry.entry_id != entry_id); + Ok(()) + } + } + + struct MockSubmitter { + wal: Arc, + fail_unload: HashSet, + } + + #[async_trait] + impl RegularTransferSubmitter for MockSubmitter { + async fn prepare_unload_groups( + &self, + groups: &[UnloadGroupDraft], + ) -> Result, String> { + Ok(groups + .iter() + .cloned() + .map(|draft| PreparedUnloadGroup { + recycler_revision: 1, + readiness_block_hash: [7; 32], + origin: UnloadOriginPreparation { + recycler_ring: RingProofParams { + ring_exponent: 9, + ring_index: draft.recycler.index, + ring_revision: 1, + ring_members: vec![[1; 32]], + }, + person_origin: PersonOriginKind::Lite, + people_ring: RingProofParams { + ring_exponent: 9, + ring_index: 2, + ring_revision: 1, + ring_members: vec![[2; 32]], + }, + token: ResolvedUnloadToken { period: 3, counter: draft.recycler.index }, + }, + draft, + }) + .collect()) + } + + async fn submit_split(&self, submission: &SplitTransferSubmission) -> Result<(), String> { + self.wal + .update_checkpoint( + &submission.wal_entry_id, + CheckpointBlock::Known { number: 10, hash: [9; 32] }, + ) + .await + } + + async fn submit_unload_group( + &self, + submission: &PreparedUnloadGroup, + ) -> Result<(), String> { + self.wal + .update_checkpoint( + &submission.draft.wal_entry_id, + CheckpointBlock::Known { number: 10, hash: [9; 32] }, + ) + .await?; + if self.fail_unload.contains(&submission.draft.recycler.index) { + Err("scripted ambiguous unload failure".into()) + } else { + Ok(()) + } + } + } + + fn context() -> DenominationBreakdownContext { + DenominationBreakdownContext { + asset_unit: 1, + max_exponent: 10, + min_exponent: 0, + precision: 2, + } + } + + fn voucher(index: u32, exponent: i16, recycler: u32) -> Voucher { + Voucher { + exponent, + derivation_index: index, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: VoucherRemoteState::InRecycler { recycler_index: recycler }, + local_state: VoucherLocalState::Available, + privacy: VoucherPrivacyLevel::Full, + } + } + + #[test] + fn selector_snapshot_is_aggregate_only_and_uses_value_digit_counts() { + let coins = vec![ + Coin { exponent: 2, derivation_index: 99, age: Some(1), state: CoinState::Available }, + Coin { exponent: 1, derivation_index: 100, age: Some(14), state: CoinState::Available }, + Coin { + exponent: 0, + derivation_index: 101, + age: Some(1), + state: CoinState::PendingTransfer, + }, + ]; + let mut ready = voucher(7, 3, 4); + ready.ready_at_ms = 0; + let mut locked = voucher(8, 1, 4); + locked.local_state = VoucherLocalState::PendingTransfer; + locked.privacy = VoucherPrivacyLevel::Degraded; + let diagnostic = selector_snapshot_diagnostic(&coins, &[ready, locked], &context(), 1_000); + assert_eq!(diagnostic.selectable_coins, 1); + assert_eq!(diagnostic.expiring_coins, 1); + assert_eq!(diagnostic.locked_coins, 2); + assert_eq!(diagnostic.unloadable_vouchers, 1); + assert_eq!(diagnostic.locked_vouchers, 1); + assert_eq!(diagnostic.full_vouchers, 1); + assert_eq!(diagnostic.degraded_vouchers, 1); + assert_eq!(diagnostic.selectable_coin_value_digits, 1); // value 4 + assert_eq!(diagnostic.unloadable_voucher_value_digits, 1); // value 8 + } + + fn service( + vouchers: Vec, + fail_unload: HashSet, + ) -> ( + Arc, + Arc, + Arc, + Arc, + ) { + service_with_context(vouchers, fail_unload, context()) + } + + fn service_with_context( + vouchers: Vec, + fail_unload: HashSet, + denominations: DenominationBreakdownContext, + ) -> ( + Arc, + Arc, + Arc, + Arc, + ) { + let coins = Arc::new(InMemoryCoinRepository::default()); + let vouchers = Arc::new(InMemoryVoucherRepository::with_vouchers(vouchers)); + let wal = Arc::new(MemWal::default()); + let submitter = Arc::new(MockSubmitter { wal: Arc::clone(&wal), fail_unload }); + let service = Arc::new(RegularCoinTransferService::new( + &[0x33; 32], + RegularCoinTransferParts { + spawner: crate::test_spawner(), + coins: Arc::clone(&coins) as Arc<_>, + vouchers: Arc::clone(&vouchers) as Arc<_>, + wal: Arc::clone(&wal) as Arc<_>, + allocator: Arc::new(CoinAllocator::new(Arc::new( + InMemoryCoinageIndexStore::default(), + ))), + submitter, + denominations, + max_consolidation: 100, + clock: Arc::new(FixedClock(1_000)), + session_generation: 4, + committer: None, + }, + )); + (service, coins, vouchers, wal) + } + + /// Native amounts stay in CASH cents while the selector stays in raw + /// asset planks. This regression covers real-scale CASH amounts and + /// proves the 10,000x boundary is applied before all three selector + /// strategies run. + #[tokio::test] + async fn native_cash_amounts_preview_at_six_decimal_asset_precision() { + let denominations = DenominationBreakdownContext { + asset_unit: 10_000, + max_exponent: 14, + min_exponent: 0, + precision: 6, + }; + // 2^14 + 2^11 + 2^10 + 2^9 + 2^5 = 20,000 cents = 200 CASH. + let inventory = vec![ + voucher(1, 14, 1), + voucher(2, 11, 2), + voucher(3, 10, 3), + voucher(4, 9, 4), + voucher(5, 5, 5), + ]; + let (service, _, _, _) = service_with_context(inventory, HashSet::new(), denominations); + + for (cash, cents, expected_planks) in [ + (1, 100, 1_000_000), + (10, 1_000, 10_000_000), + (100, 10_000, 100_000_000), + (200, 20_000, 200_000_000), + ] { + let planks = service.cash_cents_to_planks(cents).unwrap(); + assert_eq!(planks, expected_planks, "{cash} CASH conversion"); + let preview = service.preview(planks).await.unwrap(); + assert_eq!(preview.full_amount, expected_planks, "{cash} CASH preview"); + assert_eq!( + service.cash_cents_from_planks(preview.full_amount), + Some(cents), + "{cash} CASH projection" + ); + } + } + + #[tokio::test] + async fn six_voucher_balance_previews_and_confirms_one_cash() { + let inventory = vec![ + voucher(1, 10, 1), // 1024 + voucher(2, 4, 2), // 16 + voucher(3, 4, 3), // 16 + voucher(4, 3, 4), // 8 + voucher(5, 1, 5), // 2 + voucher(6, 1, 6), // 2 + ]; + assert_eq!(compute_balance(&[], &inventory, &context(), 1_000).total_planks(), 1_068); + let (service, _coins, vouchers, wal) = service(inventory, HashSet::new()); + let preview = service.preview(100).await.unwrap(); + assert_eq!(preview.strategy, TransferPreviewStrategy::UnloadIntoCoins); + assert_eq!(preview.full_amount, 100); + service + .confirm(&preview.preview_id, TransferPreviewChoice::Full, |memo| async move { + assert_eq!(memo.total_value, 100); + Ok(()) + }) + .await + .unwrap(); + assert_eq!(vouchers.list().await.unwrap().len(), 5); + assert_eq!( + wal.load_operation(&preview.preview_id).await.unwrap()[0].operation, + WalOperation::TransferCompleted + ); + } + + #[tokio::test] + async fn split_persists_change_retires_destination_and_preserves_receipt() { + let coins = Arc::new(InMemoryCoinRepository::with_coins([Coin { + exponent: 3, + derivation_index: 100, + age: Some(1), + state: crate::CoinState::Available, + }])); + let vouchers = Arc::new(InMemoryVoucherRepository::default()); + let wal = Arc::new(MemWal::default()); + let service = Arc::new(RegularCoinTransferService::new( + &[0x33; 32], + RegularCoinTransferParts { + spawner: crate::test_spawner(), + coins: Arc::clone(&coins) as Arc<_>, + vouchers, + wal: Arc::clone(&wal) as Arc<_>, + allocator: Arc::new(CoinAllocator::new(Arc::new( + InMemoryCoinageIndexStore::default(), + ))), + submitter: Arc::new(MockSubmitter { + wal: Arc::clone(&wal), + fail_unload: HashSet::new(), + }), + denominations: context(), + max_consolidation: 100, + clock: Arc::new(FixedClock(1_000)), + session_generation: 4, + committer: None, + }, + )); + let preview = service.preview(3).await.unwrap(); + assert_eq!(preview.strategy, TransferPreviewStrategy::Split); + service + .confirm(&preview.preview_id, TransferPreviewChoice::Full, |memo| async move { + assert_eq!(memo.total_value, 3); + Ok(()) + }) + .await + .unwrap(); + let rows = coins.list().await.unwrap(); + assert_eq!( + rows.iter().find(|coin| coin.derivation_index == 100).unwrap().state, + crate::CoinState::Spent + ); + assert!( + rows.iter() + .any(|coin| coin.state == crate::CoinState::Spent && coin.derivation_index != 100) + ); + assert!(rows.iter().any(|coin| coin.state == crate::CoinState::Available)); + assert_eq!( + wal.load_operation(&preview.preview_id).await.unwrap()[0].operation, + WalOperation::TransferCompleted + ); + } + + #[tokio::test] + async fn multi_group_unload_commits_success_and_keeps_ambiguous_group_reserved() { + let (service, _, vouchers, wal) = + service(vec![voucher(1, 1, 1), voucher(2, 0, 2)], HashSet::from([2])); + let preview = service.preview(3).await.unwrap(); + service + .confirm(&preview.preview_id, TransferPreviewChoice::Full, |_| async { Ok(()) }) + .await + .unwrap(); + let remaining = vouchers.list().await.unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].derivation_index, 2); + assert_eq!(remaining[0].local_state, VoucherLocalState::PendingTransfer); + let entries = wal.load_operation(&preview.preview_id).await.unwrap(); + assert!(entries.iter().any(|entry| entry.operation == WalOperation::TransferAccepted)); + let unresolved = + entries.iter().find(|entry| entry.operation == WalOperation::IntoCoins).unwrap(); + assert_eq!(unresolved.payload.input_vouchers[0].derivation_index, 2); + assert!(matches!(unresolved.checkpoint, CheckpointBlock::Known { .. })); + } + + #[test] + fn spendable_voucher_snapshot_never_returns_false_empty_wallet() { + let inventory = vec![ + voucher(1, 10, 1), + voucher(2, 4, 2), + voucher(3, 4, 3), + voucher(4, 3, 4), + voucher(5, 1, 5), + voucher(6, 1, 6), + ]; + let selector = CoinSelector::new(context(), 100); + for amount in 1..=1_068 { + assert_ne!( + selector.select(amount, &[], &inventory, 1_000), + Err(CoinSelectionError::EmptyWallet), + "false empty wallet at amount {amount}" + ); + } + } + + /// Property sweep for the opaque boundary: confirmation must execute the + /// exact amount retained by preview, across every representable amount in + /// the source voucher. It must never reselect a different total. + #[tokio::test] + async fn preview_to_confirm_preserves_every_representable_amount() { + for amount in 1..=64_u128 { + let (service, _, _, _) = service(vec![voucher(1, 6, 1)], HashSet::new()); + let preview = service.preview(amount).await.unwrap(); + assert_eq!(preview.full_amount, amount); + service + .confirm(&preview.preview_id, TransferPreviewChoice::Full, move |memo| async move { + assert_eq!(memo.total_value, amount); + Ok(()) + }) + .await + .unwrap(); + } + } + + #[tokio::test] + async fn preview_rejects_a_changed_repository_snapshot() { + let inventory = vec![voucher(1, 10, 1)]; + let (service, _coins, vouchers, _) = service(inventory, HashSet::new()); + let preview = service.preview(100).await.unwrap(); + vouchers.set_local_state(1, VoucherLocalState::PendingTransfer).await.unwrap(); + assert_eq!( + service + .confirm(&preview.preview_id, TransferPreviewChoice::Full, |_| async { Ok(()) }) + .await, + Err(RegularTransferError::BalanceChanged) + ); + } + + #[tokio::test] + async fn same_preview_confirmations_are_coalesced() { + let (service, _, _, _) = service(vec![voucher(1, 10, 1)], HashSet::new()); + let preview = service.preview(100).await.unwrap(); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let first = { + let service = Arc::clone(&service); + let calls = Arc::clone(&calls); + let id = preview.preview_id.clone(); + tokio::spawn(async move { + service + .confirm(&id, TransferPreviewChoice::Full, move |_| async move { + calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + tokio::task::yield_now().await; + Ok(()) + }) + .await + }) + }; + let second = service.confirm(&preview.preview_id, TransferPreviewChoice::Full, |_| async { + panic!("coalesced confirmation must not receive the memo") + }); + assert!(first.await.unwrap().is_ok()); + assert!(second.await.is_ok()); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[test] + fn diagnostics_contain_only_public_selection_state() { + let fixture = [ + voucher(7, 10, 9), + voucher(8, 4, 9), + voucher(9, 4, 9), + voucher(10, 3, 9), + voucher(11, 1, 9), + voucher(12, 1, 9), + ]; + let rows = voucher_selection_diagnostics(&fixture, 0); + assert_eq!(rows.len(), 6); + assert_eq!(rows[0].derivation_index, 7); + assert_eq!(rows[0].remote_state, VoucherRemoteState::InRecycler { recycler_index: 9 }); + assert_eq!(rows[0].effective_privacy, EffectivePrivacy::Full); + } + + fn restart(service: &RegularCoinTransferService) -> Arc { + Arc::new(RegularCoinTransferService::new( + &[0x33; 32], + RegularCoinTransferParts { + spawner: crate::test_spawner(), + coins: Arc::clone(&service.coins), + vouchers: Arc::clone(&service.vouchers), + wal: Arc::clone(&service.wal), + allocator: Arc::clone(&service.allocator), + submitter: Arc::clone(&service.submitter), + denominations: service.denominations.clone(), + max_consolidation: service.max_consolidation, + clock: Arc::clone(&service.clock), + session_generation: service.session_generation + 1, + committer: service.committer.clone(), + }, + )) + } + + #[tokio::test] + async fn restart_after_transport_acceptance_replays_same_allocations_once() { + let (service, coins, vouchers, wal) = service(vec![voucher(1, 3, 1)], HashSet::new()); + let preview = service.preview(3).await.unwrap(); + assert_eq!(preview.max_debit_amount, 8); + let (accepted, received) = tokio::sync::oneshot::channel(); + let transfer = { + let service = Arc::clone(&service); + tokio::spawn(async move { + service + .confirm_operation( + "host:payment-1", + &preview.preview_id, + TransferPreviewChoice::Full, + move |memo| async move { + accepted.send(memo.identifier()).unwrap(); + // Transport durably accepted but its acknowledgement + // has not returned when the process disappears. + std::future::pending::>().await + }, + ) + .await + }) + }; + let accepted_identifier = received.await.unwrap(); + let before = wal.load_operation("host:payment-1").await.unwrap(); + assert!(before.iter().any(|entry| entry.operation == WalOperation::TransferPrepared)); + assert!(before.iter().any(|entry| entry.operation == WalOperation::IntoCoins)); + assert_eq!( + vouchers.list().await.unwrap()[0].local_state, + VoucherLocalState::PendingTransfer + ); + transfer.abort(); + let _ = transfer.await; + let restarted = restart(&service); + restarted + .resume_operation("host:payment-1", move |memo| async move { + assert_eq!(memo.identifier(), accepted_identifier); + assert_eq!(memo.total_value, 3); + Ok(()) + }) + .await + .unwrap(); + assert!(vouchers.list().await.unwrap().is_empty()); + let after = coins.list().await.unwrap(); + assert_eq!( + after + .iter() + .filter(|coin| coin.state == CoinState::Available) + .map(|coin| context().value_in_planks(coin.exponent)) + .sum::(), + 5 + ); + let receipt = wal.load_operation("host:payment-1").await.unwrap(); + assert_eq!(receipt.len(), 1); + assert_eq!(receipt[0].operation, WalOperation::TransferCompleted); + assert_eq!( + receipt[0].payload.output_coins, + before + .iter() + .find(|entry| entry.operation == WalOperation::TransferPrepared) + .unwrap() + .payload + .output_coins + ); + restarted + .confirm_operation( + "host:payment-1", + "no-preview-after-restart", + TransferPreviewChoice::Full, + |_| async { panic!("completed operation must not hand off or debit again") }, + ) + .await + .unwrap(); + assert_eq!(coins.list().await.unwrap(), after); + } + + #[tokio::test] + async fn rejected_operation_keeps_identity_but_releases_only_its_inputs() { + let (service, _, vouchers, wal) = service(vec![voucher(1, 3, 1)], HashSet::new()); + let preview = service.preview(3).await.unwrap(); + assert_eq!( + service + .confirm_operation( + "rejected", + &preview.preview_id, + TransferPreviewChoice::Full, + |_| async { Err(()) } + ) + .await, + Err(RegularTransferError::HandoffRejected) + ); + assert_eq!(vouchers.list().await.unwrap()[0].local_state, VoucherLocalState::Available); + let restarted = restart(&service); + assert_eq!( + restarted + .resume_operation("rejected", |_| async { + panic!("rejected operation identity must not start a new debit") + }) + .await, + Err(RegularTransferError::HandoffRejected) + ); + let entries = wal.load_operation("rejected").await.unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].operation, WalOperation::TransferRejected); + } + + #[tokio::test] + async fn exact_operation_preserves_receipt_without_reexporting_coin_secrets() { + let (service, coins, _, wal) = service(Vec::new(), HashSet::new()); + coins + .upsert(&Coin { + derivation_index: 90, + exponent: 2, + age: Some(1), + state: CoinState::Available, + }) + .await + .unwrap(); + let preview = service.preview(4).await.unwrap(); + let observed = Arc::clone(&wal); + service + .confirm_operation( + "exact", + &preview.preview_id, + TransferPreviewChoice::Full, + move |memo| async move { + let entries = observed.load_operation("exact").await.unwrap(); + let handoff = entries + .iter() + .find(|entry| entry.operation == WalOperation::SecretHandoff) + .unwrap(); + assert_eq!(handoff.payload.input_coins[0].derivation_index, 90); + assert_eq!(memo.total_value, 4); + Ok(()) + }, + ) + .await + .unwrap(); + assert_eq!(coins.list().await.unwrap()[0].state, CoinState::Spent); + restart(&service) + .resume_operation("exact", |_| async { + panic!("accepted exact-coin secret must not be handed out again") + }) + .await + .unwrap(); + assert_eq!( + wal.load_operation("exact").await.unwrap()[0].operation, + WalOperation::TransferCompleted + ); + } } diff --git a/rust/crates/truapi-coinage/src/tx_extensions.rs b/rust/crates/truapi-coinage/src/tx_extensions.rs index 0175181480..928b085f3a 100644 --- a/rust/crates/truapi-coinage/src/tx_extensions.rs +++ b/rust/crates/truapi-coinage/src/tx_extensions.rs @@ -9,43 +9,33 @@ use parity_scale_codec::{Decode, Encode}; pub struct AsCoinage(pub Option); impl AsCoinage { - pub const IDENTIFIER: &'static str = "AsCoinage"; + pub const IDENTIFIER: &'static str = "AsCoinage"; - pub const fn as_coin() -> Self { - Self(Some(AsCoinageInfo::AsCoin)) - } + pub const fn as_coin() -> Self { + Self(Some(AsCoinageInfo::AsCoin)) + } - pub const fn infallible_unpaid_signed(nonce: u32) -> Self { - Self(Some(AsCoinageInfo::InfallibleUnpaidSigned(nonce))) - } + pub const fn infallible_unpaid_signed(nonce: u32) -> Self { + Self(Some(AsCoinageInfo::InfallibleUnpaidSigned(nonce))) + } - pub fn unload_token_people( - proof: CoinagePeopleProof, - period: u32, - counter: u32, - alias_proofs: Vec>, - ) -> Self { - Self(Some(AsCoinageInfo::AsUnloadTokenPeople { - proof, - period, - counter, - alias_proofs, - })) - } + pub fn unload_token_people( + proof: CoinagePeopleProof, + period: u32, + counter: u32, + alias_proofs: Vec>, + ) -> Self { + Self(Some(AsCoinageInfo::AsUnloadTokenPeople { proof, period, counter, alias_proofs })) + } - pub fn unload_token_lite_people( - proof: CoinagePeopleProof, - period: u32, - counter: u32, - alias_proofs: Vec>, - ) -> Self { - Self(Some(AsCoinageInfo::AsUnloadTokenLitePeople { - proof, - period, - counter, - alias_proofs, - })) - } + pub fn unload_token_lite_people( + proof: CoinagePeopleProof, + period: u32, + counter: u32, + alias_proofs: Vec>, + ) -> Self { + Self(Some(AsCoinageInfo::AsUnloadTokenLitePeople { proof, period, counter, alias_proofs })) + } } /// The People-ring half of the Coinage unload-token proof @@ -54,129 +44,113 @@ impl AsCoinage { /// 1000032) is the ring revision the proof was built against. #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct CoinagePeopleProof { - pub proof: Vec, - pub ring: u32, - pub revision: u32, + pub proof: Vec, + pub ring: u32, + pub revision: u32, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub enum AsCoinageInfo { - /// Dispatch as the sr25519 coin which signed the extrinsic. - #[codec(index = 0)] - AsCoin, - /// Full-person free unload token. - #[codec(index = 1)] - AsUnloadTokenPeople { - proof: CoinagePeopleProof, - period: u32, - counter: u32, - alias_proofs: Vec>, - }, - /// Lite-person free unload token. - #[codec(index = 2)] - AsUnloadTokenLitePeople { - proof: CoinagePeopleProof, - period: u32, - counter: u32, - alias_proofs: Vec>, - }, - /// Paid unload-token ring proof. - #[codec(index = 3)] - AsUnloadTokenPaid { - proof: Vec, - period: u32, - paid_token_ring_index: u32, - paid_token_ring_revision: u32, - alias_proofs: Vec>, - }, - /// A fee-recycler output used as the unload token. `retry_counter` - /// joined in the 2026-08 runtime (spec 1000032). - #[codec(index = 4)] - AsUnloadTokenFromOutput { - fee_recycler_value: i8, - fee_recycler_index: u32, - fee_recycler_revision: u32, - retry_counter: u8, - alias_proofs: Vec>, - }, - #[codec(index = 5)] - InfallibleUnpaidSigned(u32), + /// Dispatch as the sr25519 coin which signed the extrinsic. + #[codec(index = 0)] + AsCoin, + /// Full-person free unload token. + #[codec(index = 1)] + AsUnloadTokenPeople { + proof: CoinagePeopleProof, + period: u32, + counter: u32, + alias_proofs: Vec>, + }, + /// Lite-person free unload token. + #[codec(index = 2)] + AsUnloadTokenLitePeople { + proof: CoinagePeopleProof, + period: u32, + counter: u32, + alias_proofs: Vec>, + }, + /// Paid unload-token ring proof. + #[codec(index = 3)] + AsUnloadTokenPaid { + proof: Vec, + period: u32, + paid_token_ring_index: u32, + paid_token_ring_revision: u32, + alias_proofs: Vec>, + }, + /// A fee-recycler output used as the unload token. `retry_counter` + /// joined in the 2026-08 runtime (spec 1000032). + #[codec(index = 4)] + AsUnloadTokenFromOutput { + fee_recycler_value: i8, + fee_recycler_index: u32, + fee_recycler_revision: u32, + retry_counter: u8, + alias_proofs: Vec>, + }, + #[codec(index = 5)] + InfallibleUnpaidSigned(u32), } #[cfg(test)] mod tests { - use super::*; - /// `AsCoinage(None)` is the metadata default. Coin-origin calls opt in - /// with `Some(AsCoin)`: option tag 1 followed by enum variant 0. - #[test] - fn as_coinage_as_coin_encoding_is_pinned() { - assert_eq!(AsCoinage(None).encode(), vec![0]); - assert_eq!(AsCoinage::as_coin().encode(), vec![1, 0]); - assert_eq!( - AsCoinage::decode(&mut AsCoinage::as_coin().encode().as_slice()).unwrap(), - AsCoinage::as_coin() - ); - } + use super::*; + /// `AsCoinage(None)` is the metadata default. Coin-origin calls opt in + /// with `Some(AsCoin)`: option tag 1 followed by enum variant 0. + #[test] + fn as_coinage_as_coin_encoding_is_pinned() { + assert_eq!(AsCoinage(None).encode(), vec![0]); + assert_eq!(AsCoinage::as_coin().encode(), vec![1, 0]); + assert_eq!( + AsCoinage::decode(&mut AsCoinage::as_coin().encode().as_slice()).unwrap(), + AsCoinage::as_coin() + ); + } - #[test] - fn as_coinage_infallible_unpaid_signed_encoding_is_pinned() { - assert_eq!( - AsCoinage::infallible_unpaid_signed(7).encode(), - vec![1, 5, 7, 0, 0, 0] - ); - assert_eq!( - AsCoinage::decode(&mut AsCoinage::infallible_unpaid_signed(7).encode().as_slice()) - .unwrap(), - AsCoinage::infallible_unpaid_signed(7) - ); - } + #[test] + fn as_coinage_infallible_unpaid_signed_encoding_is_pinned() { + assert_eq!(AsCoinage::infallible_unpaid_signed(7).encode(), vec![1, 5, 7, 0, 0, 0]); + assert_eq!( + AsCoinage::decode(&mut AsCoinage::infallible_unpaid_signed(7).encode().as_slice()) + .unwrap(), + AsCoinage::infallible_unpaid_signed(7) + ); + } - #[test] - fn as_coinage_people_unload_encoding_is_pinned() { - let extension = AsCoinage::unload_token_people( - CoinagePeopleProof { - proof: vec![0xAA, 0xBB], - ring: 7, - revision: 3, - }, - 9, - 2, - vec![vec![0x11], vec![0x22, 0x33]], - ); - // Option::Some, variant 1, compact proof len, proof, ring, revision, - // period, counter, compact alias-proof count and one compact length - // each. - assert_eq!( - extension.encode(), - vec![ - 1, 1, 8, 0xAA, 0xBB, 7, 0, 0, 0, 3, 0, 0, 0, 9, 0, 0, 0, 2, 0, 0, 0, 8, 4, 0x11, 8, - 0x22, 0x33, - ] - ); - assert_eq!( - AsCoinage::decode(&mut extension.encode().as_slice()).unwrap(), - extension - ); - } + #[test] + fn as_coinage_people_unload_encoding_is_pinned() { + let extension = AsCoinage::unload_token_people( + CoinagePeopleProof { proof: vec![0xAA, 0xBB], ring: 7, revision: 3 }, + 9, + 2, + vec![vec![0x11], vec![0x22, 0x33]], + ); + // Option::Some, variant 1, compact proof len, proof, ring, revision, + // period, counter, compact alias-proof count and one compact length + // each. + assert_eq!( + extension.encode(), + vec![ + 1, 1, 8, 0xAA, 0xBB, 7, 0, 0, 0, 3, 0, 0, 0, 9, 0, 0, 0, 2, 0, 0, 0, 8, 4, 0x11, 8, + 0x22, 0x33, + ] + ); + assert_eq!(AsCoinage::decode(&mut extension.encode().as_slice()).unwrap(), extension); + } - /// `retry_counter` sits between the recycler revision and the alias - /// proofs (2026-08 runtime). - #[test] - fn as_coinage_from_output_encoding_is_pinned() { - let extension = AsCoinage(Some(AsCoinageInfo::AsUnloadTokenFromOutput { - fee_recycler_value: -2, - fee_recycler_index: 5, - fee_recycler_revision: 9, - retry_counter: 4, - alias_proofs: vec![vec![0x77]], - })); - assert_eq!( - extension.encode(), - vec![1, 4, 0xFE, 5, 0, 0, 0, 9, 0, 0, 0, 4, 4, 4, 0x77] - ); - assert_eq!( - AsCoinage::decode(&mut extension.encode().as_slice()).unwrap(), - extension - ); - } + /// `retry_counter` sits between the recycler revision and the alias + /// proofs (2026-08 runtime). + #[test] + fn as_coinage_from_output_encoding_is_pinned() { + let extension = AsCoinage(Some(AsCoinageInfo::AsUnloadTokenFromOutput { + fee_recycler_value: -2, + fee_recycler_index: 5, + fee_recycler_revision: 9, + retry_counter: 4, + alias_proofs: vec![vec![0x77]], + })); + assert_eq!(extension.encode(), vec![1, 4, 0xFE, 5, 0, 0, 0, 9, 0, 0, 0, 4, 4, 4, 0x77]); + assert_eq!(AsCoinage::decode(&mut extension.encode().as_slice()).unwrap(), extension); + } } diff --git a/rust/crates/truapi-coinage/src/voucher_location.rs b/rust/crates/truapi-coinage/src/voucher_location.rs index cbd6a9dade..6729663f3c 100644 --- a/rust/crates/truapi-coinage/src/voucher_location.rs +++ b/rust/crates/truapi-coinage/src/voucher_location.rs @@ -2,31 +2,36 @@ // Derived from paritytech/brevity-dozer, core/crates/brevity-coinage. // Copyright the Brevity contributors. See NOTICE and LICENSE in this crate. -use std::collections::{HashMap, HashSet}; -use {parking_lot::Mutex, std::sync::Arc}; +use parking_lot::Mutex; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use async_trait::async_trait; use futures::future::AbortHandle; use tokio::sync::mpsc; use tracing::{debug, warn}; -use crate::model::{Voucher, VoucherPrivacyLevel, VoucherRemoteState, ring_readiness_upgraded}; -use crate::repo::VoucherRepository; +use crate::{ + model::{Voucher, VoucherPrivacyLevel, VoucherRemoteState, ring_readiness_upgraded}, + repo::VoucherRepository, +}; /// A member's on-chain ring position (`Members.Members` decode). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RingPosition { - /// Membership submitted, no ring slot yet. - Onboarding, - /// Assigned to ring `ring_index` at slot `included_at`. - Included { ring_index: u32, included_at: u32 }, + /// Membership submitted, no ring slot yet. + Onboarding, + /// Assigned to ring `ring_index` at slot `included_at`. + Included { ring_index: u32, included_at: u32 }, } /// A ring's key status (`Members.RingKeysStatus` decode). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RingStatus { - /// How many member keys the ring has actually included. - pub included_members: u32, + /// How many member keys the ring has actually included. + pub included_members: u32, } /// One partial emission from the batched subscription. Both vectors are @@ -34,8 +39,8 @@ pub struct RingStatus { /// entry disappeared. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct VoucherLocationUpdate { - pub ring_positions: Vec<(u32, Option)>, - pub ring_statuses: Vec<(u32, RingStatus)>, + pub ring_positions: Vec<(u32, Option)>, + pub ring_statuses: Vec<(u32, RingStatus)>, } /// The chain-subscription effect: ONE batched storage subscription @@ -44,804 +49,724 @@ pub struct VoucherLocationUpdate { /// stops emitting once dropped). #[async_trait] pub trait VoucherLocationSubscriber: Send + Sync { - /// `pending` — derivation indices still needing a location (not in a - /// recycler); `included` — accumulated included positions as - /// `(derivation_index, ring_index)`; `degraded` — degraded - /// in-recycler vouchers as `(derivation_index, recycler_index)`. - async fn subscribe( - &self, - pending: Vec, - included: Vec<(u32, u32)>, - degraded: Vec<(u32, u32)>, - ) -> Result, String>; + /// `pending` — derivation indices still needing a location (not in a + /// recycler); `included` — accumulated included positions as + /// `(derivation_index, ring_index)`; `degraded` — degraded + /// in-recycler vouchers as `(derivation_index, recycler_index)`. + async fn subscribe( + &self, + pending: Vec, + included: Vec<(u32, u32)>, + degraded: Vec<(u32, u32)>, + ) -> Result, String>; } #[derive(Default)] struct LocationState { - /// The baseline: what the LIVE subscription covers. - subscribed_indices: HashSet, - /// Included positions seen so far (non-included ones are removed). - positions: HashMap, - /// Ring statuses seen so far. - statuses: HashMap, + /// The baseline: what the LIVE subscription covers. + subscribed_indices: HashSet, + /// Included positions seen so far (non-included ones are removed). + positions: HashMap, + /// Ring statuses seen so far. + statuses: HashMap, } /// The service. `sync` (re)builds the subscription from current local /// vouchers; call it at startup and after voucher saves. `stop` tears /// the subscription down. pub struct VoucherLocationService { - spawner: crate::Spawner, - vouchers: Arc, - chain: Arc, - state: Mutex, - task: Mutex>, + spawner: crate::Spawner, + vouchers: Arc, + chain: Arc, + state: Mutex, + task: Mutex>, } impl VoucherLocationService { - pub fn new( - vouchers: Arc, - chain: Arc, - spawner: crate::Spawner, - ) -> Self { - Self { - vouchers, - chain, - state: Mutex::new(LocationState::default()), - spawner, - task: Mutex::new(None), - } - } - - /// (Re)builds the batched subscription: prune accumulated state to - /// subscribe the three families. With nothing to watch, the live - /// subscription is torn down. - pub async fn sync(self: &Arc) -> Result<(), String> { - let vouchers = self.vouchers.list().await?; - let pending: Vec = vouchers - .iter() - .filter(|v| !v.remote_state.is_in_recycler()) - .map(|v| v.derivation_index) - .collect(); - let degraded: Vec<(u32, u32)> = vouchers - .iter() - .filter_map(|v| match v.remote_state { - VoucherRemoteState::InRecycler { recycler_index } - if v.privacy == VoucherPrivacyLevel::Degraded => - { - Some((v.derivation_index, recycler_index)) - } - _ => None, - }) - .collect(); - - let included: Vec<(u32, u32)> = { - let mut state = self.state.lock(); - let current: HashSet = pending.iter().copied().collect(); - state.positions.retain(|index, _| current.contains(index)); - state.statuses.retain(|index, _| current.contains(index)); - // The baseline reflects exactly what this batch subscribes. - state.subscribed_indices = state.positions.keys().copied().collect(); - state - .positions - .iter() - .filter_map(|(index, position)| match position { - RingPosition::Included { ring_index, .. } => Some((*index, *ring_index)), - RingPosition::Onboarding => None, - }) - .collect() - }; - - if pending.is_empty() && degraded.is_empty() { - self.stop(); - return Ok(()); - } - - let receiver = self.chain.subscribe(pending, included, degraded).await?; - self.replace_task(receiver); - Ok(()) - } - - /// Tears down the live subscription and resets accumulated state. - pub fn stop(&self) { - if let Some(handle) = self.task.lock().take() { - handle.abort(); - } - *self.state.lock() = LocationState::default(); - } - - fn replace_task(self: &Arc, mut receiver: mpsc::Receiver) { - let service = Arc::clone(self); - let handle = crate::tasks::spawn_abortable(&self.spawner, async move { - while let Some(update) = receiver.recv().await { - match service.handle_update(update).await { - Ok(true) => { - let service = Arc::clone(&service); - crate::tasks::spawn_abortable(&service.spawner.clone(), async move { - if let Err(error) = service.sync().await { - warn!(error, "voucher location resubscription failed"); - } - }); - return; - } - Ok(false) => {} - Err(error) => warn!(error, "voucher location update failed"), - } - } - }); - let previous = self.task.lock().replace(handle); - if let Some(previous) = previous { - previous.abort(); - } - } - - /// One emission. Resolves `true` when a resubscription is needed - /// (and the emission was deliberately not applied). - async fn handle_update(&self, update: VoucherLocationUpdate) -> Result { - let requires_resubscription = { - let mut state = self.state.lock(); - for (index, position) in &update.ring_positions { - match position { - Some(position @ RingPosition::Included { .. }) => { - state.positions.insert(*index, *position); - } - _ => { - state.positions.remove(index); - } - } - } - for (index, status) in &update.ring_statuses { - state.statuses.insert(*index, *status); - } - let accumulated: HashSet = state.positions.keys().copied().collect(); - accumulated != state.subscribed_indices - }; - - let voucher_map: HashMap = self - .vouchers - .list() - .await? - .into_iter() - .map(|v| (v.derivation_index, v)) - .collect(); - let mut updates: HashMap = HashMap::new(); - - let (positions, statuses) = { - let state = self.state.lock(); - (state.positions.clone(), state.statuses.clone()) - }; - let waiting_for_status = positions - .keys() - .filter(|index| !statuses.contains_key(index)) - .count(); - let waiting_for_coverage = positions - .iter() - .filter(|(index, position)| { - let RingPosition::Included { included_at, .. } = position else { - return false; - }; - statuses - .get(index) - .is_some_and(|status| status.included_members <= *included_at) - }) - .count(); - if requires_resubscription { - log_reconciliation_summary( - &voucher_map, - positions.len(), - waiting_for_status, - waiting_for_coverage, - 0, - 0, - true, - ); - return Ok(true); - } - - // Pass A — positions from THIS emission, statuses possibly - // accumulated earlier. - for (index, position) in &update.ring_positions { - let Some(voucher) = updates - .get(index) - .cloned() - .or_else(|| voucher_map.get(index).cloned()) - else { - continue; - }; - match position { - Some(RingPosition::Included { - ring_index, - included_at, - }) => { - // Deferred until the ring status covers the slot. - let Some(status) = statuses.get(index) else { - continue; - }; - if status.included_members > *included_at { - updates.insert( - *index, - committed(voucher, *ring_index, status.included_members), - ); - } - } - // Present but not included (or gone) → onboarding. - _ => { - let mut voucher = voucher; - voucher.remote_state = VoucherRemoteState::Onboarding; - updates.insert(*index, voucher); - } - } - } - - // Pass B — statuses from THIS emission, positions possibly - // accumulated earlier; also upgrades degraded in-recycler - for (index, status) in &update.ring_statuses { - let Some(voucher) = updates - .get(index) - .cloned() - .or_else(|| voucher_map.get(index).cloned()) - else { - continue; - }; - match (voucher.remote_state, positions.get(index)) { - // Pending voucher whose position accumulated earlier. - ( - _, - Some(RingPosition::Included { - ring_index, - included_at, - }), - ) if !voucher.remote_state.is_in_recycler() => { - if status.included_members > *included_at { - updates.insert( - *index, - committed(voucher, *ring_index, status.included_members), - ); - } - } - // Degraded in-recycler voucher: readiness upgrade only. - (VoucherRemoteState::InRecycler { .. }, _) - if voucher.privacy == VoucherPrivacyLevel::Degraded - && ring_readiness_upgraded(status.included_members) => - { - let mut voucher = voucher; - voucher.privacy = VoucherPrivacyLevel::Full; - updates.insert(*index, voucher); - } - _ => {} - } - } - - let mut location_updates = 0usize; - let mut privacy_updates = 0usize; - for (index, voucher) in &updates { - // Only remote_state/privacy changed above; skip no-ops so a - // repeated emission does not rewrite rows. - let Some(previous) = voucher_map.get(index) else { - continue; - }; - if previous == voucher { - continue; - } - if previous.privacy == voucher.privacy { - self.vouchers - .set_remote_state(*index, voucher.remote_state) - .await?; - location_updates += 1; - } else { - // Ring readiness changes privacy as well as location. - self.vouchers.upsert(voucher).await?; - if previous.remote_state != voucher.remote_state { - location_updates += 1; - } - if previous.privacy != voucher.privacy { - privacy_updates += 1; - } - } - } - log_reconciliation_summary( - &voucher_map, - positions.len(), - waiting_for_status, - waiting_for_coverage, - location_updates, - privacy_updates, - false, - ); - Ok(false) - } + pub fn new( + vouchers: Arc, + chain: Arc, + spawner: crate::Spawner, + ) -> Self { + Self { + vouchers, + chain, + state: Mutex::new(LocationState::default()), + spawner, + task: Mutex::new(None), + } + } + + /// (Re)builds the batched subscription: prune accumulated state to + /// subscribe the three families. With nothing to watch, the live + /// subscription is torn down. + pub async fn sync(self: &Arc) -> Result<(), String> { + let vouchers = self.vouchers.list().await?; + let pending: Vec = vouchers + .iter() + .filter(|v| !v.remote_state.is_in_recycler()) + .map(|v| v.derivation_index) + .collect(); + let degraded: Vec<(u32, u32)> = vouchers + .iter() + .filter_map(|v| match v.remote_state { + VoucherRemoteState::InRecycler { recycler_index } + if v.privacy == VoucherPrivacyLevel::Degraded => + { + Some((v.derivation_index, recycler_index)) + }, + _ => None, + }) + .collect(); + + let included: Vec<(u32, u32)> = { + let mut state = self.state.lock(); + let current: HashSet = pending.iter().copied().collect(); + state.positions.retain(|index, _| current.contains(index)); + state.statuses.retain(|index, _| current.contains(index)); + // The baseline reflects exactly what this batch subscribes. + state.subscribed_indices = state.positions.keys().copied().collect(); + state + .positions + .iter() + .filter_map(|(index, position)| match position { + RingPosition::Included { ring_index, .. } => Some((*index, *ring_index)), + RingPosition::Onboarding => None, + }) + .collect() + }; + + if pending.is_empty() && degraded.is_empty() { + self.stop(); + return Ok(()); + } + + let receiver = self.chain.subscribe(pending, included, degraded).await?; + self.replace_task(receiver); + Ok(()) + } + + /// Tears down the live subscription and resets accumulated state. + pub fn stop(&self) { + if let Some(handle) = self.task.lock().take() { + handle.abort(); + } + *self.state.lock() = LocationState::default(); + } + + fn replace_task(self: &Arc, mut receiver: mpsc::Receiver) { + let service = Arc::clone(self); + let handle = crate::tasks::spawn_abortable(&self.spawner, async move { + while let Some(update) = receiver.recv().await { + match service.handle_update(update).await { + Ok(true) => { + let service = Arc::clone(&service); + crate::tasks::spawn_abortable(&service.spawner.clone(), async move { + if let Err(error) = service.sync().await { + warn!(error, "voucher location resubscription failed"); + } + }); + return; + }, + Ok(false) => {}, + Err(error) => warn!(error, "voucher location update failed"), + } + } + }); + let previous = self.task.lock().replace(handle); + if let Some(previous) = previous { + previous.abort(); + } + } + + /// One emission. Resolves `true` when a resubscription is needed + /// (and the emission was deliberately not applied). + async fn handle_update(&self, update: VoucherLocationUpdate) -> Result { + let requires_resubscription = { + let mut state = self.state.lock(); + for (index, position) in &update.ring_positions { + match position { + Some(position @ RingPosition::Included { .. }) => { + state.positions.insert(*index, *position); + }, + _ => { + state.positions.remove(index); + }, + } + } + for (index, status) in &update.ring_statuses { + state.statuses.insert(*index, *status); + } + let accumulated: HashSet = state.positions.keys().copied().collect(); + accumulated != state.subscribed_indices + }; + + let voucher_map: HashMap = self + .vouchers + .list() + .await? + .into_iter() + .map(|v| (v.derivation_index, v)) + .collect(); + let mut updates: HashMap = HashMap::new(); + + let (positions, statuses) = { + let state = self.state.lock(); + (state.positions.clone(), state.statuses.clone()) + }; + let waiting_for_status = + positions.keys().filter(|index| !statuses.contains_key(index)).count(); + let waiting_for_coverage = positions + .iter() + .filter(|(index, position)| { + let RingPosition::Included { included_at, .. } = position else { + return false; + }; + statuses + .get(index) + .is_some_and(|status| status.included_members <= *included_at) + }) + .count(); + if requires_resubscription { + log_reconciliation_summary( + &voucher_map, + positions.len(), + waiting_for_status, + waiting_for_coverage, + 0, + 0, + true, + ); + return Ok(true); + } + + // Pass A — positions from THIS emission, statuses possibly + // accumulated earlier. + for (index, position) in &update.ring_positions { + let Some(voucher) = + updates.get(index).cloned().or_else(|| voucher_map.get(index).cloned()) + else { + continue; + }; + match position { + Some(RingPosition::Included { ring_index, included_at }) => { + // Deferred until the ring status covers the slot. + let Some(status) = statuses.get(index) else { + continue; + }; + if status.included_members > *included_at { + updates.insert( + *index, + committed(voucher, *ring_index, status.included_members), + ); + } + }, + // Present but not included (or gone) → onboarding. + _ => { + let mut voucher = voucher; + voucher.remote_state = VoucherRemoteState::Onboarding; + updates.insert(*index, voucher); + }, + } + } + + // Pass B — statuses from THIS emission, positions possibly + // accumulated earlier; also upgrades degraded in-recycler + for (index, status) in &update.ring_statuses { + let Some(voucher) = + updates.get(index).cloned().or_else(|| voucher_map.get(index).cloned()) + else { + continue; + }; + match (voucher.remote_state, positions.get(index)) { + // Pending voucher whose position accumulated earlier. + (_, Some(RingPosition::Included { ring_index, included_at })) + if !voucher.remote_state.is_in_recycler() => + { + if status.included_members > *included_at { + updates.insert( + *index, + committed(voucher, *ring_index, status.included_members), + ); + } + }, + // Degraded in-recycler voucher: readiness upgrade only. + (VoucherRemoteState::InRecycler { .. }, _) + if voucher.privacy == VoucherPrivacyLevel::Degraded && + ring_readiness_upgraded(status.included_members) => + { + let mut voucher = voucher; + voucher.privacy = VoucherPrivacyLevel::Full; + updates.insert(*index, voucher); + }, + _ => {}, + } + } + + let mut location_updates = 0usize; + let mut privacy_updates = 0usize; + for (index, voucher) in &updates { + // Only remote_state/privacy changed above; skip no-ops so a + // repeated emission does not rewrite rows. + let Some(previous) = voucher_map.get(index) else { + continue; + }; + if previous == voucher { + continue; + } + if previous.privacy == voucher.privacy { + self.vouchers.set_remote_state(*index, voucher.remote_state).await?; + location_updates += 1; + } else { + // Ring readiness changes privacy as well as location. + self.vouchers.upsert(voucher).await?; + if previous.remote_state != voucher.remote_state { + location_updates += 1; + } + if previous.privacy != voucher.privacy { + privacy_updates += 1; + } + } + } + log_reconciliation_summary( + &voucher_map, + positions.len(), + waiting_for_status, + waiting_for_coverage, + location_updates, + privacy_updates, + false, + ); + Ok(false) + } } fn log_reconciliation_summary( - vouchers: &HashMap, - tracked_positions: usize, - waiting_for_status: usize, - waiting_for_coverage: usize, - location_changes: usize, - privacy_changes: usize, - resubscription_required: bool, + vouchers: &HashMap, + tracked_positions: usize, + waiting_for_status: usize, + waiting_for_coverage: usize, + location_changes: usize, + privacy_changes: usize, + resubscription_required: bool, ) { - let tracked_total = vouchers.len(); - let in_recycler_total = vouchers - .values() - .filter(|voucher| voucher.remote_state.is_in_recycler()) - .count(); - let pending_location_total = tracked_total.saturating_sub(in_recycler_total); - let degraded_total = vouchers - .values() - .filter(|voucher| voucher.privacy == VoucherPrivacyLevel::Degraded) - .count(); - debug!( - tracked_total, - in_recycler_total, - pending_location_total, - degraded_total, - waiting_for_status, - waiting_for_coverage, - location_changes, - privacy_changes, - tracked_positions, - resubscription_required, - changes_scope = "current_emission", - "coinage voucher location emission reconciled" - ); + let tracked_total = vouchers.len(); + let in_recycler_total = vouchers + .values() + .filter(|voucher| voucher.remote_state.is_in_recycler()) + .count(); + let pending_location_total = tracked_total.saturating_sub(in_recycler_total); + let degraded_total = vouchers + .values() + .filter(|voucher| voucher.privacy == VoucherPrivacyLevel::Degraded) + .count(); + debug!( + tracked_total, + in_recycler_total, + pending_location_total, + degraded_total, + waiting_for_status, + waiting_for_coverage, + location_changes, + privacy_changes, + tracked_positions, + resubscription_required, + changes_scope = "current_emission", + "coinage voucher location emission reconciled" + ); } fn committed(mut voucher: Voucher, ring_index: u32, included_members: u32) -> Voucher { - voucher.remote_state = VoucherRemoteState::InRecycler { - recycler_index: ring_index, - }; - if voucher.privacy == VoucherPrivacyLevel::Degraded && ring_readiness_upgraded(included_members) - { - voucher.privacy = VoucherPrivacyLevel::Full; - } - voucher + voucher.remote_state = VoucherRemoteState::InRecycler { recycler_index: ring_index }; + if voucher.privacy == VoucherPrivacyLevel::Degraded && ring_readiness_upgraded(included_members) + { + voucher.privacy = VoucherPrivacyLevel::Full; + } + voucher } #[cfg(test)] mod tests { - use super::*; - use crate::balance::compute_balance; - use crate::constants::MINIMUM_RING_SIZE; - use crate::denomination::DenominationBreakdownContext; - use crate::model::VoucherLocalState; - use crate::repo::InMemoryVoucherRepository; - - /// One recorded `subscribe` call's arguments. - type SubscribeCall = (Vec, Vec<(u32, u32)>, Vec<(u32, u32)>); - - /// Scripted subscriber: records each subscribe call's arguments and - /// hands out a fresh channel per call. - #[derive(Default)] - struct MockSubscriber { - calls: Mutex>, - senders: Mutex>>, - } - - impl MockSubscriber { - fn latest_sender(&self) -> mpsc::Sender { - self.senders - .lock() - .last() - .expect("no subscription yet") - .clone() - } - } - - #[async_trait] - impl VoucherLocationSubscriber for MockSubscriber { - async fn subscribe( - &self, - pending: Vec, - included: Vec<(u32, u32)>, - degraded: Vec<(u32, u32)>, - ) -> Result, String> { - self.calls.lock().push((pending, included, degraded)); - let (tx, rx) = mpsc::channel(8); - self.senders.lock().push(tx); - Ok(rx) - } - } - - fn onboarding_voucher(index: u32) -> Voucher { - Voucher { - exponent: 1, - derivation_index: index, - allocated_at_ms: 0, - ready_at_ms: 0, - remote_state: VoucherRemoteState::Onboarding, - local_state: VoucherLocalState::Available, - privacy: VoucherPrivacyLevel::Full, - } - } - - fn degraded_in_recycler(index: u32, recycler: u32) -> Voucher { - Voucher { - remote_state: VoucherRemoteState::InRecycler { - recycler_index: recycler, - }, - privacy: VoucherPrivacyLevel::Degraded, - ..onboarding_voucher(index) - } - } - - fn service( - vouchers: Arc, - ) -> (Arc, Arc) { - let subscriber = Arc::new(MockSubscriber::default()); - ( - Arc::new(VoucherLocationService::new( - vouchers, - Arc::clone(&subscriber) as Arc, - crate::test_spawner(), - )), - subscriber, - ) - } - - async fn voucher_state(repo: &InMemoryVoucherRepository, index: u32) -> Voucher { - repo.list() - .await - .unwrap() - .into_iter() - .find(|v| v.derivation_index == index) - .unwrap() - } - - async fn settle(mut probe: impl AsyncFnMut() -> Option) -> T { - for _ in 0..1_000 { - if let Some(value) = probe().await { - return value; - } - tokio::task::yield_now().await; - } - panic!("never settled"); - } - - #[tokio::test] - async fn two_phase_accumulation_commits_only_when_both_halves_agree() { - let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([ - onboarding_voucher(1), - ])); - let (service, subscriber) = service(Arc::clone(&repo)); - service.sync().await.unwrap(); - assert_eq!(subscriber.calls.lock().len(), 1); - assert_eq!( - subscriber.calls.lock()[0].0, - vec![1], - "pending voucher subscribed" - ); - - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![( - 1, - Some(RingPosition::Included { - ring_index: 4, - included_at: 2, - }), - )], - ring_statuses: vec![], - }) - .await - .unwrap(); - settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; - assert_eq!( - subscriber.calls.lock()[1].1, - vec![(1, 4)], - "resubscription carries the accumulated included position" - ); - assert_eq!( - voucher_state(&repo, 1).await.remote_state, - VoucherRemoteState::Onboarding, - "no commit before the ring status arrives" - ); - - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![], - ring_statuses: vec![( - 1, - RingStatus { - included_members: 3, - }, - )], - }) - .await - .unwrap(); - let committed = settle(async || { - let voucher = voucher_state(&repo, 1).await; - voucher.remote_state.is_in_recycler().then_some(voucher) - }) - .await; - assert_eq!( - committed.remote_state, - VoucherRemoteState::InRecycler { recycler_index: 4 } - ); - } - - /// Position and status arriving in the same emission still forces a - /// resubscription, since the baseline only tracks previously-known - /// included indices; the commit lands once the status is re-delivered - /// on the new subscription. - #[tokio::test] - async fn position_and_status_in_one_emission_commit_after_resync() { - let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([ - onboarding_voucher(7), - ])); - let (service, subscriber) = service(Arc::clone(&repo)); - service.sync().await.unwrap(); - - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![( - 7, - Some(RingPosition::Included { - ring_index: 2, - included_at: 0, - }), - )], - ring_statuses: vec![( - 7, - RingStatus { - included_members: 1, - }, - )], - }) - .await - .unwrap(); - // The first emission triggers resubscription; re-deliver the - // status on the new batch (position stays accumulated). - settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![], - ring_statuses: vec![( - 7, - RingStatus { - included_members: 1, - }, - )], - }) - .await - .unwrap(); - let committed = settle(async || { - let voucher = voucher_state(&repo, 7).await; - voucher.remote_state.is_in_recycler().then_some(voucher) - }) - .await; - assert_eq!( - committed.remote_state, - VoucherRemoteState::InRecycler { recycler_index: 2 } - ); - } - - #[tokio::test] - async fn ring_size_upgrade_boundary() { - let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([ - degraded_in_recycler(1, 9), - ])); - let (service, subscriber) = service(Arc::clone(&repo)); - service.sync().await.unwrap(); - assert_eq!( - subscriber.calls.lock()[0].2, - vec![(1, 9)], - "degraded in-recycler voucher gets a ring-status request" - ); - - // One below the threshold: NOT upgraded. - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![], - ring_statuses: vec![( - 1, - RingStatus { - included_members: MINIMUM_RING_SIZE - 1, - }, - )], - }) - .await - .unwrap(); - for _ in 0..64 { - tokio::task::yield_now().await; - } - assert_eq!( - voucher_state(&repo, 1).await.privacy, - VoucherPrivacyLevel::Degraded - ); - - // Exactly the threshold: upgraded. - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![], - ring_statuses: vec![( - 1, - RingStatus { - included_members: MINIMUM_RING_SIZE, - }, - )], - }) - .await - .unwrap(); - let upgraded = settle(async || { - let voucher = voucher_state(&repo, 1).await; - (voucher.privacy == VoucherPrivacyLevel::Full).then_some(voucher) - }) - .await; - assert!(upgraded.remote_state.is_in_recycler(), "location untouched"); - } - - #[test] - fn minimum_ring_size_is_ten() { - assert_eq!(MINIMUM_RING_SIZE, 10); - } - - #[tokio::test] - async fn stale_accumulated_state_is_pruned_on_sync() { - let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([ - onboarding_voucher(1), - onboarding_voucher(2), - ])); - let (service, subscriber) = service(Arc::clone(&repo)); - service.sync().await.unwrap(); - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![( - 2, - Some(RingPosition::Included { - ring_index: 1, - included_at: 0, - }), - )], - ring_statuses: vec![], - }) - .await - .unwrap(); - settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; - - // Voucher 2 disappears locally; the next sync prunes it. - repo.remove(2).await.unwrap(); - service.sync().await.unwrap(); - let calls = subscriber.calls.lock(); - let last = calls.last().unwrap(); - assert_eq!(last.0, vec![1], "only the live voucher is pending"); - assert!(last.1.is_empty(), "stale accumulated position pruned"); - } - - /// A not-included member entry maps the voucher to `Onboarding`, and - /// an all-quiet wallet tears the subscription down. - #[tokio::test] - async fn not_included_position_marks_onboarding() { - let mut unlocated = onboarding_voucher(3); - unlocated.remote_state = VoucherRemoteState::Unlocated; - let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([unlocated])); - let (service, subscriber) = service(Arc::clone(&repo)); - service.sync().await.unwrap(); - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: vec![(3, Some(RingPosition::Onboarding))], - ring_statuses: vec![], - }) - .await - .unwrap(); - let committed = settle(async || { - let voucher = voucher_state(&repo, 3).await; - (voucher.remote_state == VoucherRemoteState::Onboarding).then_some(()) - }) - .await; - let () = committed; - - // Nothing left to watch once the voucher graduates fully. - repo.remove(3).await.unwrap(); - service.sync().await.unwrap(); - assert!(service.task.lock().is_none(), "subscription torn down"); - } - - #[tokio::test] - async fn six_vouchers_converge_across_reordered_partial_emissions() { - let recyclers = [2, 2, 3, 4, 4, 5]; - let original = (1u32..=6) - .map(|index| Voucher { - exponent: i16::try_from(index - 1).unwrap(), - derivation_index: index, - allocated_at_ms: 1_000 + i64::from(index), - ready_at_ms: 2_000 + i64::from(index), - remote_state: VoucherRemoteState::Onboarding, - local_state: VoucherLocalState::Available, - privacy: VoucherPrivacyLevel::Full, - }) - .collect::>(); - let repo = Arc::new(InMemoryVoucherRepository::with_vouchers(original.clone())); - let (service, subscriber) = service(Arc::clone(&repo)); - service.sync().await.unwrap(); - - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: (1u32..=6) - .map(|index| { - ( - index, - Some(RingPosition::Included { - ring_index: recyclers[usize::try_from(index - 1).unwrap()], - included_at: index - 1, - }), - ) - }) - .collect(), - ring_statuses: Vec::new(), - }) - .await - .unwrap(); - settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; - let mut included = subscriber.calls.lock()[1].1.clone(); - included.sort_unstable(); - assert_eq!( - included, - (1u32..=6) - .map(|index| (index, recyclers[usize::try_from(index - 1).unwrap()])) - .collect::>(), - "the replacement batch covers every newly included voucher" - ); - - for index in [6u32, 2, 5, 1, 4, 3] { - subscriber - .latest_sender() - .send(VoucherLocationUpdate { - ring_positions: Vec::new(), - ring_statuses: vec![( - index, - RingStatus { - included_members: MINIMUM_RING_SIZE, - }, - )], - }) - .await - .unwrap(); - } - - let converged = settle(async || { - let rows = repo.list().await.unwrap(); - rows.iter() - .all(|voucher| voucher.remote_state.is_in_recycler()) - .then_some(rows) - }) - .await; - for (before, after) in original.iter().zip(&converged) { - assert_eq!(after.derivation_index, before.derivation_index); - assert_eq!(after.exponent, before.exponent); - assert_eq!(after.allocated_at_ms, before.allocated_at_ms); - assert_eq!(after.ready_at_ms, before.ready_at_ms); - assert_eq!(after.local_state, before.local_state); - assert_eq!(after.privacy, before.privacy); - assert_eq!( - after.remote_state, - VoucherRemoteState::InRecycler { - recycler_index: recyclers - [usize::try_from(before.derivation_index - 1).unwrap()] - } - ); - } - - let balance = compute_balance( - &[], - &converged, - &DenominationBreakdownContext { - asset_unit: 1, - max_exponent: 10, - min_exponent: 0, - precision: 2, - }, - 10_000, - ); - assert_eq!(balance.full_privacy_planks, 63); - assert_eq!(balance.degraded_planks, 0); - } + use super::*; + use crate::{ + balance::compute_balance, constants::MINIMUM_RING_SIZE, + denomination::DenominationBreakdownContext, model::VoucherLocalState, + repo::InMemoryVoucherRepository, + }; + + /// One recorded `subscribe` call's arguments. + type SubscribeCall = (Vec, Vec<(u32, u32)>, Vec<(u32, u32)>); + + /// Scripted subscriber: records each subscribe call's arguments and + /// hands out a fresh channel per call. + #[derive(Default)] + struct MockSubscriber { + calls: Mutex>, + senders: Mutex>>, + } + + impl MockSubscriber { + fn latest_sender(&self) -> mpsc::Sender { + self.senders.lock().last().expect("no subscription yet").clone() + } + } + + #[async_trait] + impl VoucherLocationSubscriber for MockSubscriber { + async fn subscribe( + &self, + pending: Vec, + included: Vec<(u32, u32)>, + degraded: Vec<(u32, u32)>, + ) -> Result, String> { + self.calls.lock().push((pending, included, degraded)); + let (tx, rx) = mpsc::channel(8); + self.senders.lock().push(tx); + Ok(rx) + } + } + + fn onboarding_voucher(index: u32) -> Voucher { + Voucher { + exponent: 1, + derivation_index: index, + allocated_at_ms: 0, + ready_at_ms: 0, + remote_state: VoucherRemoteState::Onboarding, + local_state: VoucherLocalState::Available, + privacy: VoucherPrivacyLevel::Full, + } + } + + fn degraded_in_recycler(index: u32, recycler: u32) -> Voucher { + Voucher { + remote_state: VoucherRemoteState::InRecycler { recycler_index: recycler }, + privacy: VoucherPrivacyLevel::Degraded, + ..onboarding_voucher(index) + } + } + + fn service( + vouchers: Arc, + ) -> (Arc, Arc) { + let subscriber = Arc::new(MockSubscriber::default()); + ( + Arc::new(VoucherLocationService::new( + vouchers, + Arc::clone(&subscriber) as Arc, + crate::test_spawner(), + )), + subscriber, + ) + } + + async fn voucher_state(repo: &InMemoryVoucherRepository, index: u32) -> Voucher { + repo.list() + .await + .unwrap() + .into_iter() + .find(|v| v.derivation_index == index) + .unwrap() + } + + async fn settle(mut probe: impl AsyncFnMut() -> Option) -> T { + for _ in 0..1_000 { + if let Some(value) = probe().await { + return value; + } + tokio::task::yield_now().await; + } + panic!("never settled"); + } + + #[tokio::test] + async fn two_phase_accumulation_commits_only_when_both_halves_agree() { + let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([onboarding_voucher(1)])); + let (service, subscriber) = service(Arc::clone(&repo)); + service.sync().await.unwrap(); + assert_eq!(subscriber.calls.lock().len(), 1); + assert_eq!(subscriber.calls.lock()[0].0, vec![1], "pending voucher subscribed"); + + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![( + 1, + Some(RingPosition::Included { ring_index: 4, included_at: 2 }), + )], + ring_statuses: vec![], + }) + .await + .unwrap(); + settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; + assert_eq!( + subscriber.calls.lock()[1].1, + vec![(1, 4)], + "resubscription carries the accumulated included position" + ); + assert_eq!( + voucher_state(&repo, 1).await.remote_state, + VoucherRemoteState::Onboarding, + "no commit before the ring status arrives" + ); + + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![], + ring_statuses: vec![(1, RingStatus { included_members: 3 })], + }) + .await + .unwrap(); + let committed = settle(async || { + let voucher = voucher_state(&repo, 1).await; + voucher.remote_state.is_in_recycler().then_some(voucher) + }) + .await; + assert_eq!(committed.remote_state, VoucherRemoteState::InRecycler { recycler_index: 4 }); + } + + /// Position and status arriving in the same emission still forces a + /// resubscription, since the baseline only tracks previously-known + /// included indices; the commit lands once the status is re-delivered + /// on the new subscription. + #[tokio::test] + async fn position_and_status_in_one_emission_commit_after_resync() { + let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([onboarding_voucher(7)])); + let (service, subscriber) = service(Arc::clone(&repo)); + service.sync().await.unwrap(); + + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![( + 7, + Some(RingPosition::Included { ring_index: 2, included_at: 0 }), + )], + ring_statuses: vec![(7, RingStatus { included_members: 1 })], + }) + .await + .unwrap(); + // The first emission triggers resubscription; re-deliver the + // status on the new batch (position stays accumulated). + settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![], + ring_statuses: vec![(7, RingStatus { included_members: 1 })], + }) + .await + .unwrap(); + let committed = settle(async || { + let voucher = voucher_state(&repo, 7).await; + voucher.remote_state.is_in_recycler().then_some(voucher) + }) + .await; + assert_eq!(committed.remote_state, VoucherRemoteState::InRecycler { recycler_index: 2 }); + } + + #[tokio::test] + async fn ring_size_upgrade_boundary() { + let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([degraded_in_recycler(1, 9)])); + let (service, subscriber) = service(Arc::clone(&repo)); + service.sync().await.unwrap(); + assert_eq!( + subscriber.calls.lock()[0].2, + vec![(1, 9)], + "degraded in-recycler voucher gets a ring-status request" + ); + + // One below the threshold: NOT upgraded. + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![], + ring_statuses: vec![(1, RingStatus { included_members: MINIMUM_RING_SIZE - 1 })], + }) + .await + .unwrap(); + for _ in 0..64 { + tokio::task::yield_now().await; + } + assert_eq!(voucher_state(&repo, 1).await.privacy, VoucherPrivacyLevel::Degraded); + + // Exactly the threshold: upgraded. + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![], + ring_statuses: vec![(1, RingStatus { included_members: MINIMUM_RING_SIZE })], + }) + .await + .unwrap(); + let upgraded = settle(async || { + let voucher = voucher_state(&repo, 1).await; + (voucher.privacy == VoucherPrivacyLevel::Full).then_some(voucher) + }) + .await; + assert!(upgraded.remote_state.is_in_recycler(), "location untouched"); + } + + #[test] + fn minimum_ring_size_is_ten() { + assert_eq!(MINIMUM_RING_SIZE, 10); + } + + #[tokio::test] + async fn stale_accumulated_state_is_pruned_on_sync() { + let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([ + onboarding_voucher(1), + onboarding_voucher(2), + ])); + let (service, subscriber) = service(Arc::clone(&repo)); + service.sync().await.unwrap(); + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![( + 2, + Some(RingPosition::Included { ring_index: 1, included_at: 0 }), + )], + ring_statuses: vec![], + }) + .await + .unwrap(); + settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; + + // Voucher 2 disappears locally; the next sync prunes it. + repo.remove(2).await.unwrap(); + service.sync().await.unwrap(); + let calls = subscriber.calls.lock(); + let last = calls.last().unwrap(); + assert_eq!(last.0, vec![1], "only the live voucher is pending"); + assert!(last.1.is_empty(), "stale accumulated position pruned"); + } + + /// A not-included member entry maps the voucher to `Onboarding`, and + /// an all-quiet wallet tears the subscription down. + #[tokio::test] + async fn not_included_position_marks_onboarding() { + let mut unlocated = onboarding_voucher(3); + unlocated.remote_state = VoucherRemoteState::Unlocated; + let repo = Arc::new(InMemoryVoucherRepository::with_vouchers([unlocated])); + let (service, subscriber) = service(Arc::clone(&repo)); + service.sync().await.unwrap(); + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: vec![(3, Some(RingPosition::Onboarding))], + ring_statuses: vec![], + }) + .await + .unwrap(); + let committed = settle(async || { + let voucher = voucher_state(&repo, 3).await; + (voucher.remote_state == VoucherRemoteState::Onboarding).then_some(()) + }) + .await; + let () = committed; + + // Nothing left to watch once the voucher graduates fully. + repo.remove(3).await.unwrap(); + service.sync().await.unwrap(); + assert!(service.task.lock().is_none(), "subscription torn down"); + } + + #[tokio::test] + async fn six_vouchers_converge_across_reordered_partial_emissions() { + let recyclers = [2, 2, 3, 4, 4, 5]; + let original = (1u32..=6) + .map(|index| Voucher { + exponent: i16::try_from(index - 1).unwrap(), + derivation_index: index, + allocated_at_ms: 1_000 + i64::from(index), + ready_at_ms: 2_000 + i64::from(index), + remote_state: VoucherRemoteState::Onboarding, + local_state: VoucherLocalState::Available, + privacy: VoucherPrivacyLevel::Full, + }) + .collect::>(); + let repo = Arc::new(InMemoryVoucherRepository::with_vouchers(original.clone())); + let (service, subscriber) = service(Arc::clone(&repo)); + service.sync().await.unwrap(); + + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: (1u32..=6) + .map(|index| { + ( + index, + Some(RingPosition::Included { + ring_index: recyclers[usize::try_from(index - 1).unwrap()], + included_at: index - 1, + }), + ) + }) + .collect(), + ring_statuses: Vec::new(), + }) + .await + .unwrap(); + settle(async || (subscriber.calls.lock().len() == 2).then_some(())).await; + let mut included = subscriber.calls.lock()[1].1.clone(); + included.sort_unstable(); + assert_eq!( + included, + (1u32..=6) + .map(|index| (index, recyclers[usize::try_from(index - 1).unwrap()])) + .collect::>(), + "the replacement batch covers every newly included voucher" + ); + + for index in [6u32, 2, 5, 1, 4, 3] { + subscriber + .latest_sender() + .send(VoucherLocationUpdate { + ring_positions: Vec::new(), + ring_statuses: vec![( + index, + RingStatus { included_members: MINIMUM_RING_SIZE }, + )], + }) + .await + .unwrap(); + } + + let converged = settle(async || { + let rows = repo.list().await.unwrap(); + rows.iter().all(|voucher| voucher.remote_state.is_in_recycler()).then_some(rows) + }) + .await; + for (before, after) in original.iter().zip(&converged) { + assert_eq!(after.derivation_index, before.derivation_index); + assert_eq!(after.exponent, before.exponent); + assert_eq!(after.allocated_at_ms, before.allocated_at_ms); + assert_eq!(after.ready_at_ms, before.ready_at_ms); + assert_eq!(after.local_state, before.local_state); + assert_eq!(after.privacy, before.privacy); + assert_eq!( + after.remote_state, + VoucherRemoteState::InRecycler { + recycler_index: recyclers + [usize::try_from(before.derivation_index - 1).unwrap()] + } + ); + } + + let balance = compute_balance( + &[], + &converged, + &DenominationBreakdownContext { + asset_unit: 1, + max_exponent: 10, + min_exponent: 0, + precision: 2, + }, + 10_000, + ); + assert_eq!(balance.full_privacy_planks, 63); + assert_eq!(balance.degraded_planks, 0); + } } diff --git a/rust/crates/truapi-coinage/src/wal.rs b/rust/crates/truapi-coinage/src/wal.rs index 3e9844f964..6ad9f91a7e 100644 --- a/rust/crates/truapi-coinage/src/wal.rs +++ b/rust/crates/truapi-coinage/src/wal.rs @@ -9,334 +9,297 @@ use crate::constants::WAL_MORTALITY_BLOCKS; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WalOperation { - /// Voucher unload into coins — recovery probes the expected output - /// coins on-chain. - IntoCoins, - /// Voucher offboard into an external asset — recovery checks the - /// input vouchers were consumed. - IntoExternalAsset, - /// Coin recycling — recovery checks the input coin was consumed and - /// the surplus voucher appeared. - RecycleIntoVoucher, - /// Whole coin secrets were (or may have been) handed off out of band. - /// Unlike an extrinsic, a memo has no mortal era. Recovery therefore - /// retains its input reservation while any input is still on-chain and - /// retires it only once every input is absent. The live sender deletes - /// this entry only when a handoff reports an explicit pre-acceptance - /// rejection. - SecretHandoff, - /// A regular Coinage split. It has coin inputs and expected coin - /// outputs like `IntoCoins`, but remains distinct so recovery and - /// diagnostics never infer that vouchers were involved. - Split, - /// Durable operation receipt. Prepared does not prove whether the - /// idempotent transport accepted the memo before a process stopped. - TransferPrepared, - TransferAccepted, - /// All outgoing allocations finalized successfully or were observed with - /// exact outputs and consumed inputs during recovery. Pass-through inputs - /// were retired locally. This does not itself prove recipient claim. - TransferCompleted, - /// Transport definitively rejected the memo before accepting it. - TransferRejected, + /// Voucher unload into coins — recovery probes the expected output + /// coins on-chain. + IntoCoins, + /// Voucher offboard into an external asset — recovery checks the + /// input vouchers were consumed. + IntoExternalAsset, + /// Coin recycling — recovery checks the input coin was consumed and + /// the surplus voucher appeared. + RecycleIntoVoucher, + /// Whole coin secrets were (or may have been) handed off out of band. + /// Unlike an extrinsic, a memo has no mortal era. Recovery therefore + /// retains its input reservation while any input is still on-chain and + /// retires it only once every input is absent. The live sender deletes + /// this entry only when a handoff reports an explicit pre-acceptance + /// rejection. + SecretHandoff, + /// A regular Coinage split. It has coin inputs and expected coin + /// outputs like `IntoCoins`, but remains distinct so recovery and + /// diagnostics never infer that vouchers were involved. + Split, + /// Durable operation receipt. Prepared does not prove whether the + /// idempotent transport accepted the memo before a process stopped. + TransferPrepared, + TransferAccepted, + /// All outgoing allocations finalized successfully or were observed with + /// exact outputs and consumed inputs during recovery. Pass-through inputs + /// were retired locally. This does not itself prove recipient claim. + TransferCompleted, + /// Transport definitively rejected the memo before accepting it. + TransferRejected, } impl WalOperation { - pub fn as_raw(self) -> i64 { - match self { - WalOperation::IntoCoins => 0, - WalOperation::IntoExternalAsset => 1, - WalOperation::RecycleIntoVoucher => 2, - WalOperation::SecretHandoff => 3, - WalOperation::Split => 4, - WalOperation::TransferPrepared => 5, - WalOperation::TransferAccepted => 6, - WalOperation::TransferCompleted => 7, - WalOperation::TransferRejected => 8, - } - } + pub fn as_raw(self) -> i64 { + match self { + WalOperation::IntoCoins => 0, + WalOperation::IntoExternalAsset => 1, + WalOperation::RecycleIntoVoucher => 2, + WalOperation::SecretHandoff => 3, + WalOperation::Split => 4, + WalOperation::TransferPrepared => 5, + WalOperation::TransferAccepted => 6, + WalOperation::TransferCompleted => 7, + WalOperation::TransferRejected => 8, + } + } - pub fn from_raw(raw: i64) -> Option { - Some(match raw { - 0 => WalOperation::IntoCoins, - 1 => WalOperation::IntoExternalAsset, - 2 => WalOperation::RecycleIntoVoucher, - 3 => WalOperation::SecretHandoff, - 4 => WalOperation::Split, - 5 => WalOperation::TransferPrepared, - 6 => WalOperation::TransferAccepted, - 7 => WalOperation::TransferCompleted, - 8 => WalOperation::TransferRejected, - _ => return None, - }) - } + pub fn from_raw(raw: i64) -> Option { + Some(match raw { + 0 => WalOperation::IntoCoins, + 1 => WalOperation::IntoExternalAsset, + 2 => WalOperation::RecycleIntoVoucher, + 3 => WalOperation::SecretHandoff, + 4 => WalOperation::Split, + 5 => WalOperation::TransferPrepared, + 6 => WalOperation::TransferAccepted, + 7 => WalOperation::TransferCompleted, + 8 => WalOperation::TransferRejected, + _ => return None, + }) + } - pub fn is_transfer_receipt(self) -> bool { - matches!( - self, - Self::TransferPrepared - | Self::TransferAccepted - | Self::TransferCompleted - | Self::TransferRejected - ) - } + pub fn is_transfer_receipt(self) -> bool { + matches!( + self, + Self::TransferPrepared | + Self::TransferAccepted | + Self::TransferCompleted | + Self::TransferRejected + ) + } } /// One derived asset referenced from a WAL payload: enough to re-derive /// its key (index) and materialize it locally (exponent) at recovery. #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] pub struct WalCoinRef { - pub derivation_index: u32, - pub exponent: i16, + pub derivation_index: u32, + pub exponent: i16, } /// The SCALE payload of a WAL entry (`transfer_wal_entries.payload`): /// inputs consumed and outputs expected by the journaled extrinsic. #[derive(Debug, Clone, PartialEq, Eq, Default, Encode)] pub struct WalPayload { - pub input_coins: Vec, - pub input_vouchers: Vec, - pub output_coins: Vec, - pub output_vouchers: Vec, - /// Subset of `output_coins` delivered in the recipient memo. Recovery - /// materializes these as locally `Spent`, while change remains - /// `Available`. Appending the field preserves the v1 prefix layout. - pub destination_coins: Vec, + pub input_coins: Vec, + pub input_vouchers: Vec, + pub output_coins: Vec, + pub output_vouchers: Vec, + /// Subset of `output_coins` delivered in the recipient memo. Recovery + /// materializes these as locally `Spent`, while change remains + /// `Available`. Appending the field preserves the v1 prefix layout. + pub destination_coins: Vec, } impl Decode for WalPayload { - fn decode(input: &mut I) -> Result { - let input_coins = Vec::::decode(input)?; - let input_vouchers = Vec::::decode(input)?; - let output_coins = Vec::::decode(input)?; - let output_vouchers = Vec::::decode(input)?; - // Rows written before destination/change distinction end after the - // fourth vector. Treat that exact legacy shape as all-change. - let destination_coins = match input.remaining_len()? { - Some(0) => Vec::new(), - _ => Vec::::decode(input)?, - }; - Ok(Self { - input_coins, - input_vouchers, - output_coins, - output_vouchers, - destination_coins, - }) - } + fn decode(input: &mut I) -> Result { + let input_coins = Vec::::decode(input)?; + let input_vouchers = Vec::::decode(input)?; + let output_coins = Vec::::decode(input)?; + let output_vouchers = Vec::::decode(input)?; + // Rows written before destination/change distinction end after the + // fourth vector. Treat that exact legacy shape as all-change. + let destination_coins = match input.remaining_len()? { + Some(0) => Vec::new(), + _ => Vec::::decode(input)?, + }; + Ok(Self { input_coins, input_vouchers, output_coins, output_vouchers, destination_coins }) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CheckpointBlock { - Pending, - Known { number: u64, hash: [u8; 32] }, + Pending, + Known { number: u64, hash: [u8; 32] }, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct TransferWalEntry { - pub entry_id: String, - pub operation: WalOperation, - pub payload: WalPayload, - pub checkpoint: CheckpointBlock, - pub created_at_ms: i64, + pub entry_id: String, + pub operation: WalOperation, + pub payload: WalPayload, + pub checkpoint: CheckpointBlock, + pub created_at_ms: i64, } /// Hex encoding makes the operation/child boundary unambiguous even when a /// host identifier contains punctuation. All children share this namespace. pub fn operation_entry_id(operation_id: &str, child: &str) -> String { - format!( - "cash-operation:{}:{child}", - hex::encode(operation_id.as_bytes()) - ) + format!("cash-operation:{}:{child}", hex::encode(operation_id.as_bytes())) } impl TransferWalEntry { - pub fn belongs_to_operation(&self, operation_id: &str) -> bool { - self.entry_id - .starts_with(&operation_entry_id(operation_id, "")) - } + pub fn belongs_to_operation(&self, operation_id: &str) -> bool { + self.entry_id.starts_with(&operation_entry_id(operation_id, "")) + } - /// The durable receipt identifier for any correlated child or receipt. - pub fn operation_parent_id(&self) -> Option { - let suffix = self.entry_id.strip_prefix("cash-operation:")?; - let (operation, child) = suffix.split_once(':')?; - if operation.is_empty() || child.is_empty() { - return None; - } - Some(format!("cash-operation:{operation}:parent")) - } + /// The durable receipt identifier for any correlated child or receipt. + pub fn operation_parent_id(&self) -> Option { + let suffix = self.entry_id.strip_prefix("cash-operation:")?; + let (operation, child) = suffix.split_once(':')?; + if operation.is_empty() || child.is_empty() { + return None; + } + Some(format!("cash-operation:{operation}:parent")) + } - pub fn is_expired(&self, finalized_block: u64) -> bool { - match self.checkpoint { - CheckpointBlock::Pending => true, - CheckpointBlock::Known { number, .. } => { - finalized_block > number.saturating_add(WAL_MORTALITY_BLOCKS) - } - } - } + pub fn is_expired(&self, finalized_block: u64) -> bool { + match self.checkpoint { + CheckpointBlock::Pending => true, + CheckpointBlock::Known { number, .. } => { + finalized_block > number.saturating_add(WAL_MORTALITY_BLOCKS) + }, + } + } - pub fn is_forked(&self, canonical_hash_at_checkpoint: Option<&[u8; 32]>) -> bool { - match (&self.checkpoint, canonical_hash_at_checkpoint) { - (CheckpointBlock::Known { hash, .. }, Some(canonical)) => hash != canonical, - _ => false, - } - } + pub fn is_forked(&self, canonical_hash_at_checkpoint: Option<&[u8; 32]>) -> bool { + match (&self.checkpoint, canonical_hash_at_checkpoint) { + (CheckpointBlock::Known { hash, .. }, Some(canonical)) => hash != canonical, + _ => false, + } + } } /// Durable WAL persistence. `save_all` must commit the whole batch atomically; /// checkpoint writes must be durable before an adapter broadcasts. #[async_trait] pub trait WalStore: Send + Sync { - /// Inserts or durably replaces the entry with the same identifier. - async fn save(&self, entry: &TransferWalEntry) -> Result<(), String>; + /// Inserts or durably replaces the entry with the same identifier. + async fn save(&self, entry: &TransferWalEntry) -> Result<(), String>; - async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String>; + async fn save_all(&self, entries: &[TransferWalEntry]) -> Result<(), String>; - async fn update_checkpoint( - &self, - entry_id: &str, - checkpoint: CheckpointBlock, - ) -> Result<(), String>; + async fn update_checkpoint( + &self, + entry_id: &str, + checkpoint: CheckpointBlock, + ) -> Result<(), String>; - async fn load_all(&self) -> Result, String>; + async fn load_all(&self) -> Result, String>; - /// Includes the permanent parent receipt even after every child settles. - async fn load_operation(&self, operation_id: &str) -> Result, String> { - let prefix = operation_entry_id(operation_id, ""); - Ok(self - .load_all() - .await? - .into_iter() - .filter(|entry| entry.entry_id.starts_with(&prefix)) - .collect()) - } + /// Includes the permanent parent receipt even after every child settles. + async fn load_operation(&self, operation_id: &str) -> Result, String> { + let prefix = operation_entry_id(operation_id, ""); + Ok(self + .load_all() + .await? + .into_iter() + .filter(|entry| entry.entry_id.starts_with(&prefix)) + .collect()) + } - async fn delete(&self, entry_id: &str) -> Result<(), String>; + async fn delete(&self, entry_id: &str) -> Result<(), String>; } #[cfg(test)] mod tests { - use super::*; + use super::*; - fn entry(checkpoint: CheckpointBlock) -> TransferWalEntry { - TransferWalEntry { - entry_id: "e1".into(), - operation: WalOperation::IntoCoins, - payload: WalPayload::default(), - checkpoint, - created_at_ms: 0, - } - } + fn entry(checkpoint: CheckpointBlock) -> TransferWalEntry { + TransferWalEntry { + entry_id: "e1".into(), + operation: WalOperation::IntoCoins, + payload: WalPayload::default(), + checkpoint, + created_at_ms: 0, + } + } - #[test] - fn mortality_boundary_is_checkpoint_plus_300() { - let known = entry(CheckpointBlock::Known { - number: 1_000, - hash: [1; 32], - }); - assert!(!known.is_expired(1_300), "at the boundary: still alive"); - assert!(known.is_expired(1_301), "one past the boundary: dead"); - let near_max = entry(CheckpointBlock::Known { - number: u64::MAX - 10, - hash: [1; 32], - }); - assert!(!near_max.is_expired(u64::MAX), "saturating add, no wrap"); - } + #[test] + fn mortality_boundary_is_checkpoint_plus_300() { + let known = entry(CheckpointBlock::Known { number: 1_000, hash: [1; 32] }); + assert!(!known.is_expired(1_300), "at the boundary: still alive"); + assert!(known.is_expired(1_301), "one past the boundary: dead"); + let near_max = entry(CheckpointBlock::Known { number: u64::MAX - 10, hash: [1; 32] }); + assert!(!near_max.is_expired(u64::MAX), "saturating add, no wrap"); + } - #[test] - fn pending_checkpoint_is_immediately_expired() { - assert!(entry(CheckpointBlock::Pending).is_expired(0)); - } + #[test] + fn pending_checkpoint_is_immediately_expired() { + assert!(entry(CheckpointBlock::Pending).is_expired(0)); + } - #[test] - fn fork_detection_compares_canonical_hash() { - let known = entry(CheckpointBlock::Known { - number: 5, - hash: [1; 32], - }); - assert!(known.is_forked(Some(&[2; 32]))); - assert!(!known.is_forked(Some(&[1; 32]))); - assert!(!known.is_forked(None), "unavailable hash is not a fork"); - assert!(!entry(CheckpointBlock::Pending).is_forked(Some(&[2; 32]))); - } + #[test] + fn fork_detection_compares_canonical_hash() { + let known = entry(CheckpointBlock::Known { number: 5, hash: [1; 32] }); + assert!(known.is_forked(Some(&[2; 32]))); + assert!(!known.is_forked(Some(&[1; 32]))); + assert!(!known.is_forked(None), "unavailable hash is not a fork"); + assert!(!entry(CheckpointBlock::Pending).is_forked(Some(&[2; 32]))); + } - #[test] - fn operation_raw_round_trips() { - for op in [ - WalOperation::IntoCoins, - WalOperation::IntoExternalAsset, - WalOperation::RecycleIntoVoucher, - WalOperation::SecretHandoff, - WalOperation::Split, - WalOperation::TransferPrepared, - WalOperation::TransferAccepted, - WalOperation::TransferCompleted, - WalOperation::TransferRejected, - ] { - assert_eq!(WalOperation::from_raw(op.as_raw()), Some(op)); - } - assert_eq!(WalOperation::from_raw(9), None); - } + #[test] + fn operation_raw_round_trips() { + for op in [ + WalOperation::IntoCoins, + WalOperation::IntoExternalAsset, + WalOperation::RecycleIntoVoucher, + WalOperation::SecretHandoff, + WalOperation::Split, + WalOperation::TransferPrepared, + WalOperation::TransferAccepted, + WalOperation::TransferCompleted, + WalOperation::TransferRejected, + ] { + assert_eq!(WalOperation::from_raw(op.as_raw()), Some(op)); + } + assert_eq!(WalOperation::from_raw(9), None); + } - #[test] - fn payload_scale_round_trips() { - let payload = WalPayload { - input_coins: vec![WalCoinRef { - derivation_index: 1, - exponent: 4, - }], - input_vouchers: vec![], - output_coins: vec![ - WalCoinRef { - derivation_index: 9, - exponent: 2, - }, - WalCoinRef { - derivation_index: 10, - exponent: -1, - }, - ], - output_vouchers: vec![], - destination_coins: vec![WalCoinRef { - derivation_index: 9, - exponent: 2, - }], - }; - let encoded = payload.encode(); - assert_eq!(WalPayload::decode(&mut &encoded[..]).unwrap(), payload); - } + #[test] + fn payload_scale_round_trips() { + let payload = WalPayload { + input_coins: vec![WalCoinRef { derivation_index: 1, exponent: 4 }], + input_vouchers: vec![], + output_coins: vec![ + WalCoinRef { derivation_index: 9, exponent: 2 }, + WalCoinRef { derivation_index: 10, exponent: -1 }, + ], + output_vouchers: vec![], + destination_coins: vec![WalCoinRef { derivation_index: 9, exponent: 2 }], + }; + let encoded = payload.encode(); + assert_eq!(WalPayload::decode(&mut &encoded[..]).unwrap(), payload); + } - #[test] - fn legacy_payload_without_destination_suffix_still_decodes() { - let legacy = ( - vec![WalCoinRef { - derivation_index: 1, - exponent: 0, - }], - Vec::::new(), - vec![WalCoinRef { - derivation_index: 2, - exponent: 1, - }], - Vec::::new(), - ) - .encode(); - let decoded = WalPayload::decode(&mut &legacy[..]).unwrap(); - assert!(decoded.destination_coins.is_empty()); - assert_eq!(decoded.output_coins[0].derivation_index, 2); - } - #[test] - fn operation_namespace_cannot_match_a_different_host_identifier() { - let mut child = entry(CheckpointBlock::Pending); - child.entry_id = operation_entry_id("wallet:payment", "unload-0"); - assert!(child.belongs_to_operation("wallet:payment")); - assert!(!child.belongs_to_operation("wallet")); - assert!(!child.belongs_to_operation("wallet:payment:unload")); - assert_eq!( - child.operation_parent_id(), - Some(operation_entry_id("wallet:payment", "parent")) - ); - child.entry_id = "legacy-split".into(); - assert_eq!(child.operation_parent_id(), None); - } + #[test] + fn legacy_payload_without_destination_suffix_still_decodes() { + let legacy = ( + vec![WalCoinRef { derivation_index: 1, exponent: 0 }], + Vec::::new(), + vec![WalCoinRef { derivation_index: 2, exponent: 1 }], + Vec::::new(), + ) + .encode(); + let decoded = WalPayload::decode(&mut &legacy[..]).unwrap(); + assert!(decoded.destination_coins.is_empty()); + assert_eq!(decoded.output_coins[0].derivation_index, 2); + } + #[test] + fn operation_namespace_cannot_match_a_different_host_identifier() { + let mut child = entry(CheckpointBlock::Pending); + child.entry_id = operation_entry_id("wallet:payment", "unload-0"); + assert!(child.belongs_to_operation("wallet:payment")); + assert!(!child.belongs_to_operation("wallet")); + assert!(!child.belongs_to_operation("wallet:payment:unload")); + assert_eq!( + child.operation_parent_id(), + Some(operation_entry_id("wallet:payment", "parent")) + ); + child.entry_id = "legacy-split".into(); + assert_eq!(child.operation_parent_id(), None); + } } diff --git a/rust/crates/truapi-host-cli/js/scripts/chat-allowance-smoke.ts b/rust/crates/truapi-host-cli/js/scripts/chat-allowance-smoke.ts new file mode 100644 index 0000000000..90861497c2 --- /dev/null +++ b/rust/crates/truapi-host-cli/js/scripts/chat-allowance-smoke.ts @@ -0,0 +1,26 @@ +/// +// Does the host grant the per-index Statement Store allowance a Chat device +// needs? echat asks for exactly this on its first request. Scratch script for +// the host-channel prototype; not part of the battery. +export {}; +const login = await truapi.account.requestLogin({ reason: undefined }); +if (!login.isOk() || (login.value !== "Success" && login.value !== "AlreadyConnected")) { + throw new Error(`requestLogin failed: ${login.isOk() ? login.value : JSON.stringify(login.error)}`); +} +const user = await truapi.account.getUserId(); +console.log("user:", user.isOk() ? JSON.stringify(user.value) : JSON.stringify(user.error)); +const started = Date.now(); +const result = await truapi.resourceAllocation.request({ + resources: [{ tag: "ProductStatementStoreAllowance", value: { tag: "Raw", value: "0x8390f327c2e6785b30da233de87fc95733b60f3b9194275232df45af2104d887" } }], +}); +console.log(`allocation answered after ${((Date.now() - started) / 1000).toFixed(1)}s:`, JSON.stringify(result)); +assert(result.isOk(), "resource allocation failed:", result); +const [outcome] = result.value.outcomes; +console.log("ProductStatementStoreAllowance(Raw) outcome:", outcome); +// Ask again: a second request should find the slot already allocated and answer fast. +const again = Date.now(); +const second = await truapi.resourceAllocation.request({ + resources: [{ tag: "ProductStatementStoreAllowance", value: { tag: "Raw", value: "0x8390f327c2e6785b30da233de87fc95733b60f3b9194275232df45af2104d887" } }], +}); +console.log(`second request after ${((Date.now() - again) / 1000).toFixed(1)}s:`, JSON.stringify(second)); +console.log(outcome === "Allocated" ? "CHAT_ALLOWANCE_OK" : "CHAT_ALLOWANCE_NOT_ALLOCATED"); diff --git a/rust/crates/truapi-host-cli/js/scripts/host-channel-share.ts b/rust/crates/truapi-host-cli/js/scripts/host-channel-share.ts new file mode 100644 index 0000000000..2bf17320d6 --- /dev/null +++ b/rust/crates/truapi-host-cli/js/scripts/host-channel-share.ts @@ -0,0 +1,28 @@ +/// +// Host-channel demo, Alice's side: keep this signing host alive for its pairing, +// then, when the trigger file appears, disclose a profile reference to every +// Chat app's contacts and stay alive so the host channel can post and receive. +// Scratch script for the prototype; not part of the battery. +import { existsSync, unlinkSync } from "node:fs"; +export {}; +const TRIGGER = process.env.HOST_CHANNEL_TRIGGER ?? "/tmp/host-channel-share.go"; +const STOP = process.env.HOST_CHANNEL_STOP ?? "/tmp/host-channel-share.stop"; +const REFERENCE = process.env.HOST_CHANNEL_REFERENCE ?? "seity-contacts:v1:demo"; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const login = await truapi.account.requestLogin({ reason: undefined }); +if (!login.isOk() || (login.value !== "Success" && login.value !== "AlreadyConnected")) { + throw new Error(`requestLogin failed: ${login.isOk() ? login.value : JSON.stringify(login.error)}`); +} +const user = await truapi.account.getUserId(); +console.log("alice user:", user.isOk() ? JSON.stringify(user.value) : JSON.stringify(user.error)); +console.log(`waiting for ${TRIGGER} (handshake first), then disclosing; ${STOP} ends the run`); +while (!existsSync(TRIGGER) && !existsSync(STOP)) await sleep(2000); +if (existsSync(TRIGGER)) { + unlinkSync(TRIGGER); + const result = await truapi.profile.disclose({ reference: REFERENCE, audiences: [{ tag: "ChatApps" }] }); + console.log("disclose:", JSON.stringify(result)); + console.log("HOST_CHANNEL_DISCLOSED"); +} +while (!existsSync(STOP)) await sleep(2000); +unlinkSync(STOP); +console.log("HOST_CHANNEL_SHARE_DONE"); diff --git a/rust/crates/truapi-host-cli/js/scripts/host-channel-wait.ts b/rust/crates/truapi-host-cli/js/scripts/host-channel-wait.ts new file mode 100644 index 0000000000..0d564febc4 --- /dev/null +++ b/rust/crates/truapi-host-cli/js/scripts/host-channel-wait.ts @@ -0,0 +1,19 @@ +/// +// Host-channel demo, Bob's side: keep this signing host alive for its pairing +// and its background receiver until the stop file appears. The host's own log +// shows `host channel key recorded for a peer` and +// `host channel reference recorded from a contact`. +import { existsSync, unlinkSync } from "node:fs"; +export {}; +const STOP = process.env.HOST_CHANNEL_STOP ?? "/tmp/host-channel-wait.stop"; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const login = await truapi.account.requestLogin({ reason: undefined }); +if (!login.isOk() || (login.value !== "Success" && login.value !== "AlreadyConnected")) { + throw new Error(`requestLogin failed: ${login.isOk() ? login.value : JSON.stringify(login.error)}`); +} +const user = await truapi.account.getUserId(); +console.log("bob user:", user.isOk() ? JSON.stringify(user.value) : JSON.stringify(user.error)); +console.log(`alive until ${STOP}`); +while (!existsSync(STOP)) await sleep(2000); +unlinkSync(STOP); +console.log("HOST_CHANNEL_WAIT_DONE"); diff --git a/rust/crates/truapi-host-cli/src/chat_files.rs b/rust/crates/truapi-host-cli/src/chat_files.rs index 314712ead8..23ddd095d5 100644 --- a/rust/crates/truapi-host-cli/src/chat_files.rs +++ b/rust/crates/truapi-host-cli/src/chat_files.rs @@ -1,17 +1,19 @@ //! Host-private, bounded Chat file custody. Paths never leave the trusted CLI UI. -use std::collections::HashMap; -use std::fs::{self, File, OpenOptions}; -use std::io::{Read, Seek, SeekFrom, Write}; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; +use std::{ + collections::HashMap, + fs::{self, File, OpenOptions}, + io::{Read, Seek, SeekFrom, Write}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; use sha2::{Digest, Sha256}; use tempfile::NamedTempFile; -use truapi::latest::{ - GenericError, HostNativeChatAttachmentKind, HostNativeChatAttachmentMetadata, +use truapi::{ + latest::{GenericError, HostNativeChatAttachmentKind, HostNativeChatAttachmentMetadata}, + platform::NativeChatPickedFile, }; -use truapi::platform::NativeChatPickedFile; const MAX_READ: u32 = 2_000_000; const BLOCK_SIZE: u64 = 65_536; @@ -20,718 +22,594 @@ const HEADER_SIZE: u64 = 12; pub(crate) const DIRECTORY: &str = "chat-files"; pub(crate) fn error(reason: &'static str) -> GenericError { - GenericError { - reason: reason.to_string(), - } + GenericError { reason: reason.to_string() } } async fn blocking( - operation: impl FnOnce() -> Result + Send + 'static, + operation: impl FnOnce() -> Result + Send + 'static, ) -> Result { - tokio::task::spawn_blocking(operation) - .await - .map_err(|_| error("Chat file operation interrupted"))? + tokio::task::spawn_blocking(operation) + .await + .map_err(|_| error("Chat file operation interrupted"))? } fn opaque_id() -> Result { - let mut bytes = [0_u8; 32]; - getrandom::getrandom(&mut bytes).map_err(|_| error("Chat file randomness unavailable"))?; - Ok(hex::encode(bytes)) + let mut bytes = [0_u8; 32]; + getrandom::getrandom(&mut bytes).map_err(|_| error("Chat file randomness unavailable"))?; + Ok(hex::encode(bytes)) } fn valid_id(id: &str) -> Result<(), GenericError> { - if id.len() != 64 - || !id - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) - { - return Err(error("Invalid Chat file handle")); - } - Ok(()) + if id.len() != 64 || + !id.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(error("Invalid Chat file handle")); + } + Ok(()) } fn sync_directory(path: &Path) -> Result<(), GenericError> { - #[cfg(unix)] - File::open(path) - .and_then(|file| file.sync_all()) - .map_err(|_| error("Could not synchronize Chat file directory"))?; - #[cfg(not(unix))] - let _ = path; - Ok(()) + #[cfg(unix)] + File::open(path) + .and_then(|file| file.sync_all()) + .map_err(|_| error("Could not synchronize Chat file directory"))?; + #[cfg(not(unix))] + let _ = path; + Ok(()) } fn private_directory(root: &Path) -> Result { - let directory = root.join(DIRECTORY); - let mut builder = fs::DirBuilder::new(); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - builder.mode(0o700); - } - match builder.create(&directory) { - Ok(()) => sync_directory(root)?, - Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {} - Err(_) => return Err(error("Could not create private Chat file storage")), - } - let metadata = fs::symlink_metadata(&directory) - .map_err(|_| error("Private Chat file storage unavailable"))?; - if !metadata.is_dir() || metadata.file_type().is_symlink() { - return Err(error("Invalid private Chat file storage")); - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)) - .map_err(|_| error("Could not protect private Chat file storage"))?; - } - Ok(directory) + let directory = root.join(DIRECTORY); + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + match builder.create(&directory) { + Ok(()) => sync_directory(root)?, + Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {}, + Err(_) => return Err(error("Could not create private Chat file storage")), + } + let metadata = fs::symlink_metadata(&directory) + .map_err(|_| error("Private Chat file storage unavailable"))?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(error("Invalid private Chat file storage")); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)) + .map_err(|_| error("Could not protect private Chat file storage"))?; + } + Ok(directory) } fn open_regular(path: &Path) -> Result { - let mut options = OpenOptions::new(); - options.read(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.custom_flags( - (rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32, - ); - } - let file = options - .open(path) - .map_err(|_| error("Could not open Chat file"))?; - if !file - .metadata() - .map_err(|_| error("Could not inspect Chat file"))? - .is_file() - { - return Err(error("Chat selection must be a regular file")); - } - Ok(file) + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags( + (rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32 + ); + } + let file = options.open(path).map_err(|_| error("Could not open Chat file"))?; + if !file.metadata().map_err(|_| error("Could not inspect Chat file"))?.is_file() { + return Err(error("Chat selection must be a regular file")); + } + Ok(file) } fn source_path(root: &Path, source_id: &str) -> Result { - valid_id(source_id)?; - Ok(private_directory(root)?.join(source_id)) + valid_id(source_id)?; + Ok(private_directory(root)?.join(source_id)) } fn data_start(size: u32) -> u64 { - HEADER_SIZE + u64::from(size).div_ceil(BLOCK_SIZE) * 32 + HEADER_SIZE + u64::from(size).div_ceil(BLOCK_SIZE) * 32 } fn remove_snapshot(path: &Path) -> std::io::Result<()> { - #[cfg(windows)] - { - let metadata = fs::symlink_metadata(path)?; - if !metadata.is_file() || metadata.file_type().is_symlink() { - return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); - } - let mut permissions = metadata.permissions(); - permissions.set_readonly(false); - fs::set_permissions(path, permissions)?; - } - fs::remove_file(path) + #[cfg(windows)] + { + let metadata = fs::symlink_metadata(path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); + } + let mut permissions = metadata.permissions(); + permissions.set_readonly(false); + fs::set_permissions(path, permissions)?; + } + fs::remove_file(path) } // Own completed imports until the async callback actually receives its result. // Dropping a cancelled callback or a failed multi-selection removes its imports. struct Imports { - directory: PathBuf, - files: Vec, + directory: PathBuf, + files: Vec, } impl Drop for Imports { - fn drop(&mut self) { - for file in &self.files { - let _ = remove_snapshot(&self.directory.join(&file.source_id)); - } - } + fn drop(&mut self) { + for file in &self.files { + let _ = remove_snapshot(&self.directory.join(&file.source_id)); + } + } } fn import_one(directory: &Path, path: &Path) -> Result { - let mut input = open_regular(path)?; - let before = input - .metadata() - .map_err(|_| error("Could not inspect selected Chat file"))?; - let size = u32::try_from(before.len()) - .map_err(|_| error("Chat files must fit in a u32 byte count"))?; - let mut snapshot = - NamedTempFile::new_in(directory).map_err(|_| error("Could not create Chat snapshot"))?; - snapshot - .seek(SeekFrom::Start(data_start(size))) - .map_err(|_| error("Could not prepare Chat snapshot"))?; - let mut hashes = Vec::with_capacity(u64::from(size).div_ceil(BLOCK_SIZE) as usize * 32); - let mut buffer = vec![0_u8; BLOCK_SIZE as usize]; - let mut remaining = u64::from(size); - while remaining > 0 { - let count = remaining.min(BLOCK_SIZE) as usize; - input - .read_exact(&mut buffer[..count]) - .map_err(|_| error("Selected Chat file changed or could not be read"))?; - snapshot - .write_all(&buffer[..count]) - .map_err(|_| error("Could not write Chat snapshot"))?; - hashes.extend_from_slice(&Sha256::digest(&buffer[..count])); - remaining -= count as u64; - } - let after = input - .metadata() - .map_err(|_| error("Could not inspect selected Chat file"))?; - if input - .read(&mut buffer[..1]) - .map_err(|_| error("Could not read selected Chat file"))? - != 0 - || before.len() != after.len() - || before.modified().ok() != after.modified().ok() - { - return Err(error("Selected Chat file changed while importing")); - } - snapshot - .seek(SeekFrom::Start(0)) - .and_then(|_| snapshot.write_all(MAGIC)) - .and_then(|_| snapshot.write_all(&size.to_le_bytes())) - .and_then(|_| snapshot.write_all(&hashes)) - .map_err(|_| error("Could not seal Chat snapshot"))?; - let mut permissions = snapshot - .as_file() - .metadata() - .map_err(|_| error("Could not inspect Chat snapshot"))? - .permissions(); - permissions.set_readonly(true); - snapshot - .as_file() - .set_permissions(permissions) - .and_then(|_| snapshot.as_file().sync_all()) - .map_err(|_| error("Could not protect and synchronize Chat snapshot"))?; - let source_id = opaque_id()?; - snapshot - .persist_noclobber(directory.join(&source_id)) - .map_err(|_| error("Could not publish Chat snapshot"))?; - Ok(NativeChatPickedFile { - source_id, - metadata: HostNativeChatAttachmentMetadata { - mime_type: "application/octet-stream".to_string(), - size_bytes: size, - kind: HostNativeChatAttachmentKind::File, - }, - }) + let mut input = open_regular(path)?; + let before = input.metadata().map_err(|_| error("Could not inspect selected Chat file"))?; + let size = u32::try_from(before.len()) + .map_err(|_| error("Chat files must fit in a u32 byte count"))?; + let mut snapshot = + NamedTempFile::new_in(directory).map_err(|_| error("Could not create Chat snapshot"))?; + snapshot + .seek(SeekFrom::Start(data_start(size))) + .map_err(|_| error("Could not prepare Chat snapshot"))?; + let mut hashes = Vec::with_capacity(u64::from(size).div_ceil(BLOCK_SIZE) as usize * 32); + let mut buffer = vec![0_u8; BLOCK_SIZE as usize]; + let mut remaining = u64::from(size); + while remaining > 0 { + let count = remaining.min(BLOCK_SIZE) as usize; + input + .read_exact(&mut buffer[..count]) + .map_err(|_| error("Selected Chat file changed or could not be read"))?; + snapshot + .write_all(&buffer[..count]) + .map_err(|_| error("Could not write Chat snapshot"))?; + hashes.extend_from_slice(&Sha256::digest(&buffer[..count])); + remaining -= count as u64; + } + let after = input.metadata().map_err(|_| error("Could not inspect selected Chat file"))?; + if input + .read(&mut buffer[..1]) + .map_err(|_| error("Could not read selected Chat file"))? != + 0 || before.len() != after.len() || + before.modified().ok() != after.modified().ok() + { + return Err(error("Selected Chat file changed while importing")); + } + snapshot + .seek(SeekFrom::Start(0)) + .and_then(|_| snapshot.write_all(MAGIC)) + .and_then(|_| snapshot.write_all(&size.to_le_bytes())) + .and_then(|_| snapshot.write_all(&hashes)) + .map_err(|_| error("Could not seal Chat snapshot"))?; + let mut permissions = snapshot + .as_file() + .metadata() + .map_err(|_| error("Could not inspect Chat snapshot"))? + .permissions(); + permissions.set_readonly(true); + snapshot + .as_file() + .set_permissions(permissions) + .and_then(|_| snapshot.as_file().sync_all()) + .map_err(|_| error("Could not protect and synchronize Chat snapshot"))?; + let source_id = opaque_id()?; + snapshot + .persist_noclobber(directory.join(&source_id)) + .map_err(|_| error("Could not publish Chat snapshot"))?; + Ok(NativeChatPickedFile { + source_id, + metadata: HostNativeChatAttachmentMetadata { + mime_type: "application/octet-stream".to_string(), + size_bytes: size, + kind: HostNativeChatAttachmentKind::File, + }, + }) } fn import_files(root: &Path, paths: Vec) -> Result { - let directory = private_directory(root)?; - let mut imports = Imports { - directory, - files: Vec::with_capacity(paths.len()), - }; - for path in paths { - imports.files.push(import_one(&imports.directory, &path)?); - } - sync_directory(&imports.directory)?; - Ok(imports) + let directory = private_directory(root)?; + let mut imports = Imports { directory, files: Vec::with_capacity(paths.len()) }; + for path in paths { + imports.files.push(import_one(&imports.directory, &path)?); + } + sync_directory(&imports.directory)?; + Ok(imports) } fn read_file( - root: &Path, - source_id: &str, - offset: u64, - length: u32, + root: &Path, + source_id: &str, + offset: u64, + length: u32, ) -> Result, GenericError> { - if length > MAX_READ { - return Err(error("Chat file reads are limited to 2000000 bytes")); - } - let end = offset - .checked_add(u64::from(length)) - .ok_or_else(|| error("Chat file range overflow"))?; - let mut file = open_regular(&source_path(root, source_id)?)?; - let actual = file - .metadata() - .map_err(|_| error("Could not inspect Chat snapshot"))?; - let mut header = [0_u8; HEADER_SIZE as usize]; - file.read_exact(&mut header) - .map_err(|_| error("Invalid Chat snapshot"))?; - if &header[..8] != MAGIC || !actual.permissions().readonly() { - return Err(error("Chat snapshot is not immutable")); - } - let size = u32::from_le_bytes(header[8..12].try_into().expect("fixed size field")); - let start = data_start(size); - if actual.len() != start + u64::from(size) || end > u64::from(size) { - return Err(error("Chat file range or snapshot size is invalid")); - } - let mut result = Vec::with_capacity(length as usize); - if length == 0 { - return Ok(result); - } - let mut buffer = vec![0_u8; BLOCK_SIZE as usize]; - for block in offset / BLOCK_SIZE..=(end - 1) / BLOCK_SIZE { - let block_start = block * BLOCK_SIZE; - let count = (u64::from(size) - block_start).min(BLOCK_SIZE) as usize; - let mut expected = [0_u8; 32]; - file.seek(SeekFrom::Start(HEADER_SIZE + block * 32)) - .and_then(|_| file.read_exact(&mut expected)) - .and_then(|_| file.seek(SeekFrom::Start(start + block_start))) - .and_then(|_| file.read_exact(&mut buffer[..count])) - .map_err(|_| error("Could not read Chat snapshot"))?; - if Sha256::digest(&buffer[..count])[..] != expected { - return Err(error("Chat snapshot integrity check failed")); - } - let from = offset.saturating_sub(block_start) as usize; - let to = (end - block_start).min(count as u64) as usize; - result.extend_from_slice(&buffer[from..to]); - } - Ok(result) + if length > MAX_READ { + return Err(error("Chat file reads are limited to 2000000 bytes")); + } + let end = offset + .checked_add(u64::from(length)) + .ok_or_else(|| error("Chat file range overflow"))?; + let mut file = open_regular(&source_path(root, source_id)?)?; + let actual = file.metadata().map_err(|_| error("Could not inspect Chat snapshot"))?; + let mut header = [0_u8; HEADER_SIZE as usize]; + file.read_exact(&mut header).map_err(|_| error("Invalid Chat snapshot"))?; + if &header[..8] != MAGIC || !actual.permissions().readonly() { + return Err(error("Chat snapshot is not immutable")); + } + let size = u32::from_le_bytes(header[8..12].try_into().expect("fixed size field")); + let start = data_start(size); + if actual.len() != start + u64::from(size) || end > u64::from(size) { + return Err(error("Chat file range or snapshot size is invalid")); + } + let mut result = Vec::with_capacity(length as usize); + if length == 0 { + return Ok(result); + } + let mut buffer = vec![0_u8; BLOCK_SIZE as usize]; + for block in offset / BLOCK_SIZE..=(end - 1) / BLOCK_SIZE { + let block_start = block * BLOCK_SIZE; + let count = (u64::from(size) - block_start).min(BLOCK_SIZE) as usize; + let mut expected = [0_u8; 32]; + file.seek(SeekFrom::Start(HEADER_SIZE + block * 32)) + .and_then(|_| file.read_exact(&mut expected)) + .and_then(|_| file.seek(SeekFrom::Start(start + block_start))) + .and_then(|_| file.read_exact(&mut buffer[..count])) + .map_err(|_| error("Could not read Chat snapshot"))?; + if Sha256::digest(&buffer[..count])[..] != expected { + return Err(error("Chat snapshot integrity check failed")); + } + let from = offset.saturating_sub(block_start) as usize; + let to = (end - block_start).min(count as u64) as usize; + result.extend_from_slice(&buffer[from..to]); + } + Ok(result) } struct Export { - root: PathBuf, - destination: PathBuf, - temporary: Option, - size: u64, - written: u64, + root: PathBuf, + destination: PathBuf, + temporary: Option, + size: u64, + written: u64, } impl Export { - fn prepare(root: PathBuf, destination: PathBuf, size: u32) -> Result { - let name = destination - .file_name() - .ok_or_else(|| error("Chat export needs a file name"))?; - let parent = destination - .parent() - .filter(|path| !path.as_os_str().is_empty()) - .unwrap_or(Path::new(".")); - let parent = - fs::canonicalize(parent).map_err(|_| error("Chat export directory is unavailable"))?; - let destination = parent.join(name); - match fs::symlink_metadata(&destination) { - Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => {} - _ => { - return Err(error( - "Chat export destination already exists or is unavailable; choose a new file name", - )); - } - } - let temporary = - NamedTempFile::new_in(&parent).map_err(|_| error("Could not create Chat export"))?; - Ok(Self { - root, - destination, - temporary: Some(temporary), - size: u64::from(size), - written: 0, - }) - } - - fn write(&mut self, offset: u64, data: &[u8]) -> Result<(), GenericError> { - let end = offset - .checked_add(data.len() as u64) - .ok_or_else(|| error("Chat export range overflow"))?; - if data.len() > MAX_READ as usize || offset != self.written || end > self.size { - return Err(error( - "Chat export writes must be bounded, contiguous and within the declared size", - )); - } - let file = self - .temporary - .as_mut() - .ok_or_else(|| error("Chat export is already published"))?; - // A failed write may have written a prefix. Retrying the same offset - // overwrites that prefix instead of silently appending duplicate bytes. - file.seek(SeekFrom::Start(offset)) - .and_then(|_| file.write_all(data)) - .map_err(|_| error("Could not write Chat export"))?; - self.written = end; - Ok(()) - } - - fn finish(&mut self) -> Result<(), GenericError> { - if self.written != self.size { - return Err(error("Chat export is incomplete")); - } - if let Some(file) = &self.temporary { - if file - .as_file() - .metadata() - .map_err(|_| error("Could not inspect Chat export"))? - .len() - != self.size - { - return Err(error("Chat export size is invalid")); - } - file.as_file() - .sync_all() - .map_err(|_| error("Could not synchronize Chat export"))?; - } - if let Some(file) = self.temporary.take() - && let Err(cause) = file.persist_noclobber(&self.destination) - { - self.temporary = Some(cause.file); - return Err(error( - "Could not publish Chat export without overwriting an existing file", - )); - } - // If this sync fails, retain the published state: cancellation may only - // remove a staging file, never the completed user destination. - sync_directory( - self.destination - .parent() - .expect("canonical destination has a parent"), - ) - } + fn prepare(root: PathBuf, destination: PathBuf, size: u32) -> Result { + let name = destination.file_name().ok_or_else(|| error("Chat export needs a file name"))?; + let parent = destination + .parent() + .filter(|path| !path.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let parent = + fs::canonicalize(parent).map_err(|_| error("Chat export directory is unavailable"))?; + let destination = parent.join(name); + match fs::symlink_metadata(&destination) { + Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => {}, + _ => { + return Err(error( + "Chat export destination already exists or is unavailable; choose a new file name", + )); + }, + } + let temporary = + NamedTempFile::new_in(&parent).map_err(|_| error("Could not create Chat export"))?; + Ok(Self { + root, + destination, + temporary: Some(temporary), + size: u64::from(size), + written: 0, + }) + } + + fn write(&mut self, offset: u64, data: &[u8]) -> Result<(), GenericError> { + let end = offset + .checked_add(data.len() as u64) + .ok_or_else(|| error("Chat export range overflow"))?; + if data.len() > MAX_READ as usize || offset != self.written || end > self.size { + return Err(error( + "Chat export writes must be bounded, contiguous and within the declared size", + )); + } + let file = self + .temporary + .as_mut() + .ok_or_else(|| error("Chat export is already published"))?; + // A failed write may have written a prefix. Retrying the same offset + // overwrites that prefix instead of silently appending duplicate bytes. + file.seek(SeekFrom::Start(offset)) + .and_then(|_| file.write_all(data)) + .map_err(|_| error("Could not write Chat export"))?; + self.written = end; + Ok(()) + } + + fn finish(&mut self) -> Result<(), GenericError> { + if self.written != self.size { + return Err(error("Chat export is incomplete")); + } + if let Some(file) = &self.temporary { + if file + .as_file() + .metadata() + .map_err(|_| error("Could not inspect Chat export"))? + .len() != self.size + { + return Err(error("Chat export size is invalid")); + } + file.as_file() + .sync_all() + .map_err(|_| error("Could not synchronize Chat export"))?; + } + if let Some(file) = self.temporary.take() && + let Err(cause) = file.persist_noclobber(&self.destination) + { + self.temporary = Some(cause.file); + return Err(error( + "Could not publish Chat export without overwriting an existing file", + )); + } + // If this sync fails, retain the published state: cancellation may only + // remove a staging file, never the completed user destination. + sync_directory(self.destination.parent().expect("canonical destination has a parent")) + } } #[derive(Clone, Default)] pub(crate) struct ChatFiles { - exports: Arc>>, + exports: Arc>>, } impl ChatFiles { - pub(crate) async fn import( - root: PathBuf, - paths: Vec, - ) -> Result, GenericError> { - let mut imports = blocking(move || import_files(&root, paths)).await?; - Ok(std::mem::take(&mut imports.files)) - } - - pub(crate) async fn read( - root: PathBuf, - source_id: String, - offset: u64, - length: u32, - ) -> Result, GenericError> { - blocking(move || read_file(&root, &source_id, offset, length)).await - } - - pub(crate) async fn release(root: PathBuf, source_id: String) -> Result<(), GenericError> { - blocking(move || { - let path = source_path(&root, &source_id)?; - match remove_snapshot(&path) { - Ok(()) => sync_directory(path.parent().expect("snapshot has a parent")), - Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(_) => Err(error("Could not release Chat snapshot")), - } - }) - .await - } - - pub(crate) async fn begin_export( - &self, - root: PathBuf, - destination: PathBuf, - size: u32, - ) -> Result { - let (id, export) = - blocking(move || Ok((opaque_id()?, Export::prepare(root, destination, size)?))).await?; - self.exports - .lock() - .map_err(|_| error("Chat exports unavailable"))? - .insert(id.clone(), export); - Ok(id) - } - - pub(crate) async fn write_export( - &self, - root: PathBuf, - id: String, - offset: u64, - data: Vec, - ) -> Result<(), GenericError> { - valid_id(&id)?; - let exports = self.exports.clone(); - blocking(move || { - let mut exports = exports - .lock() - .map_err(|_| error("Chat exports unavailable"))?; - let export = exports - .get_mut(&id) - .filter(|export| export.root == root) - .ok_or_else(|| error("Unknown Chat export"))?; - export.write(offset, &data) - }) - .await - } - - pub(crate) async fn finish_export( - &self, - root: PathBuf, - id: String, - ) -> Result<(), GenericError> { - valid_id(&id)?; - let exports = self.exports.clone(); - blocking(move || { - let mut exports = exports - .lock() - .map_err(|_| error("Chat exports unavailable"))?; - let export = exports - .get_mut(&id) - .filter(|export| export.root == root) - .ok_or_else(|| error("Unknown Chat export"))?; - export.finish()?; - exports.remove(&id); - Ok(()) - }) - .await - } - - pub(crate) async fn cancel_export( - &self, - root: PathBuf, - id: String, - ) -> Result<(), GenericError> { - valid_id(&id)?; - let exports = self.exports.clone(); - blocking(move || { - let mut exports = exports - .lock() - .map_err(|_| error("Chat exports unavailable"))?; - if exports.get(&id).is_some_and(|export| export.root != root) { - return Err(error("Unknown Chat export")); - } - exports.remove(&id); - Ok(()) - }) - .await - } + pub(crate) async fn import( + root: PathBuf, + paths: Vec, + ) -> Result, GenericError> { + let mut imports = blocking(move || import_files(&root, paths)).await?; + Ok(std::mem::take(&mut imports.files)) + } + + pub(crate) async fn read( + root: PathBuf, + source_id: String, + offset: u64, + length: u32, + ) -> Result, GenericError> { + blocking(move || read_file(&root, &source_id, offset, length)).await + } + + pub(crate) async fn release(root: PathBuf, source_id: String) -> Result<(), GenericError> { + blocking(move || { + let path = source_path(&root, &source_id)?; + match remove_snapshot(&path) { + Ok(()) => sync_directory(path.parent().expect("snapshot has a parent")), + Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(_) => Err(error("Could not release Chat snapshot")), + } + }) + .await + } + + pub(crate) async fn begin_export( + &self, + root: PathBuf, + destination: PathBuf, + size: u32, + ) -> Result { + let (id, export) = + blocking(move || Ok((opaque_id()?, Export::prepare(root, destination, size)?))).await?; + self.exports + .lock() + .map_err(|_| error("Chat exports unavailable"))? + .insert(id.clone(), export); + Ok(id) + } + + pub(crate) async fn write_export( + &self, + root: PathBuf, + id: String, + offset: u64, + data: Vec, + ) -> Result<(), GenericError> { + valid_id(&id)?; + let exports = self.exports.clone(); + blocking(move || { + let mut exports = exports.lock().map_err(|_| error("Chat exports unavailable"))?; + let export = exports + .get_mut(&id) + .filter(|export| export.root == root) + .ok_or_else(|| error("Unknown Chat export"))?; + export.write(offset, &data) + }) + .await + } + + pub(crate) async fn finish_export( + &self, + root: PathBuf, + id: String, + ) -> Result<(), GenericError> { + valid_id(&id)?; + let exports = self.exports.clone(); + blocking(move || { + let mut exports = exports.lock().map_err(|_| error("Chat exports unavailable"))?; + let export = exports + .get_mut(&id) + .filter(|export| export.root == root) + .ok_or_else(|| error("Unknown Chat export"))?; + export.finish()?; + exports.remove(&id); + Ok(()) + }) + .await + } + + pub(crate) async fn cancel_export( + &self, + root: PathBuf, + id: String, + ) -> Result<(), GenericError> { + valid_id(&id)?; + let exports = self.exports.clone(); + blocking(move || { + let mut exports = exports.lock().map_err(|_| error("Chat exports unavailable"))?; + if exports.get(&id).is_some_and(|export| export.root != root) { + return Err(error("Unknown Chat export")); + } + exports.remove(&id); + Ok(()) + }) + .await + } } #[cfg(test)] mod tests { - use super::*; - - #[tokio::test] - async fn snapshots_survive_original_changes_and_backend_restart_until_release() { - let root = tempfile::tempdir().unwrap(); - let original = root.path().join("selected"); - let bytes = vec![42; BLOCK_SIZE as usize + 7]; - fs::write(&original, &bytes).unwrap(); - let selected = ChatFiles::import(root.path().to_path_buf(), vec![original.clone()]) - .await - .unwrap(); - let source = selected[0].source_id.clone(); - fs::write(original, b"changed").unwrap(); - // Reads require no process-local registry: only the durable source ID. - let range = ChatFiles::read(root.path().to_path_buf(), source.clone(), BLOCK_SIZE - 2, 9) - .await - .unwrap(); - assert_eq!(range, bytes[BLOCK_SIZE as usize - 2..]); - assert!( - ChatFiles::read(root.path().to_path_buf(), source.clone(), 0, MAX_READ + 1) - .await - .is_err() - ); - assert!( - ChatFiles::read(root.path().to_path_buf(), source.clone(), u64::MAX, 2) - .await - .is_err() - ); - assert!( - ChatFiles::read( - root.path().to_path_buf(), - source.clone(), - bytes.len() as u64, - 1 - ) - .await - .is_err() - ); - assert_eq!( - ChatFiles::read( - root.path().to_path_buf(), - source.clone(), - bytes.len() as u64, - 0 - ) - .await - .unwrap(), - Vec::::new() - ); - ChatFiles::release(root.path().to_path_buf(), source.clone()) - .await - .unwrap(); - ChatFiles::release(root.path().to_path_buf(), source.clone()) - .await - .unwrap(); - assert!( - ChatFiles::read(root.path().to_path_buf(), source, 0, 1) - .await - .is_err() - ); - assert!( - ChatFiles::read(root.path().to_path_buf(), "../selected".to_string(), 0, 1) - .await - .is_err() - ); - } - - #[test] - fn snapshot_corruption_is_rejected_even_when_size_does_not_change() { - let root = tempfile::tempdir().unwrap(); - let original = root.path().join("selected"); - fs::write(&original, b"original").unwrap(); - let imports = import_files(root.path(), vec![original]).unwrap(); - let id = &imports.files[0].source_id; - let path = source_path(root.path(), id).unwrap(); - let mut permissions = fs::metadata(&path).unwrap().permissions(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - permissions.set_mode(0o600); - } - #[cfg(not(unix))] - permissions.set_readonly(false); - fs::set_permissions(&path, permissions.clone()).unwrap(); - let mut file = OpenOptions::new().write(true).open(&path).unwrap(); - file.seek(SeekFrom::Start(data_start(8))).unwrap(); - file.write_all(b"tampered").unwrap(); - permissions.set_readonly(true); - file.set_permissions(permissions).unwrap(); - drop(file); - assert!(read_file(root.path(), id, 0, 8).is_err()); - } - - #[tokio::test] - async fn export_enforces_order_size_and_no_clobber_and_cancel_keeps_completed_file() { - let root = tempfile::tempdir().unwrap(); - let scope = root.path().to_path_buf(); - let destination = root.path().join("download"); - let store = ChatFiles::default(); - let id = store - .begin_export(scope.clone(), destination.clone(), 4) - .await - .unwrap(); - assert!( - store - .write_export(scope.clone(), id.clone(), 1, vec![1]) - .await - .is_err() - ); - assert!( - store - .write_export(scope.clone(), id.clone(), 0, vec![0; 5]) - .await - .is_err() - ); - store - .write_export(scope.clone(), id.clone(), 0, vec![1, 2]) - .await - .unwrap(); - assert!( - store - .finish_export(scope.clone(), id.clone()) - .await - .is_err() - ); - assert!(!destination.exists()); - store - .write_export(scope.clone(), id.clone(), 2, vec![3, 4]) - .await - .unwrap(); - fs::write(&destination, b"existing").unwrap(); - assert!( - store - .finish_export(scope.clone(), id.clone()) - .await - .is_err() - ); - assert_eq!(fs::read(&destination).unwrap(), b"existing"); - fs::remove_file(&destination).unwrap(); - store - .finish_export(scope.clone(), id.clone()) - .await - .unwrap(); - store - .cancel_export(scope.clone(), id.clone()) - .await - .unwrap(); - store.cancel_export(scope.clone(), id).await.unwrap(); - assert_eq!(fs::read(&destination).unwrap(), [1, 2, 3, 4]); - let partial = root.path().join("partial"); - let id = store - .begin_export(scope.clone(), partial.clone(), 1) - .await - .unwrap(); - store - .cancel_export(scope.clone(), id.clone()) - .await - .unwrap(); - store.cancel_export(scope, id).await.unwrap(); - assert!(!partial.exists()); - } - - #[test] - fn failed_multi_selection_does_not_retain_partial_snapshots() { - let root = tempfile::tempdir().unwrap(); - let selected = root.path().join("selected"); - fs::write(&selected, b"data").unwrap(); - assert!(import_files(root.path(), vec![selected, root.path().join("missing")]).is_err()); - assert_eq!( - fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), - 0 - ); - } - - #[test] - fn oversized_native_files_are_rejected_before_importing_bytes() { - let root = tempfile::tempdir().unwrap(); - let selected = root.path().join("oversized"); - File::create(&selected) - .unwrap() - .set_len(u64::from(u32::MAX) + 1) - .unwrap(); - assert!(import_files(root.path(), vec![selected]).is_err()); - assert_eq!( - fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), - 0 - ); - } - - #[tokio::test] - async fn exact_read_limit_and_identity_scope_are_enforced() { - let first = tempfile::tempdir().unwrap(); - let second = tempfile::tempdir().unwrap(); - let selected = first.path().join("selected"); - let bytes = vec![17; MAX_READ as usize]; - fs::write(&selected, &bytes).unwrap(); - let imported = ChatFiles::import(first.path().to_path_buf(), vec![selected]) - .await - .unwrap(); - let source = imported[0].source_id.clone(); - assert_eq!( - ChatFiles::read(first.path().to_path_buf(), source.clone(), 0, MAX_READ) - .await - .unwrap(), - bytes - ); - assert!( - ChatFiles::read(second.path().to_path_buf(), source, 0, 1) - .await - .is_err() - ); - let store = ChatFiles::default(); - let destination = first.path().join("download"); - let id = store - .begin_export(first.path().to_path_buf(), destination.clone(), 0) - .await - .unwrap(); - assert!( - store - .finish_export(second.path().to_path_buf(), id.clone()) - .await - .is_err() - ); - assert!( - store - .cancel_export(second.path().to_path_buf(), id.clone()) - .await - .is_err() - ); - store - .finish_export(first.path().to_path_buf(), id.clone()) - .await - .unwrap(); - store - .cancel_export(first.path().to_path_buf(), id) - .await - .unwrap(); - assert_eq!(fs::read(destination).unwrap(), Vec::::new()); - } + use super::*; + + #[tokio::test] + async fn snapshots_survive_original_changes_and_backend_restart_until_release() { + let root = tempfile::tempdir().unwrap(); + let original = root.path().join("selected"); + let bytes = vec![42; BLOCK_SIZE as usize + 7]; + fs::write(&original, &bytes).unwrap(); + let selected = ChatFiles::import(root.path().to_path_buf(), vec![original.clone()]) + .await + .unwrap(); + let source = selected[0].source_id.clone(); + fs::write(original, b"changed").unwrap(); + // Reads require no process-local registry: only the durable source ID. + let range = ChatFiles::read(root.path().to_path_buf(), source.clone(), BLOCK_SIZE - 2, 9) + .await + .unwrap(); + assert_eq!(range, bytes[BLOCK_SIZE as usize - 2..]); + assert!( + ChatFiles::read(root.path().to_path_buf(), source.clone(), 0, MAX_READ + 1) + .await + .is_err() + ); + assert!( + ChatFiles::read(root.path().to_path_buf(), source.clone(), u64::MAX, 2) + .await + .is_err() + ); + assert!( + ChatFiles::read(root.path().to_path_buf(), source.clone(), bytes.len() as u64, 1) + .await + .is_err() + ); + assert_eq!( + ChatFiles::read(root.path().to_path_buf(), source.clone(), bytes.len() as u64, 0) + .await + .unwrap(), + Vec::::new() + ); + ChatFiles::release(root.path().to_path_buf(), source.clone()).await.unwrap(); + ChatFiles::release(root.path().to_path_buf(), source.clone()).await.unwrap(); + assert!(ChatFiles::read(root.path().to_path_buf(), source, 0, 1).await.is_err()); + assert!( + ChatFiles::read(root.path().to_path_buf(), "../selected".to_string(), 0, 1) + .await + .is_err() + ); + } + + #[test] + fn snapshot_corruption_is_rejected_even_when_size_does_not_change() { + let root = tempfile::tempdir().unwrap(); + let original = root.path().join("selected"); + fs::write(&original, b"original").unwrap(); + let imports = import_files(root.path(), vec![original]).unwrap(); + let id = &imports.files[0].source_id; + let path = source_path(root.path(), id).unwrap(); + let mut permissions = fs::metadata(&path).unwrap().permissions(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + permissions.set_mode(0o600); + } + #[cfg(not(unix))] + permissions.set_readonly(false); + fs::set_permissions(&path, permissions.clone()).unwrap(); + let mut file = OpenOptions::new().write(true).open(&path).unwrap(); + file.seek(SeekFrom::Start(data_start(8))).unwrap(); + file.write_all(b"tampered").unwrap(); + permissions.set_readonly(true); + file.set_permissions(permissions).unwrap(); + drop(file); + assert!(read_file(root.path(), id, 0, 8).is_err()); + } + + #[tokio::test] + async fn export_enforces_order_size_and_no_clobber_and_cancel_keeps_completed_file() { + let root = tempfile::tempdir().unwrap(); + let scope = root.path().to_path_buf(); + let destination = root.path().join("download"); + let store = ChatFiles::default(); + let id = store.begin_export(scope.clone(), destination.clone(), 4).await.unwrap(); + assert!(store.write_export(scope.clone(), id.clone(), 1, vec![1]).await.is_err()); + assert!(store.write_export(scope.clone(), id.clone(), 0, vec![0; 5]).await.is_err()); + store.write_export(scope.clone(), id.clone(), 0, vec![1, 2]).await.unwrap(); + assert!(store.finish_export(scope.clone(), id.clone()).await.is_err()); + assert!(!destination.exists()); + store.write_export(scope.clone(), id.clone(), 2, vec![3, 4]).await.unwrap(); + fs::write(&destination, b"existing").unwrap(); + assert!(store.finish_export(scope.clone(), id.clone()).await.is_err()); + assert_eq!(fs::read(&destination).unwrap(), b"existing"); + fs::remove_file(&destination).unwrap(); + store.finish_export(scope.clone(), id.clone()).await.unwrap(); + store.cancel_export(scope.clone(), id.clone()).await.unwrap(); + store.cancel_export(scope.clone(), id).await.unwrap(); + assert_eq!(fs::read(&destination).unwrap(), [1, 2, 3, 4]); + let partial = root.path().join("partial"); + let id = store.begin_export(scope.clone(), partial.clone(), 1).await.unwrap(); + store.cancel_export(scope.clone(), id.clone()).await.unwrap(); + store.cancel_export(scope, id).await.unwrap(); + assert!(!partial.exists()); + } + + #[test] + fn failed_multi_selection_does_not_retain_partial_snapshots() { + let root = tempfile::tempdir().unwrap(); + let selected = root.path().join("selected"); + fs::write(&selected, b"data").unwrap(); + assert!(import_files(root.path(), vec![selected, root.path().join("missing")]).is_err()); + assert_eq!(fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), 0); + } + + #[test] + fn oversized_native_files_are_rejected_before_importing_bytes() { + let root = tempfile::tempdir().unwrap(); + let selected = root.path().join("oversized"); + File::create(&selected).unwrap().set_len(u64::from(u32::MAX) + 1).unwrap(); + assert!(import_files(root.path(), vec![selected]).is_err()); + assert_eq!(fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), 0); + } + + #[tokio::test] + async fn exact_read_limit_and_identity_scope_are_enforced() { + let first = tempfile::tempdir().unwrap(); + let second = tempfile::tempdir().unwrap(); + let selected = first.path().join("selected"); + let bytes = vec![17; MAX_READ as usize]; + fs::write(&selected, &bytes).unwrap(); + let imported = ChatFiles::import(first.path().to_path_buf(), vec![selected]).await.unwrap(); + let source = imported[0].source_id.clone(); + assert_eq!( + ChatFiles::read(first.path().to_path_buf(), source.clone(), 0, MAX_READ) + .await + .unwrap(), + bytes + ); + assert!(ChatFiles::read(second.path().to_path_buf(), source, 0, 1).await.is_err()); + let store = ChatFiles::default(); + let destination = first.path().join("download"); + let id = store + .begin_export(first.path().to_path_buf(), destination.clone(), 0) + .await + .unwrap(); + assert!(store.finish_export(second.path().to_path_buf(), id.clone()).await.is_err()); + assert!(store.cancel_export(second.path().to_path_buf(), id.clone()).await.is_err()); + store.finish_export(first.path().to_path_buf(), id.clone()).await.unwrap(); + store.cancel_export(first.path().to_path_buf(), id).await.unwrap(); + assert_eq!(fs::read(destination).unwrap(), Vec::::new()); + } } diff --git a/rust/crates/truapi-host-cli/src/main.rs b/rust/crates/truapi-host-cli/src/main.rs index 48559e2588..5df4597b2f 100644 --- a/rust/crates/truapi-host-cli/src/main.rs +++ b/rust/crates/truapi-host-cli/src/main.rs @@ -26,6 +26,7 @@ mod network; mod platform; mod pocket; mod product_config; +mod profile; mod qr_scanner; mod register_name; mod scanner; @@ -56,9 +57,9 @@ use clap::{ use futures::future::BoxFuture; use tracing_subscriber::{Layer, layer::SubscriberExt, util::SubscriberInitExt}; use truapi::{ - AnnouncedPairing, DebugSink, PairedSsoPeer, PairingHostConfig, PairingHostRuntime, - PairingProposal, ResponderExit, SigningHostConfig, SigningHostRuntime, StatementRenewalTarget, - WsDebugSink, + AnnouncedPairing, DebugSink, PairedSsoPeer, PairingHostConfig, PairingHostRuntime, + PairingProposal, ResponderExit, SigningHostConfig, SigningHostRuntime, StatementRenewalTarget, + WsDebugSink, host_logic::dotns_gateway::{ MAX_BASE_LABEL_LEN, MIN_PERSON_LABEL_LEN, is_lite_label, is_registrable_full_label, }, @@ -72,16 +73,16 @@ use crate::{ network::{Network, NetworkConfig}, platform::{ApprovalPolicy, CliPlatform, CliStoragePaths}, sessions::{ - CurrentSession, DEFAULT_SESSION_NAME, PairedHost, PairedHostMetadata, SessionCatalog, - SessionClearTarget, SessionProfile, + CurrentSession, DEFAULT_SESSION_NAME, PairedHost, PairedHostMetadata, SessionCatalog, + SessionClearTarget, SessionProfile, }, signing_shell::{ - ApprovalCommand, DeviceCommand, HELP_TEXT, PAIRING_HELP_TEXT, PairCommand, ProductCommand, - ScriptCommand, SessionCommand, ShellCommand, parse_command, + ApprovalCommand, DeviceCommand, HELP_TEXT, PAIRING_HELP_TEXT, PairCommand, ProductCommand, + ScriptCommand, SessionCommand, ShellCommand, parse_command, }, terminal_ui::{ - ActiveTerminalUi, ActivityState, DriveResult, PairingImageInput, SystemEvent, TerminalUi, - UiHandle, + ActiveTerminalUi, ActivityState, DriveResult, PairingImageInput, SystemEvent, TerminalUi, + UiHandle, }, }; @@ -101,275 +102,275 @@ const STATE_VERSION: &str = "v2"; version = update::CURRENT_VERSION )] struct Cli { - /// Log verbosity. Defaults to the saved `/log` level, then `info`. - /// `RUST_LOG` takes precedence when set. - #[arg(long, global = true, value_enum, env = "TRUAPI_HOST_LOG")] - log_level: Option, - /// Stream every product frame to a wire debugger listening on this loopback - /// `ws://` URL, e.g. `ws://127.0.0.1:9231`. The target must be loopback, and - /// an unreachable debugger never fails a dispatch. Frames go out whole and - /// the debugger decodes all of them, so a tapped signing host puts its - /// payloads on that socket: point it at a debugger you run yourself. Only - /// `pairing-host`, `dev` and `signing-host` read this. - #[arg(long, global = true, env = "TRUAPI_DEBUGGER_URL", value_name = "URL")] - debugger: Option, - #[command(subcommand)] - command: Command, + /// Log verbosity. Defaults to the saved `/log` level, then `info`. + /// `RUST_LOG` takes precedence when set. + #[arg(long, global = true, value_enum, env = "TRUAPI_HOST_LOG")] + log_level: Option, + /// Stream every product frame to a wire debugger listening on this loopback + /// `ws://` URL, e.g. `ws://127.0.0.1:9231`. The target must be loopback, and + /// an unreachable debugger never fails a dispatch. Frames go out whole and + /// the debugger decodes all of them, so a tapped signing host puts its + /// payloads on that socket: point it at a debugger you run yourself. Only + /// `pairing-host`, `dev` and `signing-host` read this. + #[arg(long, global = true, env = "TRUAPI_DEBUGGER_URL", value_name = "URL")] + debugger: Option, + #[command(subcommand)] + command: Command, } #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, derive_more::Display)] #[display(rename_all = "lowercase")] enum LogLevel { - Error, - Warn, - Info, - Debug, - Trace, + Error, + Warn, + Info, + Debug, + Trace, } impl LogLevel { - const fn as_filter(self) -> &'static str { - match self { - Self::Error => "error", - Self::Warn => "warn", - Self::Info => "info", - Self::Debug => "debug", - Self::Trace => "trace", - } - } - - fn scoped_filter(self) -> String { - let level = self.as_filter(); - format!("warn,truapi={level},truapi_host={level}") - } + const fn as_filter(self) -> &'static str { + match self { + Self::Error => "error", + Self::Warn => "warn", + Self::Info => "info", + Self::Debug => "debug", + Self::Trace => "trace", + } + } + + fn scoped_filter(self) -> String { + let level = self.as_filter(); + format!("warn,truapi={level},truapi_host={level}") + } } impl FromStr for LogLevel { - type Err = String; - - fn from_str(value: &str) -> Result { - match value.trim().to_ascii_lowercase().as_str() { - "error" => Ok(Self::Error), - "warn" => Ok(Self::Warn), - "info" => Ok(Self::Info), - "debug" => Ok(Self::Debug), - "trace" => Ok(Self::Trace), - _ => Err(format!( - "invalid log level `{value}`; expected error, warn, info, debug, or trace" - )), - } - } + type Err = String; + + fn from_str(value: &str) -> Result { + match value.trim().to_ascii_lowercase().as_str() { + "error" => Ok(Self::Error), + "warn" => Ok(Self::Warn), + "info" => Ok(Self::Info), + "debug" => Ok(Self::Debug), + "trace" => Ok(Self::Trace), + _ => Err(format!( + "invalid log level `{value}`; expected error, warn, info, debug, or trace" + )), + } + } } fn resolve_log_level(selected: Option, saved: Option) -> LogLevel { - selected.or(saved).unwrap_or(LogLevel::Info) + selected.or(saved).unwrap_or(LogLevel::Info) } fn startup_filter( - rust_log: Option<&str>, - log_level: LogLevel, + rust_log: Option<&str>, + log_level: LogLevel, ) -> (tracing_subscriber::EnvFilter, String) { if let Some(value) = rust_log.map(str::trim).filter(|value| !value.is_empty()) && let Ok(filter) = tracing_subscriber::EnvFilter::try_new(value) - { - return (filter, value.to_string()); - } + { + return (filter, value.to_string()); + } (tracing_subscriber::EnvFilter::new(log_level.scoped_filter()), log_level.to_string()) } fn load_log_level(base_path: &Path) -> Result> { - let path = base_path.join(LOG_LEVEL_FILE); - let value = match std::fs::read_to_string(&path) { - Ok(value) => value, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(error).with_context(|| format!("read {}", path.display())), - }; - value - .trim() - .parse() - .map(Some) - .map_err(anyhow::Error::msg) - .with_context(|| format!("read saved log level from {}", path.display())) + let path = base_path.join(LOG_LEVEL_FILE); + let value = match std::fs::read_to_string(&path) { + Ok(value) => value, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error).with_context(|| format!("read {}", path.display())), + }; + value + .trim() + .parse() + .map(Some) + .map_err(anyhow::Error::msg) + .with_context(|| format!("read saved log level from {}", path.display())) } fn store_log_level(base_path: &Path, level: LogLevel) -> Result<()> { - let path = base_path.join(LOG_LEVEL_FILE); - platform::atomic_write(&path, format!("{level}\n").as_bytes()) - .map_err(anyhow::Error::msg) - .with_context(|| format!("persist saved log level {}", path.display())) + let path = base_path.join(LOG_LEVEL_FILE); + platform::atomic_write(&path, format!("{level}\n").as_bytes()) + .map_err(anyhow::Error::msg) + .with_context(|| format!("persist saved log level {}", path.display())) } #[derive(Clone)] struct LogController { - reload: Arc Result<(), String> + Send + Sync>, - base_path: PathBuf, + reload: Arc Result<(), String> + Send + Sync>, + base_path: PathBuf, } impl LogController { - fn set(&self, level: LogLevel) -> Result<()> { - store_log_level(&self.base_path, level)?; - (self.reload)(level).map_err(anyhow::Error::msg) - } + fn set(&self, level: LogLevel) -> Result<()> { + store_log_level(&self.base_path, level)?; + (self.reload)(level).map_err(anyhow::Error::msg) + } } #[derive(Subcommand)] enum Command { - /// Run a seedless pairing host for product scripts or interactive pairing. - /// - /// With `--script`, exits with the script's status. Without it, stays in an - /// interactive terminal UI where scripts can be run repeatedly. - PairingHost(PairingHostArgs), - /// Run a product against a local signing host, with one command. - /// - /// Starts a host on loopback, waits for its signer, then runs the wrapped - /// development command with the host already live. The product reaches it - /// through a development-only `