Skip to main content

quai_signer/
lib.rs

1//! Local signing binds a key to an explicit chain; no network or automatic sends.
2pub use quai_abi::TypedData;
3use quai_consensus::{
4    QiTransaction, QuaiTransaction, SignedQiTransaction, SignedQuaiTransaction, U256,
5};
6use quai_crypto::{
7    PublicKey, RecoverableSignature, SchnorrPublicKey, SchnorrSignature, SecretKey, hash_message,
8    keccak256,
9};
10use quai_primitives::{Address, QiAddress};
11use std::fmt;
12use thiserror::Error;
13
14/// Explicit policy for typed-data domains that omit a chain identifier.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum DomainPolicy {
17    /// Require the domain's chain ID to equal the signer's configured chain.
18    RequireChainId,
19    /// Permit an absent/null chain ID; any present chain ID must still match.
20    /// Such signatures may be usable on multiple chains and require explicit review.
21    AllowUnbound,
22}
23
24impl DomainPolicy {
25    /// Check a validated document against an explicit nonzero chain before any signing prompt.
26    pub fn validate(self, data: &TypedData, chain_id: U256) -> Result<(), SignerError> {
27        if chain_id == U256::ZERO {
28            return Err(SignerError::ChainMismatch);
29        }
30        match data.domain().get("chainId").filter(|v| !v.is_null()) {
31            None if self == DomainPolicy::RequireChainId => {
32                return Err(SignerError::ChainMismatch);
33            }
34            None => (),
35            Some(value) => {
36                let chain = match value {
37                    serde_json::Value::Number(n) => n
38                        .as_u64()
39                        .map(U256::from)
40                        .ok_or(SignerError::ChainMismatch)?,
41                    serde_json::Value::String(text) => {
42                        let (digits, radix) = text
43                            .strip_prefix("0x")
44                            .or_else(|| text.strip_prefix("0X"))
45                            .map_or((text.as_str(), 10), |digits| (digits, 16));
46                        U256::from_str_radix(digits, radix)
47                            .map_err(|_| SignerError::ChainMismatch)?
48                    }
49                    _ => return Err(SignerError::ChainMismatch),
50                };
51                if chain != chain_id {
52                    return Err(SignerError::ChainMismatch);
53                }
54            }
55        }
56        Ok(())
57    }
58}
59
60/// Signing failures contain no key, payload or backend diagnostic strings.
61#[derive(Debug, Error)]
62#[non_exhaustive]
63pub enum SignerError {
64    /// The configured chain must be nonzero and equal the transaction chain.
65    #[error("signer chain ID mismatch or invalid chain ID")]
66    ChainMismatch,
67    /// The key/address must select a supported zone.
68    #[error("signer address does not select a supported zone")]
69    InvalidAddress,
70    /// A watch-only signer cannot authorize transactions or messages.
71    #[error("watch-only signer cannot sign")]
72    WatchOnly,
73    /// Invalid ledger, transaction or signature.
74    #[error("transaction signing failed validation")]
75    InvalidTransaction,
76    /// Message signature creation failed.
77    #[error("message signing failed")]
78    MessageSigning,
79    /// The Qi message would also be a valid Qi transaction signature.
80    #[error("refusing to sign a Qi transaction as a message")]
81    QiTransactionMessage,
82    /// This signer has not implemented the distinct Qi message format.
83    #[error("Qi message signing is unsupported by this signer")]
84    QiMessageUnsupported,
85    /// This adapter has not implemented typed-data signing.
86    #[error("typed-data signing is unsupported by this signer")]
87    TypedDataUnsupported,
88}
89
90/// Synchronous local-signing contract; remote/browser signing adapters are separate.
91pub trait Signer {
92    /// Public signing address.
93    fn address(&self) -> Address;
94    /// The chain explicitly bound to this signer.
95    fn chain_id(&self) -> U256;
96    /// Sign the exact Quai payload after checking the configured chain.
97    fn sign_quai(
98        &self,
99        transaction: &QuaiTransaction,
100    ) -> Result<SignedQuaiTransaction, SignerError>;
101    /// Sign an ordinary single-input Qi transfer after checking chain and key ownership.
102    fn sign_qi_single(
103        &self,
104        transaction: &QiTransaction,
105    ) -> Result<SignedQiTransaction, SignerError>;
106    /// Personal-message ECDSA signature. This format does not bind chain ID.
107    fn sign_message(&self, message: &[u8]) -> Result<RecoverableSignature, SignerError>;
108    /// Qi BIP340 signature over Keccak(message), with no prefix or chain binding.
109    /// String callers must explicitly supply UTF-8 bytes. Requires a Qi key.
110    fn sign_qi_message(&self, _message: &[u8]) -> Result<SchnorrSignature, SignerError> {
111        Err(SignerError::QiMessageUnsupported)
112    }
113    /// Sign an immutable validated typed-data document with explicit domain policy.
114    fn sign_typed_data(
115        &self,
116        _data: &TypedData,
117        _policy: DomainPolicy,
118    ) -> Result<RecoverableSignature, SignerError> {
119        Err(SignerError::TypedDataUnsupported)
120    }
121}
122
123/// A non-cloneable zeroizing local key bound to a chain identity.
124pub struct LocalSigner {
125    key: SecretKey,
126    address: Address,
127    chain_id: U256,
128}
129impl LocalSigner {
130    /// Full public key, required to bind a Qi message signature to its address.
131    pub fn public_key(&self) -> PublicKey {
132        self.key.public_key()
133    }
134    /// Bind a validated key to a nonzero chain and known address zone.
135    pub fn new(key: SecretKey, chain_id: U256) -> Result<Self, SignerError> {
136        if chain_id == U256::ZERO {
137            return Err(SignerError::ChainMismatch);
138        }
139        let address = key.public_key().address();
140        address.zone().map_err(|_| SignerError::InvalidAddress)?;
141        Ok(Self {
142            key,
143            address,
144            chain_id,
145        })
146    }
147}
148impl fmt::Debug for LocalSigner {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.debug_struct("LocalSigner")
151            .field("address", &self.address)
152            .field("chain_id", &self.chain_id)
153            .finish_non_exhaustive()
154    }
155}
156impl Signer for LocalSigner {
157    fn address(&self) -> Address {
158        self.address
159    }
160    fn chain_id(&self) -> U256 {
161        self.chain_id
162    }
163    fn sign_quai(&self, tx: &QuaiTransaction) -> Result<SignedQuaiTransaction, SignerError> {
164        if tx.chain_id != self.chain_id {
165            return Err(SignerError::ChainMismatch);
166        }
167        tx.sign(&self.key)
168            .map_err(|_| SignerError::InvalidTransaction)
169    }
170    fn sign_qi_single(&self, tx: &QiTransaction) -> Result<SignedQiTransaction, SignerError> {
171        if tx.chain_id != self.chain_id {
172            return Err(SignerError::ChainMismatch);
173        }
174        tx.sign_single(&self.key)
175            .map_err(|_| SignerError::InvalidTransaction)
176    }
177    fn sign_message(&self, message: &[u8]) -> Result<RecoverableSignature, SignerError> {
178        self.key
179            .sign_prehash(&hash_message(message))
180            .map_err(|_| SignerError::MessageSigning)
181    }
182    fn sign_qi_message(&self, message: &[u8]) -> Result<SchnorrSignature, SignerError> {
183        sign_qi_message(&self.key, message)
184    }
185    fn sign_typed_data(
186        &self,
187        data: &TypedData,
188        policy: DomainPolicy,
189    ) -> Result<RecoverableSignature, SignerError> {
190        policy.validate(data, self.chain_id)?;
191        self.key
192            .sign_prehash(data.signing_hash().bytes())
193            .map_err(|_| SignerError::MessageSigning)
194    }
195}
196
197/// Public identity with an explicit inability to sign, suitable for watch-only applications.
198#[derive(Clone, Copy, Debug)]
199pub struct WatchOnlySigner {
200    address: Address,
201    chain_id: U256,
202}
203impl WatchOnlySigner {
204    /// Bind a known-zone public address to a nonzero chain.
205    pub fn new(address: Address, chain_id: U256) -> Result<Self, SignerError> {
206        if chain_id == U256::ZERO {
207            return Err(SignerError::ChainMismatch);
208        }
209        address.zone().map_err(|_| SignerError::InvalidAddress)?;
210        Ok(Self { address, chain_id })
211    }
212}
213impl Signer for WatchOnlySigner {
214    fn address(&self) -> Address {
215        self.address
216    }
217    fn chain_id(&self) -> U256 {
218        self.chain_id
219    }
220    fn sign_quai(&self, _: &QuaiTransaction) -> Result<SignedQuaiTransaction, SignerError> {
221        Err(SignerError::WatchOnly)
222    }
223    fn sign_qi_single(&self, _: &QiTransaction) -> Result<SignedQiTransaction, SignerError> {
224        Err(SignerError::WatchOnly)
225    }
226    fn sign_message(&self, _: &[u8]) -> Result<RecoverableSignature, SignerError> {
227        Err(SignerError::WatchOnly)
228    }
229    fn sign_qi_message(&self, _: &[u8]) -> Result<SchnorrSignature, SignerError> {
230        Err(SignerError::WatchOnly)
231    }
232    fn sign_typed_data(
233        &self,
234        _: &TypedData,
235        _: DomainPolicy,
236    ) -> Result<RecoverableSignature, SignerError> {
237        Err(SignerError::WatchOnly)
238    }
239}
240
241/// Sign the published Qi wallet message format: BIP340 over Keccak(raw bytes).
242/// No prefix, length, network or application domain is inserted. Callers own the
243/// exact message semantics. Fresh auxiliary entropy is required on each call.
244///
245/// Every Qi spend signs BIP340 over Keccak of its unsigned protobuf, so without
246/// a domain prefix a message whose bytes are an unsigned transaction yields a
247/// valid spend signature: a requester could present a transfer of the signer's
248/// output as a "message". The format is fixed by the published wallets, so the
249/// prefix cannot be added. Instead, any message that parses as a transaction
250/// with inputs, which every Qi spend has, is refused with
251/// [`SignerError::QiTransactionMessage`]. The parse is lenient, so an oversized
252/// or non-canonical encoding is refused too rather than slipping past a strict
253/// decoder.
254pub fn sign_qi_message(key: &SecretKey, message: &[u8]) -> Result<SchnorrSignature, SignerError> {
255    QiAddress::try_from(key.public_key().address()).map_err(|_| SignerError::InvalidAddress)?;
256    if quai_consensus::has_transaction_inputs(message) {
257        return Err(SignerError::QiTransactionMessage);
258    }
259    key.sign_schnorr(&keccak256(message))
260        .map_err(|_| SignerError::MessageSigning)
261}
262
263/// Verify the Qi message format against an explicit full public key and address.
264/// BIP340 has no recovery byte; an x-only key cannot select the address's Y parity.
265pub fn verify_qi_message(
266    address: QiAddress,
267    public_key: &PublicKey,
268    message: &[u8],
269    signature: &SchnorrSignature,
270) -> Result<(), SignerError> {
271    if public_key.address() != address.address() {
272        return Err(SignerError::InvalidAddress);
273    }
274    let compressed = public_key.to_compressed();
275    let mut x = [0; 32];
276    x.copy_from_slice(&compressed[1..]);
277    SchnorrPublicKey::from_bytes(&x)
278        .and_then(|key| key.verify(&keccak256(message), signature))
279        .map_err(|_| SignerError::MessageSigning)
280}