use chacha20poly1305::{
aead::{Aead, KeyInit, Payload},
ChaCha20Poly1305, Key, Nonce,
};
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand::rngs::OsRng;
use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519StaticSecret};
use zeroize::Zeroize;
pub const NOISE_PROTOCOL_NAME: &str = "Noise_XX_25519_ChaChaPoly_BLAKE3";
pub const NOISE_HASHLEN: usize = 32;
pub const NOISE_BLOCKLEN: usize = 64;
pub const NOISE_KEYLEN: usize = 32;
pub const NOISE_TAGLEN: usize = 16;
pub const NOISE_NONCELEN: usize = 12;
pub const NOISE_FRAME_HEADER_LEN: usize = 2;
pub fn blake3_digest(data: &[u8]) -> [u8; 32] {
let hash = blake3::hash(data);
*hash.as_bytes()
}
pub fn hmac_blake3(key: &[u8], data: &[u8]) -> [u8; 32] {
let mut k = [0u8; NOISE_BLOCKLEN];
if key.len() > NOISE_BLOCKLEN {
let digest = blake3_digest(key);
k[..32].copy_from_slice(&digest);
} else {
k[..key.len()].copy_from_slice(key);
}
let mut ipad = [0u8; NOISE_BLOCKLEN];
let mut opad = [0u8; NOISE_BLOCKLEN];
for i in 0..NOISE_BLOCKLEN {
ipad[i] = k[i] ^ 0x36;
opad[i] = k[i] ^ 0x5c;
}
let mut inner_input = Vec::with_capacity(NOISE_BLOCKLEN + data.len());
inner_input.extend_from_slice(&ipad);
inner_input.extend_from_slice(data);
let inner_hash = blake3_digest(&inner_input);
let mut outer_input = Vec::with_capacity(NOISE_BLOCKLEN + 32);
outer_input.extend_from_slice(&opad);
outer_input.extend_from_slice(&inner_hash);
blake3_digest(&outer_input)
}
pub fn hkdf2(ck: &[u8; 32], ikm: &[u8]) -> ([u8; 32], [u8; 32]) {
let prk = hmac_blake3(ck, ikm);
let out1 = hmac_blake3(&prk, &[0x01]);
let mut info2 = Vec::with_capacity(33);
info2.extend_from_slice(&out1);
info2.push(0x02);
let out2 = hmac_blake3(&prk, &info2);
(out1, out2)
}
pub fn hkdf3(ck: &[u8; 32], ikm: &[u8]) -> ([u8; 32], [u8; 32], [u8; 32]) {
let prk = hmac_blake3(ck, ikm);
let out1 = hmac_blake3(&prk, &[0x01]);
let mut info2 = Vec::with_capacity(33);
info2.extend_from_slice(&out1);
info2.push(0x02);
let out2 = hmac_blake3(&prk, &info2);
let mut info3 = Vec::with_capacity(33);
info3.extend_from_slice(&out2);
info3.push(0x03);
let out3 = hmac_blake3(&prk, &info3);
(out1, out2, out3)
}
#[derive(Clone)]
pub struct SovereignNodeIdentity {
pub did: String,
pub ed25519_public_key: [u8; 32],
pub ed25519_private_key: [u8; 32],
pub x25519_public_key: [u8; 32],
pub x25519_private_key: [u8; 32],
signing_key: SigningKey,
x25519_secret: X25519StaticSecret,
}
impl SovereignNodeIdentity {
pub fn generate() -> Self {
let mut seed = [0u8; 32];
let mut rng = OsRng;
rand::RngCore::fill_bytes(&mut rng, &mut seed);
Self::from_seed(&seed)
}
pub fn from_seed(seed: &[u8; 32]) -> Self {
let mut ed_input = Vec::with_capacity(44);
ed_input.extend_from_slice(seed);
ed_input.extend_from_slice(b"ed25519:seed");
let ed_seed = blake3_digest(&ed_input);
let mut x_input = Vec::with_capacity(42);
x_input.extend_from_slice(seed);
x_input.extend_from_slice(b"x25519:seed");
let x_seed = blake3_digest(&x_input);
let signing_key = SigningKey::from_bytes(&ed_seed);
let verifying_key = signing_key.verifying_key();
let ed_pub = verifying_key.to_bytes();
let x_secret = X25519StaticSecret::from(x_seed);
let x_pub = X25519PublicKey::from(&x_secret).to_bytes();
let did = format!("did:pkc:{}", bs58::encode(&ed_pub).into_string());
Self {
did,
ed25519_public_key: ed_pub,
ed25519_private_key: ed_seed,
x25519_public_key: x_pub,
x25519_private_key: x_seed,
signing_key,
x25519_secret: x_secret,
}
}
pub fn sign(&self, message: &[u8]) -> [u8; 64] {
let sig: Signature = self.signing_key.sign(message);
sig.to_bytes()
}
pub fn did_to_public_key(did: &str) -> Result<[u8; 32], String> {
if !did.starts_with("did:pkc:") {
return Err(format!("Invalid DID prefix for '{}'", did));
}
let rest = &did["did:pkc:".len()..];
let bytes = if rest.starts_with('z') {
let decoded = bs58::decode(&rest[1..]).into_vec().map_err(|e| e.to_string())?;
if decoded.len() >= 2 && decoded[0] == 0xed && decoded[1] == 0x01 {
decoded[2..].to_vec()
} else {
decoded
}
} else {
bs58::decode(rest).into_vec().map_err(|e| e.to_string())?
};
if bytes.len() != 32 {
return Err(format!("Invalid public key length from DID: {}", bytes.len()));
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Ok(arr)
}
pub fn public_key_to_did(pubkey: &[u8; 32]) -> String {
format!("did:pkc:{}", bs58::encode(pubkey).into_string())
}
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
Self::verify_signature(&self.ed25519_public_key, message, signature)
}
pub fn verify_signature(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
if let Ok(vk) = VerifyingKey::from_bytes(public_key) {
let sig = Signature::from_bytes(signature);
vk.verify(message, &sig).is_ok()
} else {
false
}
}
pub fn diffie_hellman(&self, peer_x25519_public: &[u8; 32]) -> [u8; 32] {
let peer_pub = X25519PublicKey::from(*peer_x25519_public);
*self.x25519_secret.diffie_hellman(&peer_pub).as_bytes()
}
}
#[derive(Clone, Default)]
pub struct NoiseCipherState {
pub key: Option<[u8; 32]>,
pub nonce: u64,
}
impl NoiseCipherState {
pub fn new() -> Self {
Self { key: None, nonce: 0 }
}
pub fn initialize_key(&mut self, key: Option<[u8; 32]>) {
self.key = key;
self.nonce = 0;
}
pub fn has_key(&self) -> bool {
self.key.is_some()
}
pub fn encrypt_with_ad(&mut self, ad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, String> {
let key_bytes = match self.key {
Some(k) => k,
None => return Ok(plaintext.to_vec()),
};
let key = Key::from(key_bytes);
let cipher = ChaCha20Poly1305::new(&key);
let mut nonce_bytes = [0u8; NOISE_NONCELEN];
nonce_bytes[4..12].copy_from_slice(&self.nonce.to_be_bytes());
let nonce = Nonce::from(nonce_bytes);
let payload = Payload { msg: plaintext, aad: ad };
let ciphertext = cipher
.encrypt(&nonce, payload)
.map_err(|e| format!("ChaCha20Poly1305 encryption failed: {}", e))?;
self.nonce += 1;
Ok(ciphertext)
}
pub fn decrypt_with_ad(&mut self, ad: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let key_bytes = match self.key {
Some(k) => k,
None => return Ok(ciphertext.to_vec()),
};
if ciphertext.len() < NOISE_TAGLEN {
self.zeroize();
return Err(format!("Ciphertext too short: {} < {}", ciphertext.len(), NOISE_TAGLEN));
}
let key = Key::from(key_bytes);
let cipher = ChaCha20Poly1305::new(&key);
let mut nonce_bytes = [0u8; NOISE_NONCELEN];
nonce_bytes[4..12].copy_from_slice(&self.nonce.to_be_bytes());
let nonce = Nonce::from(nonce_bytes);
let payload = Payload { msg: ciphertext, aad: ad };
let plaintext = cipher
.decrypt(&nonce, payload)
.map_err(|e| {
self.zeroize();
format!("MAC verification failed: {} (INV-257-01)", e)
})?;
self.nonce += 1;
Ok(plaintext)
}
pub fn zeroize(&mut self) {
if let Some(ref mut k) = self.key {
k.zeroize();
}
self.key = None;
self.nonce = 0;
}
}
#[derive(Clone)]
pub struct NoiseSymmetricState {
pub cipher: NoiseCipherState,
pub ck: [u8; 32],
pub h: [u8; 32],
}
impl NoiseSymmetricState {
pub fn new(protocol_name: &str) -> Self {
let mut h = [0u8; 32];
let name_bytes = protocol_name.as_bytes();
if name_bytes.len() <= 32 {
h[..name_bytes.len()].copy_from_slice(name_bytes);
} else {
h = blake3_digest(name_bytes);
}
let ck = h;
Self {
cipher: NoiseCipherState::new(),
ck,
h,
}
}
pub fn mix_key(&mut self, ikm: &[u8]) {
let (next_ck, temp_k) = hkdf2(&self.ck, ikm);
self.ck = next_ck;
self.cipher.initialize_key(Some(temp_k));
}
pub fn mix_hash(&mut self, data: &[u8]) {
let mut input = Vec::with_capacity(self.h.len() + data.len());
input.extend_from_slice(&self.h);
input.extend_from_slice(data);
self.h = blake3_digest(&input);
}
pub fn mix_key_and_hash(&mut self, ikm: &[u8]) {
let (next_ck, temp_h, temp_k) = hkdf3(&self.ck, ikm);
self.ck = next_ck;
self.mix_hash(&temp_h);
self.cipher.initialize_key(Some(temp_k));
}
pub fn encrypt_and_hash(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, String> {
let ciphertext = self.cipher.encrypt_with_ad(&self.h, plaintext)?;
self.mix_hash(&ciphertext);
Ok(ciphertext)
}
pub fn decrypt_and_hash(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>, String> {
let plaintext = self.cipher.decrypt_with_ad(&self.h, ciphertext)?;
self.mix_hash(ciphertext);
Ok(plaintext)
}
pub fn split(&mut self) -> (NoiseCipherState, NoiseCipherState) {
let (k1, k2) = hkdf2(&self.ck, &[]);
let mut c1 = NoiseCipherState::new();
c1.initialize_key(Some(k1));
let mut c2 = NoiseCipherState::new();
c2.initialize_key(Some(k2));
(c1, c2)
}
pub fn zeroize(&mut self) {
self.ck.zeroize();
self.h.zeroize();
self.cipher.zeroize();
}
}
#[path = "noise_handshake.rs"]
mod noise_handshake;
#[allow(unused_imports)]
pub use noise_handshake::*;
#[path = "noise_transport.rs"]
mod noise_transport;
#[allow(unused_imports)]
pub use noise_transport::*;
#[cfg(test)]
#[path = "noise_tests.rs"]
mod tests;