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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// SPDX-License-Identifier: CC0-1.0

use crate::dag::{InternalSharing, PostOrderIterItem};
use crate::encode;
use crate::jet::Jet;
use crate::types::{self, arrow::Arrow};
use crate::{BitIter, BitWriter, Cmr, FailEntropy, Value};

use std::io;
use std::marker::PhantomData;
use std::sync::Arc;

use super::{
    Commit, CommitData, CommitNode, Converter, Inner, Marker, NoDisconnect, NoWitness, Node,
};
use super::{CoreConstructible, DisconnectConstructible, JetConstructible, WitnessConstructible};

/// ID used to share [`ConstructNode`]s.
///
/// This is impossible to construct, which is a promise that it is impossible
/// to share [`ConstructNode`]s.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub enum ConstructId {}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct Construct<J> {
    /// Makes the type non-constructible.
    never: std::convert::Infallible,
    /// Required by Rust.
    phantom: std::marker::PhantomData<J>,
}

impl<J: Jet> Marker for Construct<J> {
    type CachedData = ConstructData<J>;
    type Witness = NoWitness;
    type Disconnect = Option<Arc<ConstructNode<J>>>;
    type SharingId = ConstructId;
    type Jet = J;

    fn compute_sharing_id(_: Cmr, _: &ConstructData<J>) -> Option<ConstructId> {
        None
    }
}

pub type ConstructNode<J> = Node<Construct<J>>;

impl<J: Jet> ConstructNode<J> {
    /// Accessor for the node's arrow
    pub fn arrow(&self) -> &Arrow {
        self.data.arrow()
    }

    /// Sets the source and target type of the node to unit
    pub fn set_arrow_to_program(&self) -> Result<(), types::Error> {
        let unit_ty = types::Type::unit();
        self.arrow()
            .source
            .unify(&unit_ty, "setting root source to unit")?;
        self.arrow()
            .target
            .unify(&unit_ty, "setting root target to unit")?;
        Ok(())
    }

    /// Convert a [`ConstructNode`] to a [`CommitNode`] by finalizing all of the types.
    ///
    /// Also sets the source and target type of this node to unit. This is almost
    /// certainly what you want, since the resulting `CommitNode` cannot be further
    /// composed, and needs to be 1->1 to go on-chain. But if you don't, call
    /// [`Self::finalize_types_without_fixing`] instead.
    pub fn finalize_types(&self) -> Result<Arc<CommitNode<J>>, crate::Error> {
        self.set_arrow_to_program()?;
        self.finalize_types_non_program()
    }

    /// Convert a [`ConstructNode`] to a [`CommitNode`] by finalizing all of the types.
    ///
    /// Does *not* sets the source and target type of this node to unit.
    pub fn finalize_types_non_program(&self) -> Result<Arc<CommitNode<J>>, crate::Error> {
        struct FinalizeTypes<J: Jet>(PhantomData<J>);

        impl<J: Jet> Converter<Construct<J>, Commit<J>> for FinalizeTypes<J> {
            type Error = crate::Error;
            fn convert_witness(
                &mut self,
                _: &PostOrderIterItem<&ConstructNode<J>>,
                _: &NoWitness,
            ) -> Result<NoWitness, Self::Error> {
                Ok(NoWitness)
            }

            fn convert_disconnect(
                &mut self,
                _: &PostOrderIterItem<&ConstructNode<J>>,
                maybe_converted: Option<&Arc<CommitNode<J>>>,
                _: &Option<Arc<ConstructNode<J>>>,
            ) -> Result<NoDisconnect, Self::Error> {
                if maybe_converted.is_some() {
                    Err(crate::Error::DisconnectCommitTime)
                } else {
                    Ok(NoDisconnect)
                }
            }

            fn convert_data(
                &mut self,
                data: &PostOrderIterItem<&ConstructNode<J>>,
                inner: Inner<&Arc<CommitNode<J>>, J, &NoDisconnect, &NoWitness>,
            ) -> Result<Arc<CommitData<J>>, Self::Error> {
                let converted_data = inner.map(|node| node.cached_data());
                CommitData::new(&data.node.data.arrow, converted_data)
                    .map(Arc::new)
                    .map_err(crate::Error::from)
            }
        }

        self.convert::<InternalSharing, _, _>(&mut FinalizeTypes(PhantomData))
    }

    /// Decode a Simplicity expression from bits, without witness data.
    ///
    /// # Usage
    ///
    /// Use this method only if the serialization **does not** include the witness data.
    /// This means, the program simply has no witness during commitment,
    /// or the witness is provided by other means.
    ///
    /// If the serialization contains the witness data, then use [`RedeemNode::decode()`].
    pub fn decode<I: Iterator<Item = u8>>(
        bits: &mut BitIter<I>,
    ) -> Result<Arc<Self>, crate::decode::Error> {
        crate::decode::decode_expression(bits)
    }

    /// Encode a Simplicity expression to bits, with no witness data
    pub fn encode<W: io::Write>(&self, w: &mut BitWriter<W>) -> io::Result<usize> {
        let program_bits = encode::encode_program(self, w)?;
        w.flush_all()?;
        Ok(program_bits)
    }
}

#[derive(Clone, Debug)]
pub struct ConstructData<J> {
    arrow: Arrow,
    /// This isn't really necessary, but it helps type inference if every
    /// struct has a <J> parameter, since it forces the choice of jets to
    /// be consistent without the user needing to specify it too many times.
    phantom: PhantomData<J>,
}

impl<J: Jet> ConstructData<J> {
    /// Constructs a new [`ConstructData`] from an (unfinalized) type arrow
    pub fn new(arrow: Arrow) -> Self {
        ConstructData {
            arrow,
            phantom: PhantomData,
        }
    }

    /// Accessor for the node's arrow
    pub fn arrow(&self) -> &Arrow {
        &self.arrow
    }
}

impl<J> CoreConstructible for ConstructData<J> {
    fn iden() -> Self {
        ConstructData {
            arrow: Arrow::iden(),
            phantom: PhantomData,
        }
    }

    fn unit() -> Self {
        ConstructData {
            arrow: Arrow::unit(),
            phantom: PhantomData,
        }
    }

    fn injl(child: &Self) -> Self {
        ConstructData {
            arrow: Arrow::injl(&child.arrow),
            phantom: PhantomData,
        }
    }

    fn injr(child: &Self) -> Self {
        ConstructData {
            arrow: Arrow::injr(&child.arrow),
            phantom: PhantomData,
        }
    }

    fn take(child: &Self) -> Self {
        ConstructData {
            arrow: Arrow::take(&child.arrow),
            phantom: PhantomData,
        }
    }

    fn drop_(child: &Self) -> Self {
        ConstructData {
            arrow: Arrow::drop_(&child.arrow),
            phantom: PhantomData,
        }
    }

    fn comp(left: &Self, right: &Self) -> Result<Self, types::Error> {
        Ok(ConstructData {
            arrow: Arrow::comp(&left.arrow, &right.arrow)?,
            phantom: PhantomData,
        })
    }

    fn case(left: &Self, right: &Self) -> Result<Self, types::Error> {
        Ok(ConstructData {
            arrow: Arrow::case(&left.arrow, &right.arrow)?,
            phantom: PhantomData,
        })
    }

    fn assertl(left: &Self, right: Cmr) -> Result<Self, types::Error> {
        Ok(ConstructData {
            arrow: Arrow::assertl(&left.arrow, right)?,
            phantom: PhantomData,
        })
    }

    fn assertr(left: Cmr, right: &Self) -> Result<Self, types::Error> {
        Ok(ConstructData {
            arrow: Arrow::assertr(left, &right.arrow)?,
            phantom: PhantomData,
        })
    }

    fn pair(left: &Self, right: &Self) -> Result<Self, types::Error> {
        Ok(ConstructData {
            arrow: Arrow::pair(&left.arrow, &right.arrow)?,
            phantom: PhantomData,
        })
    }

    fn fail(entropy: FailEntropy) -> Self {
        ConstructData {
            arrow: Arrow::fail(entropy),
            phantom: PhantomData,
        }
    }

    fn const_word(word: Arc<Value>) -> Self {
        ConstructData {
            arrow: Arrow::const_word(word),
            phantom: PhantomData,
        }
    }
}

impl<J: Jet> DisconnectConstructible<Option<Arc<ConstructNode<J>>>> for ConstructData<J> {
    fn disconnect(
        left: &Self,
        right: &Option<Arc<ConstructNode<J>>>,
    ) -> Result<Self, types::Error> {
        let right = right.as_ref();
        Ok(ConstructData {
            arrow: Arrow::disconnect(&left.arrow, &right.map(|n| n.arrow()))?,
            phantom: PhantomData,
        })
    }
}

impl<J> WitnessConstructible<NoWitness> for ConstructData<J> {
    fn witness(witness: NoWitness) -> Self {
        ConstructData {
            arrow: Arrow::witness(witness),
            phantom: PhantomData,
        }
    }
}

impl<J: Jet> JetConstructible<J> for ConstructData<J> {
    fn jet(jet: J) -> Self {
        ConstructData {
            arrow: Arrow::jet(jet),
            phantom: PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jet::Core;

    #[test]
    fn occurs_check_error() {
        let iden = Arc::<ConstructNode<Core>>::iden();
        let node = Arc::<ConstructNode<Core>>::disconnect(&iden, &Some(Arc::clone(&iden))).unwrap();

        assert!(matches!(
            node.finalize_types_non_program(),
            Err(crate::Error::Type(types::Error::OccursCheck)),
        ));
    }

    #[test]
    fn occurs_check_2() {
        // A more complicated occurs-check test that caused a deadlock in the past.
        let iden = Arc::<ConstructNode<Core>>::iden();
        let injr = Arc::<ConstructNode<Core>>::injr(&iden);
        let pair = Arc::<ConstructNode<Core>>::pair(&injr, &iden).unwrap();
        let drop = Arc::<ConstructNode<Core>>::drop_(&pair);

        let case1 = Arc::<ConstructNode<Core>>::case(&drop, &drop).unwrap();
        let case2 = Arc::<ConstructNode<Core>>::case(&case1, &case1).unwrap();

        let comp1 = Arc::<ConstructNode<Core>>::comp(&case2, &case2).unwrap();
        let comp2 = Arc::<ConstructNode<Core>>::comp(&comp1, &case1).unwrap();

        assert!(matches!(
            comp2.finalize_types_non_program(),
            Err(crate::Error::Type(types::Error::OccursCheck)),
        ));
    }

    #[test]
    fn occurs_check_3() {
        // A similar example that caused a slightly different deadlock in the past.
        let wit = Arc::<ConstructNode<Core>>::witness(NoWitness);
        let drop = Arc::<ConstructNode<Core>>::drop_(&wit);

        let comp1 = Arc::<ConstructNode<Core>>::comp(&drop, &drop).unwrap();
        let comp2 = Arc::<ConstructNode<Core>>::comp(&comp1, &comp1).unwrap();
        let comp3 = Arc::<ConstructNode<Core>>::comp(&comp2, &comp2).unwrap();
        let comp4 = Arc::<ConstructNode<Core>>::comp(&comp3, &comp3).unwrap();
        let comp5 = Arc::<ConstructNode<Core>>::comp(&comp4, &comp4).unwrap();

        let case = Arc::<ConstructNode<Core>>::case(&comp5, &comp4).unwrap();
        let drop2 = Arc::<ConstructNode<Core>>::drop_(&case);
        let case2 = Arc::<ConstructNode<Core>>::case(&drop2, &case).unwrap();
        let comp6 = Arc::<ConstructNode<Core>>::comp(&case2, &case2).unwrap();
        let case3 = Arc::<ConstructNode<Core>>::case(&comp6, &comp6).unwrap();

        let comp7 = Arc::<ConstructNode<Core>>::comp(&case3, &case3).unwrap();
        let comp8 = Arc::<ConstructNode<Core>>::comp(&comp7, &comp7).unwrap();

        assert!(matches!(
            comp8.finalize_types_non_program(),
            Err(crate::Error::Type(types::Error::OccursCheck)),
        ));
    }

    #[test]
    fn type_check_error() {
        let unit = Arc::<ConstructNode<Core>>::unit();
        let case = Arc::<ConstructNode<Core>>::case(&unit, &unit).unwrap();

        assert!(matches!(
            Arc::<ConstructNode<Core>>::disconnect(&case, &Some(unit)),
            Err(types::Error::Bind { .. }),
        ));
    }

    #[test]
    fn scribe() {
        let unit = Arc::<ConstructNode<Core>>::unit();
        let bit0 = Arc::<ConstructNode<Core>>::injl(&unit);
        let bit1 = Arc::<ConstructNode<Core>>::injr(&unit);
        let bits01 = Arc::<ConstructNode<Core>>::pair(&bit0, &bit1).unwrap();

        assert_eq!(
            unit.cmr(),
            Arc::<ConstructNode<Core>>::scribe(&Value::Unit).cmr()
        );
        assert_eq!(
            bit0.cmr(),
            Arc::<ConstructNode<Core>>::scribe(&Value::u1(0)).cmr()
        );
        assert_eq!(
            bit1.cmr(),
            Arc::<ConstructNode<Core>>::scribe(&Value::u1(1)).cmr()
        );
        assert_eq!(
            bits01.cmr(),
            Arc::<ConstructNode<Core>>::scribe(&Value::u2(1)).cmr()
        );
    }
}