Skip to main content

aptos_sdk/crypto/
secp256k1.rs

1//! Secp256k1 ECDSA signature scheme implementation.
2//!
3//! Secp256k1 is the same elliptic curve used by Bitcoin and Ethereum.
4//!
5//! # Security: Signature Malleability
6//!
7//! This implementation enforces **low-S only** signatures to match the Aptos
8//! blockchain's on-chain verification, which rejects high-S signatures to
9//! prevent signature malleability attacks.
10//!
11//! - **Signing** always produces low-S signatures (the `k256` crate normalizes
12//!   by default).
13//! - **Parsing** (`from_bytes`, `from_hex`) rejects high-S signatures.
14//! - **Verification** also rejects high-S signatures as a defense-in-depth
15//!   measure.
16
17use crate::crypto::traits::{PublicKey, Signature, Signer, Verifier};
18use crate::error::{AptosError, AptosResult};
19use k256::ecdsa::{
20    Signature as K256Signature, SigningKey, VerifyingKey,
21    signature::hazmat::{PrehashSigner, PrehashVerifier},
22};
23use k256::elliptic_curve::Generate;
24use serde::{Deserialize, Serialize};
25use std::fmt;
26use zeroize::Zeroize;
27
28/// Secp256k1 private key length in bytes.
29pub const SECP256K1_PRIVATE_KEY_LENGTH: usize = 32;
30/// Secp256k1 public key length in bytes (compressed).
31pub const SECP256K1_PUBLIC_KEY_LENGTH: usize = 33;
32/// Secp256k1 uncompressed public key length in bytes.
33#[allow(dead_code)] // Public API constant
34pub const SECP256K1_PUBLIC_KEY_UNCOMPRESSED_LENGTH: usize = 65;
35/// Secp256k1 signature length in bytes (raw fixed-width `r || s`, 32 bytes each).
36pub const SECP256K1_SIGNATURE_LENGTH: usize = 64;
37
38/// A Secp256k1 ECDSA private key.
39///
40/// The private key is zeroized when dropped.
41#[derive(Clone, Zeroize)]
42#[zeroize(drop)]
43pub struct Secp256k1PrivateKey {
44    #[zeroize(skip)]
45    #[allow(unused)] // Field is used; lint false positive from Zeroize derive
46    inner: SigningKey,
47}
48
49impl Secp256k1PrivateKey {
50    /// Generates a new random Secp256k1 private key.
51    pub fn generate() -> Self {
52        let signing_key = SigningKey::generate();
53        Self { inner: signing_key }
54    }
55
56    /// Creates a private key from raw bytes.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`AptosError::InvalidPrivateKey`] if:
61    /// - The byte slice length is not exactly 32 bytes
62    /// - The bytes do not represent a valid Secp256k1 private key
63    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
64        if bytes.len() != SECP256K1_PRIVATE_KEY_LENGTH {
65            return Err(AptosError::InvalidPrivateKey(format!(
66                "expected {} bytes, got {}",
67                SECP256K1_PRIVATE_KEY_LENGTH,
68                bytes.len()
69            )));
70        }
71        let signing_key = SigningKey::from_slice(bytes)
72            .map_err(|e| AptosError::InvalidPrivateKey(e.to_string()))?;
73        Ok(Self { inner: signing_key })
74    }
75
76    /// Creates a private key from a hex string.
77    ///
78    /// # Errors
79    ///
80    /// Returns [`AptosError::Hex`] if the hex string is invalid.
81    /// Returns [`AptosError::InvalidPrivateKey`] if the decoded bytes are not exactly 32 bytes or do not represent a valid Secp256k1 private key.
82    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
83        let bytes = const_hex::decode(hex_str)?;
84        Self::from_bytes(&bytes)
85    }
86
87    /// Creates a private key from AIP-80 format string.
88    ///
89    /// AIP-80 format: `secp256k1-priv-0x{hex_bytes}`
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if the format is invalid or the key bytes are invalid.
94    pub fn from_aip80(s: &str) -> AptosResult<Self> {
95        const PREFIX: &str = "secp256k1-priv-";
96        if let Some(hex_part) = s.strip_prefix(PREFIX) {
97            Self::from_hex(hex_part)
98        } else {
99            Err(AptosError::InvalidPrivateKey(format!(
100                "invalid AIP-80 format: expected prefix '{PREFIX}'"
101            )))
102        }
103    }
104
105    /// Returns the private key as bytes.
106    pub fn to_bytes(&self) -> [u8; SECP256K1_PRIVATE_KEY_LENGTH] {
107        self.inner.to_bytes().into()
108    }
109
110    /// Returns the private key as a hex string.
111    pub fn to_hex(&self) -> String {
112        const_hex::encode_prefixed(self.inner.to_bytes())
113    }
114
115    /// Returns the private key in AIP-80 format.
116    ///
117    /// AIP-80 format: `secp256k1-priv-0x{hex_bytes}`
118    pub fn to_aip80(&self) -> String {
119        format!("secp256k1-priv-{}", self.to_hex())
120    }
121
122    /// Returns the corresponding public key.
123    pub fn public_key(&self) -> Secp256k1PublicKey {
124        Secp256k1PublicKey {
125            inner: *self.inner.verifying_key(),
126        }
127    }
128
129    /// Signs `message` and returns a low-S ECDSA signature over the
130    /// `SHA3-256` digest of `message`.
131    ///
132    /// Aptos on-chain verification (see `aptos-crypto::secp256k1_ecdsa::Signature::verify`)
133    /// hashes the signing-message preimage with **SHA-3-256** before invoking
134    /// ECDSA on the 32-byte digest. We mirror that flow exactly: compute the
135    /// SHA-3-256 digest first, then sign it via `PrehashSigner` so the k256
136    /// crate does not apply its default SHA-256 internally.
137    ///
138    /// Historical note: prior versions of this SDK relied on `Signer::sign`
139    /// which does an internal SHA-256, producing a signature over
140    /// `SHA-256(message)` (or, with a SHA-256 pre-hash, over
141    /// `SHA-256(SHA-256(message))`). Both forms verified internally but
142    /// were rejected by the chain because the chain hashes with SHA-3-256.
143    ///
144    /// # Panics
145    ///
146    /// Panics only in the (mathematically impossible) case that
147    /// `k256::ecdsa::SigningKey::sign_prehash` returns `Err` for a 32-byte
148    /// prehash, which the `signature::hazmat::PrehashSigner` contract for
149    /// `secp256k1` does not produce.
150    pub fn sign(&self, message: &[u8]) -> Secp256k1Signature {
151        let digest = crate::crypto::sha3_256(message);
152        let signature: K256Signature = self
153            .inner
154            .sign_prehash(&digest)
155            .expect("32-byte SHA3-256 digest is a valid ECDSA prehash");
156        // SECURITY: Ensure low-S (defense-in-depth; k256 should already do this)
157        let normalized = signature.normalize_s();
158        Secp256k1Signature { inner: normalized }
159    }
160
161    /// Signs a 32-byte pre-computed digest directly, with NO further hashing.
162    ///
163    /// The caller is responsible for ensuring `digest` is the correct hash
164    /// for the on-chain verification scheme (Aptos uses SHA-3-256).
165    ///
166    /// # Panics
167    ///
168    /// Panics only if `k256::ecdsa::SigningKey::sign_prehash` returns `Err`
169    /// for the supplied 32-byte digest, which the
170    /// `signature::hazmat::PrehashSigner` contract for `secp256k1` does not
171    /// produce.
172    pub fn sign_prehashed(&self, digest: &[u8; 32]) -> Secp256k1Signature {
173        let signature: K256Signature = self
174            .inner
175            .sign_prehash(digest)
176            .expect("32-byte digest is a valid ECDSA prehash");
177        let normalized = signature.normalize_s();
178        Secp256k1Signature { inner: normalized }
179    }
180}
181
182impl Signer for Secp256k1PrivateKey {
183    type Signature = Secp256k1Signature;
184
185    fn sign(&self, message: &[u8]) -> Secp256k1Signature {
186        Secp256k1PrivateKey::sign(self, message)
187    }
188
189    fn public_key(&self) -> Secp256k1PublicKey {
190        Secp256k1PrivateKey::public_key(self)
191    }
192}
193
194impl fmt::Debug for Secp256k1PrivateKey {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        write!(f, "Secp256k1PrivateKey([REDACTED])")
197    }
198}
199
200/// A Secp256k1 ECDSA public key.
201#[derive(Clone, Copy, PartialEq, Eq)]
202pub struct Secp256k1PublicKey {
203    inner: VerifyingKey,
204}
205
206impl Secp256k1PublicKey {
207    /// Creates a public key from bytes in any accepted encoding.
208    ///
209    /// Accepts all of the following:
210    /// - 33-byte SEC1 compressed (`0x02`/`0x03` prefix)
211    /// - 65-byte SEC1 uncompressed (`0x04` prefix)
212    /// - 64-byte raw `X || Y` affine coordinates (the Aptos on-chain encoding,
213    ///   with the leading `0x04` marker dropped)
214    ///
215    /// # Errors
216    ///
217    /// Returns [`AptosError::InvalidPublicKey`] if the bytes do not decode to a
218    /// valid Secp256k1 public key in one of the accepted encodings.
219    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
220        // Accept any SEC1-style encoding (33 compressed, 65 uncompressed) as
221        // before; *also* accept the raw 64-byte `(X || Y)` Aptos on-chain
222        // format by reconstructing the SEC1 uncompressed form (a leading 0x04
223        // followed by the 64 raw bytes).
224        if bytes.len() == 64 {
225            let mut sec1 = Vec::with_capacity(65);
226            sec1.push(0x04);
227            sec1.extend_from_slice(bytes);
228            return VerifyingKey::from_sec1_bytes(&sec1)
229                .map(|inner| Self { inner })
230                .map_err(|e| AptosError::InvalidPublicKey(e.to_string()));
231        }
232        let verifying_key = VerifyingKey::from_sec1_bytes(bytes)
233            .map_err(|e| AptosError::InvalidPublicKey(e.to_string()))?;
234        Ok(Self {
235            inner: verifying_key,
236        })
237    }
238
239    /// Creates a public key from a hex string.
240    ///
241    /// # Errors
242    ///
243    /// Returns [`AptosError::Hex`] if the hex string is invalid.
244    /// Returns [`AptosError::InvalidPublicKey`] if the decoded bytes do not represent a valid
245    /// Secp256k1 public key in one of the encodings accepted by [`Self::from_bytes`]
246    /// (33-byte compressed, 65-byte SEC1 uncompressed, or 64-byte raw `X || Y`).
247    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
248        let bytes = const_hex::decode(hex_str)?;
249        Self::from_bytes(&bytes)
250    }
251
252    /// Creates a public key from AIP-80 format string.
253    ///
254    /// AIP-80 format: `secp256k1-pub-0x{hex_bytes}`
255    ///
256    /// # Errors
257    ///
258    /// Returns an error if the format is invalid or the key bytes are invalid.
259    pub fn from_aip80(s: &str) -> AptosResult<Self> {
260        const PREFIX: &str = "secp256k1-pub-";
261        if let Some(hex_part) = s.strip_prefix(PREFIX) {
262            Self::from_hex(hex_part)
263        } else {
264            Err(AptosError::InvalidPublicKey(format!(
265                "invalid AIP-80 format: expected prefix '{PREFIX}'"
266            )))
267        }
268    }
269
270    /// Returns the public key as compressed bytes (33 bytes).
271    pub fn to_bytes(&self) -> Vec<u8> {
272        self.inner.to_sec1_bytes().to_vec()
273    }
274
275    /// Returns the public key in SEC1 uncompressed encoding (65 bytes, leading 0x04 marker).
276    ///
277    /// Most Aptos on-chain APIs use the *raw* 64-byte encoding (the `X || Y`
278    /// coordinates with the 0x04 marker dropped) -- see [`Self::to_raw_bytes`].
279    /// This method is retained for callers that need the SEC1 form.
280    pub fn to_uncompressed_bytes(&self) -> Vec<u8> {
281        self.inner.to_sec1_point(false).as_bytes().to_vec()
282    }
283
284    /// Returns the public key as the raw 64 bytes of the `X || Y` affine
285    /// coordinates, without the leading SEC1 0x04 uncompressed-point marker.
286    ///
287    /// This is the encoding expected by `aptos-stdlib`'s
288    /// `secp256k1::ecdsa_raw_public_key_from_64_bytes` and by the
289    /// `AnyPublicKey::Secp256k1Ecdsa` variant on-chain (each variant carries a
290    /// `vector<u8>` of length 64).
291    pub fn to_raw_bytes(&self) -> [u8; 64] {
292        let uncompressed = self.to_uncompressed_bytes();
293        // The encoded form is always `0x04 || X(32) || Y(32)` so we can safely
294        // drop the first byte here.
295        debug_assert_eq!(uncompressed.len(), 65);
296        debug_assert_eq!(uncompressed[0], 0x04);
297        let mut out = [0u8; 64];
298        out.copy_from_slice(&uncompressed[1..]);
299        out
300    }
301
302    /// Returns the public key as a hex string (compressed format).
303    pub fn to_hex(&self) -> String {
304        const_hex::encode_prefixed(self.to_bytes())
305    }
306
307    /// Returns the public key in AIP-80 format (compressed).
308    ///
309    /// AIP-80 format: `secp256k1-pub-0x{hex_bytes}`
310    pub fn to_aip80(&self) -> String {
311        format!("secp256k1-pub-{}", self.to_hex())
312    }
313
314    /// Verifies a signature against a message.
315    ///
316    /// # Security
317    ///
318    /// Rejects high-S signatures before verification, matching Aptos on-chain
319    /// behavior. This is a defense-in-depth check; signatures created through
320    /// this SDK's `from_bytes` are already guaranteed to be low-S.
321    ///
322    /// # Errors
323    ///
324    /// Returns [`AptosError::SignatureVerificationFailed`] if the signature has
325    /// a high-S value, is invalid, or does not match the message.
326    pub fn verify(&self, message: &[u8], signature: &Secp256k1Signature) -> AptosResult<()> {
327        // SECURITY: Reject high-S signatures (matches aptos-core behavior)
328        if signature.inner.normalize_s() != signature.inner {
329            return Err(AptosError::SignatureVerificationFailed);
330        }
331        // Aptos hashes secp256k1 signing messages with SHA-3-256 -- not SHA-256.
332        // Match that exactly via `verify_prehash` so k256 does not apply its
333        // default SHA-256 hashing.
334        let digest = crate::crypto::sha3_256(message);
335        self.inner
336            .verify_prehash(&digest, &signature.inner)
337            .map_err(|_| AptosError::SignatureVerificationFailed)
338    }
339
340    /// Verifies a signature against a pre-hashed message.
341    ///
342    /// # Security
343    ///
344    /// Rejects high-S signatures before verification, matching Aptos on-chain
345    /// behavior.
346    ///
347    /// # Errors
348    ///
349    /// Returns [`AptosError::SignatureVerificationFailed`] if the signature has
350    /// a high-S value, is invalid, or does not match the hash.
351    pub fn verify_prehashed(
352        &self,
353        hash: &[u8; 32],
354        signature: &Secp256k1Signature,
355    ) -> AptosResult<()> {
356        // SECURITY: Reject high-S signatures (matches aptos-core behavior)
357        if signature.inner.normalize_s() != signature.inner {
358            return Err(AptosError::SignatureVerificationFailed);
359        }
360        // Verify against the 32-byte digest directly (no additional hashing).
361        self.inner
362            .verify_prehash(hash, &signature.inner)
363            .map_err(|_| AptosError::SignatureVerificationFailed)
364    }
365
366    /// Derives the account address for this public key.
367    ///
368    /// Uses the `SingleKey` authentication scheme (`scheme_id` = 2):
369    /// `auth_key = SHA3-256(BCS(AnyPublicKey::Secp256k1Ecdsa) || 0x02)`
370    ///
371    /// Where `BCS(AnyPublicKey::Secp256k1Ecdsa)` = `0x01 || ULEB128(65) || uncompressed_public_key`
372    pub fn to_address(&self) -> crate::types::AccountAddress {
373        // BCS format: variant_byte || ULEB128(length) || pubkey_bytes.
374        //
375        // The chain's `AccountAuthenticator::SingleKey` authentication-key
376        // derivation goes through `bcs::to_bytes(&AnyPublicKey)`, which for
377        // the `Secp256k1Ecdsa` variant re-serializes the underlying
378        // `secp256k1_ecdsa::PublicKey` via `libsecp256k1::PublicKey::serialize()`
379        // -- always producing 65 bytes of SEC1 uncompressed encoding
380        // (0x04 || X || Y), regardless of which form (33/64/65) was on the
381        // wire. We must therefore derive the address using the same 65-byte
382        // canonical form to obtain an address the chain will agree with.
383        let uncompressed = self.to_uncompressed_bytes();
384        let mut bcs_bytes = Vec::with_capacity(1 + 1 + uncompressed.len());
385        bcs_bytes.push(0x01); // AnyPublicKey::Secp256k1Ecdsa variant
386        bcs_bytes.push(65); // ULEB128(65)
387        bcs_bytes.extend_from_slice(&uncompressed);
388        crate::crypto::derive_address(&bcs_bytes, crate::crypto::SINGLE_KEY_SCHEME)
389    }
390}
391
392impl PublicKey for Secp256k1PublicKey {
393    const LENGTH: usize = SECP256K1_PUBLIC_KEY_LENGTH;
394
395    fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
396        Secp256k1PublicKey::from_bytes(bytes)
397    }
398
399    fn to_bytes(&self) -> Vec<u8> {
400        Secp256k1PublicKey::to_bytes(self)
401    }
402}
403
404impl Verifier for Secp256k1PublicKey {
405    type Signature = Secp256k1Signature;
406
407    fn verify(&self, message: &[u8], signature: &Secp256k1Signature) -> AptosResult<()> {
408        Secp256k1PublicKey::verify(self, message, signature)
409    }
410}
411
412impl fmt::Debug for Secp256k1PublicKey {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        write!(f, "Secp256k1PublicKey({})", self.to_hex())
415    }
416}
417
418impl fmt::Display for Secp256k1PublicKey {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        write!(f, "{}", self.to_hex())
421    }
422}
423
424impl Serialize for Secp256k1PublicKey {
425    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
426    where
427        S: serde::Serializer,
428    {
429        if serializer.is_human_readable() {
430            serializer.serialize_str(&self.to_hex())
431        } else {
432            serializer.serialize_bytes(&self.to_bytes())
433        }
434    }
435}
436
437impl<'de> Deserialize<'de> for Secp256k1PublicKey {
438    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
439    where
440        D: serde::Deserializer<'de>,
441    {
442        if deserializer.is_human_readable() {
443            let s = String::deserialize(deserializer)?;
444            Self::from_hex(&s).map_err(serde::de::Error::custom)
445        } else {
446            let bytes = Vec::<u8>::deserialize(deserializer)?;
447            Self::from_bytes(&bytes).map_err(serde::de::Error::custom)
448        }
449    }
450}
451
452/// A Secp256k1 ECDSA signature.
453#[derive(Clone, Copy, PartialEq, Eq)]
454pub struct Secp256k1Signature {
455    inner: K256Signature,
456}
457
458impl Secp256k1Signature {
459    /// Creates a signature from raw bytes (64 bytes, r || s).
460    ///
461    /// # Security
462    ///
463    /// Rejects high-S signatures to match Aptos on-chain verification behavior.
464    /// The Aptos VM only accepts low-S (canonical) ECDSA signatures to prevent
465    /// signature malleability attacks.
466    ///
467    /// # Errors
468    ///
469    /// Returns [`AptosError::InvalidSignature`] if:
470    /// - The byte slice length is not exactly 64 bytes
471    /// - The bytes do not represent a valid Secp256k1 signature
472    /// - The signature has a high-S value (not canonical)
473    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
474        if bytes.len() != SECP256K1_SIGNATURE_LENGTH {
475            return Err(AptosError::InvalidSignature(format!(
476                "expected {} bytes, got {}",
477                SECP256K1_SIGNATURE_LENGTH,
478                bytes.len()
479            )));
480        }
481        let signature = K256Signature::from_slice(bytes)
482            .map_err(|e| AptosError::InvalidSignature(e.to_string()))?;
483        // SECURITY: Reject high-S signatures. Aptos on-chain verification only
484        // accepts low-S (canonical) signatures to prevent malleability.
485        // normalize_s() changes the signature iff it was high-S.
486        if signature.normalize_s() != signature {
487            return Err(AptosError::InvalidSignature(
488                "high-S signature rejected: Aptos requires low-S (canonical) ECDSA signatures"
489                    .into(),
490            ));
491        }
492        Ok(Self { inner: signature })
493    }
494
495    /// Creates a signature from a hex string.
496    ///
497    /// # Errors
498    ///
499    /// Returns [`AptosError::Hex`] if the hex string is invalid.
500    /// Returns [`AptosError::InvalidSignature`] if the decoded bytes are not exactly 64 bytes or do not represent a valid Secp256k1 signature.
501    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
502        let bytes = const_hex::decode(hex_str)?;
503        Self::from_bytes(&bytes)
504    }
505
506    /// Returns the signature as bytes (64 bytes, r || s).
507    pub fn to_bytes(&self) -> [u8; SECP256K1_SIGNATURE_LENGTH] {
508        self.inner.to_bytes().into()
509    }
510
511    /// Returns the signature as a hex string.
512    pub fn to_hex(&self) -> String {
513        const_hex::encode_prefixed(self.to_bytes())
514    }
515}
516
517impl Signature for Secp256k1Signature {
518    type PublicKey = Secp256k1PublicKey;
519    const LENGTH: usize = SECP256K1_SIGNATURE_LENGTH;
520
521    fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
522        Secp256k1Signature::from_bytes(bytes)
523    }
524
525    fn to_bytes(&self) -> Vec<u8> {
526        self.inner.to_bytes().to_vec()
527    }
528}
529
530impl fmt::Debug for Secp256k1Signature {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        write!(f, "Secp256k1Signature({})", self.to_hex())
533    }
534}
535
536impl fmt::Display for Secp256k1Signature {
537    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538        write!(f, "{}", self.to_hex())
539    }
540}
541
542impl Serialize for Secp256k1Signature {
543    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
544    where
545        S: serde::Serializer,
546    {
547        if serializer.is_human_readable() {
548            serializer.serialize_str(&self.to_hex())
549        } else {
550            serializer.serialize_bytes(&self.to_bytes())
551        }
552    }
553}
554
555impl<'de> Deserialize<'de> for Secp256k1Signature {
556    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
557    where
558        D: serde::Deserializer<'de>,
559    {
560        if deserializer.is_human_readable() {
561            let s = String::deserialize(deserializer)?;
562            Self::from_hex(&s).map_err(serde::de::Error::custom)
563        } else {
564            let bytes = Vec::<u8>::deserialize(deserializer)?;
565            Self::from_bytes(&bytes).map_err(serde::de::Error::custom)
566        }
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573
574    #[test]
575    fn test_generate_and_sign() {
576        let private_key = Secp256k1PrivateKey::generate();
577        let message = b"hello world";
578        let signature = private_key.sign(message);
579
580        let public_key = private_key.public_key();
581        assert!(public_key.verify(message, &signature).is_ok());
582    }
583
584    #[test]
585    fn test_wrong_message_fails() {
586        let private_key = Secp256k1PrivateKey::generate();
587        let message = b"hello world";
588        let wrong_message = b"hello world!";
589        let signature = private_key.sign(message);
590
591        let public_key = private_key.public_key();
592        assert!(public_key.verify(wrong_message, &signature).is_err());
593    }
594
595    #[test]
596    fn test_from_bytes_roundtrip() {
597        let private_key = Secp256k1PrivateKey::generate();
598        let bytes = private_key.to_bytes();
599        let restored = Secp256k1PrivateKey::from_bytes(&bytes).unwrap();
600        assert_eq!(private_key.to_bytes(), restored.to_bytes());
601    }
602
603    #[test]
604    fn test_public_key_compressed() {
605        let private_key = Secp256k1PrivateKey::generate();
606        let public_key = private_key.public_key();
607
608        // Compressed should be 33 bytes
609        assert_eq!(public_key.to_bytes().len(), 33);
610
611        // Uncompressed should be 65 bytes
612        assert_eq!(public_key.to_uncompressed_bytes().len(), 65);
613    }
614
615    #[test]
616    fn test_public_key_from_bytes_roundtrip() {
617        let private_key = Secp256k1PrivateKey::generate();
618        let public_key = private_key.public_key();
619        let bytes = public_key.to_bytes();
620        let restored = Secp256k1PublicKey::from_bytes(&bytes).unwrap();
621        assert_eq!(public_key.to_bytes(), restored.to_bytes());
622    }
623
624    #[test]
625    fn test_signature_from_bytes_roundtrip() {
626        let private_key = Secp256k1PrivateKey::generate();
627        let signature = private_key.sign(b"test");
628        let bytes = signature.to_bytes();
629        let restored = Secp256k1Signature::from_bytes(&bytes).unwrap();
630        assert_eq!(signature.to_bytes(), restored.to_bytes());
631    }
632
633    #[test]
634    fn test_hex_roundtrip() {
635        let private_key = Secp256k1PrivateKey::generate();
636        let hex = private_key.to_hex();
637        let restored = Secp256k1PrivateKey::from_hex(&hex).unwrap();
638        assert_eq!(private_key.to_bytes(), restored.to_bytes());
639    }
640
641    #[test]
642    fn test_public_key_hex_roundtrip() {
643        let private_key = Secp256k1PrivateKey::generate();
644        let public_key = private_key.public_key();
645        let hex = public_key.to_hex();
646        let restored = Secp256k1PublicKey::from_hex(&hex).unwrap();
647        assert_eq!(public_key.to_bytes(), restored.to_bytes());
648    }
649
650    #[test]
651    fn test_signature_hex_roundtrip() {
652        let private_key = Secp256k1PrivateKey::generate();
653        let signature = private_key.sign(b"test");
654        let hex = signature.to_hex();
655        let restored = Secp256k1Signature::from_hex(&hex).unwrap();
656        assert_eq!(signature.to_bytes(), restored.to_bytes());
657    }
658
659    #[test]
660    fn test_invalid_private_key_bytes() {
661        let bytes = vec![0u8; 16]; // Wrong length
662        let result = Secp256k1PrivateKey::from_bytes(&bytes);
663        assert!(result.is_err());
664    }
665
666    #[test]
667    fn test_invalid_public_key_bytes() {
668        let bytes = vec![0u8; 16]; // Wrong length
669        let result = Secp256k1PublicKey::from_bytes(&bytes);
670        assert!(result.is_err());
671    }
672
673    #[test]
674    fn test_invalid_signature_bytes() {
675        let bytes = vec![0u8; 16]; // Wrong length
676        let result = Secp256k1Signature::from_bytes(&bytes);
677        assert!(result.is_err());
678    }
679
680    #[test]
681    fn test_high_s_signature_rejected() {
682        use k256::elliptic_curve::ops::Neg;
683
684        // Sign a message (produces low-S)
685        let private_key = Secp256k1PrivateKey::generate();
686        let signature = private_key.sign(b"test message");
687
688        // Construct high-S by negating the S component: S' = n - S
689        let low_s_sig = k256::ecdsa::Signature::from_slice(&signature.to_bytes()).unwrap();
690        let (r, s) = low_s_sig.split_scalars();
691        let neg_s = s.neg();
692        let high_s_sig = k256::ecdsa::Signature::from_scalars(r, neg_s).unwrap();
693        // Confirm it really is high-S (normalize_s changes high-S signatures)
694        assert!(
695            high_s_sig.normalize_s() != high_s_sig,
696            "constructed signature should be high-S"
697        );
698        let high_s_bytes = high_s_sig.to_bytes();
699
700        // from_bytes should reject high-S
701        let result = Secp256k1Signature::from_bytes(&high_s_bytes);
702        assert!(result.is_err(), "high-S signature should be rejected");
703        assert!(
704            result
705                .unwrap_err()
706                .to_string()
707                .contains("high-S signature rejected"),
708            "error message should mention high-S rejection"
709        );
710
711        // Verify should also reject high-S (defense-in-depth via inner field)
712        let sig_with_high_s = Secp256k1Signature { inner: high_s_sig };
713        let public_key = private_key.public_key();
714        let result = public_key.verify(b"test message", &sig_with_high_s);
715        assert!(result.is_err(), "verify should reject high-S signature");
716    }
717
718    #[test]
719    fn test_signing_always_produces_low_s() {
720        // Run multiple iterations to increase confidence
721        for _ in 0..20 {
722            let private_key = Secp256k1PrivateKey::generate();
723            let signature = private_key.sign(b"test low-s");
724            // normalize_s leaves already low-S signatures unchanged
725            assert!(
726                signature.inner.normalize_s() == signature.inner,
727                "signing must always produce low-S signatures"
728            );
729        }
730    }
731
732    #[test]
733    fn test_sign_prehashed_and_verify_prehashed_roundtrip() {
734        let private_key = Secp256k1PrivateKey::generate();
735        let public_key = private_key.public_key();
736        let hash = crate::crypto::sha3_256(b"prehash roundtrip");
737
738        let signature = private_key.sign_prehashed(&hash);
739        public_key.verify_prehashed(&hash, &signature).unwrap();
740    }
741
742    #[test]
743    fn test_verify_prehashed_wrong_hash_fails() {
744        let private_key = Secp256k1PrivateKey::generate();
745        let public_key = private_key.public_key();
746        let hash = crate::crypto::sha3_256(b"prehash correct");
747        let wrong_hash = crate::crypto::sha3_256(b"prehash wrong");
748        let signature = private_key.sign_prehashed(&hash);
749
750        let result = public_key.verify_prehashed(&wrong_hash, &signature);
751        assert!(result.is_err());
752    }
753
754    #[test]
755    fn test_json_serialization_public_key() {
756        let private_key = Secp256k1PrivateKey::generate();
757        let public_key = private_key.public_key();
758        let json = serde_json::to_string(&public_key).unwrap();
759        let restored: Secp256k1PublicKey = serde_json::from_str(&json).unwrap();
760        assert_eq!(public_key.to_bytes(), restored.to_bytes());
761    }
762
763    #[test]
764    fn test_json_serialization_signature() {
765        let private_key = Secp256k1PrivateKey::generate();
766        let signature = private_key.sign(b"test");
767        let json = serde_json::to_string(&signature).unwrap();
768        let restored: Secp256k1Signature = serde_json::from_str(&json).unwrap();
769        assert_eq!(signature.to_bytes(), restored.to_bytes());
770    }
771
772    #[test]
773    fn test_key_lengths() {
774        assert_eq!(Secp256k1PublicKey::LENGTH, SECP256K1_PUBLIC_KEY_LENGTH);
775        assert_eq!(Secp256k1Signature::LENGTH, SECP256K1_SIGNATURE_LENGTH);
776    }
777
778    #[test]
779    fn test_display_debug() {
780        let private_key = Secp256k1PrivateKey::generate();
781        let public_key = private_key.public_key();
782        let signature = private_key.sign(b"test");
783
784        // Debug should contain type name
785        assert!(format!("{public_key:?}").contains("Secp256k1PublicKey"));
786        assert!(format!("{signature:?}").contains("Secp256k1Signature"));
787
788        // Display should show hex
789        assert!(format!("{public_key}").starts_with("0x"));
790        assert!(format!("{signature}").starts_with("0x"));
791    }
792
793    #[test]
794    fn test_private_key_aip80_roundtrip() {
795        let private_key = Secp256k1PrivateKey::generate();
796        let aip80 = private_key.to_aip80();
797
798        // Should have correct prefix
799        assert!(aip80.starts_with("secp256k1-priv-0x"));
800
801        // Should roundtrip correctly
802        let restored = Secp256k1PrivateKey::from_aip80(&aip80).unwrap();
803        assert_eq!(private_key.to_bytes(), restored.to_bytes());
804    }
805
806    #[test]
807    fn test_private_key_aip80_format() {
808        let bytes = [0x01; 32];
809        let private_key = Secp256k1PrivateKey::from_bytes(&bytes).unwrap();
810        let aip80 = private_key.to_aip80();
811
812        // Expected format: secp256k1-priv-0x0101...01
813        let expected = format!("secp256k1-priv-0x{}", "01".repeat(32));
814        assert_eq!(aip80, expected);
815    }
816
817    #[test]
818    fn test_private_key_aip80_invalid_prefix() {
819        let result = Secp256k1PrivateKey::from_aip80("ed25519-priv-0x01");
820        assert!(result.is_err());
821    }
822
823    #[test]
824    fn test_public_key_aip80_roundtrip() {
825        let private_key = Secp256k1PrivateKey::generate();
826        let public_key = private_key.public_key();
827        let aip80 = public_key.to_aip80();
828
829        // Should have correct prefix
830        assert!(aip80.starts_with("secp256k1-pub-0x"));
831
832        // Should roundtrip correctly
833        let restored = Secp256k1PublicKey::from_aip80(&aip80).unwrap();
834        assert_eq!(public_key.to_bytes(), restored.to_bytes());
835    }
836
837    #[test]
838    fn test_public_key_aip80_invalid_prefix() {
839        let result = Secp256k1PublicKey::from_aip80("ed25519-pub-0x01");
840        assert!(result.is_err());
841    }
842
843    #[test]
844    fn test_signer_trait() {
845        use crate::crypto::traits::Signer;
846
847        let private_key = Secp256k1PrivateKey::generate();
848        let message = b"trait test";
849
850        let signature = Signer::sign(&private_key, message);
851        let public_key = Signer::public_key(&private_key);
852
853        assert!(public_key.verify(message, &signature).is_ok());
854    }
855
856    #[test]
857    fn test_verifier_trait() {
858        use crate::crypto::traits::Verifier;
859
860        let private_key = Secp256k1PrivateKey::generate();
861        let public_key = private_key.public_key();
862        let message = b"verifier test";
863        let signature = private_key.sign(message);
864
865        assert!(Verifier::verify(&public_key, message, &signature).is_ok());
866    }
867
868    #[test]
869    fn test_public_key_trait() {
870        use crate::crypto::traits::PublicKey;
871
872        let private_key = Secp256k1PrivateKey::generate();
873        let public_key = private_key.public_key();
874        let bytes = PublicKey::to_bytes(&public_key);
875        let restored = Secp256k1PublicKey::from_bytes(&bytes).unwrap();
876        assert_eq!(public_key.to_bytes(), restored.to_bytes());
877    }
878
879    #[test]
880    fn test_signature_trait() {
881        use crate::crypto::traits::Signature;
882
883        let private_key = Secp256k1PrivateKey::generate();
884        let signature = private_key.sign(b"test");
885        let bytes = Signature::to_bytes(&signature);
886        let restored = Secp256k1Signature::from_bytes(&bytes).unwrap();
887        assert_eq!(signature.to_bytes(), restored.to_bytes());
888    }
889
890    #[test]
891    fn test_private_key_debug() {
892        let private_key = Secp256k1PrivateKey::generate();
893        let debug = format!("{private_key:?}");
894        assert!(debug.contains("REDACTED"));
895        assert!(!debug.contains(&private_key.to_hex()));
896    }
897
898    #[test]
899    fn test_address_derivation() {
900        let private_key = Secp256k1PrivateKey::generate();
901        let public_key = private_key.public_key();
902        let address = public_key.to_address();
903
904        // Address should not be zero
905        assert!(!address.is_zero());
906
907        // Same public key should derive same address
908        let address2 = public_key.to_address();
909        assert_eq!(address, address2);
910    }
911
912    #[test]
913    fn test_uncompressed_bytes() {
914        let private_key = Secp256k1PrivateKey::generate();
915        let public_key = private_key.public_key();
916
917        // Uncompressed should be 65 bytes (0x04 prefix + 64 bytes)
918        let uncompressed = public_key.to_uncompressed_bytes();
919        assert_eq!(uncompressed.len(), 65);
920        assert_eq!(uncompressed[0], 0x04); // Uncompressed point prefix
921    }
922
923    #[test]
924    fn test_private_key_clone() {
925        let private_key = Secp256k1PrivateKey::generate();
926        let cloned = private_key.clone();
927        assert_eq!(private_key.to_bytes(), cloned.to_bytes());
928    }
929
930    #[test]
931    fn test_public_key_equality() {
932        let private_key = Secp256k1PrivateKey::generate();
933        let pk1 = private_key.public_key();
934        let pk2 = private_key.public_key();
935        assert_eq!(pk1, pk2);
936
937        let different = Secp256k1PrivateKey::generate().public_key();
938        assert_ne!(pk1, different);
939    }
940
941    #[test]
942    fn test_signature_equality() {
943        let private_key = Secp256k1PrivateKey::generate();
944        let sig1 = private_key.sign(b"test");
945        let sig2 = private_key.sign(b"test");
946        // Note: ECDSA signatures may have randomness, so they might not be equal
947        // But they should both verify
948        let public_key = private_key.public_key();
949        assert!(public_key.verify(b"test", &sig1).is_ok());
950        assert!(public_key.verify(b"test", &sig2).is_ok());
951    }
952
953    /// The documented drop-clearing guarantee relies on the inner `k256`
954    /// `SigningKey` zeroizing its secret on drop. This compile-time assertion
955    /// pins that contract so the `crypto/mod.rs` docs stay truthful.
956    #[test]
957    fn test_inner_key_zeroizes_on_drop() {
958        fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
959        assert_zeroize_on_drop::<SigningKey>();
960    }
961}