Skip to main content

aptos_sdk/crypto/
traits.rs

1//! Cryptographic traits for the Aptos SDK.
2//!
3//! These traits provide a unified interface for different signature schemes.
4
5use crate::error::AptosResult;
6
7/// A trait for types that can sign messages.
8pub trait Signer {
9    /// The signature type produced by this signer.
10    type Signature: Signature;
11
12    /// Signs the given message and returns a signature.
13    fn sign(&self, message: &[u8]) -> Self::Signature;
14
15    /// Returns the public key corresponding to this signer.
16    fn public_key(&self) -> <Self::Signature as Signature>::PublicKey;
17}
18
19/// A trait for types that can verify signatures.
20pub trait Verifier {
21    /// The signature type this verifier can check.
22    type Signature: Signature;
23
24    /// Verifies that the signature is valid for the given message.
25    ///
26    /// # Errors
27    ///
28    /// Returns an error if the signature is invalid for the message.
29    fn verify(&self, message: &[u8], signature: &Self::Signature) -> AptosResult<()>;
30}
31
32/// A trait for public key types.
33pub trait PublicKey: Clone + Sized {
34    /// The length of the public key in bytes.
35    ///
36    /// A value of `0` is a sentinel meaning "variable length": schemes whose
37    /// serialized size is not fixed (e.g. the multi-key / multi-Ed25519
38    /// aggregates) set `LENGTH = 0` rather than a concrete byte count.
39    const LENGTH: usize;
40
41    /// Creates a public key from bytes.
42    ///
43    /// # Errors
44    ///
45    /// Returns an error if the bytes have an invalid length or format.
46    fn from_bytes(bytes: &[u8]) -> AptosResult<Self>;
47
48    /// Returns the public key as bytes.
49    fn to_bytes(&self) -> Vec<u8>;
50
51    /// Returns the public key as a hex string with 0x prefix.
52    fn to_hex(&self) -> String {
53        const_hex::encode_prefixed(self.to_bytes())
54    }
55}
56
57/// A trait for signature types.
58pub trait Signature: Clone + Sized {
59    /// The public key type for this signature scheme.
60    type PublicKey: PublicKey;
61
62    /// The length of the signature in bytes.
63    ///
64    /// A value of `0` is a sentinel meaning "variable length": schemes whose
65    /// serialized size is not fixed (e.g. the multi-key / multi-Ed25519
66    /// aggregates) set `LENGTH = 0` rather than a concrete byte count.
67    const LENGTH: usize;
68
69    /// Creates a signature from bytes.
70    ///
71    /// # Errors
72    ///
73    /// Returns an error if the bytes have an invalid length or format.
74    fn from_bytes(bytes: &[u8]) -> AptosResult<Self>;
75
76    /// Returns the signature as bytes.
77    fn to_bytes(&self) -> Vec<u8>;
78
79    /// Returns the signature as a hex string with 0x prefix.
80    fn to_hex(&self) -> String {
81        const_hex::encode_prefixed(self.to_bytes())
82    }
83}