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 const LENGTH: usize;
36
37 /// Creates a public key from bytes.
38 ///
39 /// # Errors
40 ///
41 /// Returns an error if the bytes have an invalid length or format.
42 fn from_bytes(bytes: &[u8]) -> AptosResult<Self>;
43
44 /// Returns the public key as bytes.
45 fn to_bytes(&self) -> Vec<u8>;
46
47 /// Returns the public key as a hex string with 0x prefix.
48 fn to_hex(&self) -> String {
49 format!("0x{}", hex::encode(self.to_bytes()))
50 }
51}
52
53/// A trait for signature types.
54pub trait Signature: Clone + Sized {
55 /// The public key type for this signature scheme.
56 type PublicKey: PublicKey;
57
58 /// The length of the signature in bytes.
59 const LENGTH: usize;
60
61 /// Creates a signature from bytes.
62 ///
63 /// # Errors
64 ///
65 /// Returns an error if the bytes have an invalid length or format.
66 fn from_bytes(bytes: &[u8]) -> AptosResult<Self>;
67
68 /// Returns the signature as bytes.
69 fn to_bytes(&self) -> Vec<u8>;
70
71 /// Returns the signature as a hex string with 0x prefix.
72 fn to_hex(&self) -> String {
73 format!("0x{}", hex::encode(self.to_bytes()))
74 }
75}