cometbft_proto/
lib.rs

1//! cometbft-proto library gives the developer access to the CometBFT proto-defined structs.
2
3#![cfg_attr(not(any(feature = "grpc-server", feature = "grpc-client")), no_std)]
4#![deny(warnings, trivial_casts, trivial_numeric_casts, unused_import_braces)]
5#![allow(clippy::large_enum_variant)]
6#![forbid(unsafe_code)]
7
8extern crate alloc;
9
10mod prelude;
11
12/// Built-in prost_types with slight customization to enable JSON-encoding
13#[allow(warnings)]
14pub mod google {
15    pub mod protobuf {
16        // custom Timeout and Duration types that have valid doctest documentation texts
17        include!("protobuf.rs");
18    }
19}
20
21#[allow(warnings)]
22mod cometbft;
23mod error;
24
25use core::{convert::TryFrom, fmt::Display};
26
27use bytes::{Buf, BufMut};
28pub use cometbft::*;
29pub use error::Error;
30use prost::Message;
31
32pub mod serializers;
33
34use prelude::*;
35
36/// Allows for easy Google Protocol Buffers encoding and decoding of domain
37/// types with validation.
38///
39/// ## Examples
40///
41/// ```rust
42/// use bytes::BufMut;
43/// use prost::Message;
44/// use core::convert::TryFrom;
45/// use cometbft_proto::Protobuf;
46///
47/// // This struct would ordinarily be automatically generated by prost.
48/// #[derive(Clone, PartialEq, Message)]
49/// pub struct MyRawType {
50///     #[prost(uint64, tag="1")]
51///     pub a: u64,
52///     #[prost(string, tag="2")]
53///     pub b: String,
54/// }
55///
56/// #[derive(Clone)]
57/// pub struct MyDomainType {
58///     a: u64,
59///     b: String,
60/// }
61///
62/// impl MyDomainType {
63///     /// Trivial constructor with basic validation logic.
64///     pub fn new(a: u64, b: String) -> Result<Self, String> {
65///         if a < 1 {
66///             return Err("a must be greater than 0".to_owned());
67///         }
68///         Ok(Self { a, b })
69///     }
70/// }
71///
72/// impl TryFrom<MyRawType> for MyDomainType {
73///     type Error = String;
74///
75///     fn try_from(value: MyRawType) -> Result<Self, Self::Error> {
76///         Self::new(value.a, value.b)
77///     }
78/// }
79///
80/// impl From<MyDomainType> for MyRawType {
81///     fn from(value: MyDomainType) -> Self {
82///         Self { a: value.a, b: value.b }
83///     }
84/// }
85///
86/// impl Protobuf<MyRawType> for MyDomainType {}
87///
88///
89/// // Simulate an incoming valid raw message
90/// let valid_raw = MyRawType { a: 1, b: "Hello!".to_owned() };
91/// let mut valid_raw_bytes: Vec<u8> = Vec::new();
92/// valid_raw.encode(&mut valid_raw_bytes).unwrap();
93/// assert!(!valid_raw_bytes.is_empty());
94///
95/// // Try to decode the simulated incoming message
96/// let valid_domain = MyDomainType::decode(valid_raw_bytes.clone().as_ref()).unwrap();
97/// assert_eq!(1, valid_domain.a);
98/// assert_eq!("Hello!".to_owned(), valid_domain.b);
99///
100/// // Encode it to compare the serialized form to what we received
101/// let mut valid_domain_bytes: Vec<u8> = Vec::new();
102/// valid_domain.encode(&mut valid_domain_bytes).unwrap();
103/// assert_eq!(valid_raw_bytes, valid_domain_bytes);
104///
105/// // Simulate an incoming invalid raw message
106/// let invalid_raw = MyRawType { a: 0, b: "Hello!".to_owned() };
107/// let mut invalid_raw_bytes: Vec<u8> = Vec::new();
108/// invalid_raw.encode(&mut invalid_raw_bytes).unwrap();
109///
110/// // We expect a validation error here
111/// assert!(MyDomainType::decode(invalid_raw_bytes.as_ref()).is_err());
112/// ```
113pub trait Protobuf<T: Message + From<Self> + Default>
114where
115    Self: Sized + Clone + TryFrom<T>,
116    <Self as TryFrom<T>>::Error: Display,
117{
118    /// Encode into a buffer in Protobuf format.
119    ///
120    /// Uses [`prost::Message::encode`] after converting into its counterpart
121    /// Protobuf data structure.
122    ///
123    /// [`prost::Message::encode`]: https://docs.rs/prost/*/prost/trait.Message.html#method.encode
124    fn encode<B: BufMut>(self, buf: &mut B) -> Result<(), Error> {
125        T::from(self).encode(buf).map_err(Error::encode_message)
126    }
127
128    /// Encode with a length-delimiter to a buffer in Protobuf format.
129    ///
130    /// An error will be returned if the buffer does not have sufficient capacity.
131    ///
132    /// Uses [`prost::Message::encode_length_delimited`] after converting into
133    /// its counterpart Protobuf data structure.
134    ///
135    /// [`prost::Message::encode_length_delimited`]: https://docs.rs/prost/*/prost/trait.Message.html#method.encode_length_delimited
136    fn encode_length_delimited<B: BufMut>(self, buf: &mut B) -> Result<(), Error> {
137        T::from(self)
138            .encode_length_delimited(buf)
139            .map_err(Error::encode_message)
140    }
141
142    /// Constructor that attempts to decode an instance from a buffer.
143    ///
144    /// The entire buffer will be consumed.
145    ///
146    /// Similar to [`prost::Message::decode`] but with additional validation
147    /// prior to constructing the destination type.
148    ///
149    /// [`prost::Message::decode`]: https://docs.rs/prost/*/prost/trait.Message.html#method.decode
150    fn decode<B: Buf>(buf: B) -> Result<Self, Error> {
151        let raw = T::decode(buf).map_err(Error::decode_message)?;
152
153        Self::try_from(raw).map_err(Error::try_from::<T, Self, _>)
154    }
155
156    /// Constructor that attempts to decode a length-delimited instance from
157    /// the buffer.
158    ///
159    /// The entire buffer will be consumed.
160    ///
161    /// Similar to [`prost::Message::decode_length_delimited`] but with
162    /// additional validation prior to constructing the destination type.
163    ///
164    /// [`prost::Message::decode_length_delimited`]: https://docs.rs/prost/*/prost/trait.Message.html#method.decode_length_delimited
165    fn decode_length_delimited<B: Buf>(buf: B) -> Result<Self, Error> {
166        let raw = T::decode_length_delimited(buf).map_err(Error::decode_message)?;
167
168        Self::try_from(raw).map_err(Error::try_from::<T, Self, _>)
169    }
170
171    /// Returns the encoded length of the message without a length delimiter.
172    ///
173    /// Uses [`prost::Message::encoded_len`] after converting to its
174    /// counterpart Protobuf data structure.
175    ///
176    /// [`prost::Message::encoded_len`]: https://docs.rs/prost/*/prost/trait.Message.html#method.encoded_len
177    fn encoded_len(self) -> usize {
178        T::from(self).encoded_len()
179    }
180
181    /// Encodes into a Protobuf-encoded `Vec<u8>`.
182    fn encode_vec(self) -> Vec<u8> {
183        T::from(self).encode_to_vec()
184    }
185
186    /// Constructor that attempts to decode a Protobuf-encoded instance from a
187    /// `Vec<u8>` (or equivalent).
188    fn decode_vec(v: &[u8]) -> Result<Self, Error> {
189        Self::decode(v)
190    }
191
192    /// Encode with a length-delimiter to a `Vec<u8>` Protobuf-encoded message.
193    fn encode_length_delimited_vec(self) -> Vec<u8> {
194        T::from(self).encode_length_delimited_to_vec()
195    }
196
197    /// Constructor that attempts to decode a Protobuf-encoded instance with a
198    /// length-delimiter from a `Vec<u8>` or equivalent.
199    fn decode_length_delimited_vec(v: &[u8]) -> Result<Self, Error> {
200        Self::decode_length_delimited(v)
201    }
202}