push_decoder/
lib.rs

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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! Push decoder for bitcoin blocks and transactions.

#![forbid(unsafe_code)]
#![allow(bare_trait_objects)]
#![allow(ellipsis_inclusive_range_patterns)]
#![warn(rustdoc::broken_intra_doc_links)]
#![warn(missing_docs)]
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]

#[cfg(not(any(feature = "std", feature = "no-std")))]
compile_error!("at least one of the `std` or `no-std` features must be enabled");

use bitcoin::absolute::LockTime;
use bitcoin::hash_types::TxMerkleNode;
use merkle::IncrementalHasher;
use bitcoin::{io, Amount};

extern crate alloc;
extern crate core;

/// Incremental merkle tree hasher
pub mod merkle;

use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::mem;
use core::ops::{Deref, DerefMut};

use bitcoin::consensus::{encode, Decodable, Encodable};
use bitcoin::hashes::{sha256::HashEngine, Hash, HashEngine as _};
use bitcoin::{
    OutPoint, ScriptBuf, Sequence, TxIn, TxOut, Txid,
    VarInt,
};
use bitcoin::blockdata::block::Header as BlockHeader;

use log::*;

/// Block decoder error
#[derive(Debug)]
pub enum Error {
    /// the input did not contain enough data to parse a block
    IncompleteData,
    /// the input contained invalid data
    ParseError,
    /// the input contained more data than the block
    TrailingData,
}

impl From<encode::Error> for Error {
    fn from(e: encode::Error) -> Self {
        debug!("parse error: {}", e);
        Error::ParseError
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        debug!("IO error: {}", e);
        Error::ParseError
    }
}

/// Block decoder listener.
pub trait Listener {
    /// called after a block header is parsed
    fn on_block_start(&mut self, header: &BlockHeader);
    /// called after a transaction header is parsed
    fn on_transaction_start(&mut self, version: i32);
    /// called after a transaction input is parsed
    fn on_transaction_input(&mut self, txin: &TxIn);
    /// called after a transaction output is parsed
    fn on_transaction_output(&mut self, txout: &TxOut);
    /// called after a transaction locktime is parsed at the end of the transaction
    fn on_transaction_end(&mut self, locktime: LockTime, txid: Txid);
    /// called after the complete block has been parsed
    fn on_block_end(&mut self);
}

#[derive(Debug, PartialEq)]
enum ParserState {
    BeforeHeader,
    ReadingTransactionHeader,
    // remaining inputs
    ReadingInputs(usize),
    // remaining inputs, prev outpoint, remaining script size
    ReadingInputScript(usize, OutPoint, usize),
    // remaining inputs, elements in input, bytes in element
    ReadingWitnesses(usize, usize, usize),
    BeforeOutputs,
    ReadingOutputs(usize),
    // remaining inputs, value, remaining script size
    ReadingOutputScript(usize, u64, usize),
    ReadingLockTime,
    FinishedBlock,
}

// Wrapper around a VecDeque<u8> that implements io::Read.
// Needed because Read was only added in 1.63 and core2 also doesn't have it.
struct Buffer(VecDeque<u8>);

impl Buffer {
    fn with_capacity(capacity: usize) -> Self {
        Self(VecDeque::with_capacity(capacity))
    }
}

impl Deref for Buffer {
    type Target = VecDeque<u8>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Buffer {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl io::Read for Buffer {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let (ref mut front, _) = self.as_slices();
        let n = io::Read::read(front, buf)?;
        self.drain(..n);
        Ok(n)
    }
}

/// Push decoder for bitcoin blocks.
///
/// IMPORTANT: you must call `finish()` after the last byte of the block has been supplied,
/// in order to complete the block validation and ensure that there is no trailing data.
///
/// The decoder uses a limited amount of memory by streaming parse results
/// to a listener.
///
/// Scripts beyond `max_script_size` are replaced with the empty script (saves
/// 10 KB of peak memory usage).
///
/// The computed transactionm IDs cover the original script.
pub struct BlockDecoder {
    buffer: Buffer,
    buffer_capacity: usize,
    // scripts beyond this size are replaced with the empty script
    max_script_size: usize,
    parser_state: ParserState,
    // current script - reset after each input and output
    script: Option<Vec<u8>>,
    // number of transactions remaining in the block
    remaining_txs: usize,
    // number of inputs in the current transaction if the transaction has witnesses
    segwit_inputs: Option<usize>,
    // hasher for computing the current transaction's ID
    hasher: HashEngine,
    // merkle tree hasher
    merkle: IncrementalHasher,
    // merkle root from the header
    merkle_root: Option<TxMerkleNode>,
}

impl BlockDecoder {
    /// Create a new decoder with a max script size of 100 bytes
    pub fn new() -> Self {
        Self::new_with_capacity(100, 100)
    }

    /// Create a new decoder with a specific buffer capacity.
    /// must be at least 100 bytes.
    pub fn new_with_capacity(buffer_capacity: usize, max_script_size: usize) -> Self {
        assert!(buffer_capacity >= 100);
        let hasher = Txid::engine();
        Self {
            buffer: Buffer::with_capacity(buffer_capacity),
            buffer_capacity,
            max_script_size,
            parser_state: ParserState::BeforeHeader,
            script: None,
            remaining_txs: 0,
            segwit_inputs: None,
            hasher,
            merkle: IncrementalHasher::new(),
            merkle_root: None,
        }
    }

    /// Supply data to the decoder
    pub fn decode_next<L: Listener>(
        &mut self,
        mut data: &[u8],
        listener: &mut L,
    ) -> Result<(), Error> {
        while !data.is_empty() {
            let bytes_to_copy = usize::min(data.len(), self.buffer_capacity - self.buffer.len());
            trace!("copying {} bytes", bytes_to_copy);
            self.buffer.extend(&data[..bytes_to_copy]);
            data = &data[bytes_to_copy..];

            if !self.parse_step(listener)? {
                break;
            }
        }

        trace!("data is empty");
        // Attempt to completely parse any remaining data in the buffer
        self.parse_step(listener)?;
        trace!(
            "no progress possible at state {:?} len {}",
            self.parser_state,
            self.buffer.len()
        );
        Ok(())
    }

    /// Signal that no more data will be supplied, validate that the block is complete.
    pub fn finish(self) -> Result<(), Error> {
        assert_eq!(
            self.merkle_root,
            Some(self.merkle.finish()),
            "merkle root mismatch"
        );
        if self.parser_state != ParserState::FinishedBlock {
            Err(Error::IncompleteData)
        } else {
            Ok(())
        }
    }

    // parse as much as we can of the buffer and return true if we made progress
    fn parse_step<L: Listener>(&mut self, listener: &mut L) -> Result<bool, Error> {

        let initial_buffer_len = self.buffer.len();

        loop {
            trace!("state is {:?} len {}", self.parser_state, self.buffer.len());
            trace!("buffer {}", hex::encode(self.buffer.make_contiguous()));

            match self.parser_state {
                ParserState::BeforeHeader =>
                // less than 2^32 transactions - max 5 byte varint
                {
                    if self.buffer.len() >= 80 + 5 {
                        let header = BlockHeader::consensus_decode(&mut self.buffer)?;
                        listener.on_block_start(&header);
                        self.merkle_root = Some(header.merkle_root);
                        let tx_count = VarInt::consensus_decode(&mut self.buffer)?;
                        self.remaining_txs = tx_count.0 as usize;
                        // merkle tree must have at least one leaf
                        if self.remaining_txs == 0 {
                            return Err(Error::IncompleteData);
                        }
                        self.parser_state = ParserState::ReadingTransactionHeader;
                    } else {
                        break;
                    }
                }
                ParserState::ReadingTransactionHeader => {
                    // less than 2^32 outputs, max 5 byte varint
                    if self.buffer.len() >= 4 + 5 {
                        let version = i32::consensus_decode(&mut self.buffer)?;
                        version.consensus_encode(&mut self.hasher)?;

                        let mut input_count = VarInt::consensus_decode(&mut self.buffer)?;
                        if input_count.0 == 0 {
                            // segwit variant
                            let expected_one = VarInt::consensus_decode(&mut self.buffer)?;
                            if expected_one.0 != 1 {
                                return Err(Error::ParseError);
                            }

                            // now we have the real count
                            input_count = VarInt::consensus_decode(&mut self.buffer)?;
                            self.segwit_inputs = Some(input_count.0 as usize);
                        } else {
                            self.segwit_inputs = None;
                        }

                        input_count.consensus_encode(&mut self.hasher)?;

                        listener.on_transaction_start(version);
                        if input_count.0 > 0 {
                            self.parser_state = ParserState::ReadingInputs(input_count.0 as usize);
                        } else {
                            // not really allowed by bitcoind, but be lenient
                            self.parser_state = ParserState::BeforeOutputs;
                        }
                    } else {
                        break;
                    }
                }
                ParserState::ReadingInputs(remaining_inputs) => {
                    // the script length must not be longer than 10000 bytes, max 3 byte varint
                    if self.buffer.len() >= 36 + 3 {
                        let outpoint = OutPoint::consensus_decode(&mut self.buffer)?;
                        outpoint.consensus_encode(&mut self.hasher)?;

                        let script_len = VarInt::consensus_decode(&mut self.buffer)?;
                        script_len.consensus_encode(&mut self.hasher)?;
                        self.script = if script_len.0 > self.max_script_size as u64 {
                            None
                        } else {
                            Some(Vec::<u8>::with_capacity(script_len.0 as usize))
                        };
                        self.parser_state = ParserState::ReadingInputScript(
                            remaining_inputs,
                            outpoint,
                            script_len.0 as usize,
                        );
                    } else {
                        break;
                    }
                }
                ParserState::ReadingInputScript(
                    mut remaining_inputs,
                    outpoint,
                    mut remaining_script_len,
                ) => {
                    if self.buffer.is_empty() {
                        break;
                    }
                    let to_read = usize::min(remaining_script_len, self.buffer.len());

                    if let Some(ref mut script) = self.script {
                        script.extend(self.buffer.range(..to_read));
                    }

                    for byte in self.buffer.drain(..to_read) {
                        self.hasher.input(&[byte]);
                    }

                    remaining_script_len -= to_read;
                    self.parser_state = ParserState::ReadingInputScript(
                        remaining_inputs,
                        outpoint,
                        remaining_script_len,
                    );

                    if remaining_script_len == 0 {
                        if self.buffer.len() >= 4 {
                            let sequence = Sequence(u32::consensus_decode(&mut self.buffer)?);
                            sequence.consensus_encode(&mut self.hasher)?;
                            let script = self.script.take().unwrap_or(Vec::new());
                            let txin = TxIn {
                                previous_output: outpoint,
                                script_sig: ScriptBuf::from(script),
                                sequence,
                                witness: Default::default(),
                            };
                            listener.on_transaction_input(&txin);
                            remaining_inputs -= 1;

                            if remaining_inputs == 0 {
                                self.parser_state = ParserState::BeforeOutputs;
                            } else {
                                self.parser_state = ParserState::ReadingInputs(remaining_inputs);
                            }
                        } else {
                            // not enough data in buffer, wait for more
                            break;
                        }
                    }
                }
                ParserState::ReadingWitnesses(
                    mut remaining_inputs,
                    mut remaining_witnesses,
                    mut remaining_witness_len,
                ) => {
                    if remaining_witness_len > 0 {
                        if self.buffer.is_empty() {
                            break;
                        }
                        let to_read = usize::min(remaining_witness_len, self.buffer.len());
                        self.buffer.drain(..to_read);
                        remaining_witness_len -= to_read;
                        self.parser_state = ParserState::ReadingWitnesses(
                            remaining_inputs,
                            remaining_witnesses,
                            remaining_witness_len,
                        );
                    } else if remaining_witnesses > 0 {
                        if self.buffer.len() < 5 {
                            break;
                        }
                        let witness_length = VarInt::consensus_decode(&mut self.buffer)?.0 as usize;
                        remaining_witnesses -= 1;
                        self.parser_state = ParserState::ReadingWitnesses(
                            remaining_inputs,
                            remaining_witnesses,
                            witness_length,
                        );
                    } else if remaining_inputs > 0 {
                        if self.buffer.len() < 5 {
                            break;
                        }
                        let witnesses = VarInt::consensus_decode(&mut self.buffer)?.0 as usize;
                        remaining_inputs -= 1;
                        self.parser_state =
                            ParserState::ReadingWitnesses(remaining_inputs, witnesses, 0);
                    } else {
                        self.parser_state = ParserState::ReadingLockTime;
                    }
                }
                ParserState::BeforeOutputs => {
                    // less than 2^32 outputs
                    if self.buffer.len() >= 5 {
                        let output_count = VarInt::consensus_decode(&mut self.buffer)?;
                        output_count.consensus_encode(&mut self.hasher)?;
                        self.parser_state = ParserState::ReadingOutputs(output_count.0 as usize);
                    } else {
                        break;
                    }
                }
                ParserState::ReadingOutputs(remaining_outputs) => {
                    // the script length must not be longer than 10000 bytes, max 3 byte varint
                    if self.buffer.len() >= 8 + 3 {
                        let value = u64::consensus_decode(&mut self.buffer)?;
                        value.consensus_encode(&mut self.hasher)?;

                        let script_len = VarInt::consensus_decode(&mut self.buffer)?;
                        script_len.consensus_encode(&mut self.hasher)?;
                        self.script = if script_len.0 > self.max_script_size as u64 {
                            None
                        } else {
                            Some(Vec::with_capacity(script_len.0 as usize))
                        };
                        self.parser_state = ParserState::ReadingOutputScript(
                            remaining_outputs,
                            value,
                            script_len.0 as usize,
                        );
                    } else {
                        break;
                    }
                }
                ParserState::ReadingOutputScript(
                    mut remaining_outputs,
                    value,
                    mut remaining_script_len,
                ) => {
                    if self.buffer.is_empty() {
                        break;
                    }
                    let to_read = usize::min(remaining_script_len, self.buffer.len());
                    if let Some(ref mut script) = self.script {
                        script.extend(self.buffer.range(..to_read));
                    }
                    for byte in self.buffer.drain(..to_read) {
                        self.hasher.input(&[byte]);
                    }
                    remaining_script_len -= to_read;
                    if remaining_script_len > 0 {
                        self.parser_state = ParserState::ReadingOutputScript(
                            remaining_outputs,
                            value,
                            remaining_script_len,
                        );
                    } else {
                        let script = self.script.take().unwrap_or(Vec::new());
                        let txout = TxOut {
                            value: Amount::from_sat(value),
                            script_pubkey: ScriptBuf::from(script),
                        };
                        listener.on_transaction_output(&txout);
                        remaining_outputs -= 1;

                        if remaining_outputs == 0 {
                            if let Some(segwit_inputs) = self.segwit_inputs {
                                self.parser_state =
                                    ParserState::ReadingWitnesses(segwit_inputs, 0, 0);
                            } else {
                                self.parser_state = ParserState::ReadingLockTime;
                            }
                        } else {
                            self.parser_state = ParserState::ReadingOutputs(remaining_outputs);
                        }
                    }
                }
                ParserState::ReadingLockTime => {
                    if self.buffer.len() >= 4 {
                        let locktime = LockTime::consensus_decode(&mut self.buffer)?;
                        locktime.consensus_encode(&mut self.hasher)?;
                        // this also resets the hasher
                        let engine = mem::take(&mut self.hasher);
                        let txid = Txid::from_engine(engine);
                        let txid_hash = txid.as_raw_hash();
                        self.merkle.add(TxMerkleNode::from_raw_hash(txid_hash.clone()));
                        listener.on_transaction_end(locktime, txid);
                        self.remaining_txs -= 1;
                        if self.remaining_txs == 0 {
                            self.parser_state = ParserState::FinishedBlock;
                            listener.on_block_end();
                        } else {
                            self.parser_state = ParserState::ReadingTransactionHeader;
                        }
                    } else {
                        break;
                    }
                }
                ParserState::FinishedBlock => {
                    // ensure that we have consumed all bytes from the buffer
                    if self.buffer.is_empty() {
                        break;
                    } else {
                        return Err(Error::TrailingData);
                    }
                }
            }
        }

        Ok(self.buffer.len() != initial_buffer_len)
    }
}

/// Test utilities
#[cfg(feature = "std")]
#[allow(missing_docs)]
pub mod test_util {
    use super::*;

    pub struct MockListener {
        pub block_headers: Vec<BlockHeader>,
        pub transaction_versions: Vec<i32>,
        pub transaction_inputs: Vec<TxIn>,
        pub transaction_outputs: Vec<TxOut>,
        pub transaction_locktimes: Vec<LockTime>,
        pub transaction_ids: Vec<Txid>,
        pub output_index: usize,
    }

    impl MockListener {
        pub fn new() -> Self {
            Self {
                block_headers: Vec::new(),
                transaction_versions: Vec::new(),
                transaction_inputs: Vec::new(),
                transaction_outputs: Vec::new(),
                transaction_locktimes: Vec::new(),
                transaction_ids: Vec::new(),
                output_index: 0,
            }
        }
    }

    impl Listener for MockListener {
        fn on_block_start(&mut self, header: &BlockHeader) {
            self.block_headers.push(header.clone());
        }

        fn on_transaction_start(&mut self, version: i32) {
            trace!("on_transaction_start({})", version);
            self.output_index = 0;
            self.transaction_versions.push(version);
        }

        fn on_transaction_input(&mut self, txin: &TxIn) {
            trace!("on_transaction_input: {:?}", txin);
            // fail fast
            assert_eq!(txin.sequence, Sequence::default());
            self.transaction_inputs.push(txin.clone());
        }

        fn on_transaction_output(&mut self, txout: &TxOut) {
            trace!("on_transaction_output: {:?}", txout);
            // fail fast
            assert_eq!(txout.value.to_sat(), self.output_index as u64);

            self.output_index += 1;
            self.transaction_outputs.push(txout.clone());
        }

        fn on_transaction_end(&mut self, locktime: LockTime, txid: Txid) {
            self.transaction_locktimes.push(locktime);
            self.transaction_ids.push(txid);
        }

        fn on_block_end(&mut self) {}
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec::Vec;
    use bitcoin::block::Version as BlockVersion;
    use bitcoin::transaction::Version;
    use bitcoin::consensus::{serialize, Encodable};
    use bitcoin::hashes::Hash;
    use bitcoin::{Block, BlockHash, CompactTarget, Transaction, Witness};
    use test_log::test;

    use super::test_util::MockListener;
    use super::*;

    #[test]
    fn test_decode_block_with_no_inputs() {
        let mut listener = MockListener::new();
        let mut decoder = BlockDecoder::new();
        // create a block with one transaction
        let mut block = Block {
            header: BlockHeader {
                version: BlockVersion::ONE,
                prev_blockhash: BlockHash::all_zeros(),
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0,
                bits: CompactTarget::from_consensus(0),
                nonce: 0,
            },
            txdata: vec![Transaction {
                version: Version::ONE,
                lock_time: LockTime::from_consensus(0),
                input: vec![],
                output: vec![TxOut {
                    value: Amount::ZERO,
                    script_pubkey: ScriptBuf::from(vec![0x33, 0x44]),
                }],
            }],
        };
        block.header.merkle_root = block.compute_merkle_root().unwrap();
        let mut block_bytes = Vec::new();
        block.consensus_encode(&mut block_bytes).unwrap();
        trace!("block: {}\n{:#?}", hex::encode(block_bytes.clone()), block);
        decoder.decode_next(&block_bytes, &mut listener).unwrap();
        decoder.finish().unwrap();
        assert_eq!(listener.transaction_ids.len(), 1);
        assert_eq!(listener.transaction_inputs.len(), 0);
    }

    #[test]
    fn test_decode_block() {
        let mut listener = MockListener::new();
        let mut decoder = BlockDecoder::new();
        // create a block with one transaction
        let mut block = Block {
            header: BlockHeader {
                version: BlockVersion::ONE,
                prev_blockhash: BlockHash::all_zeros(),
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0,
                bits: CompactTarget::from_consensus(0),
                nonce: 0,
            },
            txdata: vec![Transaction {
                version: Version::ONE,
                lock_time: LockTime::from_consensus(0),
                input: vec![TxIn {
                    previous_output: OutPoint {
                        txid: Txid::from_slice(&[0x33u8; 32]).unwrap(),
                        vout: 0x44,
                    },
                    script_sig: ScriptBuf::from(vec![0x11, 0x22]),
                    sequence: Default::default(),
                    witness: Default::default(),
                }],
                output: vec![TxOut {
                    value: Amount::ZERO,
                    script_pubkey: ScriptBuf::from(vec![0x33, 0x44]),
                }],
            }],
        };
        block.header.merkle_root = block.compute_merkle_root().unwrap();

        let mut block_bytes = Vec::new();
        block.consensus_encode(&mut block_bytes).unwrap();
        trace!("block: {}\n{:#?}", hex::encode(block_bytes.clone()), block);
        decoder.decode_next(&block_bytes, &mut listener).unwrap();
        decoder.finish().unwrap();
        assert_eq!(listener.block_headers.len(), 1);
        assert_eq!(listener.block_headers[0], block.header);

        assert_eq!(listener.transaction_versions.len(), 1);
        assert_eq!(listener.transaction_inputs.len(), 1);
        assert_eq!(
            listener.transaction_inputs[0].script_sig.as_bytes(),
            &[0x11, 0x22]
        );
        assert_eq!(listener.transaction_outputs.len(), 1);
        assert_eq!(
            listener.transaction_outputs[0].script_pubkey.as_bytes(),
            &[0x33, 0x44]
        );
        assert_eq!(listener.transaction_locktimes.len(), 1);

        assert_eq!(listener.transaction_ids.len(), 1);
        assert_eq!(listener.transaction_ids[0], block.txdata[0].compute_txid());

        // parse a segwit block
        let mut listener = MockListener::new();
        let mut decoder = BlockDecoder::new();
        block.txdata[0].input[0].witness =
            Witness::from_slice(&vec![vec![0x11, 0x22], vec![], vec![0x33, 0x44]]);
        let mut block_bytes = Vec::new();
        block.consensus_encode(&mut block_bytes).unwrap();
        trace!("block: {}\n{:#?}", hex::encode(block_bytes.clone()), block);
        let ser = serialize(&block.txdata[0]);
        Transaction::consensus_decode(&mut &ser[..]).unwrap();
        trace!("tx: {}\n{:#?}", hex::encode(ser), block.txdata[0]);

        decoder.decode_next(&block_bytes, &mut listener).unwrap();
        decoder.finish().unwrap();
        assert_eq!(listener.transaction_ids.len(), 1);
        assert_eq!(listener.transaction_ids[0], block.txdata[0].compute_txid());
    }
}