sidechain_domain/
crypto.rs

1//! Cryptographic utilities for use by the domain types
2
3/// Computes a BLAKE2b hash of arbitrary static length for given `data`
4pub fn blake2b<const N: usize>(data: &[u8]) -> [u8; N] {
5	blake2b_simd::Params::new()
6		.hash_length(N)
7		.hash(data)
8		.as_bytes()
9		.try_into()
10		.unwrap_or_else(|_| panic!("hash output always has expected length of {N}"))
11}
12
13#[cfg(feature = "std")]
14pub use full_crypto::*;
15
16#[cfg(feature = "std")]
17mod full_crypto {
18	use crate::*;
19	use plutus::ToDatum;
20	use plutus::to_datum_cbor_bytes;
21	use secp256k1::{Message, PublicKey, SecretKey, ecdsa::Signature};
22
23	/// Crates a 32 bytes (256 bits) BLAKE2b hash of the Plutus datum representation of `msg`
24	pub fn hash<T: ToDatum>(msg: T) -> [u8; 32] {
25		blake2b(to_datum_cbor_bytes(msg).as_slice())
26	}
27
28	/// Calculates the public key and signature for given private key and hashed data.
29	pub fn sc_public_key_and_signature(key: SecretKey, hashed: [u8; 32]) -> (PublicKey, Signature) {
30		let public_key = PublicKey::from_secret_key_global(&key);
31		let signature = key.sign_ecdsa(Message::from_digest_slice(hashed.as_slice()).unwrap());
32		(public_key, signature)
33	}
34
35	/// Signs the Plutus data bytes of `datum_msg` using `key` and returns it together with the verification key.
36	pub fn sc_public_key_and_signature_for_datum<T: ToDatum>(
37		key: SecretKey,
38		datum_msg: T,
39	) -> (PublicKey, Signature) {
40		let hashed_msg = hash(datum_msg);
41		sc_public_key_and_signature(key, hashed_msg)
42	}
43
44	/// Signs the Plutus data bytes of `datum_msg` using `key` and returns it together with the verification key.
45	pub fn cardano_spo_public_key_and_signature<T: ToDatum>(
46		key: ed25519_zebra::SigningKey,
47		datum_msg: T,
48	) -> (StakePoolPublicKey, MainchainSignature) {
49		let message = to_datum_cbor_bytes(datum_msg);
50		let signature = MainchainSignature(key.sign(&message).into());
51		let public = StakePoolPublicKey(ed25519_zebra::VerificationKey::from(&key).into());
52		(public, signature)
53	}
54}