use crate::identity::error::SigningError;
use crate::identity::Keypair;
use crate::{identity, DecodeError, PublicKey};
use std::convert::TryInto;
use std::fmt;
use unsigned_varint::encode::usize_buffer;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedEnvelope {
key: PublicKey,
payload_type: Vec<u8>,
payload: Vec<u8>,
signature: Vec<u8>,
}
impl SignedEnvelope {
pub fn new(
key: &Keypair,
domain_separation: String,
payload_type: Vec<u8>,
payload: Vec<u8>,
) -> Result<Self, SigningError> {
let buffer = signature_payload(domain_separation, &payload_type, &payload);
let signature = key.sign(&buffer)?;
Ok(Self {
key: key.public(),
payload_type,
payload,
signature,
})
}
#[must_use]
pub fn verify(&self, domain_separation: String) -> bool {
let buffer = signature_payload(domain_separation, &self.payload_type, &self.payload);
self.key.verify(&buffer, &self.signature)
}
pub fn payload_and_signing_key(
&self,
domain_separation: String,
expected_payload_type: &[u8],
) -> Result<(&[u8], &PublicKey), ReadPayloadError> {
if self.payload_type != expected_payload_type {
return Err(ReadPayloadError::UnexpectedPayloadType {
expected: expected_payload_type.to_vec(),
got: self.payload_type.clone(),
});
}
if !self.verify(domain_separation) {
return Err(ReadPayloadError::InvalidSignature);
}
Ok((&self.payload, &self.key))
}
pub fn into_protobuf_encoding(self) -> Vec<u8> {
use prost::Message;
let envelope = crate::envelope_proto::Envelope {
public_key: Some((&self.key).into()),
payload_type: self.payload_type,
payload: self.payload,
signature: self.signature,
};
let mut buf = Vec::with_capacity(envelope.encoded_len());
envelope
.encode(&mut buf)
.expect("Vec<u8> provides capacity as needed");
buf
}
pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<Self, DecodingError> {
use prost::Message;
let envelope = crate::envelope_proto::Envelope::decode(bytes).map_err(DecodeError)?;
Ok(Self {
key: envelope
.public_key
.ok_or(DecodingError::MissingPublicKey)?
.try_into()?,
payload_type: envelope.payload_type,
payload: envelope.payload,
signature: envelope.signature,
})
}
}
fn signature_payload(domain_separation: String, payload_type: &[u8], payload: &[u8]) -> Vec<u8> {
let mut domain_sep_length_buffer = usize_buffer();
let domain_sep_length =
unsigned_varint::encode::usize(domain_separation.len(), &mut domain_sep_length_buffer);
let mut payload_type_length_buffer = usize_buffer();
let payload_type_length =
unsigned_varint::encode::usize(payload_type.len(), &mut payload_type_length_buffer);
let mut payload_length_buffer = usize_buffer();
let payload_length = unsigned_varint::encode::usize(payload.len(), &mut payload_length_buffer);
let mut buffer = Vec::with_capacity(
domain_sep_length.len()
+ domain_separation.len()
+ payload_type_length.len()
+ payload_type.len()
+ payload_length.len()
+ payload.len(),
);
buffer.extend_from_slice(domain_sep_length);
buffer.extend_from_slice(domain_separation.as_bytes());
buffer.extend_from_slice(payload_type_length);
buffer.extend_from_slice(payload_type);
buffer.extend_from_slice(payload_length);
buffer.extend_from_slice(payload);
buffer
}
#[derive(thiserror::Error, Debug)]
pub enum DecodingError {
#[error("Failed to decode envelope")]
InvalidEnvelope(#[from] DecodeError),
#[error("Failed to convert public key")]
InvalidPublicKey(#[from] identity::error::DecodingError),
#[error("Public key is missing from protobuf struct")]
MissingPublicKey,
}
#[derive(Debug)]
pub enum ReadPayloadError {
InvalidSignature,
UnexpectedPayloadType { expected: Vec<u8>, got: Vec<u8> },
}
impl fmt::Display for ReadPayloadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidSignature => write!(f, "Invalid signature"),
Self::UnexpectedPayloadType { expected, got } => write!(
f,
"Unexpected payload type, expected {:?} but got {:?}",
expected, got
),
}
}
}
impl std::error::Error for ReadPayloadError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test_roundtrip() {
let kp = Keypair::generate_ed25519();
let payload = "some payload".as_bytes();
let domain_separation = "domain separation".to_string();
let payload_type: Vec<u8> = "payload type".into();
let env = SignedEnvelope::new(
&kp,
domain_separation.clone(),
payload_type.clone(),
payload.into(),
)
.expect("Failed to create envelope");
let (actual_payload, signing_key) = env
.payload_and_signing_key(domain_separation, &payload_type)
.expect("Failed to extract payload and public key");
assert_eq!(actual_payload, payload);
assert_eq!(signing_key, &kp.public());
}
}