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
use crate::parser::blk_file::BlkFile;
use crate::parser::errors::{OpError, OpResult};
use crate::parser::proto::full_proto::{FBlockHeader, FTxOut};
use crate::parser::proto::simple_proto::{SBlockHeader, STxOut};
use crate::parser::tx_index::TxDB;
use crate::BlockIndex;
use bitcoin::{Block, BlockHash, BlockHeader, Transaction, TxIn, TxOut, Txid};
use log::warn;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;

///
/// This type refer to `Block` structs where inputs are
/// replaced by connected outputs.
///
/// ## Implementors:
/// - SConnectedBlock
/// - FConnectedBlock
///
pub trait ConnectedBlock {
    ///
    /// Associated output type.
    ///
    type Tx: ConnectedTx + Send;

    ///
    /// Construct a ConnectedBlock from parts of a block.
    ///
    /// Used in `iter_connected.rs`.
    ///
    fn from(block_header: BlockHeader, block_hash: BlockHash) -> Self;

    ///
    /// Add a new transaction in this block.
    ///
    /// Used in `iter_connected.rs`.
    ///
    fn add_tx(&mut self, tx: Self::Tx);

    ///
    /// Construct a ConnectedBlock and connect the transactions.
    ///
    fn connect(
        block: Block,
        tx_db: &TxDB,
        blk_index: &BlockIndex,
        blk_file: &BlkFile,
    ) -> OpResult<Self>
    where
        Self: Sized;
}

///
/// This type refer to `Transaction` structs where inputs are
/// replaced by connected outputs.
///
/// ## Implementors:
/// - STransaction
/// - FTransaction
///
pub trait ConnectedTx {
    ///
    /// Associated output type.
    ///
    type TOut: 'static + From<TxOut> + Send;

    ///
    /// Construct a ConnectedTx from Transaction without blank inputs.
    ///
    /// This function is used in `iter_connected.rs`.
    ///
    fn from(tx: &Transaction) -> Self;

    ///
    /// Add a input to this ConnectedTx.
    ///
    /// This function is used in `iter_connected.rs`.
    ///
    fn add_input(&mut self, input: Self::TOut);

    ///
    /// Build ConnectedTx from Tx,
    /// and attach inputs to this ConnectedTx using tx-index.
    ///
    fn connect(
        tx: Transaction,
        tx_db: &TxDB,
        blk_index: &BlockIndex,
        blk_file: &BlkFile,
    ) -> OpResult<Self>
    where
        Self: Sized;
}

///
/// Simple format of connected block.
/// See fields for details of this struct.
///
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct SConnectedBlock {
    pub header: SBlockHeader,
    pub txdata: Vec<SConnectedTransaction>,
}

///
/// Full format of connected block.
/// See fields for details of this struct.
///
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct FConnectedBlock {
    pub header: FBlockHeader,
    pub txdata: Vec<FConnectedTransaction>,
}

///
/// Simple format of connected transaction.
/// See fields for details of this struct.
///
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct SConnectedTransaction {
    pub txid: Txid,
    pub input: Vec<STxOut>,
    pub output: Vec<STxOut>,
}

///
/// Full format of connected transaction.
/// See fields for details of this struct.
///
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct FConnectedTransaction {
    pub version: i32,
    pub lock_time: u32,
    pub txid: Txid,
    pub input: Vec<FTxOut>,
    pub output: Vec<FTxOut>,
}

impl ConnectedTx for FConnectedTransaction {
    type TOut = FTxOut;

    fn from(tx: &Transaction) -> Self {
        FConnectedTransaction {
            version: tx.version,
            lock_time: tx.lock_time,
            txid: tx.txid(),
            input: Vec::new(),
            output: tx.output.clone().into_iter().map(|x| x.into()).collect(),
        }
    }

    fn add_input(&mut self, input: Self::TOut) {
        self.input.push(input);
    }

    fn connect(
        tx: Transaction,
        tx_db: &TxDB,
        blk_index: &BlockIndex,
        blk_file: &BlkFile,
    ) -> OpResult<Self> {
        let is_coinbase = tx.is_coin_base();
        Ok(FConnectedTransaction {
            version: tx.version,
            lock_time: tx.lock_time,
            txid: tx.txid(),
            input: connect_tx_inputs(&tx.input, is_coinbase, tx_db, blk_index, blk_file)?
                .into_iter()
                .map(|x| x.into())
                .collect(),
            output: tx.output.into_iter().map(|x| x.into()).collect(),
        })
    }
}

impl ConnectedTx for SConnectedTransaction {
    type TOut = STxOut;

    fn from(tx: &Transaction) -> Self {
        SConnectedTransaction {
            txid: tx.txid(),
            input: Vec::new(),
            output: tx.output.clone().into_iter().map(|x| x.into()).collect(),
        }
    }

    fn add_input(&mut self, input: Self::TOut) {
        self.input.push(input);
    }

    fn connect(
        tx: Transaction,
        tx_db: &TxDB,
        blk_index: &BlockIndex,
        blk_file: &BlkFile,
    ) -> OpResult<Self> {
        let is_coinbase = tx.is_coin_base();
        Ok(SConnectedTransaction {
            txid: tx.txid(),
            input: connect_tx_inputs(&tx.input, is_coinbase, tx_db, blk_index, blk_file)?
                .into_iter()
                .map(|x| x.into())
                .collect(),
            output: tx.output.into_iter().map(|x| x.into()).collect(),
        })
    }
}

impl ConnectedBlock for FConnectedBlock {
    type Tx = FConnectedTransaction;

    fn from(block_header: BlockHeader, block_hash: BlockHash) -> Self {
        FConnectedBlock {
            header: FBlockHeader::parse(block_header, block_hash),
            txdata: Vec::new(),
        }
    }

    fn add_tx(&mut self, tx: Self::Tx) {
        self.txdata.push(tx);
    }

    fn connect(
        block: Block,
        tx_db: &TxDB,
        blk_index: &BlockIndex,
        blk_file: &BlkFile,
    ) -> OpResult<Self> {
        let block_hash = block.header.block_hash();
        Ok(FConnectedBlock {
            header: FBlockHeader::parse(block.header, block_hash),
            txdata: connect_block_inputs(block.txdata, tx_db, blk_index, blk_file)?,
        })
    }
}

impl ConnectedBlock for SConnectedBlock {
    type Tx = SConnectedTransaction;

    fn from(block_header: BlockHeader, block_hash: BlockHash) -> Self {
        SConnectedBlock {
            header: SBlockHeader::parse(block_header, block_hash),
            txdata: Vec::new(),
        }
    }

    fn add_tx(&mut self, tx: Self::Tx) {
        self.txdata.push(tx);
    }

    fn connect(
        block: Block,
        tx_db: &TxDB,
        blk_index: &BlockIndex,
        blk_file: &BlkFile,
    ) -> OpResult<Self> {
        let block_hash = block.header.block_hash();
        Ok(SConnectedBlock {
            header: SBlockHeader::parse(block.header, block_hash),
            txdata: connect_block_inputs(block.txdata, tx_db, blk_index, blk_file)?,
        })
    }
}

///
/// This function is used for connecting transaction inputs for a single block.
///
#[inline]
fn connect_block_inputs<Tx>(
    transactions: Vec<Transaction>,
    tx_db: &TxDB,
    blk_index: &BlockIndex,
    blk_file: &BlkFile,
) -> OpResult<Vec<Tx>>
where
    Tx: ConnectedTx,
{
    // collect all inputs
    let mut all_tx_in = Vec::with_capacity(transactions.len());
    for tx in &transactions {
        for tx_in in &tx.input {
            all_tx_in.push(tx_in);
        }
    }

    // connect transactions inputs in parallel
    let mut connected_outputs: VecDeque<Option<TxOut>> = all_tx_in
        .par_iter()
        .map(|x| connect_input(x, tx_db, blk_index, blk_file))
        .collect();

    // reconstruct block
    let mut connected_tx = Vec::with_capacity(transactions.len());
    for tx in transactions {
        let outpoints_count = if tx.is_coin_base() { 0 } else { tx.input.len() };

        let mut outputs = Vec::with_capacity(outpoints_count);
        for _ in 0..tx.input.len() {
            let connected_out = connected_outputs.pop_front().unwrap();
            if let Some(out) = connected_out {
                // also do not push the null input connected to coinbase transaction
                outputs.push(out);
            }
        }
        // check if any output is missing
        if outputs.len() != outpoints_count {
            return Err(OpError::from(
                "some outpoints aren't found, tx_index is not fully synced",
            ));
        }
        let mut tx = Tx::from(&tx);
        for o in outputs {
            tx.add_input(o.into());
        }
        connected_tx.push(tx);
    }
    Ok(connected_tx)
}

///
/// This function converts multiple Inputs of a single transaction to Outputs in parallel.
///
#[inline]
fn connect_tx_inputs(
    tx_in: &[TxIn],
    is_coinbase: bool,
    tx_db: &TxDB,
    blk_index: &BlockIndex,
    blk_file: &BlkFile,
) -> OpResult<Vec<TxOut>> {
    let connected_outputs: Vec<TxOut> = tx_in
        .par_iter()
        .filter_map(|x| connect_input(x, tx_db, blk_index, blk_file))
        .collect();

    let outpoints_count = if is_coinbase { 0 } else { tx_in.len() };
    let received = connected_outputs.len();

    // some outpoints aren't found
    if received != outpoints_count {
        Err(OpError::from(
            format!("some outpoints aren't found, tx_index is not fully synced, (expected: {}, read: {}, txid)", outpoints_count, received).as_str(),
        ))
    } else {
        Ok(connected_outputs)
    }
}

///
/// This function connect a single TxIn to outputs. It converts:
/// - read failure to `None`
/// - coinbase transaction output to `None`
///
/// It is used in `connect_output_tx_in` and `connect_output`.
///
#[inline]
fn connect_input(
    tx_in: &TxIn,
    tx_db: &TxDB,
    blk_index: &BlockIndex,
    blk_file: &BlkFile,
) -> Option<TxOut> {
    let outpoint = tx_in.previous_output;
    let tx_id = &outpoint.txid;
    let n = outpoint.vout;
    // skip coinbase transaction
    if !is_coin_base(tx_in) {
        // special treatment of genesis tx, which cannot be found in tx-index.
        if tx_db.is_genesis_tx(tx_id) {
            return match blk_index.records.first() {
                None => None,
                Some(pos) => match blk_file.read_block(pos.n_file, pos.n_data_pos) {
                    Ok(mut blk) => {
                        let mut tx = blk.txdata.swap_remove(0);
                        Some(tx.output.swap_remove(0))
                    }
                    Err(_) => None,
                },
            };
        }
        if let Ok(record) = tx_db.get_tx_record(tx_id) {
            if let Ok(mut tx) =
                blk_file.read_transaction(record.n_file, record.n_pos, record.n_tx_offset)
            {
                let len = tx.output.len();
                if n >= len as u32 {
                    warn!("outpoint {} exceeds range", &outpoint);
                    None
                } else {
                    Some(tx.output.swap_remove(n as usize))
                }
            } else {
                warn!("fail to read transaction {}", &outpoint);
                None
            }
        } else {
            warn!("cannot find outpoint {} in txDB", &outpoint);
            None
        }
    } else {
        // skip coinbase transaction
        None
    }
}

#[inline]
fn is_coin_base(tx_in: &TxIn) -> bool {
    tx_in.previous_output.is_null()
}