1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! Veriform decoder

pub(crate) mod message;
pub mod sequence;

mod decodable;
mod event;
mod traits;
mod vint64;

#[cfg(feature = "log")]
#[macro_use]
mod trace;

pub use self::traits::{Decode, DecodeRef, DecodeSeq};

pub(crate) use self::{decodable::Decodable, event::Event};

use crate::{
    error::{self, Error},
    field::{Tag, WireType},
    verihash::DigestOutput,
    Message,
};
use digest::Digest;
use heapless::consts::U16;

/// Veriform decoder.
///
/// This type contains message decoding state and also performs Verihash
/// computation.
///
/// It's intended to be used in conjunction with the [`Message`] trait.
pub struct Decoder<D: Digest> {
    /// Stack of message decoders (max nesting depth 16)
    stack: heapless::Vec<message::Decoder<D>, U16>,

    /// Sequence decoder if we're presently decoding a sequence
    // TODO(tarcieri): support nested sequences?
    seq_decoder: Option<sequence::Decoder<D>>,
}

impl<D> Decoder<D>
where
    D: Digest,
{
    /// Initialize decoder
    pub fn new() -> Self {
        let mut stack = heapless::Vec::new();
        stack.push(message::Decoder::new()).unwrap();
        Decoder {
            stack,
            seq_decoder: None,
        }
    }

    /// Fill the provided slice with the digest of the message if it fits
    // TODO(tarcieri): find a better way to handle generic digest sizes
    pub fn fill_digest(&mut self, output: &mut [u8]) -> Result<(), Error> {
        let digest = self
            .peek()
            .compute_digest()?
            .ok_or_else(|| error::Kind::Hashing)?;

        if digest.len() != output.len() {
            return Err(error::Kind::Hashing)?;
        }

        output.copy_from_slice(&digest);
        Ok(())
    }

    /// Get the depth of the pushdown stack
    #[cfg(feature = "log")]
    pub(crate) fn depth(&self) -> usize {
        self.stack.len()
    }

    /// Push a new message decoder down onto the stack
    fn push(&mut self) -> Result<(), Error> {
        self.stack
            .push(message::Decoder::new())
            .map_err(|_| error::Kind::NestingDepth.into())
    }

    /// Pop the message decoder from the stack when we've finished a message.
    ///
    /// Returns a digest of the nested message if message hashing is enabled.
    ///
    /// Panics if the decoder stack underflows.
    // TODO(tarcieri): panic-free higher-level API, possibly RAII-based?
    fn pop(&mut self) -> Option<DigestOutput<D>> {
        self.stack.pop().unwrap().compute_digest().unwrap()
    }

    /// Peek at the message decoder on the top of the stack
    fn peek(&mut self) -> &mut message::Decoder<D> {
        self.stack.last_mut().unwrap()
    }

    /// Push a sequence decoder
    // TODO(tarcieri): support nested sequences?
    fn push_seq(&mut self, wire_type: WireType, length: usize) -> Result<(), Error> {
        if self.seq_decoder.is_none() {
            self.seq_decoder = Some(sequence::Decoder::new(wire_type, length));
            Ok(())
        } else {
            Err(error::Kind::NestedSequence.into())
        }
    }

    /// Pop the sequence decoder.
    ///
    /// Panics if the decoder stack underflows.
    // TODO(tarcieri): panic-free higher-level API, possibly RAII-based?
    fn pop_seq(&mut self) -> Option<DigestOutput<D>> {
        self.seq_decoder.take().unwrap().compute_digest().unwrap()
    }

    /// Peek at the sequence decoder.
    fn peek_seq(&mut self) -> &mut sequence::Decoder<D> {
        self.seq_decoder.as_mut().unwrap()
    }
}

impl<D> Default for Decoder<D>
where
    D: Digest,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<D, M> Decode<M> for Decoder<D>
where
    D: Digest,
    M: Message,
{
    fn decode(&mut self, tag: Tag, input: &mut &[u8]) -> Result<M, Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: msg?", tag);

        self.peek().expect_header(input, tag, WireType::Message)?;
        let msg_bytes = self.peek().decode_message(input)?;

        self.push()?;
        let msg = M::decode(self, msg_bytes)?;

        if let Some(digest) = self.pop() {
            self.peek().hash_message_digest(tag, &digest)?;
        }

        Ok(msg)
    }
}

impl<D> Decode<u64> for Decoder<D>
where
    D: Digest,
{
    fn decode(&mut self, tag: Tag, input: &mut &[u8]) -> Result<u64, Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: uint64?", tag);

        self.peek().expect_header(input, tag, WireType::UInt64)?;
        self.peek().decode_uint64(input)
    }
}

impl<D> Decode<i64> for Decoder<D>
where
    D: Digest,
{
    fn decode(&mut self, tag: Tag, input: &mut &[u8]) -> Result<i64, Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: sint64?", tag);

        self.peek().expect_header(input, tag, WireType::SInt64)?;
        self.peek().decode_sint64(input)
    }
}

impl<D> DecodeRef<[u8]> for Decoder<D>
where
    D: Digest,
{
    fn decode_ref<'a>(&mut self, tag: Tag, input: &mut &'a [u8]) -> Result<&'a [u8], Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: bytes?", tag);

        self.peek().expect_header(input, tag, WireType::Bytes)?;
        self.peek().decode_bytes(input)
    }
}

impl<D> DecodeRef<str> for Decoder<D>
where
    D: Digest,
{
    fn decode_ref<'a>(&mut self, tag: Tag, input: &mut &'a [u8]) -> Result<&'a str, Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: string?", tag);

        self.peek().expect_header(input, tag, WireType::String)?;
        self.peek().decode_string(input)
    }
}

impl<D, M> DecodeSeq<M, D> for Decoder<D>
where
    D: Digest,
    M: Message,
{
    fn decode_seq<'a, 'b>(
        &'a mut self,
        tag: Tag,
        input: &mut &'b [u8],
    ) -> Result<sequence::Iter<'a, 'b, M, D>, Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: seq<msg>?", tag);

        self.peek().expect_header(input, tag, WireType::Sequence)?;
        let seq_bytes = self.peek().decode_sequence(WireType::Message, input)?;
        self.push_seq(WireType::Message, seq_bytes.len())?;

        Ok(sequence::Iter::new(self, tag, seq_bytes))
    }
}

impl<D> DecodeSeq<u64, D> for Decoder<D>
where
    D: Digest,
{
    fn decode_seq<'a, 'b>(
        &'a mut self,
        tag: Tag,
        input: &mut &'b [u8],
    ) -> Result<sequence::Iter<'a, 'b, u64, D>, Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: seq<uint64>?", tag);

        self.peek().expect_header(input, tag, WireType::Sequence)?;
        let seq_bytes = self.peek().decode_sequence(WireType::UInt64, input)?;
        self.push_seq(WireType::UInt64, seq_bytes.len())?;

        Ok(sequence::Iter::new(self, tag, seq_bytes))
    }
}

impl<D> DecodeSeq<i64, D> for Decoder<D>
where
    D: Digest,
{
    fn decode_seq<'a, 'b>(
        &'a mut self,
        tag: Tag,
        input: &mut &'b [u8],
    ) -> Result<sequence::Iter<'a, 'b, i64, D>, Error> {
        #[cfg(feature = "log")]
        begin!(self, "[{}]: seq<sint64>?", tag);

        self.peek().expect_header(input, tag, WireType::Sequence)?;
        let seq_bytes = self.peek().decode_sequence(WireType::SInt64, input)?;
        self.push_seq(WireType::SInt64, seq_bytes.len())?;

        Ok(sequence::Iter::new(self, tag, seq_bytes))
    }
}

#[cfg(all(test, feature = "sha2"))]
mod tests {
    use super::{Decode, DecodeRef};
    use crate::Decoder;

    #[test]
    fn decode_uint64() {
        let input = [138, 10, 85];
        let mut input_ref = &input[..];

        let value: u64 = Decoder::new().decode(42, &mut input_ref).unwrap();
        assert_eq!(value, 42);
        assert!(input_ref.is_empty());
    }

    #[test]
    fn decode_sint64() {
        let input = [206, 10, 167];
        let mut input_ref = &input[..];

        let value: i64 = Decoder::new().decode(43, &mut input_ref).unwrap();
        assert_eq!(value, -42);
        assert!(input_ref.is_empty());
    }

    #[test]
    fn decode_bytes() {
        let input = [73, 11, 98, 121, 116, 101, 115];
        let mut input_ref = &input[..];

        let bytes: &[u8] = Decoder::new().decode_ref(2, &mut input_ref).unwrap();
        assert_eq!(bytes, &[98, 121, 116, 101, 115]);
        assert!(input_ref.is_empty());
    }

    #[test]
    fn decode_string() {
        let input = [139, 7, 98, 97, 122];
        let mut input_ref = &input[..];

        let string: &str = Decoder::new().decode_ref(4, &mut input_ref).unwrap();
        assert_eq!(string, "baz");
        assert!(input_ref.is_empty());
    }
}