aptos-sdk 0.4.1

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! Secp256k1 ECDSA signature scheme implementation.
//!
//! Secp256k1 is the same elliptic curve used by Bitcoin and Ethereum.
//!
//! # Security: Signature Malleability
//!
//! This implementation enforces **low-S only** signatures to match the Aptos
//! blockchain's on-chain verification, which rejects high-S signatures to
//! prevent signature malleability attacks.
//!
//! - **Signing** always produces low-S signatures (the `k256` crate normalizes
//!   by default).
//! - **Parsing** (`from_bytes`, `from_hex`) rejects high-S signatures.
//! - **Verification** also rejects high-S signatures as a defense-in-depth
//!   measure.

use crate::crypto::traits::{PublicKey, Signature, Signer, Verifier};
use crate::error::{AptosError, AptosResult};
use k256::ecdsa::{
    Signature as K256Signature, SigningKey, VerifyingKey, signature::Signer as K256Signer,
    signature::Verifier as K256Verifier,
};
use serde::{Deserialize, Serialize};
use std::fmt;
use zeroize::Zeroize;

/// Secp256k1 private key length in bytes.
pub const SECP256K1_PRIVATE_KEY_LENGTH: usize = 32;
/// Secp256k1 public key length in bytes (compressed).
pub const SECP256K1_PUBLIC_KEY_LENGTH: usize = 33;
/// Secp256k1 uncompressed public key length in bytes.
#[allow(dead_code)] // Public API constant
pub const SECP256K1_PUBLIC_KEY_UNCOMPRESSED_LENGTH: usize = 65;
/// Secp256k1 signature length in bytes (DER encoded max).
pub const SECP256K1_SIGNATURE_LENGTH: usize = 64;

/// A Secp256k1 ECDSA private key.
///
/// The private key is zeroized when dropped.
#[derive(Clone, Zeroize)]
#[zeroize(drop)]
pub struct Secp256k1PrivateKey {
    #[zeroize(skip)]
    #[allow(unused)] // Field is used; lint false positive from Zeroize derive
    inner: SigningKey,
}

impl Secp256k1PrivateKey {
    /// Generates a new random Secp256k1 private key.
    pub fn generate() -> Self {
        let signing_key = SigningKey::random(&mut rand::rngs::OsRng);
        Self { inner: signing_key }
    }

    /// Creates a private key from raw bytes.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::InvalidPrivateKey`] if:
    /// - The byte slice length is not exactly 32 bytes
    /// - The bytes do not represent a valid Secp256k1 private key
    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
        if bytes.len() != SECP256K1_PRIVATE_KEY_LENGTH {
            return Err(AptosError::InvalidPrivateKey(format!(
                "expected {} bytes, got {}",
                SECP256K1_PRIVATE_KEY_LENGTH,
                bytes.len()
            )));
        }
        let signing_key = SigningKey::from_slice(bytes)
            .map_err(|e| AptosError::InvalidPrivateKey(e.to_string()))?;
        Ok(Self { inner: signing_key })
    }

    /// Creates a private key from a hex string.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::Hex`] if the hex string is invalid.
    /// Returns [`AptosError::InvalidPrivateKey`] if the decoded bytes are not exactly 32 bytes or do not represent a valid Secp256k1 private key.
    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
        let bytes = const_hex::decode(hex_str)?;
        Self::from_bytes(&bytes)
    }

    /// Creates a private key from AIP-80 format string.
    ///
    /// AIP-80 format: `secp256k1-priv-0x{hex_bytes}`
    ///
    /// # Errors
    ///
    /// Returns an error if the format is invalid or the key bytes are invalid.
    pub fn from_aip80(s: &str) -> AptosResult<Self> {
        const PREFIX: &str = "secp256k1-priv-";
        if let Some(hex_part) = s.strip_prefix(PREFIX) {
            Self::from_hex(hex_part)
        } else {
            Err(AptosError::InvalidPrivateKey(format!(
                "invalid AIP-80 format: expected prefix '{PREFIX}'"
            )))
        }
    }

    /// Returns the private key as bytes.
    pub fn to_bytes(&self) -> [u8; SECP256K1_PRIVATE_KEY_LENGTH] {
        self.inner.to_bytes().into()
    }

    /// Returns the private key as a hex string.
    pub fn to_hex(&self) -> String {
        const_hex::encode_prefixed(self.inner.to_bytes())
    }

    /// Returns the private key in AIP-80 format.
    ///
    /// AIP-80 format: `secp256k1-priv-0x{hex_bytes}`
    pub fn to_aip80(&self) -> String {
        format!("secp256k1-priv-{}", self.to_hex())
    }

    /// Returns the corresponding public key.
    pub fn public_key(&self) -> Secp256k1PublicKey {
        Secp256k1PublicKey {
            inner: *self.inner.verifying_key(),
        }
    }

    /// Signs a message (pre-hashed with SHA256) and returns a low-S signature.
    ///
    /// The `k256` crate produces low-S signatures by default. An additional
    /// normalization step is included as defense-in-depth to guarantee Aptos
    /// on-chain compatibility.
    pub fn sign(&self, message: &[u8]) -> Secp256k1Signature {
        // Hash the message with SHA256 first (standard for ECDSA)
        let hash = crate::crypto::sha2_256(message);
        let signature: K256Signature = self.inner.sign(&hash);
        // SECURITY: Ensure low-S (defense-in-depth; k256 should already do this)
        let normalized = signature.normalize_s().unwrap_or(signature);
        Secp256k1Signature { inner: normalized }
    }

    /// Signs a pre-hashed message directly and returns a low-S signature.
    ///
    /// The `k256` crate produces low-S signatures by default. An additional
    /// normalization step is included as defense-in-depth.
    pub fn sign_prehashed(&self, hash: &[u8; 32]) -> Secp256k1Signature {
        let signature: K256Signature = self.inner.sign(hash);
        // SECURITY: Ensure low-S (defense-in-depth; k256 should already do this)
        let normalized = signature.normalize_s().unwrap_or(signature);
        Secp256k1Signature { inner: normalized }
    }
}

impl Signer for Secp256k1PrivateKey {
    type Signature = Secp256k1Signature;

    fn sign(&self, message: &[u8]) -> Secp256k1Signature {
        Secp256k1PrivateKey::sign(self, message)
    }

    fn public_key(&self) -> Secp256k1PublicKey {
        Secp256k1PrivateKey::public_key(self)
    }
}

impl fmt::Debug for Secp256k1PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Secp256k1PrivateKey([REDACTED])")
    }
}

/// A Secp256k1 ECDSA public key.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Secp256k1PublicKey {
    inner: VerifyingKey,
}

impl Secp256k1PublicKey {
    /// Creates a public key from compressed bytes (33 bytes).
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::InvalidPublicKey`] if the bytes do not represent a valid Secp256k1 compressed public key.
    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
        let verifying_key = VerifyingKey::from_sec1_bytes(bytes)
            .map_err(|e| AptosError::InvalidPublicKey(e.to_string()))?;
        Ok(Self {
            inner: verifying_key,
        })
    }

    /// Creates a public key from a hex string.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::Hex`] if the hex string is invalid.
    /// Returns [`AptosError::InvalidPublicKey`] if the decoded bytes do not represent a valid Secp256k1 compressed public key.
    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
        let bytes = const_hex::decode(hex_str)?;
        Self::from_bytes(&bytes)
    }

    /// Creates a public key from AIP-80 format string.
    ///
    /// AIP-80 format: `secp256k1-pub-0x{hex_bytes}`
    ///
    /// # Errors
    ///
    /// Returns an error if the format is invalid or the key bytes are invalid.
    pub fn from_aip80(s: &str) -> AptosResult<Self> {
        const PREFIX: &str = "secp256k1-pub-";
        if let Some(hex_part) = s.strip_prefix(PREFIX) {
            Self::from_hex(hex_part)
        } else {
            Err(AptosError::InvalidPublicKey(format!(
                "invalid AIP-80 format: expected prefix '{PREFIX}'"
            )))
        }
    }

    /// Returns the public key as compressed bytes (33 bytes).
    pub fn to_bytes(&self) -> Vec<u8> {
        self.inner.to_sec1_bytes().to_vec()
    }

    /// Returns the public key as uncompressed bytes (65 bytes).
    pub fn to_uncompressed_bytes(&self) -> Vec<u8> {
        #[allow(unused_imports)]
        use k256::elliptic_curve::sec1::ToEncodedPoint;
        self.inner.to_encoded_point(false).as_bytes().to_vec()
    }

    /// Returns the public key as a hex string (compressed format).
    pub fn to_hex(&self) -> String {
        const_hex::encode_prefixed(self.to_bytes())
    }

    /// Returns the public key in AIP-80 format (compressed).
    ///
    /// AIP-80 format: `secp256k1-pub-0x{hex_bytes}`
    pub fn to_aip80(&self) -> String {
        format!("secp256k1-pub-{}", self.to_hex())
    }

    /// Verifies a signature against a message.
    ///
    /// # Security
    ///
    /// Rejects high-S signatures before verification, matching Aptos on-chain
    /// behavior. This is a defense-in-depth check; signatures created through
    /// this SDK's `from_bytes` are already guaranteed to be low-S.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::SignatureVerificationFailed`] if the signature has
    /// a high-S value, is invalid, or does not match the message.
    pub fn verify(&self, message: &[u8], signature: &Secp256k1Signature) -> AptosResult<()> {
        // SECURITY: Reject high-S signatures (matches aptos-core behavior)
        if signature.inner.normalize_s().is_some() {
            return Err(AptosError::SignatureVerificationFailed);
        }
        let hash = crate::crypto::sha2_256(message);
        self.inner
            .verify(&hash, &signature.inner)
            .map_err(|_| AptosError::SignatureVerificationFailed)
    }

    /// Verifies a signature against a pre-hashed message.
    ///
    /// # Security
    ///
    /// Rejects high-S signatures before verification, matching Aptos on-chain
    /// behavior.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::SignatureVerificationFailed`] if the signature has
    /// a high-S value, is invalid, or does not match the hash.
    pub fn verify_prehashed(
        &self,
        hash: &[u8; 32],
        signature: &Secp256k1Signature,
    ) -> AptosResult<()> {
        // SECURITY: Reject high-S signatures (matches aptos-core behavior)
        if signature.inner.normalize_s().is_some() {
            return Err(AptosError::SignatureVerificationFailed);
        }
        self.inner
            .verify(hash, &signature.inner)
            .map_err(|_| AptosError::SignatureVerificationFailed)
    }

    /// Derives the account address for this public key.
    ///
    /// Uses the `SingleKey` authentication scheme (`scheme_id` = 2):
    /// `auth_key = SHA3-256(BCS(AnyPublicKey::Secp256k1) || 0x02)`
    ///
    /// Where `BCS(AnyPublicKey::Secp256k1)` = `0x01 || ULEB128(65) || uncompressed_public_key`
    pub fn to_address(&self) -> crate::types::AccountAddress {
        // BCS format: variant_byte || ULEB128(length) || uncompressed_public_key
        let uncompressed = self.to_uncompressed_bytes();
        let mut bcs_bytes = Vec::with_capacity(1 + 1 + uncompressed.len());
        bcs_bytes.push(0x01); // Secp256k1 variant
        bcs_bytes.push(65); // ULEB128(65) = 0x41, but 65 < 128 so it's just 65
        bcs_bytes.extend_from_slice(&uncompressed);
        crate::crypto::derive_address(&bcs_bytes, crate::crypto::SINGLE_KEY_SCHEME)
    }
}

impl PublicKey for Secp256k1PublicKey {
    const LENGTH: usize = SECP256K1_PUBLIC_KEY_LENGTH;

    fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
        Secp256k1PublicKey::from_bytes(bytes)
    }

    fn to_bytes(&self) -> Vec<u8> {
        Secp256k1PublicKey::to_bytes(self)
    }
}

impl Verifier for Secp256k1PublicKey {
    type Signature = Secp256k1Signature;

    fn verify(&self, message: &[u8], signature: &Secp256k1Signature) -> AptosResult<()> {
        Secp256k1PublicKey::verify(self, message, signature)
    }
}

impl fmt::Debug for Secp256k1PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Secp256k1PublicKey({})", self.to_hex())
    }
}

impl fmt::Display for Secp256k1PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl Serialize for Secp256k1PublicKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&self.to_hex())
        } else {
            serializer.serialize_bytes(&self.to_bytes())
        }
    }
}

impl<'de> Deserialize<'de> for Secp256k1PublicKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            let s = String::deserialize(deserializer)?;
            Self::from_hex(&s).map_err(serde::de::Error::custom)
        } else {
            let bytes = Vec::<u8>::deserialize(deserializer)?;
            Self::from_bytes(&bytes).map_err(serde::de::Error::custom)
        }
    }
}

/// A Secp256k1 ECDSA signature.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Secp256k1Signature {
    inner: K256Signature,
}

impl Secp256k1Signature {
    /// Creates a signature from raw bytes (64 bytes, r || s).
    ///
    /// # Security
    ///
    /// Rejects high-S signatures to match Aptos on-chain verification behavior.
    /// The Aptos VM only accepts low-S (canonical) ECDSA signatures to prevent
    /// signature malleability attacks.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::InvalidSignature`] if:
    /// - The byte slice length is not exactly 64 bytes
    /// - The bytes do not represent a valid Secp256k1 signature
    /// - The signature has a high-S value (not canonical)
    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
        if bytes.len() != SECP256K1_SIGNATURE_LENGTH {
            return Err(AptosError::InvalidSignature(format!(
                "expected {} bytes, got {}",
                SECP256K1_SIGNATURE_LENGTH,
                bytes.len()
            )));
        }
        let signature = K256Signature::from_slice(bytes)
            .map_err(|e| AptosError::InvalidSignature(e.to_string()))?;
        // SECURITY: Reject high-S signatures. Aptos on-chain verification only
        // accepts low-S (canonical) signatures to prevent malleability.
        // normalize_s() returns Some(_) if the signature was high-S.
        if signature.normalize_s().is_some() {
            return Err(AptosError::InvalidSignature(
                "high-S signature rejected: Aptos requires low-S (canonical) ECDSA signatures"
                    .into(),
            ));
        }
        Ok(Self { inner: signature })
    }

    /// Creates a signature from a hex string.
    ///
    /// # Errors
    ///
    /// Returns [`AptosError::Hex`] if the hex string is invalid.
    /// Returns [`AptosError::InvalidSignature`] if the decoded bytes are not exactly 64 bytes or do not represent a valid Secp256k1 signature.
    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
        let bytes = const_hex::decode(hex_str)?;
        Self::from_bytes(&bytes)
    }

    /// Returns the signature as bytes (64 bytes, r || s).
    pub fn to_bytes(&self) -> [u8; SECP256K1_SIGNATURE_LENGTH] {
        self.inner.to_bytes().into()
    }

    /// Returns the signature as a hex string.
    pub fn to_hex(&self) -> String {
        const_hex::encode_prefixed(self.to_bytes())
    }
}

impl Signature for Secp256k1Signature {
    type PublicKey = Secp256k1PublicKey;
    const LENGTH: usize = SECP256K1_SIGNATURE_LENGTH;

    fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
        Secp256k1Signature::from_bytes(bytes)
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.inner.to_bytes().to_vec()
    }
}

impl fmt::Debug for Secp256k1Signature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Secp256k1Signature({})", self.to_hex())
    }
}

impl fmt::Display for Secp256k1Signature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_hex())
    }
}

impl Serialize for Secp256k1Signature {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&self.to_hex())
        } else {
            serializer.serialize_bytes(&self.to_bytes())
        }
    }
}

impl<'de> Deserialize<'de> for Secp256k1Signature {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            let s = String::deserialize(deserializer)?;
            Self::from_hex(&s).map_err(serde::de::Error::custom)
        } else {
            let bytes = Vec::<u8>::deserialize(deserializer)?;
            Self::from_bytes(&bytes).map_err(serde::de::Error::custom)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_and_sign() {
        let private_key = Secp256k1PrivateKey::generate();
        let message = b"hello world";
        let signature = private_key.sign(message);

        let public_key = private_key.public_key();
        assert!(public_key.verify(message, &signature).is_ok());
    }

    #[test]
    fn test_wrong_message_fails() {
        let private_key = Secp256k1PrivateKey::generate();
        let message = b"hello world";
        let wrong_message = b"hello world!";
        let signature = private_key.sign(message);

        let public_key = private_key.public_key();
        assert!(public_key.verify(wrong_message, &signature).is_err());
    }

    #[test]
    fn test_from_bytes_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let bytes = private_key.to_bytes();
        let restored = Secp256k1PrivateKey::from_bytes(&bytes).unwrap();
        assert_eq!(private_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_public_key_compressed() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();

        // Compressed should be 33 bytes
        assert_eq!(public_key.to_bytes().len(), 33);

        // Uncompressed should be 65 bytes
        assert_eq!(public_key.to_uncompressed_bytes().len(), 65);
    }

    #[test]
    fn test_public_key_from_bytes_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let bytes = public_key.to_bytes();
        let restored = Secp256k1PublicKey::from_bytes(&bytes).unwrap();
        assert_eq!(public_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_signature_from_bytes_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let signature = private_key.sign(b"test");
        let bytes = signature.to_bytes();
        let restored = Secp256k1Signature::from_bytes(&bytes).unwrap();
        assert_eq!(signature.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_hex_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let hex = private_key.to_hex();
        let restored = Secp256k1PrivateKey::from_hex(&hex).unwrap();
        assert_eq!(private_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_public_key_hex_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let hex = public_key.to_hex();
        let restored = Secp256k1PublicKey::from_hex(&hex).unwrap();
        assert_eq!(public_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_signature_hex_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let signature = private_key.sign(b"test");
        let hex = signature.to_hex();
        let restored = Secp256k1Signature::from_hex(&hex).unwrap();
        assert_eq!(signature.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_invalid_private_key_bytes() {
        let bytes = vec![0u8; 16]; // Wrong length
        let result = Secp256k1PrivateKey::from_bytes(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_public_key_bytes() {
        let bytes = vec![0u8; 16]; // Wrong length
        let result = Secp256k1PublicKey::from_bytes(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_signature_bytes() {
        let bytes = vec![0u8; 16]; // Wrong length
        let result = Secp256k1Signature::from_bytes(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_high_s_signature_rejected() {
        use k256::elliptic_curve::ops::Neg;

        // Sign a message (produces low-S)
        let private_key = Secp256k1PrivateKey::generate();
        let signature = private_key.sign(b"test message");

        // Construct high-S by negating the S component: S' = n - S
        let low_s_sig = k256::ecdsa::Signature::from_slice(&signature.to_bytes()).unwrap();
        let (r, s) = low_s_sig.split_scalars();
        let neg_s = s.neg();
        let high_s_sig = k256::ecdsa::Signature::from_scalars(r, neg_s).unwrap();
        // Confirm it really is high-S (normalize_s returns Some for high-S)
        assert!(
            high_s_sig.normalize_s().is_some(),
            "constructed signature should be high-S"
        );
        let high_s_bytes = high_s_sig.to_bytes();

        // from_bytes should reject high-S
        let result = Secp256k1Signature::from_bytes(&high_s_bytes);
        assert!(result.is_err(), "high-S signature should be rejected");
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("high-S signature rejected"),
            "error message should mention high-S rejection"
        );

        // Verify should also reject high-S (defense-in-depth via inner field)
        let sig_with_high_s = Secp256k1Signature { inner: high_s_sig };
        let public_key = private_key.public_key();
        let result = public_key.verify(b"test message", &sig_with_high_s);
        assert!(result.is_err(), "verify should reject high-S signature");
    }

    #[test]
    fn test_signing_always_produces_low_s() {
        // Run multiple iterations to increase confidence
        for _ in 0..20 {
            let private_key = Secp256k1PrivateKey::generate();
            let signature = private_key.sign(b"test low-s");
            // normalize_s returns None if already low-S
            assert!(
                signature.inner.normalize_s().is_none(),
                "signing must always produce low-S signatures"
            );
        }
    }

    #[test]
    fn test_json_serialization_public_key() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let json = serde_json::to_string(&public_key).unwrap();
        let restored: Secp256k1PublicKey = serde_json::from_str(&json).unwrap();
        assert_eq!(public_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_json_serialization_signature() {
        let private_key = Secp256k1PrivateKey::generate();
        let signature = private_key.sign(b"test");
        let json = serde_json::to_string(&signature).unwrap();
        let restored: Secp256k1Signature = serde_json::from_str(&json).unwrap();
        assert_eq!(signature.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_key_lengths() {
        assert_eq!(Secp256k1PublicKey::LENGTH, SECP256K1_PUBLIC_KEY_LENGTH);
        assert_eq!(Secp256k1Signature::LENGTH, SECP256K1_SIGNATURE_LENGTH);
    }

    #[test]
    fn test_display_debug() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let signature = private_key.sign(b"test");

        // Debug should contain type name
        assert!(format!("{public_key:?}").contains("Secp256k1PublicKey"));
        assert!(format!("{signature:?}").contains("Secp256k1Signature"));

        // Display should show hex
        assert!(format!("{public_key}").starts_with("0x"));
        assert!(format!("{signature}").starts_with("0x"));
    }

    #[test]
    fn test_private_key_aip80_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let aip80 = private_key.to_aip80();

        // Should have correct prefix
        assert!(aip80.starts_with("secp256k1-priv-0x"));

        // Should roundtrip correctly
        let restored = Secp256k1PrivateKey::from_aip80(&aip80).unwrap();
        assert_eq!(private_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_private_key_aip80_format() {
        let bytes = [0x01; 32];
        let private_key = Secp256k1PrivateKey::from_bytes(&bytes).unwrap();
        let aip80 = private_key.to_aip80();

        // Expected format: secp256k1-priv-0x0101...01
        let expected = format!("secp256k1-priv-0x{}", "01".repeat(32));
        assert_eq!(aip80, expected);
    }

    #[test]
    fn test_private_key_aip80_invalid_prefix() {
        let result = Secp256k1PrivateKey::from_aip80("ed25519-priv-0x01");
        assert!(result.is_err());
    }

    #[test]
    fn test_public_key_aip80_roundtrip() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let aip80 = public_key.to_aip80();

        // Should have correct prefix
        assert!(aip80.starts_with("secp256k1-pub-0x"));

        // Should roundtrip correctly
        let restored = Secp256k1PublicKey::from_aip80(&aip80).unwrap();
        assert_eq!(public_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_public_key_aip80_invalid_prefix() {
        let result = Secp256k1PublicKey::from_aip80("ed25519-pub-0x01");
        assert!(result.is_err());
    }

    #[test]
    fn test_signer_trait() {
        use crate::crypto::traits::Signer;

        let private_key = Secp256k1PrivateKey::generate();
        let message = b"trait test";

        let signature = Signer::sign(&private_key, message);
        let public_key = Signer::public_key(&private_key);

        assert!(public_key.verify(message, &signature).is_ok());
    }

    #[test]
    fn test_verifier_trait() {
        use crate::crypto::traits::Verifier;

        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let message = b"verifier test";
        let signature = private_key.sign(message);

        assert!(Verifier::verify(&public_key, message, &signature).is_ok());
    }

    #[test]
    fn test_public_key_trait() {
        use crate::crypto::traits::PublicKey;

        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let bytes = PublicKey::to_bytes(&public_key);
        let restored = Secp256k1PublicKey::from_bytes(&bytes).unwrap();
        assert_eq!(public_key.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_signature_trait() {
        use crate::crypto::traits::Signature;

        let private_key = Secp256k1PrivateKey::generate();
        let signature = private_key.sign(b"test");
        let bytes = Signature::to_bytes(&signature);
        let restored = Secp256k1Signature::from_bytes(&bytes).unwrap();
        assert_eq!(signature.to_bytes(), restored.to_bytes());
    }

    #[test]
    fn test_private_key_debug() {
        let private_key = Secp256k1PrivateKey::generate();
        let debug = format!("{private_key:?}");
        assert!(debug.contains("REDACTED"));
        assert!(!debug.contains(&private_key.to_hex()));
    }

    #[test]
    fn test_address_derivation() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();
        let address = public_key.to_address();

        // Address should not be zero
        assert!(!address.is_zero());

        // Same public key should derive same address
        let address2 = public_key.to_address();
        assert_eq!(address, address2);
    }

    #[test]
    fn test_uncompressed_bytes() {
        let private_key = Secp256k1PrivateKey::generate();
        let public_key = private_key.public_key();

        // Uncompressed should be 65 bytes (0x04 prefix + 64 bytes)
        let uncompressed = public_key.to_uncompressed_bytes();
        assert_eq!(uncompressed.len(), 65);
        assert_eq!(uncompressed[0], 0x04); // Uncompressed point prefix
    }

    #[test]
    fn test_private_key_clone() {
        let private_key = Secp256k1PrivateKey::generate();
        let cloned = private_key.clone();
        assert_eq!(private_key.to_bytes(), cloned.to_bytes());
    }

    #[test]
    fn test_public_key_equality() {
        let private_key = Secp256k1PrivateKey::generate();
        let pk1 = private_key.public_key();
        let pk2 = private_key.public_key();
        assert_eq!(pk1, pk2);

        let different = Secp256k1PrivateKey::generate().public_key();
        assert_ne!(pk1, different);
    }

    #[test]
    fn test_signature_equality() {
        let private_key = Secp256k1PrivateKey::generate();
        let sig1 = private_key.sign(b"test");
        let sig2 = private_key.sign(b"test");
        // Note: ECDSA signatures may have randomness, so they might not be equal
        // But they should both verify
        let public_key = private_key.public_key();
        assert!(public_key.verify(b"test", &sig1).is_ok());
        assert!(public_key.verify(b"test", &sig2).is_ok());
    }
}