Skip to main content

quai_crypto/
lib.rs

1//! Cryptographic building blocks for Quai applications.
2//!
3//! This crate has no wallet storage or transaction wire-format assumptions.
4//! Secret keys redact diagnostics and zeroize on drop. Imported input buffers
5//! remain the caller's responsibility. Browser entropy uses Web Crypto and is
6//! exercised in the SDK's actual Chromium worker tests.
7
8mod aggregate;
9pub mod curve;
10mod entropy;
11mod hash;
12pub use entropy::{MAX_RANDOM_BYTES, fill_random};
13mod keys;
14mod secret_bytes;
15mod signature_metadata;
16mod signatures;
17/// Exact unsigned integer used by legacy signature metadata helpers.
18pub use ruint::aliases::U256;
19pub use secret_bytes::SecretBytes;
20pub use signature_metadata::{SignatureMetadata, legacy_chain_id, legacy_chain_v, normalized_v};
21
22pub use aggregate::{MAX_AGGREGATE_KEYS, OrderedKeyAggregate};
23pub use hash::{
24    MESSAGE_PREFIX, hash_message, hmac_sha256, hmac_sha512, keccak256, ripemd160, sha256, sha512,
25    verify_hmac_sha256, verify_hmac_sha512,
26};
27pub use keys::{PublicKey, SecretKey};
28pub use signatures::{RecoverableSignature, SchnorrPublicKey, SchnorrSignature};
29
30/// Recover the address signing exact personal-message bytes. Text callers pass
31/// UTF-8 bytes; hex-looking text is not decoded. Recovery does not authenticate
32/// an expected signer: compare the returned address with the authorized address.
33pub fn recover_message_signer(
34    message: &[u8],
35    signature: &RecoverableSignature,
36) -> Result<quai_primitives::Address, CryptoError> {
37    signature
38        .recover_prehash(&hash_message(message))
39        .map(PublicKey::address)
40}
41
42/// Errors never include secret input or backend diagnostic strings.
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44#[non_exhaustive]
45pub enum CryptoError {
46    /// A scalar encoding is outside the secp256k1 group order.
47    InvalidScalar,
48    /// A multipart hash exceeds its explicit part, tag or byte limit.
49    HashLimit,
50    /// A secret scalar is zero or outside the secp256k1 group order.
51    InvalidSecretKey,
52    /// Ordered key aggregation requires two through the configured maximum keys.
53    InvalidKeyCount,
54    /// Public aggregation produced an invalid or infinite aggregate.
55    InvalidKeyAggregation,
56    /// Owned secret keys do not match the context's exact ordered public key list.
57    InvalidSecretKeySet,
58    /// A public key has invalid SEC1 encoding or is not a nonidentity curve point.
59    InvalidPublicKey,
60    /// A signature is malformed, noncanonical or has invalid scalar values.
61    InvalidSignature,
62    /// A signature has high S; the caller must not silently rewrite wire intent.
63    HighS,
64    /// The recovery identifier is not in the mathematical range zero through three.
65    InvalidRecoveryId,
66    /// The signature uses a recovery bit not representable in the Quai JS parity form.
67    UnsupportedRecoveryId,
68    /// Signature creation failed.
69    SigningFailed,
70    /// Signature verification or public-key recovery failed.
71    VerificationFailed,
72    /// The operating system could not provide usable cryptographic randomness.
73    RandomnessUnavailable,
74    /// Requested random output exceeds the explicit shared native/browser bound.
75    RandomRequestTooLarge,
76}
77
78impl core::fmt::Display for CryptoError {
79    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
80        f.write_str(match self {
81            Self::InvalidScalar => "invalid secp256k1 scalar",
82            Self::HashLimit => "hash input exceeds resource limit",
83            Self::InvalidSecretKey => "invalid secp256k1 secret key",
84            Self::InvalidKeyCount => "invalid ordered aggregation key count",
85            Self::InvalidKeyAggregation => "invalid ordered public key aggregate",
86            Self::InvalidSecretKeySet => "secret keys do not match ordered aggregation context",
87            Self::InvalidPublicKey => "invalid secp256k1 public key",
88            Self::InvalidSignature => "invalid signature",
89            Self::HighS => "noncanonical high-S signature",
90            Self::InvalidRecoveryId => "invalid recovery identifier",
91            Self::UnsupportedRecoveryId => {
92                "recovery identifier cannot be represented by Quai parity"
93            }
94            Self::SigningFailed => "signature generation failed",
95            Self::VerificationFailed => "signature verification failed",
96            Self::RandomnessUnavailable => "cryptographic randomness unavailable",
97            Self::RandomRequestTooLarge => "random output exceeds resource limit",
98        })
99    }
100}
101impl std::error::Error for CryptoError {}