derec-library 0.1.0

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
Documentation
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! # Error Types
//!
//! This module defines the top-level error type returned by the public APIs
//! of the library.
//!
//! ## Error model
//!
//! The crate exposes a unified [`Error`] type that wraps the error types
//! produced by each protocol flow:
//!
//! - pairing
//! - sharing
//! - verification
//! - recovery
//! - discovery
//!
//! Each flow defines its own specialized error type, which is converted into
//! [`Error`] using `From` conversions. This allows public functions to return
//! `Result<T, crate::Error>` while still preserving the precise cause of the
//! failure.
//!
//! Applications consuming this library may pattern match on the [`Error`]
//! variants to determine which protocol phase produced the error.
//!
//! ## Non-exhaustive
//!
//! The [`Error`] enum is marked `#[non_exhaustive]`, meaning additional variants
//! may be introduced in future versions without breaking API compatibility.
//! Consumers should include a fallback match arm when matching on this type.
//!
//! ## Internal invariants
//!
//! Some variants represent violations of internal invariants. These indicate
//! logic errors or unexpected states and should normally not occur in correct
//! usage of the library.

use derec_proto::SenderKind;

use crate::derec_message::DeRecMessageBuilderError;
use crate::primitives::{
    discovery::DiscoveryError, pairing::PairingError, recovery::RecoveryError,
    sharing::SharingError, unpairing::UnpairingError, verification::VerificationError,
};
use crate::protocol::{
    ChannelStoreError, RestoreError, SecretStoreError, ShareStoreError, StateStoreError,
};
use crate::transport::TransportValidationError;
use crate::types::ChannelId;

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error(transparent)]
    Pairing(#[from] PairingError),

    #[error(transparent)]
    Recovery(#[from] RecoveryError),

    #[error(transparent)]
    Discovery(#[from] DiscoveryError),

    #[error(transparent)]
    Sharing(#[from] SharingError),

    #[error(transparent)]
    Verification(#[from] VerificationError),

    #[error(transparent)]
    Unpairing(#[from] UnpairingError),

    #[error(transparent)]
    Restore(#[from] RestoreError),

    #[error(transparent)]
    DeRecMessage(#[from] DeRecMessageBuilderError),

    #[error(transparent)]
    SecretStore(#[from] SecretStoreError),

    #[error(transparent)]
    ChannelStore(#[from] ChannelStoreError),

    #[error(transparent)]
    ShareStore(#[from] ShareStoreError),

    #[error(transparent)]
    StateStore(#[from] StateStoreError),

    #[error(transparent)]
    Transport(#[from] TransportValidationError),

    #[error("invalid input: {0}")]
    InvalidInput(&'static str),

    #[error("protobuf decode error")]
    ProtobufDecode(#[source] prost::DecodeError),

    #[error("protobuf encode error")]
    ProtobufEncode(#[source] prost::EncodeError),

    #[error("internal invariant violated: {0}")]
    Invariant(&'static str),

    #[error("role mismatch on channel {channel_id:?}: expected {expected:?}, got {actual:?}")]
    RoleMismatch {
        channel_id: ChannelId,
        expected: SenderKind,
        actual: SenderKind,
    },

    /// `start(Pairing)` was called for a `channel_id` this device already
    /// uses: it has a `Paired` or `Unpairing` channel record, a replica
    /// member is recorded on it, or a key is stored under it. The contact's
    /// creator chooses its channel identifier, and pairing on one in use
    /// would overwrite or later remove the key stored there; the caller must
    /// skip the call, or unpair first and wait for
    /// [`DeRecEvent::Unpaired`](crate::protocol::DeRecEvent::Unpaired).
    #[error("channel {channel_id:?} is already paired")]
    ChannelAlreadyPaired { channel_id: ChannelId },

    /// A replica-mode flow was attempted but the protocol was built without
    /// [`DeRecProtocolBuilder::with_replica_id`](crate::protocol::DeRecProtocolBuilder::with_replica_id).
    /// Surfaces at the entry points of every flow that requires a local
    /// replica identity (initiating a replica-mode pairing, handling an
    /// inbound `PairRequest` whose `sender_kind` is `ReplicaSource` or
    /// `ReplicaDestination`, etc.).
    #[error(
        "replica id not configured: build the protocol with .with_replica_id(..) to enable replica flows"
    )]
    ReplicaIdNotConfigured,

    /// A replica pairing named a `replica_id` already held by another member
    /// of the group — including this device itself.
    ///
    /// The roster is keyed by `replica_id` and messages between members are
    /// attributed by it, so two members sharing one would overwrite each
    /// other's row and make every acknowledgement ambiguous. Raised before
    /// fingerprint verification: there is no point asking a user to confirm a
    /// pairing that cannot complete.
    ///
    /// Raised by the initiator, which learns the responder's id from its
    /// `PairResponse`. A responder that receives a colliding `PairRequest`
    /// instead refuses it with a `PairResponse` carrying `REPLICA_ID_CONFLICT`
    /// and reports
    /// [`DeRecEvent::PairingRefused`](crate::protocol::DeRecEvent::PairingRefused).
    ///
    /// `replica_id` is assigned by the application, so this is a
    /// configuration fault — most often the same identity reused on two
    /// devices. Resolution is the application's: assign a distinct id and
    /// pair again. The protocol cannot choose, because it cannot know which
    /// device is meant to keep the original.
    #[error("replica id {replica_id} is already in use by another member of the group")]
    ReplicaIdConflict { replica_id: u64 },

    /// The fingerprint compared out of band does not match the one derived
    /// from the channel key.
    ///
    /// The two sides hold different keys, which is what a man-in-the-middle
    /// on the pairing produces. A `Pending` pairing is revoked: its records,
    /// its channel key and its pairing material are deleted, so the channel
    /// can never be used. Pairing again is the only way forward. A channel
    /// already `Paired` is left as it is; removing it is an unpair.
    #[error("fingerprint does not match channel {channel_id:?}: possible man-in-the-middle")]
    FingerprintMismatch { channel_id: ChannelId },

    /// A [`DeRecTransport`](crate::protocol::DeRecTransport) reported that
    /// a message reached none of the peer's endpoints.
    ///
    /// The variant a transport returns when delivery failed, and the one the
    /// FFI and WASM bindings report when the application's transport
    /// callback fails, so the same failure reads the same in every SDK. The
    /// protocol state a failed send leaves is the same as for a message lost
    /// in transit: the request is retried, or times out.
    #[error("transport send failed: the message reached none of the peer's endpoints")]
    TransportSendFailed,

    /// A peer advertised no endpoint this library will record.
    ///
    /// Every endpoint it offered failed [`TransportPolicy`] — typically all
    /// of them were plaintext while plaintext is not opted into. Terminal:
    /// delivery is push-only, so a peer that cannot be reached cannot be
    /// sent a rejection either. The application tells the user; the protocol
    /// has nothing further to try.
    ///
    /// This is *not* a mismatch between the two sides' transports. The
    /// library no longer compares them — it records what a peer offers and
    /// leaves the choice of which to dial to
    /// [`DeRecTransport`](crate::protocol::DeRecTransport).
    ///
    /// [`TransportPolicy`]: crate::transport::TransportPolicy
    #[error(
        "peer advertised no usable transport endpoint; all {offered} offer(s) \
         were refused by transport policy"
    )]
    NoUsableEndpoint {
        /// How many endpoints the peer offered before filtering.
        offered: usize,
    },
}

impl Error {
    /// The channel this error is about, for the variants that name one:
    /// [`Error::ChannelAlreadyPaired`], [`Error::FingerprintMismatch`] and
    /// [`Error::RoleMismatch`]. Every SDK reports it as the error's
    /// `channel_id`.
    pub fn channel_id(&self) -> Option<ChannelId> {
        match self {
            Error::ChannelAlreadyPaired { channel_id }
            | Error::FingerprintMismatch { channel_id }
            | Error::RoleMismatch { channel_id, .. } => Some(*channel_id),
            _ => None,
        }
    }

    pub fn as_non_ok_status(&self) -> Option<(i32, &str)> {
        match self {
            Error::Pairing(PairingError::NonOkStatus { status, memo }) => Some((*status, memo)),
            Error::Sharing(SharingError::NonOkStatus { status, memo }) => Some((*status, memo)),
            Error::Verification(VerificationError::NonOkStatus { status, memo }) => {
                Some((*status, memo))
            }
            Error::Discovery(DiscoveryError::NonOkStatus { status, memo }) => Some((*status, memo)),
            Error::Recovery(RecoveryError::NonOkStatus { status, memo }) => Some((*status, memo)),
            Error::Unpairing(UnpairingError::NonOkStatus { status, memo }) => Some((*status, memo)),
            _ => None,
        }
    }
}