use hide_epoch::EpochRecord;
use hide_sign::{SIGNATURE_LENGTH, SigningIdentity, VERIFYING_KEY_LENGTH, VerifyingIdentity};
use crate::{DeviceId, Entry, Event, IdentityError, IdentityLog, Membership, device_id};
pub const RECOVERY_BINDING_CONTEXT: &[u8] = b"HIDE/1.0 recovery binding";
pub const EPOCH_BINDING_CONTEXT: &[u8] = b"HIDE/1.0 epoch binding";
pub const RECOVERY_BINDING_LENGTH: usize = 32 + VERIFYING_KEY_LENGTH + SIGNATURE_LENGTH;
pub const EPOCH_BINDING_LENGTH: usize = 32 * 3 + 8 + 32 + SIGNATURE_LENGTH;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecoveryBinding {
pub root: [u8; 32],
pub recovery_key: VerifyingIdentity,
pub signature: Vec<u8>,
}
fn recovery_message(root: &[u8; 32], recovery: &VerifyingIdentity) -> Vec<u8> {
let mut out = Vec::with_capacity(32 + VERIFYING_KEY_LENGTH);
out.extend_from_slice(root);
out.extend_from_slice(&recovery.to_bytes());
out
}
fn founder_key(entries: &[Entry]) -> Result<VerifyingIdentity, IdentityError> {
match entries.first().map(|entry| &entry.event) {
Some(Event::Create { device, .. }) => {
VerifyingIdentity::from_bytes(device).map_err(|_| IdentityError::BadBinding)
}
Some(_) => Err(IdentityError::BadRoot("another event")),
None => Err(IdentityError::Empty),
}
}
impl RecoveryBinding {
pub fn create(log: &IdentityLog, founder: &SigningIdentity) -> Result<Self, IdentityError> {
let root = log.root();
let expected = founder_key(log.entries())?;
if founder.verifying_key() != expected {
return Err(IdentityError::Unauthorised(0));
}
let signature = founder
.sign(
RECOVERY_BINDING_CONTEXT,
&recovery_message(&root, &log.recovery),
)
.to_vec();
Ok(Self {
root,
recovery_key: log.recovery.clone(),
signature,
})
}
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(RECOVERY_BINDING_LENGTH);
out.extend_from_slice(&self.root);
out.extend_from_slice(&self.recovery_key.to_bytes());
out.extend_from_slice(&self.signature);
out
}
pub fn decode(bytes: &[u8]) -> Result<Self, IdentityError> {
if bytes.len() != RECOVERY_BINDING_LENGTH {
return Err(IdentityError::Malformed);
}
let (root, rest) = bytes.split_at(32);
let (key, signature) = rest.split_at(VERIFYING_KEY_LENGTH);
Ok(Self {
root: root.try_into().map_err(|_| IdentityError::Malformed)?,
recovery_key: VerifyingIdentity::from_bytes(key)
.map_err(|_| IdentityError::Malformed)?,
signature: signature.to_vec(),
})
}
pub fn verify(&self, entries: Vec<Entry>) -> Result<IdentityLog, IdentityError> {
let founder = founder_key(&entries)?;
if entries.first().map(|entry| entry.link) != Some(self.root) {
return Err(IdentityError::WrongIdentity);
}
founder
.verify(
RECOVERY_BINDING_CONTEXT,
&recovery_message(&self.root, &self.recovery_key),
&self.signature,
)
.map_err(|_| IdentityError::BadBinding)?;
IdentityLog::from_entries(entries, self.recovery_key.clone())
}
pub fn verify_pinned(
&self,
entries: Vec<Entry>,
pinned_root: &[u8; 32],
) -> Result<IdentityLog, IdentityError> {
if &self.root != pinned_root {
return Err(IdentityError::WrongIdentity);
}
self.verify(entries)
}
pub fn verify_pinned_all(
bindings: &[Self],
entries: Vec<Entry>,
pinned_root: &[u8; 32],
) -> Result<IdentityLog, IdentityError> {
let founder = founder_key(&entries)?;
if entries.first().map(|entry| entry.link) != Some(*pinned_root) {
return Err(IdentityError::WrongIdentity);
}
let mut chosen: Option<&Self> = None;
for binding in bindings {
if &binding.root != pinned_root {
return Err(IdentityError::WrongIdentity);
}
if founder
.verify(
RECOVERY_BINDING_CONTEXT,
&recovery_message(&binding.root, &binding.recovery_key),
&binding.signature,
)
.is_err()
{
continue;
}
match chosen {
Some(previous) if previous.recovery_key != binding.recovery_key => {
return Err(IdentityError::ConflictingBindings);
}
Some(_) => {}
None => chosen = Some(binding),
}
}
chosen.ok_or(IdentityError::BadBinding)?.verify(entries)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpochBinding {
pub identity_root: [u8; 32],
pub identity_head: [u8; 32],
pub chain_head: [u8; 32],
pub epochs: u64,
pub signer: DeviceId,
pub signature: Vec<u8>,
}
fn chain_head(records: &[EpochRecord]) -> [u8; 32] {
records.last().map_or([0; 32], |record| record.link)
}
impl EpochBinding {
fn message(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(32 * 4 + 8);
out.extend_from_slice(&self.identity_root);
out.extend_from_slice(&self.identity_head);
out.extend_from_slice(&self.chain_head);
out.extend_from_slice(&self.epochs.to_be_bytes());
out.extend_from_slice(&self.signer);
out
}
pub fn create(
log: &IdentityLog,
device: &SigningIdentity,
records: &[EpochRecord],
) -> Result<Self, IdentityError> {
let signer = device_id(&device.verifying_key());
if !log.membership().contains(&signer) {
return Err(IdentityError::Unauthorised(log.entries().len() as u64));
}
hide_epoch::EpochChain::verify(records).map_err(|_| IdentityError::StaleBinding)?;
if records.is_empty() {
return Err(IdentityError::StaleBinding);
}
let mut binding = Self {
identity_root: log.root(),
identity_head: log.head(),
chain_head: chain_head(records),
epochs: records.len() as u64,
signer,
signature: Vec::new(),
};
binding.signature = device
.sign(EPOCH_BINDING_CONTEXT, &binding.message())
.to_vec();
Ok(binding)
}
pub fn encode(&self) -> Vec<u8> {
let mut out = self.message();
out.extend_from_slice(&self.signature);
out
}
pub fn decode(bytes: &[u8]) -> Result<Self, IdentityError> {
if bytes.len() != EPOCH_BINDING_LENGTH {
return Err(IdentityError::Malformed);
}
let field = |at: usize| -> Result<[u8; 32], IdentityError> {
bytes[at..at + 32]
.try_into()
.map_err(|_| IdentityError::Malformed)
};
Ok(Self {
identity_root: field(0)?,
identity_head: field(32)?,
chain_head: field(64)?,
epochs: u64::from_be_bytes(
bytes[96..104]
.try_into()
.map_err(|_| IdentityError::Malformed)?,
),
signer: field(104)?,
signature: bytes[136..].to_vec(),
})
}
pub fn verify(&self, log: &IdentityLog, records: &[EpochRecord]) -> Result<(), IdentityError> {
if log.root() != self.identity_root {
return Err(IdentityError::WrongIdentity);
}
if !log
.entries()
.iter()
.any(|entry| entry.link == self.identity_head)
{
return Err(IdentityError::StaleBinding);
}
hide_epoch::EpochChain::verify(records).map_err(|_| IdentityError::StaleBinding)?;
if records.is_empty()
|| records.len() as u64 != self.epochs
|| chain_head(records) != self.chain_head
{
return Err(IdentityError::StaleBinding);
}
verify_by_member(
&log.membership(),
&self.signer,
&self.message(),
&self.signature,
)
}
}
fn verify_by_member(
membership: &Membership,
signer: &DeviceId,
message: &[u8],
signature: &[u8],
) -> Result<(), IdentityError> {
let device = membership
.get(signer)
.ok_or(IdentityError::Unauthorised(0))?;
device
.key
.verify(EPOCH_BINDING_CONTEXT, message, signature)
.map_err(|_| IdentityError::BadBinding)
}