Skip to main content

simplicity/bit_encoding/
decode.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! # Decoding
4//!
5//! Functionality to decode Simplicity programs.
6//! Refer to [`crate::encode`] for information on the encoding.
7
8use crate::dag::{Dag, DagLike, InternalSharing};
9use crate::jet::Jet;
10use crate::merkle::cmr::Cmr;
11use crate::node::{
12    ConstructNode, CoreConstructible, DisconnectConstructible, WitnessConstructible,
13};
14use crate::types;
15use crate::value::Word;
16use crate::{BitIter, FailEntropy};
17use std::collections::HashSet;
18use std::sync::Arc;
19use std::{cmp, error, fmt};
20
21use super::bititer::{u2, DecodeNaturalError};
22
23type ArcNode<'brand> = Arc<ConstructNode<'brand>>;
24
25/// Decoding error
26#[non_exhaustive]
27#[derive(Debug)]
28pub enum Error {
29    /// Error closing the bitstream
30    BitIter(crate::BitIterCloseError),
31    /// Both children of a node are hidden
32    BothChildrenHidden,
33    /// Bitstream ended early
34    EndOfStream,
35    /// Hidden node occurred outside of a case combinator
36    HiddenNode,
37    /// Tried to parse a jet but the name wasn't recognized
38    InvalidJet,
39    /// Error decoding a natural number.
40    Natural(DecodeNaturalError),
41    /// Program is not encoded in canonical order
42    NotInCanonicalOrder,
43    /// Program does not have maximal sharing
44    SharingNotMaximal,
45    /// Type-checking error
46    Type(crate::types::Error),
47}
48
49impl From<crate::EarlyEndOfStreamError> for Error {
50    fn from(_: crate::EarlyEndOfStreamError) -> Self {
51        Error::EndOfStream
52    }
53}
54
55impl From<crate::BitIterCloseError> for Error {
56    fn from(e: crate::BitIterCloseError) -> Self {
57        Error::BitIter(e)
58    }
59}
60
61impl From<DecodeNaturalError> for Error {
62    fn from(e: DecodeNaturalError) -> Error {
63        Error::Natural(e)
64    }
65}
66
67impl From<crate::types::Error> for Error {
68    fn from(e: crate::types::Error) -> Error {
69        Error::Type(e)
70    }
71}
72
73impl fmt::Display for Error {
74    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75        match self {
76            Error::BitIter(ref e) => fmt::Display::fmt(e, f),
77            Error::BothChildrenHidden => f.write_str("both children of a case node are hidden"),
78            Error::EndOfStream => f.write_str("bitstream ended early"),
79            Error::HiddenNode => write!(f, "hidden node occurred outside of a case combinator"),
80            Error::InvalidJet => write!(f, "unrecognized jet"),
81            Error::Natural(ref e) => e.fmt(f),
82            Error::NotInCanonicalOrder => f.write_str("program not in canonical order"),
83            Error::SharingNotMaximal => f.write_str("Decoded programs must have maximal sharing"),
84            Error::Type(ref e) => fmt::Display::fmt(e, f),
85        }
86    }
87}
88
89impl error::Error for Error {
90    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
91        match *self {
92            Error::BitIter(ref e) => Some(e),
93            Error::BothChildrenHidden => None,
94            Error::EndOfStream => None,
95            Error::HiddenNode => None,
96            Error::InvalidJet => None,
97            Error::Natural(ref e) => Some(e),
98            Error::NotInCanonicalOrder => None,
99            Error::SharingNotMaximal => None,
100            Error::Type(ref e) => Some(e),
101        }
102    }
103}
104
105#[derive(Debug)]
106enum DecodeNode {
107    Iden,
108    Unit,
109    InjL(usize),
110    InjR(usize),
111    Take(usize),
112    Drop(usize),
113    Comp(usize, usize),
114    Case(usize, usize),
115    Pair(usize, usize),
116    Disconnect1(usize),
117    Disconnect(usize, usize),
118    Witness,
119    Fail(FailEntropy),
120    Hidden(Cmr),
121    Jet(Box<dyn Jet>),
122    Word(Word),
123}
124
125impl DagLike for (usize, &'_ [DecodeNode]) {
126    type Node = DecodeNode;
127
128    fn data(&self) -> &DecodeNode {
129        &self.1[self.0]
130    }
131
132    fn as_dag_node(&self) -> Dag<Self> {
133        let nodes = &self.1;
134        match self.1[self.0] {
135            DecodeNode::Iden
136            | DecodeNode::Unit
137            | DecodeNode::Fail(..)
138            | DecodeNode::Hidden(..)
139            | DecodeNode::Jet(..)
140            | DecodeNode::Word(..) => Dag::Nullary,
141            DecodeNode::InjL(i)
142            | DecodeNode::InjR(i)
143            | DecodeNode::Take(i)
144            | DecodeNode::Drop(i)
145            | DecodeNode::Disconnect1(i) => Dag::Unary((i, nodes)),
146            DecodeNode::Comp(li, ri)
147            | DecodeNode::Case(li, ri)
148            | DecodeNode::Pair(li, ri)
149            | DecodeNode::Disconnect(li, ri) => Dag::Binary((li, nodes), (ri, nodes)),
150            DecodeNode::Witness => Dag::Nullary,
151        }
152    }
153}
154
155pub fn decode_expression<'brand, I: Iterator<Item = u8>, J: Jet>(
156    ctx: &types::Context<'brand>,
157    bits: &mut BitIter<I>,
158) -> Result<ArcNode<'brand>, Error> {
159    enum Converted<'brand> {
160        Node(ArcNode<'brand>),
161        Hidden(Cmr),
162    }
163    use Converted::{Hidden, Node};
164    impl<'brand> Converted<'brand> {
165        fn get(&self) -> Result<&ArcNode<'brand>, Error> {
166            match self {
167                Node(arc) => Ok(arc),
168                Hidden(_) => Err(Error::HiddenNode),
169            }
170        }
171    }
172
173    let len = bits.read_natural::<usize>(None)?;
174    assert_ne!(len, 0, "impossible to encode 0 in Simplicity");
175
176    let mut nodes = Vec::with_capacity(cmp::min(len, 10_000));
177    for _ in 0..len {
178        let new_node = decode_node::<I, J>(bits, nodes.len())?;
179        nodes.push(new_node);
180    }
181
182    // It is a sharing violation for any hidden node to be repeated. Track them in this set.
183    let mut hidden_set = HashSet::<Cmr>::new();
184    // Convert the DecodeNode structure into a CommitNode structure
185    let mut converted = Vec::<Converted>::with_capacity(len);
186    for data in (nodes.len() - 1, &nodes[..]).post_order_iter::<InternalSharing>() {
187        // Check canonical order as we go
188        if data.index != data.node.0 {
189            return Err(Error::NotInCanonicalOrder);
190        }
191
192        let new = match &nodes[data.node.0] {
193            DecodeNode::Unit => Node(ArcNode::unit(ctx)),
194            DecodeNode::Iden => Node(ArcNode::iden(ctx)),
195            DecodeNode::InjL(i) => Node(ArcNode::injl(converted[*i].get()?)),
196            DecodeNode::InjR(i) => Node(ArcNode::injr(converted[*i].get()?)),
197            DecodeNode::Take(i) => Node(ArcNode::take(converted[*i].get()?)),
198            DecodeNode::Drop(i) => Node(ArcNode::drop_(converted[*i].get()?)),
199            DecodeNode::Comp(i, j) => {
200                Node(ArcNode::comp(converted[*i].get()?, converted[*j].get()?)?)
201            }
202            DecodeNode::Case(i, j) => {
203                // Case is a special case, since it uniquely is allowed to have hidden
204                // children (but only one!) in which case it becomes an assertion.
205                match (&converted[*i], &converted[*j]) {
206                    (Node(left), Node(right)) => Node(ArcNode::case(left, right)?),
207                    (Node(left), Hidden(cmr)) => Node(ArcNode::assertl(left, *cmr)?),
208                    (Hidden(cmr), Node(right)) => Node(ArcNode::assertr(*cmr, right)?),
209                    (Hidden(_), Hidden(_)) => return Err(Error::BothChildrenHidden),
210                }
211            }
212            DecodeNode::Pair(i, j) => {
213                Node(ArcNode::pair(converted[*i].get()?, converted[*j].get()?)?)
214            }
215            DecodeNode::Disconnect1(i) => Node(ArcNode::disconnect(converted[*i].get()?, &None)?),
216            DecodeNode::Disconnect(i, j) => Node(ArcNode::disconnect(
217                converted[*i].get()?,
218                &Some(Arc::clone(converted[*j].get()?)),
219            )?),
220            DecodeNode::Witness => Node(ArcNode::witness(ctx, None)),
221            DecodeNode::Fail(entropy) => Node(ArcNode::fail(ctx, *entropy)),
222            DecodeNode::Hidden(cmr) => {
223                if !hidden_set.insert(*cmr) {
224                    return Err(Error::SharingNotMaximal);
225                }
226                Hidden(*cmr)
227            }
228            DecodeNode::Jet(j) => Node(ArcNode::jet(ctx, j.as_ref())),
229            DecodeNode::Word(ref w) => Node(ArcNode::const_word(ctx, w.shallow_clone())),
230        };
231        converted.push(new);
232    }
233
234    converted[len - 1].get().map(Arc::clone)
235}
236
237/// Decode a single Simplicity node from bits and
238/// insert it into a hash map at its index for future reference by ancestor nodes.
239fn decode_node<I: Iterator<Item = u8>, J: Jet>(
240    bits: &mut BitIter<I>,
241    index: usize,
242) -> Result<DecodeNode, Error> {
243    // First bit: 1 for jets/words, 0 for normal combinators
244    if bits.read_bit()? {
245        // Second bit: 1 for jets, 0 for words
246        if bits.read_bit()? {
247            J::decode(bits).map(|jet| DecodeNode::Jet(Box::new(jet)))
248        } else {
249            let n = bits.read_natural(Some(32))?;
250            let word = Word::from_bits(bits, n - 1)?;
251            Ok(DecodeNode::Word(word))
252        }
253    } else {
254        // Bits 2 and 3: code
255        match bits.read_u2()? {
256            u2::_0 => {
257                let subcode = bits.read_u2()?;
258                let i_abs = index - bits.read_natural(Some(index))?;
259                let j_abs = index - bits.read_natural(Some(index))?;
260
261                // Bits 4 and 5: subcode
262                match subcode {
263                    u2::_0 => Ok(DecodeNode::Comp(i_abs, j_abs)),
264                    u2::_1 => Ok(DecodeNode::Case(i_abs, j_abs)),
265                    u2::_2 => Ok(DecodeNode::Pair(i_abs, j_abs)),
266                    u2::_3 => Ok(DecodeNode::Disconnect(i_abs, j_abs)),
267                }
268            }
269            u2::_1 => {
270                let subcode = bits.read_u2()?;
271                let i_abs = index - bits.read_natural(Some(index))?;
272                // Bits 4 and 5: subcode
273                match subcode {
274                    u2::_0 => Ok(DecodeNode::InjL(i_abs)),
275                    u2::_1 => Ok(DecodeNode::InjR(i_abs)),
276                    u2::_2 => Ok(DecodeNode::Take(i_abs)),
277                    u2::_3 => Ok(DecodeNode::Drop(i_abs)),
278                }
279            }
280            u2::_2 => {
281                // Bits 4 and 5: subcode
282                match bits.read_u2()? {
283                    u2::_0 => Ok(DecodeNode::Iden),
284                    u2::_1 => Ok(DecodeNode::Unit),
285                    u2::_2 => Ok(DecodeNode::Fail(bits.read_fail_entropy()?)),
286                    u2::_3 => {
287                        let i_abs = index - bits.read_natural(Some(index))?;
288                        Ok(DecodeNode::Disconnect1(i_abs))
289                    }
290                }
291            }
292            u2::_3 => {
293                // Bit 4: subcode
294                if bits.read_bit()? {
295                    Ok(DecodeNode::Witness)
296                } else {
297                    Ok(DecodeNode::Hidden(bits.read_cmr()?))
298                }
299            }
300        }
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use crate::encode;
308    use crate::jet::Core;
309    use crate::node::{CommitNode, RedeemNode};
310    use crate::BitWriter;
311
312    #[test]
313    fn root_unit_to_unit() {
314        // main = jet_eq_32 :: 2^64 -> 2 # 7387d279
315        let justjet = [0x6d, 0xb8, 0x80];
316        // Should be able to decode this as an expression...
317        let mut iter = BitIter::from(&justjet[..]);
318        types::Context::with_context(|ctx| {
319            decode_expression::<_, Core>(&ctx, &mut iter).unwrap();
320        });
321        // ...but NOT as a CommitNode
322        let iter = BitIter::from(&justjet[..]);
323        CommitNode::decode::<_, Core>(iter).unwrap_err();
324        // ...or as a RedeemNode
325        let iter = BitIter::from(&justjet[..]);
326        RedeemNode::decode::<_, _, Core>(iter, BitIter::from(&[][..])).unwrap_err();
327    }
328
329    #[test]
330    fn decode_fixed_natural() {
331        let tries: Vec<(usize, usize, &[u8])> = vec![
332            (1, 1, &[0b00000000]),
333            (2, 3, &[0b10000000]),
334            (3, 3, &[0b10100000]),
335            (4, 6, &[0b11_000000]),
336            (5, 6, &[0b11_000100]),
337            (6, 6, &[0b11_001000]),
338            (7, 6, &[0b11_001100]),
339            (8, 7, &[0b110_10000]),
340            (15, 7, &[0b110_11110]),
341            (16, 11, &[0b11100000, 0b00000000]),
342            // 31
343            (31, 11, &[0b11100001, 0b11100000]),
344            // 32
345            (32, 12, &[0b11100010, 0b00000000]),
346            // 2^15
347            (32768, 23, &[0b11101111, 0b00000000, 0b00000000]),
348            (65535, 23, &[0b11101111, 0b11111111, 0b11111110]),
349            (65536, 28, &[0b11110000, 0b00000000, 0b00000000, 0b00000000]),
350            (
351                u32::MAX as usize - 1, // cast ok, in unit test
352                43,
353                &[
354                    0b11110000, 0b11111111, 0b11111111, 0b11111111, 0b11111111, 0b11000000,
355                ],
356            ),
357            (
358                u32::MAX as usize, // cast ok, in unit test
359                43,
360                &[
361                    0b11110000, 0b11111111, 0b11111111, 0b11111111, 0b11111111, 0b11100000,
362                ],
363            ),
364        ];
365
366        for (natural, len, bitvec) in tries {
367            let mut iter = BitIter::new(bitvec.iter().copied());
368
369            // Truncating the iterator causes a clean failure.
370            let mut truncated = BitIter::new(bitvec.iter().copied().take(bitvec.len() - 1));
371            assert_eq!(
372                truncated.read_natural::<usize>(None),
373                Err(DecodeNaturalError::EndOfStream(
374                    crate::EarlyEndOfStreamError
375                )),
376            );
377
378            // Test decoding under various bounds
379            assert_eq!(iter.clone().read_natural(None), Ok(natural),);
380            assert_eq!(iter.clone().read_natural::<u64>(None), Ok(natural as u64),);
381
382            assert_eq!(iter.clone().read_natural(Some(natural)), Ok(natural),);
383            assert_eq!(iter.clone().read_natural(Some(natural + 1)), Ok(natural),);
384            assert_eq!(
385                iter.clone().read_natural(Some(natural - 1)),
386                Err(DecodeNaturalError::BadIndex {
387                    got: natural,
388                    max: natural - 1
389                }),
390            );
391            assert_eq!(
392                iter.clone().read_natural(Some(0u64)),
393                Err(DecodeNaturalError::BadIndex {
394                    got: natural,
395                    max: 0
396                }),
397            );
398
399            // Try decoding as a small type.
400            if let Ok(natural) = u16::try_from(natural) {
401                assert_eq!(iter.read_natural::<u16>(None), Ok(natural),);
402            } else {
403                assert_eq!(
404                    iter.read_natural::<u16>(None),
405                    Err(DecodeNaturalError::Overflow),
406                );
407            }
408            // Attempt to re-encode.
409            let mut sink = Vec::<u8>::new();
410
411            let mut w = BitWriter::from(&mut sink);
412            encode::encode_natural(natural, &mut w).expect("encoding to vector");
413            w.flush_all().expect("flushing");
414            assert_eq!(w.n_total_written(), len);
415
416            assert_eq!(sink, bitvec);
417        }
418
419        // Test u32::MAX + 1 separately. This should always return an overflow and
420        // never succeed or panic. Just hammer it with a bunch of different types
421        // and call patterns.
422        let iter = BitIter::new(
423            [
424                0b11110001, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000,
425            ]
426            .into_iter(),
427        );
428        assert_eq!(
429            iter.clone().read_natural::<usize>(None),
430            Err(DecodeNaturalError::Overflow),
431        );
432        assert_eq!(
433            iter.clone().read_natural::<u16>(None),
434            Err(DecodeNaturalError::Overflow),
435        );
436        assert_eq!(
437            iter.clone().read_natural::<i32>(None),
438            Err(DecodeNaturalError::Overflow),
439        );
440        assert_eq!(
441            iter.clone().read_natural::<u32>(None),
442            Err(DecodeNaturalError::Overflow),
443        );
444        assert_eq!(
445            iter.clone().read_natural::<u64>(None),
446            Err(DecodeNaturalError::Overflow),
447        );
448        assert_eq!(
449            iter.clone().read_natural(Some(0u8)),
450            Err(DecodeNaturalError::Overflow),
451        );
452        assert_eq!(
453            iter.clone().read_natural(Some(0i32)),
454            Err(DecodeNaturalError::Overflow),
455        );
456        assert_eq!(
457            iter.clone().read_natural(Some(0u32)),
458            Err(DecodeNaturalError::Overflow),
459        );
460    }
461}