cardano_serialization_lib/impl_mockchain/
key.rs1use crate::chain_core::mempack::{read_mut_slice, ReadBuf, ReadError, Readable};
5use crate::chain_core::property;
6use crate::chain_crypto as crypto;
7use crate::chain_crypto::{
8 AsymmetricKey, AsymmetricPublicKey, SecretKey, SigningAlgorithm, VerificationAlgorithm,
9};
10use rand_os::rand_core::{CryptoRng, RngCore};
11
12#[derive(Clone)]
13pub enum EitherEd25519SecretKey {
14 Extended(crypto::SecretKey<crypto::Ed25519Extended>),
15 Normal(crypto::SecretKey<crypto::Ed25519>),
16}
17
18impl EitherEd25519SecretKey {
19 pub fn generate<R: RngCore + CryptoRng>(rng: R) -> Self {
20 EitherEd25519SecretKey::Extended(SecretKey::generate(rng))
21 }
22
23 pub fn to_public(&self) -> crypto::PublicKey<crypto::Ed25519> {
24 match self {
25 EitherEd25519SecretKey::Extended(sk) => sk.to_public(),
26 EitherEd25519SecretKey::Normal(sk) => sk.to_public(),
27 }
28 }
29
30 pub fn sign<T: AsRef<[u8]>>(&self, dat: &T) -> crypto::Signature<T, crypto::Ed25519> {
31 match self {
32 EitherEd25519SecretKey::Extended(sk) => sk.sign(dat),
33 EitherEd25519SecretKey::Normal(sk) => sk.sign(dat),
34 }
35 }
36
37 pub fn sign_slice<T: ?Sized>(&self, dat: &[u8]) -> crypto::Signature<T, crypto::Ed25519> {
38 match self {
39 EitherEd25519SecretKey::Extended(sk) => sk.sign_slice(dat),
40 EitherEd25519SecretKey::Normal(sk) => sk.sign_slice(dat),
41 }
42 }
43}
44
45pub type SpendingPublicKey = crypto::PublicKey<crypto::Ed25519>;
46pub type SpendingSignature<T> = crypto::Signature<T, crypto::Ed25519>;
47
48pub type Ed25519Signature<T> = crypto::Signature<T, crypto::Ed25519>;
49
50fn chain_crypto_pub_err(e: crypto::PublicKeyError) -> ReadError {
51 match e {
52 crypto::PublicKeyError::SizeInvalid => {
53 ReadError::StructureInvalid("publickey size invalid".to_string())
54 }
55 crypto::PublicKeyError::StructureInvalid => {
56 ReadError::StructureInvalid("publickey structure invalid".to_string())
57 }
58 }
59}
60fn chain_crypto_sig_err(e: crypto::SignatureError) -> ReadError {
61 match e {
62 crypto::SignatureError::SizeInvalid { expected, got } => ReadError::StructureInvalid(
63 format!("signature size invalid, expected {} got {}", expected, got),
64 ),
65 crypto::SignatureError::StructureInvalid => {
66 ReadError::StructureInvalid("signature structure invalid".to_string())
67 }
68 }
69}
70
71#[inline]
72pub fn serialize_public_key<A: AsymmetricPublicKey, W: std::io::Write>(
73 key: &crypto::PublicKey<A>,
74 mut writer: W,
75) -> Result<(), std::io::Error> {
76 writer.write_all(key.as_ref())
77}
78#[inline]
79pub fn serialize_signature<A: VerificationAlgorithm, T, W: std::io::Write>(
80 signature: &crypto::Signature<T, A>,
81 mut writer: W,
82) -> Result<(), std::io::Error> {
83 writer.write_all(signature.as_ref())
84}
85#[inline]
86pub fn deserialize_public_key<'a, A>(
87 buf: &mut ReadBuf<'a>,
88) -> Result<crypto::PublicKey<A>, ReadError>
89where
90 A: AsymmetricPublicKey,
91{
92 let mut bytes = vec![0u8; A::PUBLIC_KEY_SIZE];
93 read_mut_slice(buf, &mut bytes[..])?;
94 crypto::PublicKey::from_binary(&bytes).map_err(chain_crypto_pub_err)
95}
96#[inline]
97pub fn deserialize_signature<'a, A, T>(
98 buf: &mut ReadBuf<'a>,
99) -> Result<crypto::Signature<T, A>, ReadError>
100where
101 A: VerificationAlgorithm,
102{
103 let mut bytes = vec![0u8; A::SIGNATURE_SIZE];
104 read_mut_slice(buf, &mut bytes[..])?;
105 crypto::Signature::from_binary(&bytes).map_err(chain_crypto_sig_err)
106}
107
108pub fn make_signature<T, A>(
109 spending_key: &crypto::SecretKey<A>,
110 data: &T,
111) -> crypto::Signature<T, A::PubAlg>
112where
113 A: SigningAlgorithm,
114 <A as AsymmetricKey>::PubAlg: VerificationAlgorithm,
115 T: property::Serialize,
116{
117 let bytes = data.serialize_as_vec().unwrap();
118 spending_key.sign(&bytes).coerce()
119}
120
121pub fn verify_signature<T, A>(
122 signature: &crypto::Signature<T, A>,
123 public_key: &crypto::PublicKey<A>,
124 data: &T,
125) -> crypto::Verification
126where
127 A: VerificationAlgorithm,
128 T: property::Serialize,
129{
130 let bytes = data.serialize_as_vec().unwrap();
131 signature.clone().coerce().verify(public_key, &bytes)
132}
133
134pub struct Signed<T, A: VerificationAlgorithm> {
136 pub data: T,
137 pub sig: crypto::Signature<T, A>,
138}
139
140pub fn signed_new<T: property::Serialize, A: SigningAlgorithm>(
141 secret_key: &crypto::SecretKey<A>,
142 data: T,
143) -> Signed<T, A::PubAlg>
144where
145 A::PubAlg: VerificationAlgorithm,
146{
147 let bytes = data.serialize_as_vec().unwrap();
148 let signature = secret_key.sign(&bytes).coerce();
149 Signed {
150 data: data,
151 sig: signature,
152 }
153}
154
155impl<T: property::Serialize, A: VerificationAlgorithm> property::Serialize for Signed<T, A>
156where
157 std::io::Error: From<T::Error>,
158{
159 type Error = std::io::Error;
160 fn serialize<W: std::io::Write>(&self, mut writer: W) -> Result<(), Self::Error> {
161 self.data.serialize(&mut writer)?;
162 serialize_signature(&self.sig, &mut writer)?;
163 Ok(())
164 }
165}
166
167impl<T: Readable, A: VerificationAlgorithm> Readable for Signed<T, A> {
168 fn read<'a>(buf: &mut ReadBuf<'a>) -> Result<Self, ReadError> {
169 Ok(Signed {
170 data: T::read(buf)?,
171 sig: deserialize_signature(buf)?,
172 })
173 }
174}
175
176impl<T: PartialEq, A: VerificationAlgorithm> PartialEq<Self> for Signed<T, A> {
177 fn eq(&self, other: &Self) -> bool {
178 self.data.eq(&other.data) && self.sig.as_ref() == other.sig.as_ref()
179 }
180}
181impl<T: PartialEq, A: VerificationAlgorithm> Eq for Signed<T, A> {}
182impl<T: std::fmt::Debug, A: VerificationAlgorithm> std::fmt::Debug for Signed<T, A> {
183 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
184 write!(
185 f,
186 "Signed ( data: {:?}, signature: {:?} )",
187 self.data,
188 self.sig.as_ref()
189 )
190 }
191}
192impl<T: Clone, A: VerificationAlgorithm> Clone for Signed<T, A> {
193 fn clone(&self) -> Self {
194 Signed {
195 data: self.data.clone(),
196 sig: self.sig.clone(),
197 }
198 }
199}