elements 0.27.0

Library with support for de/serialization, parsing and executing on data structures and network messages related to Elements
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Transaction Decoders
//!
//! These are encapsulated because there are many of them, but in the end we
//! only expose the top-level ones outside of this module.

use core::fmt;

use super::{
    AssetIssuance, OutPoint, Script, Sequence, Transaction, TxIn, TxInWitness, TxOut, TxOutWitness,
    Txid,
};
use crate::confidential::{RangeProofDecoder, RangeProofDecoderError};
use crate::encoding::{
    ArrayDecoder, Decode, Decoder, Decoder2, Decoder2Error, Decoder3, Decoder4, Decoder4Error,
    DecoderStatus, UnexpectedEofError, VecDecoder,
};
use crate::locktime::{LockTime, LockTimeDecoder};
use crate::{PeginWitnessDecoder, PeginWitnessDecoderError, WitnessDecoder, WitnessDecoderError};

/// Decoder for the [`OutPoint`] type.
///
/// This is a non-public struct and we do not implement [`Decode`] for [`OutPoint`]
/// because we can't actually encode/decode outpoints independently of the rest of
/// a [`TxIn`]. This is because we mask bits into the vout of the outpoint.
#[derive(Default)]
struct OutPointDecoder {
    inner: Decoder2<ArrayDecoder<32>, ArrayDecoder<4>>,
}

/// Decoder error for the [`OutPoint`] type.
#[derive(Clone, PartialEq, Eq, Debug)]
struct OutPointDecoderError(Decoder2Error<UnexpectedEofError, UnexpectedEofError>);

impl fmt::Display for OutPointDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("error decoding outpoint")
    }
}

impl std::error::Error for OutPointDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}

impl Decoder for OutPointDecoder {
    type Output = OutPoint;
    type Error = OutPointDecoderError;

    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<DecoderStatus, Self::Error> {
        self.inner.push_bytes(bytes).map_err(OutPointDecoderError)
    }

    fn end(self) -> Result<Self::Output, Self::Error> {
        let (txid, vout) = self.inner.end().map_err(OutPointDecoderError)?;
        Ok(OutPoint { txid: Txid::from_byte_array(txid), vout: u32::from_le_bytes(vout) })
    }

    fn read_limit(&self) -> usize { self.inner.read_limit() }
}

decoder_newtype! {
    /// Decoder for the [`Sequence`] type.
    #[derive(Default)]
    pub struct SequenceDecoder(ArrayDecoder<4>);

    /// Decoder error for the [`Sequence`] type.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub struct SequenceDecoderError(UnexpectedEofError);
    const ERROR_DISPLAY = "error decoding sequence";

    impl Decode for Sequence {
        fn convert_inner(bytes) -> Result<_, UnexpectedEofError> {
            Ok(Sequence::from_consensus(u32::from_le_bytes(bytes)))
        }
    }
}

decoder_newtype! {
    /// Decoder for the [`AssetIssuance`] type.
    #[derive(Default)]
    pub struct AssetIssuanceDecoder(Decoder4<
        crate::AssetBlindingNonceDecoder,
        crate::AssetEntropyDecoder,
        crate::confidential::ValueDecoder,
        crate::confidential::ValueDecoder,
    >);
    /// Decoder error for the [`AssetIssuance`] type.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub struct AssetIssuanceDecoderError(Decoder4Error<
        crate::AssetBlindingNonceDecoderError,
        crate::AssetEntropyDecoderError,
        crate::confidential::ValueDecoderError,
        crate::confidential::ValueDecoderError,
    >);
    const ERROR_DISPLAY = "error decoding asset issuance";

    impl Decode for AssetIssuance {
        fn convert_inner(output) -> Result<_, AssetIssuanceDecoderError> {
            let (asset_blinding_nonce, asset_entropy, amount, inflation_keys) = output;
            Ok(AssetIssuance {
                asset_blinding_nonce,
                asset_entropy,
                amount,
                inflation_keys,
            })
        }
    }
}

decoder_state_machine! {
    /// Decoder for the [`TxIn`] type.
    pub struct TxInDecoder(enum TxInDecoderInner {
        Done(TxIn),
        Errored,
        Initial {
            decoder: Decoder3<
                OutPointDecoder,
                crate::script::ScriptDecoder,
                SequenceDecoder,
            >,
            => transition_initial(output, ...) -> Result {
                let (mut outpoint, script_sig, sequence) = output;
                let (is_pegin, has_issuance) = if outpoint.vout == 0xffff_ffff {
                    (false, false)
                } else {
                    let vout = outpoint.vout;
                    outpoint.vout &= !((1 << 30) | (1 << 31));
                    (vout & (1 << 30) != 0, vout & (1 << 31) != 0)
                };
                if has_issuance {
                    Ok(TxInDecoderInner::AssetIssuance {
                        decoder: AssetIssuanceDecoder::default(),
                        outpoint, script_sig, sequence, is_pegin,
                    })
                } else {
                    if outpoint.vout != 0xffff_ffff {
                        outpoint.vout &= !((1 << 30) | (1 << 31));
                    }
                    Ok(TxInDecoderInner::Done(TxIn {
                        previous_output: outpoint,
                        is_pegin,
                        script_sig,
                        sequence,
                        asset_issuance: AssetIssuance::null(),
                        witness: TxInWitness::default(),
                    }))
                }
            }
        },
        AssetIssuance {
            decoder: AssetIssuanceDecoder,
            outpoint: OutPoint,
            script_sig: Script,
            sequence: Sequence,
            is_pegin: bool
            => transition_asset_issuance(asset_issuance, ...) -> Result {
                if asset_issuance.is_null() {
                    return Err(TxInDecoderErrorInner::SuperfluousIssuance);
                }

                Ok(TxInDecoderInner::Done(TxIn {
                    previous_output: outpoint,
                    is_pegin,
                    script_sig,
                    sequence,
                    asset_issuance,
                    witness: TxInWitness::default(),
                }))
            }
        },
    });

    /// Decoder error for the [`TxIn`] type.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub struct TxInDecoderError(enum TxInDecoderErrorInner {
        [macro-inserted decoder variants]
        SuperfluousIssuance,
    });
}

impl Default for TxInDecoder {
    fn default() -> Self { Self(TxInDecoderInner::Initial { decoder: Decoder3::default() }) }
}

impl fmt::Display for TxInDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use TxInDecoderErrorInner as Inner;
        match self.0 {
            Inner::Initial(..) => f.write_str("error decoding outpoint, scriptsig or sequence"),
            Inner::AssetIssuance(..) => f.write_str("error decoding asset issuance"),
            Inner::SuperfluousIssuance =>
                f.write_str("input had issuance flag set, but null issuance"),
        }
    }
}

impl std::error::Error for TxInDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use TxInDecoderErrorInner as Inner;
        match self.0 {
            Inner::Initial(ref e) => Some(e),
            Inner::AssetIssuance(ref e) => Some(e),
            Inner::SuperfluousIssuance => None,
        }
    }
}

/// Decoder for the [`TxInWitness`] type.
#[derive(Default)]
pub struct TxInWitnessDecoder {
    inner: Decoder4<RangeProofDecoder, RangeProofDecoder, WitnessDecoder, PeginWitnessDecoder>,
}

/// Decoder error for the [`TxInWitness`] type.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TxInWitnessDecoderError(
    Decoder4Error<
        RangeProofDecoderError,
        RangeProofDecoderError,
        WitnessDecoderError,
        PeginWitnessDecoderError,
    >,
);

impl fmt::Display for TxInWitnessDecoderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("error decoding transaction input witness")
    }
}

impl std::error::Error for TxInWitnessDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}

impl Decoder for TxInWitnessDecoder {
    type Output = TxInWitness;
    type Error = TxInWitnessDecoderError;

    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<DecoderStatus, Self::Error> {
        self.inner.push_bytes(bytes).map_err(TxInWitnessDecoderError)
    }

    fn end(self) -> Result<Self::Output, Self::Error> {
        let (amount_rangeproof, inflation_keys_rangeproof, script_witness, pegin_witness) =
            self.inner.end().map_err(TxInWitnessDecoderError)?;

        Ok(TxInWitness {
            amount_rangeproof,
            inflation_keys_rangeproof,
            script_witness,
            pegin_witness,
        })
    }

    fn read_limit(&self) -> usize { self.inner.read_limit() }
}

impl Decode for TxInWitness {
    type Decoder = TxInWitnessDecoder;
}

/// An decoder for the witnesses in a sequence of [`TxIn`]s.
///
/// Comsumes a vec of [`TxIn`]s on construction and then yields that
/// same vector, with the witness fields overwritten.
#[derive(Default)]
struct TxInWitnessesDecoder {
    txins: Vec<TxIn>,
    index: usize,
    // Invariant: if this is Some then
    decoder: Option<TxInWitnessDecoder>,
}

impl TxInWitnessesDecoder {
    fn new(txins: Vec<TxIn>) -> Self { Self { txins, index: 0, decoder: None } }
}

impl Decoder for TxInWitnessesDecoder {
    type Output = Vec<TxIn>;
    type Error = TxInWitnessDecoderError;

    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<DecoderStatus, Self::Error> {
        loop {
            let Some(next_txin) = self.txins.get_mut(self.index) else {
                return Ok(DecoderStatus::Ready);
            };

            let mut decoder = self.decoder.take().unwrap_or_else(TxInWitness::decoder);
            if decoder.push_bytes(bytes)?.needs_more() {
                self.decoder = Some(decoder);
                return Ok(DecoderStatus::NeedsMore);
            }
            next_txin.witness = decoder.end()?;
            self.index += 1;
        }
    }

    fn end(mut self) -> Result<Self::Output, Self::Error> {
        loop {
            let Some(last_txin) = self.txins.get_mut(self.index) else {
                return Ok(self.txins);
            };

            last_txin.witness = self.decoder.take().unwrap_or_else(TxInWitness::decoder).end()?;
            self.index += 1;
        }
    }

    fn read_limit(&self) -> usize {
        self.decoder.as_ref().map_or(0, TxInWitnessDecoder::read_limit)
    }
}

decoder_newtype! {
    /// Decoder for the [`TxOutWitness`] type.
    #[derive(Default)]
    pub struct TxOutWitnessDecoder(Decoder2<
        crate::confidential::SurjectionProofDecoder,
        crate::confidential::RangeProofDecoder,
    >);

    /// Decoder error for the [`TxOutWitness`] type.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub struct TxOutWitnessDecoderError(Decoder2Error<
        crate::confidential::SurjectionProofDecoderError,
        crate::confidential::RangeProofDecoderError,
    >);
    const ERROR_DISPLAY = "error decoding transaction output witness";

    impl Decode for TxOutWitness {
        fn convert_inner(output) -> Result<_, TxOutWitnessDecoderErrorInner> {
            let (surjection_proof, rangeproof) = output;
            Ok(TxOutWitness {surjection_proof, rangeproof })
        }
    }
}

/// An decoder for the witnesses in a sequence of [`TxOut`]s.
///
/// Comsumes a vec of [`TxOut`]s on construction and then yields that
/// same vector, with the witness fields overwritten.
#[derive(Default)]
struct TxOutWitnessesDecoder {
    txouts: Vec<TxOut>,
    index: usize,
    // Invariant: if this is Some then
    decoder: Option<TxOutWitnessDecoder>,
}

impl TxOutWitnessesDecoder {
    fn new(txouts: Vec<TxOut>) -> Self { Self { txouts, index: 0, decoder: None } }
}

impl Decoder for TxOutWitnessesDecoder {
    type Output = Vec<TxOut>;
    type Error = TxOutWitnessDecoderError;

    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<DecoderStatus, Self::Error> {
        loop {
            let Some(next_txout) = self.txouts.get_mut(self.index) else {
                return Ok(DecoderStatus::Ready);
            };

            let mut decoder = self.decoder.take().unwrap_or_else(TxOutWitness::decoder);
            if decoder.push_bytes(bytes)?.needs_more() {
                self.decoder = Some(decoder);
                return Ok(DecoderStatus::NeedsMore);
            }
            next_txout.witness = decoder.end()?;
            self.index += 1;
        }
    }

    fn end(mut self) -> Result<Self::Output, Self::Error> {
        loop {
            let Some(last_txout) = self.txouts.get_mut(self.index) else {
                return Ok(self.txouts);
            };

            last_txout.witness = self.decoder.take().unwrap_or_else(TxOutWitness::decoder).end()?;
            self.index += 1;
        }
    }

    fn read_limit(&self) -> usize {
        self.decoder.as_ref().map_or(0, TxOutWitnessDecoder::read_limit)
    }
}

decoder_newtype! {
    /// Decoder for the [`TxOut`] type.
    #[derive(Default)]
    pub struct TxOutDecoder(Decoder4<
        crate::confidential::AssetDecoder,
        crate::confidential::ValueDecoder,
        crate::confidential::NonceDecoder,
        crate::script::ScriptDecoder,
    >);


    /// Decoder error for the [`TxOut`] type.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub struct TxOutDecoderError(Decoder4Error<
            crate::confidential::AssetDecoderError,
            crate::confidential::ValueDecoderError,
            crate::confidential::NonceDecoderError,
            crate::script::ScriptDecoderError,
    >);
    const ERROR_DISPLAY = "error decoding transaction output witness";

    impl Decode for TxOut {
        fn convert_inner(output) -> Result<_, TxOutDecoderErrorInner> {
            let (asset, value, nonce, script_pubkey) = output;
            Ok(TxOut { asset, value, nonce, script_pubkey, witness: TxOutWitness::empty() })
        }
    }
}

decoder_state_machine! {
    /// Decoder for the [`Transaction`] type.
    pub struct TransactionDecoder(enum TransactionDecoderInner {
        Done(Transaction),
        Errored,
        DecodingNonWitness {
            decoder: Decoder4<
                ArrayDecoder<4>,
                ArrayDecoder<1>,
                Decoder2<
                    VecDecoder<TxIn>,
                    VecDecoder<TxOut>,
                >,
                LockTimeDecoder,
            >,
            => transition_non_witness(output, ...) -> Result {
                let (version, wit_flag, (input, output), lock_time) = output;
                match wit_flag {
                    [0] => Ok(TransactionDecoderInner::Done(Transaction {
                        version: u32::from_le_bytes(version),
                        lock_time,
                        input,
                        output,
                    })),
                    [1] => Ok(TransactionDecoderInner::DecodingWitnesses {
                        decoder: Decoder2::new(
                            TxInWitnessesDecoder::new(input),
                            TxOutWitnessesDecoder::new(output),
                        ),
                        version: u32::from_le_bytes(version),
                        lock_time,
                    }),
                    [x] => Err(TransactionDecoderErrorInner::InvalidWitnessFlag(x)),
                }
            }
        },
        DecodingWitnesses {
            decoder: Decoder2<
                TxInWitnessesDecoder,
                TxOutWitnessesDecoder,
            >,
            version: u32,
            lock_time: LockTime
            => transition_witnesses(output, ...) -> Result {
                let (input, output) = output;
                if input.iter().all(|input| input.witness.is_empty()) &&
                    output.iter().all(|output| output.witness.is_empty()) {
                    Err(TransactionDecoderErrorInner::NoWitnesses)
                } else {
                    Ok(TransactionDecoderInner::Done(Transaction {
                        version,
                        lock_time,
                        input,
                        output,
                    }))
                }
            }
        },
    });

    /// Decoder error for the [`Transaction`] type.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub struct TransactionDecoderError(enum TransactionDecoderErrorInner {
        [macro-inserted decoder variants]
        InvalidWitnessFlag(u8),
        NoWitnesses,
    });
}

impl Default for TransactionDecoder {
    fn default() -> Self {
        Self(TransactionDecoderInner::DecodingNonWitness { decoder: Decoder4::default() })
    }
}

impl fmt::Display for TransactionDecoderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use TransactionDecoderErrorInner as Inner;

        match self.0 {
            Inner::DecodingNonWitness(..) =>
                f.write_str("failed to decode non-witness part of transaction"),
            Inner::DecodingWitnesses(..) => f.write_str("failed to decode transaction witnesses"),
            Inner::InvalidWitnessFlag(flag) => {
                write!(f, "invalid witness flag {flag} (must be 0 or 1)")
            }
            Inner::NoWitnesses => f.write_str("witness flag set but all witnesses were empty"),
        }
    }
}

impl std::error::Error for TransactionDecoderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use TransactionDecoderErrorInner as Inner;

        match self.0 {
            Inner::DecodingNonWitness(ref e) => Some(e),
            Inner::DecodingWitnesses(ref e) => Some(e),
            Inner::InvalidWitnessFlag(_) => None,
            Inner::NoWitnesses => None,
        }
    }
}