use ed25519_dalek::{Signature, VerifyingKey};
use crate::checkpoint::{Checkpoint, MAX_NOTE_BYTES, SignedNote, valid_name};
use crate::{Hash, LogError};
pub const C2SP_ED25519_ALGORITHM: u8 = 0x01;
pub const MAX_WITNESS_PROOF_LINES: usize = 63;
const COSIGNATURE_LABEL: &[u8] = b"cosignature/v1";
pub fn empty_tree_root() -> Hash {
use sha2::Digest;
let digest = sha2::Sha256::digest([]);
let mut root = [0_u8; 32];
root.copy_from_slice(&digest);
root
}
pub fn c2sp_key_id(name: &str, ed25519_public: &[u8; 32]) -> [u8; 4] {
use sha2::Digest;
let mut hasher = sha2::Sha256::new();
hasher.update(name.as_bytes());
hasher.update([0x0a, C2SP_ED25519_ALGORITHM]);
hasher.update(ed25519_public);
let digest = hasher.finalize();
[digest[0], digest[1], digest[2], digest[3]]
}
pub fn cosignature_input(timestamp: u64, checkpoint_text: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(32 + checkpoint_text.len());
out.extend_from_slice(COSIGNATURE_LABEL);
out.push(b'\n');
out.extend_from_slice(format!("time {timestamp}\n").as_bytes());
out.extend_from_slice(checkpoint_text.as_bytes());
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Witness {
pub name: String,
pub ed25519_public: [u8; 32],
}
impl Witness {
pub fn new(name: impl Into<String>, ed25519_public: [u8; 32]) -> Result<Self, LogError> {
let name = name.into();
if !valid_name(&name) {
return Err(LogError::Malformed);
}
Ok(Self {
name,
ed25519_public,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cosignature {
pub timestamp: u64,
}
pub fn verify_ed25519_cosignature(
note: &[u8],
origin: &str,
log: &hide_sign::VerifyingIdentity,
witness: &Witness,
timestamp: u64,
) -> Result<(Checkpoint, Cosignature), LogError> {
let checkpoint = Checkpoint::verify(note, origin, log)?;
if note.len() > MAX_NOTE_BYTES {
return Err(LogError::Malformed);
}
let parsed = SignedNote::decode(note)?;
let id = c2sp_key_id(&witness.name, &witness.ed25519_public);
let line = parsed
.signatures
.iter()
.find(|line| line.name == witness.name && line.key_id == id)
.ok_or(LogError::Unsigned)?;
let key =
VerifyingKey::from_bytes(&witness.ed25519_public).map_err(|_| LogError::BadSignature)?;
let signature = Signature::from_slice(&line.signature).map_err(|_| LogError::BadSignature)?;
let message = cosignature_input(timestamp, &parsed.text);
key.verify_strict(&message, &signature)
.map_err(|_| LogError::BadSignature)?;
Ok((checkpoint, Cosignature { timestamp }))
}
pub fn add_checkpoint_body(
old_size: u64,
proof: &[Hash],
note: &[u8],
) -> Result<Vec<u8>, LogError> {
use base64::Engine;
if proof.len() > MAX_WITNESS_PROOF_LINES {
return Err(LogError::ProofTooLong(proof.len()));
}
if old_size == 0 && !proof.is_empty() {
return Err(LogError::Malformed);
}
if note.len() > MAX_NOTE_BYTES {
return Err(LogError::Malformed);
}
let mut out = Vec::with_capacity(32 + 45 * proof.len() + note.len());
out.extend_from_slice(format!("old {old_size}\n").as_bytes());
for hash in proof {
out.extend_from_slice(
base64::engine::general_purpose::STANDARD
.encode(hash)
.as_bytes(),
);
out.push(b'\n');
}
out.push(b'\n');
out.extend_from_slice(note);
Ok(out)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AddCheckpointOutcome {
Cosigned(Vec<u8>),
UnknownOrigin,
NotSigned,
BadOldSize,
Conflict { newest_size: u64 },
ProofRejected,
}
pub fn classify_add_checkpoint(status: u16, body: &[u8]) -> Result<AddCheckpointOutcome, LogError> {
Ok(match status {
200 => AddCheckpointOutcome::Cosigned(body.to_vec()),
403 => AddCheckpointOutcome::NotSigned,
404 => AddCheckpointOutcome::UnknownOrigin,
400 => AddCheckpointOutcome::BadOldSize,
409 => {
let text = std::str::from_utf8(body).map_err(|_| LogError::Malformed)?;
let line = text.strip_suffix('\n').ok_or(LogError::Malformed)?;
if line.is_empty() || !line.bytes().all(|b| b.is_ascii_digit()) {
return Err(LogError::Malformed);
}
if line.len() > 1 && line.starts_with('0') {
return Err(LogError::Malformed);
}
let newest_size: u64 = line.parse().map_err(|_| LogError::Malformed)?;
AddCheckpointOutcome::Conflict { newest_size }
}
422 => AddCheckpointOutcome::ProofRejected,
_ => return Err(LogError::Malformed),
})
}
pub fn is_empty_tree_checkpoint(checkpoint: &Checkpoint) -> bool {
checkpoint.size == 0 && checkpoint.root == empty_tree_root()
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
fn checkpoint(size: u64) -> Checkpoint {
Checkpoint {
origin: "hide.example/log".into(),
size,
root: [7_u8; 32],
}
}
fn witness_key() -> SigningKey {
SigningKey::from_bytes(&[0x51; 32])
}
fn cosigned_note(timestamp: u64) -> (Vec<u8>, Witness) {
let log = hide_sign::SigningIdentity::from_bytes(&[0x42; 32]).unwrap();
let text = checkpoint(9).text().unwrap();
let mut note = checkpoint(9).sign(&log).unwrap();
let witness =
Witness::new("witness.example", witness_key().verifying_key().to_bytes()).unwrap();
let signature = witness_key().sign(&cosignature_input(timestamp, &text));
let mut raw = Vec::new();
raw.extend_from_slice(&c2sp_key_id(&witness.name, &witness.ed25519_public));
raw.extend_from_slice(&signature.to_bytes());
note.signatures.push(crate::checkpoint::NoteSignature {
name: witness.name.clone(),
key_id: c2sp_key_id(&witness.name, &witness.ed25519_public),
signature: raw[4..].to_vec(),
});
(note.encode().into_bytes(), witness)
}
#[test]
fn a_c2sp_ed25519_cosignature_verifies_over_a_hide_checkpoint() {
let log = hide_sign::SigningIdentity::from_bytes(&[0x42; 32]).unwrap();
let (note, witness) = cosigned_note(1_700_000_000);
let (checkpoint, cosignature) = verify_ed25519_cosignature(
¬e,
"hide.example/log",
&log.verifying_key(),
&witness,
1_700_000_000,
)
.expect("a genuine cosignature verifies");
assert_eq!(checkpoint.size, 9);
assert_eq!(cosignature.timestamp, 1_700_000_000);
}
#[test]
fn a_cosignature_is_bound_to_its_timestamp() {
let log = hide_sign::SigningIdentity::from_bytes(&[0x42; 32]).unwrap();
let (note, witness) = cosigned_note(1_700_000_000);
assert_eq!(
verify_ed25519_cosignature(
¬e,
"hide.example/log",
&log.verifying_key(),
&witness,
1_700_000_001
),
Err(LogError::BadSignature)
);
}
#[test]
fn a_cosignature_over_an_unsigned_checkpoint_is_refused() {
let other = hide_sign::SigningIdentity::from_bytes(&[0x43; 32]).unwrap();
let (note, witness) = cosigned_note(1_700_000_000);
assert_eq!(
verify_ed25519_cosignature(
¬e,
"hide.example/log",
&other.verifying_key(),
&witness,
1_700_000_000
),
Err(LogError::Unsigned)
);
}
#[test]
fn a_cosignature_from_another_witness_is_refused() {
let log = hide_sign::SigningIdentity::from_bytes(&[0x42; 32]).unwrap();
let (note, _) = cosigned_note(1_700_000_000);
let other = SigningKey::from_bytes(&[0x52; 32]);
let stranger = Witness::new("witness.example", other.verifying_key().to_bytes()).unwrap();
assert_eq!(
verify_ed25519_cosignature(
¬e,
"hide.example/log",
&log.verifying_key(),
&stranger,
1_700_000_000
),
Err(LogError::Unsigned)
);
}
#[test]
fn the_request_body_has_the_specified_framing() {
let note = b"origin\n1\nAAAA\n\xe2\x80\x94 sig AAAA\n";
let proof = [[1_u8; 32], [2_u8; 32]];
let body = add_checkpoint_body(5, &proof, note).unwrap();
let text = String::from_utf8(body.clone()).unwrap();
let mut lines = text.split_inclusive('\n');
assert_eq!(lines.next().unwrap(), "old 5\n");
assert_eq!(
lines.next().unwrap(),
"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=\n"
);
assert_eq!(
lines.next().unwrap(),
"AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=\n"
);
assert_eq!(lines.next().unwrap(), "\n");
assert_eq!(text.split("\n\n").nth(1).unwrap().as_bytes(), note);
}
#[test]
fn a_non_empty_proof_at_size_zero_is_refused() {
let note = b"origin\n0\nAAAA\n";
assert_eq!(
add_checkpoint_body(0, &[[1_u8; 32]], note),
Err(LogError::Malformed)
);
assert!(add_checkpoint_body(0, &[], note).is_ok());
}
#[test]
fn too_many_proof_lines_are_refused() {
let note = b"origin\n1\nAAAA\n";
let proof = vec![[1_u8; 32]; MAX_WITNESS_PROOF_LINES + 1];
assert!(matches!(
add_checkpoint_body(1, &proof, note),
Err(LogError::ProofTooLong(_))
));
assert!(add_checkpoint_body(1, &vec![[1_u8; 32]; MAX_WITNESS_PROOF_LINES], note).is_ok());
}
#[test]
fn every_named_status_is_classified() {
assert_eq!(
classify_add_checkpoint(200, b"\xe2\x80\x94 w AAAA\n").unwrap(),
AddCheckpointOutcome::Cosigned(b"\xe2\x80\x94 w AAAA\n".to_vec())
);
assert_eq!(
classify_add_checkpoint(403, b"").unwrap(),
AddCheckpointOutcome::NotSigned
);
assert_eq!(
classify_add_checkpoint(404, b"").unwrap(),
AddCheckpointOutcome::UnknownOrigin
);
assert_eq!(
classify_add_checkpoint(400, b"").unwrap(),
AddCheckpointOutcome::BadOldSize
);
assert_eq!(
classify_add_checkpoint(409, b"20852014\n").unwrap(),
AddCheckpointOutcome::Conflict {
newest_size: 20_852_014
}
);
assert_eq!(
classify_add_checkpoint(422, b"").unwrap(),
AddCheckpointOutcome::ProofRejected
);
}
#[test]
fn a_malformed_conflict_body_is_refused() {
for body in [
&b"05\n"[..],
&b"+5\n"[..],
&b"5"[..],
&b"\n"[..],
&b"5 5\n"[..],
&b"18446744073709551616\n"[..],
] {
assert_eq!(
classify_add_checkpoint(409, body),
Err(LogError::Malformed),
"accepted {body:?}"
);
}
}
#[test]
fn an_unnamed_status_is_refused() {
for status in [201, 301, 500, 0] {
assert_eq!(
classify_add_checkpoint(status, b""),
Err(LogError::Malformed)
);
}
}
#[test]
fn the_cosignature_input_cannot_be_shifted() {
assert_ne!(cosignature_input(1, "a\n"), cosignature_input(11, "\n"));
assert_eq!(
cosignature_input(1, "origin\n1\nAAAA\n"),
b"cosignature/v1\ntime 1\norigin\n1\nAAAA\n".to_vec()
);
}
#[test]
fn an_unusable_witness_name_is_refused() {
assert!(Witness::new("", [0_u8; 32]).is_err());
assert!(Witness::new("has space", [0_u8; 32]).is_err());
assert!(Witness::new("has+plus", [0_u8; 32]).is_err());
assert!(Witness::new("witness.example", [0_u8; 32]).is_ok());
}
#[test]
fn the_empty_root_matches_rfc_6962() {
use base64::Engine;
assert_eq!(
base64::engine::general_purpose::STANDARD.encode(empty_tree_root()),
"47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
);
assert!(is_empty_tree_checkpoint(&Checkpoint {
origin: "o".into(),
size: 0,
root: empty_tree_root(),
}));
assert!(!is_empty_tree_checkpoint(&Checkpoint {
origin: "o".into(),
size: 0,
root: [1_u8; 32],
}));
assert!(!is_empty_tree_checkpoint(&checkpoint(1)));
}
#[test]
fn the_two_key_id_derivations_differ() {
let log = hide_sign::SigningIdentity::from_bytes(&[0x42; 32]).unwrap();
let ed = log.verifying_key().ed25519_bytes();
let name = "witness.example";
assert_ne!(
c2sp_key_id(name, &ed),
crate::key_id(name, &log.verifying_key())
);
}
}