libp2p_core/
signed_envelope.rs

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