For the complete documentation index, see llms.txt. This page is also available as Markdown.

Rust

This section covers installing and integrating the DeRec protocol from Rust using the derec-library crate.


Rust SDK Overview

The DeRec Rust SDK is the canonical surface of the protocol. Every other binding (.NET, TypeScript/Node, TypeScript/Web, React Native, Go) wraps this crate over an FFI or WASM boundary. Rust applications depend on the crate directly.

The SDK allows applications to:

  • Distribute Secret shares across trusted Helpers using a threshold secret-sharing scheme

  • Verify Helpers still hold shares

  • Recover the Secret from a threshold of Helpers

  • Optionally extend the Owner identity across multiple devices via the replica feature, with automatic Secret synchronization between them

It exposes DeRecProtocol, an orchestrator that drives every flow on top of application-supplied storage and transport, holding no in-memory session state of its own, plus stateless primitives::* helpers for callers that want to drive the wire format directly.


Installation

Add the crate and its protobuf companion to your Cargo.toml:

[dependencies]
derec-library = "0.0.10"
derec-proto = "0.0.10"

These chapters document lib-derec 0.0.10.

derec-proto carries the generated wire types (ContactMessage, SenderKind, ContactMode, StatusEnum, TransportProtocol, ParameterRange, …). derec-library depends on it but does not re-export it, so any code that names one of those types — every sample in this section does — needs the direct dependency. Keep both at the same version; every package in the repository ships one shared version.

The minimum supported Rust version is 1.88 (edition 2024).

The crate compiles for native targets and wasm32-*.

Cargo features

Every feature is off by default. A default build compiles no serde derives, no FFI layer and no logging.

Crate
Feature
Enables

derec-library

serde

Serialize / Deserialize on the public store and channel types (SecretValue, PairingKeyMaterial, ChannelRecord, HelperChannel, ReplicaMember, ChannelStatus, …) and the protocol::types::state_record module, so a store can persist them with any serde format. Turns on derec-proto/serde. The serde format is not part of the public API.

derec-library

logging

tracing spans and events across the protocol and primitives layers. No overhead when no subscriber is installed.

derec-library

ffi

The C-ABI bridge the .NET, Go and React Native bindings link against. Implies serde. Pure-Rust consumers do not need it.

derec-proto

serde

Serialize / Deserialize on the generated protobuf types.

derec-proto

descriptor

descriptor::FILE_DESCRIPTOR_SET and descriptor::transport_descriptor(), for generating your own gRPC stubs. Enable it on a build-dependency only. See Schema distribution.

The wasm32 target pulls serde in automatically.

With logging on, install any tracing subscriber. The library never logs secret bytes, keys or share content:


Quick Start

Implement the five store traits and a transport, build the orchestrator, and drive it. The four flow chapters show how each protocol round trip flows through process(...).

The Rust samples in this section run inside an async fn returning Result<(), Box<dyn std::error::Error>>, so ? works on both derec_library::Error (from start, accept, restore) and ProcessError (from process).

DeRecProtocolBuilder is a typestate builder with six type parameters (the five stores and the transport): .build() is reachable only once every required slot is filled — with_channel_store, with_share_store, with_secret_store, with_user_secret_store, with_state_store and with_transport. with_stores(DeRecStores { channels, shares, secrets, user_secrets, state }) fills the five store slots in one call. Every store setter may be called again, before or after with_stores; the last call for a store wins. A missing slot is a compile-time error. with_own_transports is not part of the typestate: it is an ordinary setter, callable repeatedly (the last call wins), and build() checks at run time that it was called with a non-empty list. Runtime invariants are checked inside build(), which returns Result<_, derec_library::Error>:

  • threshold < 2 → Error::InvalidInput.

  • A with_max_subshares cap below the threshold → Error::InvalidInput.

  • A malformed ParameterRange → Error::InvalidInput naming the field. 0 means "no bound"; every min and max must be >= 0, and min <= max unless max is 0.

  • No own transports set, or an empty with_own_transports list → Error::InvalidInput.

  • A malformed endpoint, or two endpoints of the same protocol → Error::Transport(TransportValidationError::…), including DuplicateProtocol.

with_own_transports takes any iterator of &str, String or derec_library::transport::TransportProtocol (the library's validated endpoint type, not the proto one); a URI's scheme selects its protocol. List every endpoint this application serves, in preference order, at most one per protocol. Only https://, http://, grpcs:// and grpc:// are accepted. To change the list later, call protocol.set_own_transports(list), which validates the whole list before storing any of it and returns Result<()>.

Optional setters

Setter
Default
Purpose

with_threshold(n)

3 (DEFAULT_THRESHOLD)

The starting threshold t, counted in subshares, for a secret with no threshold stored. Once a publish records a t, that one applies; see Threshold and Secret version. Below 2 is refused at build().

with_max_subshares(max)

unset (no cap)

Cap on a sharing round's total subshares (the sum of the Helpers' weights), library-started rounds included. Never applied at recovery. See Weighted helpers.

with_timeouts(Timeouts)

300 / 60 / 60 / Enabled { 300 }

with_communication_info(map)

empty

Identity metadata sent in pairing messages.

with_auto_respond_on_failure(bool)

false

Who answers an inbound request whose handling failed: true, the library sends the response; false, it reports RequestFailed with a token the app passes to reject. See Failed requests.

with_unpair_ack(UnpairAck)

UnpairAck::Required

Whether an unpair initiator waits for the peer's acknowledgement. See Channel management.

with_auto_reply_to(bool)

false

Stamp replyToTransports with this device's own transports on every outbound request. See replyToTransports.

with_auto_accept(AutoAcceptPolicy)

every flow off

Per-flow auto-accept. See Auto-accept policy.

with_parameter_range(derec_proto::ParameterRange)

unset

Advertised parameter bounds, checked for overlap at pairing. A helper also enforces its own minShareSize / maxShareSize on every inbound share; see Helpers consent.

with_unsafe_connection(bool)

false

Accept plaintext http:// and grpc:// endpoints from any host. Development only.

with_replica_id(u64)

unset

This device's replica identity. Required for every replica flow.

with_unsafe_connection(true) accepts plaintext endpoints on any host, your own and peer-supplied. Without it, plaintext is accepted only for your own loopback endpoint (localhost, 127.0.0.1, ::1). See Transport endpoints and plaintext connections.

Configuration from a file or record

Applications usually load settings as a whole: general settings from the environment or a config file, per-user settings from a user record. DeRecProtocolConfig holds every data setting of the builder, each one optional, and with_config applies it in one call:

  • Only set fields are applied. An absent field leaves whatever the builder already holds.

  • Last write wins, per field. Each set field goes through its own with_* setter, in call order. Nested objects replace the builder's value as a whole, except timeouts: each of its fields is merged separately, so a per-user config that sets only inbound_message_secs keeps the sharing_round_secs the general config set.

  • Validation happens in build(), with the same rules as the setters. A threshold of 1 from a config file fails exactly as with_threshold(1) does.

  • Stores, the transport and secret_id are not settings and are not carried in the config.

Serialization needs the serde feature. The canonical JSON, shared by every SDK, is:

Keys are snake_case and every key is optional. replica_id and max_subshares are u64 values written as decimal strings, so they survive JSON encoders whose numbers are f64. Timeouts are whole seconds. Unknown keys are rejected at every level, so a misspelled key fails to parse instead of being silently ignored. See the DeRecProtocolConfig rustdoc for every field's accepted forms.

Timeouts

with_timeouts configures four independent budgets. Fields left out keep their default:

inbound_message is a security boundary: it bounds how stale a message may be and still be accepted, so it has to tolerate transport latency and clock skew. The other three are liveness budgets. Every value is clamped to at least one second. See Concurrency and scheduling.

tick()

Timeouts advance only inside process and tick. A publish whose peers all go quiet has nothing left to close it: the round stays open and no SharingComplete is ever emitted.

tick() returns Vec<DeRecEvent> (not a Result), is idempotent and is safe on an idle protocol. Every state-changing method on one instance takes &mut self, so calls on that instance are already serialized. Two instances sharing one secret_id and the same stores need an application lock. See Concurrency and scheduling and Timeouts and housekeeping.

Store records

The store traits are covered in Implementing a persistent store. Fields and methods a Rust store must handle:

  • HelperChannel.weight: u32 — the helper's subshare weight, which the library writes on every sharing round. HelperChannel has no Default, so a struct literal must set it (1 for an ordinary helper). A record stored without it, or with 0, reads as 1.

  • Share { secret_id, version, bytes, subshares, threshold } — subshares: Option<u32> and threshold: Option<u32> are set on owner-side shares only, and are None on a helper's share and on rows written before 0.0.9. Persist both as given, None included (nullable SQL columns), and never backfill them.

  • UserSecrets.threshold: Option<u32> — the threshold the next publish splits at. Persist it with the snapshot, None included.

  • DeRecShareStore::record_verification(secret_id, channel_id, version) — called once per verification challenge a helper accepts, after the share is found. The default body returns Ok(()).

  • Refusals — on a helper channel, save (a new share version only; an idempotent re-send never reaches it) and record_verification may return Err(ShareStoreError::Refused(Refusal::TooFrequent)). The library answers the owner with the mapped status, and the helper's call returns [NoOp]:

    derec_library::protocol::Refusal

    Status

    Memo

    TooFrequent

    TOO_FREQUENT

    "refused by the helper: too frequent"

    SizeLimitExceeded

    SIZE_LIMIT_EXCEEDED

    "refused by the helper: size limit exceeded"

    Rejected

    REJECTED

    "refused by the helper"

    Any other store error is a failed request, reported as RequestFailed (see Failed requests).

  • DeRecShareStore::keep_version(secret_id, version) -> ShareStoreFuture<'_, u32> — the one older version every helper of the round keeps; return the newest version whose SharingComplete reported threshold_met, or 0. Besides becoming each round's keepVersion, it governs this device's own proofs: when a helper confirms a round, the library deletes, through remove_versions, that channel's proofs other than the confirmed version and the returned one. See Version retention.

  • State — the sharing-round state record carries the round's threshold and keep_version (it replaces keep_list). A state store that keeps StateItemRecord as opaque JSON needs no change; one that maps fields one by one must carry both. A row written before 0.0.10 carries no keep_version, so that round removes no proof when it settles.


Protocol Flows

Every DeRec flow is started through protocol.start(DeRecFlow::*) and completed through the inbound process / accept / reject loop.

Chapter
Flows

Pairing: Owner ↔ Helper, or a replica pairing

ProtectSecret: split the Secret to Helpers and sync it to replica group members

VerifyShares: check Helpers still hold their shares

Discovery, RecoverSecret, then restore

Unpair, UpdateChannelInfo, ReplicaDiscovery, UnpairReplica, reject, auto-accept, timeouts

Each flow has the same shape: the initiator calls start(DeRecFlow::X { .. }), which returns per-target dispatch events (*Started, and *Failed for a fan-out target that could not be sent to); the library sends envelopes through your DeRecTransport; the responder feeds inbound envelopes to process and answers each DeRecEvent::ActionRequired with accept or reject. Every *Started event carries the round's trace_id. Invalid input, a missing precondition or a role mismatch returns Err before anything is sent.

ReplicaDiscovery and UnpairReplica are replica-only and require with_replica_id; see Channel management. The protocol-level catalog is in Protocol Specification / Flows.


Transport

The library opens no sockets. Every outbound envelope goes to DeRecTransport::send:

endpoints is every endpoint the peer advertised that passed the transport policy, in the peer's order. It is never empty, and every entry addresses the same peer. The library does not rank them. Deliver to one of them: stop at the first success, and return Err only when every endpoint failed. Do not deliver to all of them.

Implement SendOne (one endpoint) and wrap it instead of writing send by hand:

SequentialFailover tries each endpoint in order and is the right default. SingleEndpointTransport uses only the first, which makes that choice visible to a reviewer instead of hiding it in endpoints[0].

The store traits are also implemented for Box<T> and &mut T, and DeRecTransport for Arc<T>, so backends can be chosen at run time with trait objects.


Message Model

The crate operates on serialized protocol envelopes. Inbound and outbound envelopes are plain Vec<u8> / &[u8]. The bytes are either:

  • A serialized DeRecMessage envelope, or

  • A serialized ContactMessage (the out-of-band bootstrap; see Pairing), produced by primitives::pairing::request::encode_contact.

For channel messages, the DeRecMessage envelope carries an encrypted inner protobuf message. The library performs the encryption, decryption and framing.

Secret format. The recoverable Secret — the bytes Helpers store and recovery reconstructs — is [ version byte ] · payload. The current version byte is 3; the decoder accepts 3 and 2 and rejects 1. The payload is gzip-compressed JSON (RFC 1952), with byte fields as standard-padded base64 (RFC 4648 §4) and u64 fields as decimal strings. Version 3 records each roster entry's endpoints as transports: [{ uri, protocol }] and a replica member's role as a string. This is internal to the crate: you pass and receive a typed Secret. It matters only for cross-app interop or primitive-layer use. See Concepts → Secret. Every other wire message stays protobuf.

Applications are responsible for:

  • Delivering outbound envelopes, which the library passes to DeRecTransport::send(endpoints, message)

  • Bounding inbound message size at the transport layer, then passing envelopes to DeRecProtocol::process(...)

DeRecMessage.traceId correlates a request with its response. The orchestrator sets and echoes it; derec_library::derec_message::read_trace_id(&bytes) reads it from an envelope, for a transport that answers on the inbound connection and must pick the reply out of several outbound messages.

The DeRec protocol version, distinct from the crate version, is derec_library::protocol_version::ProtocolVersion::current() (currently 0.0). See Versioning.


Error Handling

start, accept, reject, restore and the setters return Result<T, derec_library::Error>. process returns Result<Vec<DeRecEvent>, ProcessError>, where ProcessError wraps the same Error as source.

Error is #[non_exhaustive], so every match needs a fallback arm. Its variants:

  • Per-flow wrappers: Pairing(PairingError), Sharing(SharingError), Verification, Discovery, Recovery, Unpairing, Restore(RestoreError), DeRecMessage. SharingError includes InvalidWeight { channel_id, weight }, TooManySubshares { subshares, max }, InvalidThreshold and InvalidKeepVersion { keep_version, version } (see Version retention); PairingError includes FingerprintCommitmentMismatch; see Weighted helpers

  • Store failures: ChannelStore, ShareStore, SecretStore, StateStore

  • Transport(TransportValidationError) — a malformed endpoint, or DuplicateProtocol

  • InvalidInput(&'static str), Invariant(&'static str), ProtobufDecode, ProtobufEncode

  • RoleMismatch { channel_id, expected, actual } — a flow started against, or a request arriving on, a channel whose peer has the wrong role

  • ChannelAlreadyPaired { channel_id } — start(Pairing) for a channel that is already Paired

  • ReplicaIdNotConfigured — a replica flow without with_replica_id

  • FingerprintMismatch { channel_id } — verify_fingerprint was given a fingerprint that does not match (code 17, category pairing). The Pending pairing is revoked; pair again. See Fingerprint cross-confirmation

  • ReplicaIdConflict { replica_id } — a replica pairing named an id already in the group. On the responder this is reported as DeRecEvent::PairingRefused, not an error; see Pairing

  • NoUsableEndpoint { offered } — the transport policy refused every endpoint a peer offered. Terminal at pairing.

Error::as_non_ok_status() returns (status, memo) when the error is a peer's non-Ok answer. There is no conversion from Error to StatusEnum (From<&Error> for StatusEnum was removed in 0.0.9): the library maps a failed request to a wire status itself, and an application calling reject picks its own status.

An error from process is left for what cannot be answered: an envelope that does not decode, a channel with no key, a message that does not decrypt, any other failure of the pairing handshake or of a response this device received, and a store failure before the message could be authenticated. A request that arrived on an authenticated channel and then failed is not an error; see Failed requests.

When process fails

Each process call first settles expired deadlines — sharing-round and unpair-acknowledgement timeouts — and saves the result, then handles the message. If the message then fails, those settled deadlines are never reported again, so the error carries them:

  • ProcessError::events — every event the call produced before failing. Handle them exactly as a successful call's events, then handle the error.

  • ProcessError::channel_id — the channel the message came from. None when the bytes were not a decodable envelope.

A restore that is refused because channels already sit at the recovered roster's ids returns Error::Restore(RestoreError::Conflict(channel_ids)); the vector names the colliding channels.

Failed requests

Every request that arrives on an authenticated channel gets exactly one response, even when handling it fails. A request counts as answered once its response is handed to the transport. Such a failure does not make process or accept return Err: it is reported as DeRecEvent::RequestFailed { channel_id, action_kind, responded, status, memo, error_code, message, action }, and the call's other events (AutoAccepted included) are kept.

  • action_kind — the PendingActionKind of the failed request; PendingActionKind::Failed when its body could not be decoded, or was a request type the channel cannot carry.

  • responded — true when the response was already handed to the transport. It is never sent twice, so a failure after that point is only reported.

  • status, memo — what was sent, or would have been. Always present.

  • error_code, message — the local error's DeRecErrorCode name and description. Neither goes on the wire.

  • action — when responded is false, a PendingAction::RespondToFailure token.

with_auto_respond_on_failure decides who answers:

  • On: the library sends the request's own response type with a non-Ok status. A failure with a protocol meaning keeps its status and memo: REJECTED for a role mismatch, UNSUPPORTED_TRANSPORT_PROTOCOL when no endpoint is usable or an endpoint is refused, and the flow's own status for an invalid update, an unknown share version or a refusal. Anything else (a store backend error, an internal error) is FAIL with the memo "request could not be processed", so no local error text reaches the peer. When no reply target can be resolved before any send, the event carries the token anyway.

  • Off (default): nothing is sent, and the event carries the token. Pass it to reject(token, status, &memo); the event's own status and memo send exactly what the library would have sent. accept(token) returns Error::InvalidInput, and no AutoAcceptPolicy field covers it.

action is None only when reject could never answer: a request on a replica group channel that names no member and carries no reply_to, or, with the option off, a replica copy that hands this device the group key and fails before the key is stored.

The library never expires a PendingAction, a token included; a request nobody answers leaves its sender to time out. PendingAction is Clone, so an application can keep a copy of an action it passes to accept. Resolving each action once is the application's job: rejecting the same token twice, or rejecting a copy of an action already accepted, sends a second response.

Before acting on a persisted action, accept checks its channel again. A channel that is gone or no longer Paired returns Error::InvalidInput, and nothing is stored or sent. A peer that no longer holds the role the flow requires is a failed request with status REJECTED.

A message that decrypts under the channel key but whose body does not decode, or that carries a PairRequest or PrePairRequest on a paired channel, is answered with an ErrorResponseMessage (FORMAT_ERROR, memo "message body could not be decoded"; with the option off, through its token). A received ErrorResponseMessage is reported as DeRecEvent::ErrorResponseReceived { channel_id, status, memo } and never answered. One from a 0.0.8 peer carries no timestamp and is ignored as MessageIgnored { reason: IgnoreReason::TimestampMismatch, .. }.

The protocol's own refusals are answered in both modes, each with its event: ShareRefused (a share that fails validation), ReplicaSecretRefused (a replica copy that does not check) and PairingRefused (a PairRequest outside the parameter range, or naming a replica id already in the group).

Nothing is answered for a message that fails to decrypt, an expired message, a message ignored as MessageIgnored, a response, the pairing handshake, or a replica group's removal notice.

See RequestFailed and ErrorResponseReceived.

Matching responses to requests

The library does not check that a response answers a request this device sent. A response that changes state is applied only against the flow that asked for it (a recovery in progress, the outstanding verification challenge, an unpair started here, a replica discovery in progress, an open sharing round still waiting on that helper); a replica catch-up is applied only when it is newer than what this device holds. DeRecEvent::ShareConfirmed, ShareRejected, SecretsDiscovered, ChannelInfoUpdated, ChannelInfoUpdateRejected and ErrorResponseReceived are reported as they arrive, unmatched. Record what you started (flow, channel, secret, version) and correlate each event against it, using the trace_id of the *Started events where you need an exact pairing. Decide which versions committed from DeRecEvent::SharingComplete { threshold_met, .. }, never by counting ShareConfirmed. See Matching responses to requests.

Matching events exhaustively

DeRecEvent is #[non_exhaustive], so a match on it needs a fallback arm; the 0.0.9 variants are RequestFailed, ErrorResponseReceived, PairingRefused, ShareRefused, ReplicaSecretRefused and ShareVerifyInvalid. PendingActionKind and IgnoreReason are exhaustive enums: a match on them must handle PendingActionKind::Failed, IgnoreReason::TimestampMismatch and IgnoreReason::StaleResponse. A pattern that lists the fields of ShareVerified, VerifySharesFailed, ProtectSecretStarted or ProtectSecretFailed without .. must name the fields added in 0.0.9.

The same codes cross every binding. See the cross-binding error catalog and When process fails.


API Reference

Full Rustdoc lives at docs.rs/derec-library and docs.rs/derec-proto.


SDK Architecture

The .NET, Go and React Native bindings wrap this crate's C ABI (via P/Invoke, purego and a C++/JSI native module respectively); the TypeScript bindings wrap its WASM build. Rust consumers depend on the crate directly, with no FFI layer between the application and the protocol logic.

Last updated