Files
huskies/crates/bft-json-crdt/src/keypair.rs
T

66 lines
2.0 KiB
Rust
Raw Normal View History

2026-04-29 09:25:05 +00:00
//! Ed25519 keypair utilities and type aliases for node identity and signing.
//!
//! Provides the [`AuthorId`] and [`SignedDigest`] type aliases, a SHA-256 helper,
//! and convenience wrappers around the `fastcrypto` Ed25519 primitives used
//! throughout the CRDT codebase.
2026-04-04 21:33:27 +01:00
use fastcrypto::traits::VerifyingKey;
pub use fastcrypto::{
ed25519::{
Ed25519KeyPair, Ed25519PublicKey, Ed25519Signature, ED25519_PUBLIC_KEY_LENGTH,
ED25519_SIGNATURE_LENGTH,
},
2026-05-12 18:28:42 +00:00
traits::{KeyPair, Signer, ToFromBytes},
2026-04-04 21:33:27 +01:00
// Verifier,
};
2026-05-12 18:28:42 +00:00
use rand::RngCore as _;
2026-04-04 21:33:27 +01:00
use sha2::{Digest, Sha256};
/// Represents the ID of a unique node. An Ed25519 public key
pub type AuthorId = [u8; ED25519_PUBLIC_KEY_LENGTH];
/// A signed message
pub type SignedDigest = [u8; ED25519_SIGNATURE_LENGTH];
/// Create a fake public key from a u8
pub fn make_author(n: u8) -> AuthorId {
let mut id = [0u8; ED25519_PUBLIC_KEY_LENGTH];
id[0] = n;
id
}
/// Get the least significant 32 bits of a public key
pub fn lsb_32(pubkey: AuthorId) -> u32 {
((pubkey[0] as u32) << 24)
+ ((pubkey[1] as u32) << 16)
+ ((pubkey[2] as u32) << 8)
+ (pubkey[3] as u32)
}
/// SHA256 hash of a string
pub fn sha256(input: String) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(input.as_bytes());
let result = hasher.finalize();
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&result[..]);
bytes
}
/// Generate a random Ed25519 keypair from OS rng
pub fn make_keypair() -> Ed25519KeyPair {
2026-05-12 18:28:42 +00:00
let mut seed = [0u8; 32];
rand::rng().fill_bytes(&mut seed);
Ed25519KeyPair::from_bytes(&seed).expect("32-byte seed always yields a valid Ed25519 keypair")
2026-04-04 21:33:27 +01:00
}
/// Sign a byte array
pub fn sign(keypair: &Ed25519KeyPair, message: &[u8]) -> Ed25519Signature {
keypair.sign(message)
}
/// Verify a byte array was signed by the given pubkey
pub fn verify(pubkey: Ed25519PublicKey, message: &[u8], signature: Ed25519Signature) -> bool {
pubkey.verify(message, &signature).is_ok()
}