libp2p_core/
signed_envelope.rs

1use std::fmt;
2
3use libp2p_identity::{Keypair, PublicKey, SigningError};
4use quick_protobuf::{BytesReader, Writer};
5use unsigned_varint::encode::usize_buffer;
6
7use crate::{proto, DecodeError};
8
9/// A signed envelope contains an arbitrary byte string payload, a signature of the payload, and the
10/// public key that can be used to verify the signature.
11///
12/// For more details see libp2p RFC0002: <https://github.com/libp2p/specs/blob/master/RFC/0002-signed-envelopes.md>
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct SignedEnvelope {
15    key: PublicKey,
16    payload_type: Vec<u8>,
17    payload: Vec<u8>,
18    signature: Vec<u8>,
19}
20
21impl SignedEnvelope {
22    /// Constructs a new [`SignedEnvelope`].
23    pub fn new(
24        key: &Keypair,
25        domain_separation: String,
26        payload_type: Vec<u8>,
27        payload: Vec<u8>,
28    ) -> Result<Self, SigningError> {
29        let buffer = signature_payload(domain_separation, &payload_type, &payload);
30
31        let signature = key.sign(&buffer)?;
32
33        Ok(Self {
34            key: key.public(),
35            payload_type,
36            payload,
37            signature,
38        })
39    }
40
41    /// Verify this [`SignedEnvelope`] against the provided domain-separation string.
42    #[must_use]
43    pub fn verify(&self, domain_separation: String) -> bool {
44        let buffer = signature_payload(domain_separation, &self.payload_type, &self.payload);
45
46        self.key.verify(&buffer, &self.signature)
47    }
48
49    /// Extract the payload and signing key of this [`SignedEnvelope`].
50    ///
51    /// You must provide the correct domain-separation string and expected payload type in order to
52    /// get the payload. This guards against accidental misuse of the payload where the
53    /// signature was created for a different purpose or payload type.
54    ///
55    /// It is the caller's responsibility to check that the signing key is what
56    /// is expected. For example, checking that the signing key is from a
57    /// certain peer.
58    pub fn payload_and_signing_key(
59        &self,
60        domain_separation: String,
61        expected_payload_type: &[u8],
62    ) -> Result<(&[u8], &PublicKey), ReadPayloadError> {
63        if self.payload_type != expected_payload_type {
64            return Err(ReadPayloadError::UnexpectedPayloadType {
65                expected: expected_payload_type.to_vec(),
66                got: self.payload_type.clone(),
67            });
68        }
69
70        if !self.verify(domain_separation) {
71            return Err(ReadPayloadError::InvalidSignature);
72        }
73
74        Ok((&self.payload, &self.key))
75    }
76
77    /// Encode this [`SignedEnvelope`] using the protobuf encoding specified in the RFC.
78    pub fn into_protobuf_encoding(self) -> Vec<u8> {
79        use quick_protobuf::MessageWrite;
80
81        let envelope = proto::Envelope {
82            public_key: self.key.encode_protobuf(),
83            payload_type: self.payload_type,
84            payload: self.payload,
85            signature: self.signature,
86        };
87
88        let mut buf = Vec::with_capacity(envelope.get_size());
89        let mut writer = Writer::new(&mut buf);
90
91        envelope
92            .write_message(&mut writer)
93            .expect("Encoding to succeed");
94
95        buf
96    }
97
98    /// Decode a [`SignedEnvelope`] using the protobuf encoding specified in the RFC.
99    pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<Self, DecodingError> {
100        use quick_protobuf::MessageRead;
101
102        let mut reader = BytesReader::from_bytes(bytes);
103        let envelope = proto::Envelope::from_reader(&mut reader, bytes).map_err(DecodeError)?;
104
105        Ok(Self {
106            key: PublicKey::try_decode_protobuf(&envelope.public_key)?,
107            payload_type: envelope.payload_type.to_vec(),
108            payload: envelope.payload.to_vec(),
109            signature: envelope.signature.to_vec(),
110        })
111    }
112}
113
114fn signature_payload(domain_separation: String, payload_type: &[u8], payload: &[u8]) -> Vec<u8> {
115    let mut domain_sep_length_buffer = usize_buffer();
116    let domain_sep_length =
117        unsigned_varint::encode::usize(domain_separation.len(), &mut domain_sep_length_buffer);
118
119    let mut payload_type_length_buffer = usize_buffer();
120    let payload_type_length =
121        unsigned_varint::encode::usize(payload_type.len(), &mut payload_type_length_buffer);
122
123    let mut payload_length_buffer = usize_buffer();
124    let payload_length = unsigned_varint::encode::usize(payload.len(), &mut payload_length_buffer);
125
126    let mut buffer = Vec::with_capacity(
127        domain_sep_length.len()
128            + domain_separation.len()
129            + payload_type_length.len()
130            + payload_type.len()
131            + payload_length.len()
132            + payload.len(),
133    );
134
135    buffer.extend_from_slice(domain_sep_length);
136    buffer.extend_from_slice(domain_separation.as_bytes());
137    buffer.extend_from_slice(payload_type_length);
138    buffer.extend_from_slice(payload_type);
139    buffer.extend_from_slice(payload_length);
140    buffer.extend_from_slice(payload);
141
142    buffer
143}
144
145/// Errors that occur whilst decoding a [`SignedEnvelope`] from its byte representation.
146#[derive(thiserror::Error, Debug)]
147pub enum DecodingError {
148    /// Decoding the provided bytes as a signed envelope failed.
149    #[error("Failed to decode envelope")]
150    InvalidEnvelope(#[from] DecodeError),
151    /// The public key in the envelope could not be converted to our internal public key type.
152    #[error("Failed to convert public key")]
153    InvalidPublicKey(#[from] libp2p_identity::DecodingError),
154    /// The public key in the envelope could not be converted to our internal public key type.
155    #[error("Public key is missing from protobuf struct")]
156    MissingPublicKey,
157}
158
159/// Errors that occur whilst extracting the payload of a [`SignedEnvelope`].
160#[derive(Debug)]
161pub enum ReadPayloadError {
162    /// The signature on the signed envelope does not verify
163    /// with the provided domain separation string.
164    InvalidSignature,
165    /// The payload contained in the envelope is not of the expected type.
166    UnexpectedPayloadType { expected: Vec<u8>, got: Vec<u8> },
167}
168
169impl fmt::Display for ReadPayloadError {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        match self {
172            Self::InvalidSignature => write!(f, "Invalid signature"),
173            Self::UnexpectedPayloadType { expected, got } => write!(
174                f,
175                "Unexpected payload type, expected {expected:?} but got {got:?}"
176            ),
177        }
178    }
179}
180
181impl std::error::Error for ReadPayloadError {}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn test_roundtrip() {
189        let kp = Keypair::generate_ed25519();
190        let payload = "some payload".as_bytes();
191        let domain_separation = "domain separation".to_string();
192        let payload_type: Vec<u8> = "payload type".into();
193
194        let env = SignedEnvelope::new(
195            &kp,
196            domain_separation.clone(),
197            payload_type.clone(),
198            payload.into(),
199        )
200        .expect("Failed to create envelope");
201
202        let (actual_payload, signing_key) = env
203            .payload_and_signing_key(domain_separation, &payload_type)
204            .expect("Failed to extract payload and public key");
205
206        assert_eq!(actual_payload, payload);
207        assert_eq!(signing_key, &kp.public());
208    }
209}