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
//! Block fetching and deserialization functionality.

use crate::{
    chain::{
        error::{BlockCacheError, ParseError},
        transaction::FullTransaction,
        utils::{
            display_txids_to_server, read_bytes, read_i32, read_u32, read_zcash_script_i64,
            CompactSize, ParseFromSlice,
        },
    },
    jsonrpc::{connector::JsonRpcConnector, response::GetBlockResponse},
};
use sha2::{Digest, Sha256};
use std::io::Cursor;
use zaino_proto::proto::compact_formats::{
    ChainMetadata, CompactBlock, CompactOrchardAction, CompactTx,
};

/// A block header, containing metadata about a block.
///
/// How are blocks chained together? They are chained together via the
/// backwards reference (previous header hash) present in the block
/// header. Each block points backwards to its parent, all the way
/// back to the genesis block (the first block in the blockchain).
#[derive(Debug)]
pub struct BlockHeaderData {
    /// The block's version field. This is supposed to be `4`:
    ///
    /// > The current and only defined block version number for Zcash is 4.
    ///
    /// but this was not enforced by the consensus rules, and defective mining
    /// software created blocks with other versions, so instead it's effectively
    /// a free field. The only constraint is that it must be at least `4` when
    /// interpreted as an `i32`.
    ///
    /// Size [bytes]: 4
    pub version: i32,

    /// The hash of the previous block, used to create a chain of blocks back to
    /// the genesis block.
    ///
    /// This ensures no previous block can be changed without also changing this
    /// block's header.
    ///
    /// Size [bytes]: 32
    pub hash_prev_block: Vec<u8>,

    /// The root of the Bitcoin-inherited transaction Merkle tree, binding the
    /// block header to the transactions in the block.
    ///
    /// Note that because of a flaw in Bitcoin's design, the `merkle_root` does
    /// not always precisely bind the contents of the block (CVE-2012-2459). It
    /// is sometimes possible for an attacker to create multiple distinct sets of
    /// transactions with the same Merkle root, although only one set will be
    /// valid.
    ///
    /// Size [bytes]: 32
    pub hash_merkle_root: Vec<u8>,

    /// [Pre-Sapling] A reserved field which should be ignored.
    /// [Sapling onward] The root LEBS2OSP_256(rt) of the Sapling note
    /// commitment tree corresponding to the final Sapling treestate of this
    /// block.
    ///
    /// Size [bytes]: 32
    pub hash_final_sapling_root: Vec<u8>,

    /// The block timestamp is a Unix epoch time (UTC) when the miner
    /// started hashing the header (according to the miner).
    ///
    /// Size [bytes]: 4
    pub time: u32,

    /// An encoded version of the target threshold this block's header
    /// hash must be less than or equal to, in the same nBits format
    /// used by Bitcoin.
    ///
    /// For a block at block height `height`, bits MUST be equal to
    /// `ThresholdBits(height)`.
    ///
    /// [Bitcoin-nBits](https://bitcoin.org/en/developer-reference#target-nbits)
    ///
    /// Size [bytes]: 4
    pub n_bits_bytes: Vec<u8>,

    /// An arbitrary field that miners can change to modify the header
    /// hash in order to produce a hash less than or equal to the
    /// target threshold.
    ///
    /// Size [bytes]: 32
    pub nonce: Vec<u8>,

    /// The Equihash solution.
    ///
    /// Size [bytes]: CompactLength
    pub solution: Vec<u8>,
}

impl ParseFromSlice for BlockHeaderData {
    fn parse_from_slice(
        data: &[u8],
        txid: Option<Vec<Vec<u8>>>,
        tx_version: Option<u32>,
    ) -> Result<(&[u8], Self), ParseError> {
        if txid.is_some() {
            return Err(ParseError::InvalidData(
                "txid must be None for BlockHeaderData::parse_from_slice".to_string(),
            ));
        }
        if tx_version.is_some() {
            return Err(ParseError::InvalidData(
                "tx_version must be None for BlockHeaderData::parse_from_slice".to_string(),
            ));
        }
        let mut cursor = Cursor::new(data);

        let version = read_i32(&mut cursor, "Error reading BlockHeaderData::version")?;
        let hash_prev_block = read_bytes(
            &mut cursor,
            32,
            "Error reading BlockHeaderData::hash_prev_block",
        )?;
        let hash_merkle_root = read_bytes(
            &mut cursor,
            32,
            "Error reading BlockHeaderData::hash_merkle_root",
        )?;
        let hash_final_sapling_root = read_bytes(
            &mut cursor,
            32,
            "Error reading BlockHeaderData::hash_final_sapling_root",
        )?;
        let time = read_u32(&mut cursor, "Error reading BlockHeaderData::time")?;
        let n_bits_bytes = read_bytes(
            &mut cursor,
            4,
            "Error reading BlockHeaderData::n_bits_bytes",
        )?;
        let nonce = read_bytes(&mut cursor, 32, "Error reading BlockHeaderData::nonce")?;

        let solution = {
            let compact_length = CompactSize::read(&mut cursor)?;
            read_bytes(
                &mut cursor,
                compact_length as usize,
                "Error reading BlockHeaderData::solution",
            )?
        };

        Ok((
            &data[cursor.position() as usize..],
            BlockHeaderData {
                version,
                hash_prev_block,
                hash_merkle_root,
                hash_final_sapling_root,
                time,
                n_bits_bytes,
                nonce,
                solution,
            },
        ))
    }
}

impl BlockHeaderData {
    /// Serializes the block header into a byte vector.
    pub fn to_binary(&self) -> Result<Vec<u8>, ParseError> {
        let mut buffer = Vec::new();

        buffer.extend(&self.version.to_le_bytes());
        buffer.extend(&self.hash_prev_block);
        buffer.extend(&self.hash_merkle_root);
        buffer.extend(&self.hash_final_sapling_root);
        buffer.extend(&self.time.to_le_bytes());
        buffer.extend(&self.n_bits_bytes);
        buffer.extend(&self.nonce);
        let mut solution_compact_size = Vec::new();
        CompactSize::write(&mut solution_compact_size, self.solution.len())?;
        buffer.extend(solution_compact_size);
        buffer.extend(&self.solution);

        Ok(buffer)
    }

    /// Extracts the block hash from the block header.
    pub fn get_hash(&self) -> Result<Vec<u8>, ParseError> {
        let serialized_header = self.to_binary()?;

        let mut hasher = Sha256::new();
        hasher.update(&serialized_header);
        let digest = hasher.finalize_reset();
        hasher.update(digest);
        let final_digest = hasher.finalize();

        Ok(final_digest.to_vec())
    }
}

/// Complete block header.
#[derive(Debug)]
pub struct FullBlockHeader {
    /// Block header data.
    pub raw_block_header: BlockHeaderData,

    /// Hash of the current block.
    pub cached_hash: Vec<u8>,
}

/// Zingo-Indexer Block.
#[derive(Debug)]
pub struct FullBlock {
    /// The block header, containing block metadata.
    ///
    /// Size [bytes]: 140+CompactLength
    pub hdr: FullBlockHeader,

    /// The block transactions.
    pub vtx: Vec<super::transaction::FullTransaction>,

    /// Block height.
    pub height: i32,
}

impl ParseFromSlice for FullBlock {
    fn parse_from_slice(
        data: &[u8],
        txid: Option<Vec<Vec<u8>>>,
        tx_version: Option<u32>,
    ) -> Result<(&[u8], Self), ParseError> {
        let txid = txid.ok_or_else(|| {
            ParseError::InvalidData("txid must be used for FullBlock::parse_from_slice".to_string())
        })?;
        if tx_version.is_some() {
            return Err(ParseError::InvalidData(
                "tx_version must be None for FullBlock::parse_from_slice".to_string(),
            ));
        }
        let mut cursor = Cursor::new(data);

        let (remaining_data, block_header_data) =
            BlockHeaderData::parse_from_slice(&data[cursor.position() as usize..], None, None)?;
        cursor.set_position(data.len() as u64 - remaining_data.len() as u64);
        let tx_count = CompactSize::read(&mut cursor)?;
        if txid.len() != tx_count as usize {
            return Err(ParseError::InvalidData(format!(
                "number of txids ({}) does not match tx_count ({})",
                txid.len(),
                tx_count
            )));
        }
        let mut transactions = Vec::with_capacity(tx_count as usize);
        let mut remaining_data = &data[cursor.position() as usize..];
        for txid_item in txid.iter() {
            if remaining_data.is_empty() {
                return Err(ParseError::InvalidData(
                    "parsing block transactions: not enough data for transaction.".to_string(),
                ));
            }
            let (new_remaining_data, tx) = FullTransaction::parse_from_slice(
                &data[cursor.position() as usize..],
                Some(vec![txid_item.clone()]),
                None,
            )?;
            transactions.push(tx);
            remaining_data = new_remaining_data;
            cursor.set_position(data.len() as u64 - remaining_data.len() as u64);
        }
        let block_height = Self::get_block_height(&transactions)?;
        let block_hash = block_header_data.get_hash()?;

        Ok((
            remaining_data,
            FullBlock {
                hdr: FullBlockHeader {
                    raw_block_header: block_header_data,
                    cached_hash: block_hash,
                },
                vtx: transactions,
                height: block_height,
            },
        ))
    }
}

/// Genesis block special case.
///
/// From LightWalletD:
/// see https://github.com/zcash/lightwalletd/issues/17#issuecomment-467110828.
const GENESIS_TARGET_DIFFICULTY: u32 = 520617983;

impl FullBlock {
    /// Extracts the block height from the coinbase transaction.
    pub fn get_block_height(transactions: &[FullTransaction]) -> Result<i32, ParseError> {
        let coinbase_script = transactions[0].raw_transaction.transparent_inputs[0]
            .script_sig
            .as_slice();
        let mut cursor = Cursor::new(coinbase_script);

        let height_num: i64 = read_zcash_script_i64(&mut cursor)?;
        if height_num < 0 {
            return Ok(-1);
        }
        if height_num > i64::from(u32::MAX) {
            return Ok(-1);
        }
        if (height_num as u32) == GENESIS_TARGET_DIFFICULTY {
            return Ok(0);
        }

        Ok(height_num as i32)
    }

    /// Decodes a hex encoded zcash full block into a FullBlock struct.
    pub fn parse_full_block(data: &[u8], txid: Option<Vec<Vec<u8>>>) -> Result<Self, ParseError> {
        let (remaining_data, full_block) = Self::parse_from_slice(data, txid, None)?;
        if !remaining_data.is_empty() {
            return Err(ParseError::InvalidData(format!(
                "Error decoding full block - {} bytes of Remaining data. Compact Block Created: ({:?})",
                remaining_data.len(),
                full_block.to_compact(0, 0)
            )));
        }
        Ok(full_block)
    }

    /// Converts a zcash full block into a compact block.
    pub fn to_compact(
        self,
        sapling_commitment_tree_size: u32,
        orchard_commitment_tree_size: u32,
    ) -> Result<CompactBlock, ParseError> {
        let vtx = self
            .vtx
            .into_iter()
            .enumerate()
            .filter_map(|(index, tx)| {
                if tx.has_shielded_elements() {
                    Some(tx.to_compact(index as u64))
                } else {
                    None
                }
            })
            .collect::<Result<Vec<_>, _>>()?;

        // NOTE: LightWalletD doesnt return a compact block header, however this could be used to return data if useful.
        // let header = self.hdr.raw_block_header.to_binary()?;
        let header = Vec::new();

        let compact_block = CompactBlock {
            proto_version: 0,
            height: self.height as u64,
            hash: self.hdr.cached_hash.clone(),
            prev_hash: self.hdr.raw_block_header.hash_prev_block.clone(),
            time: self.hdr.raw_block_header.time,
            header,
            vtx,
            chain_metadata: Some(ChainMetadata {
                sapling_commitment_tree_size,
                orchard_commitment_tree_size,
            }),
        };

        Ok(compact_block)
    }

    /// Decodes a hex encoded zcash full block into a CompactBlock struct.
    pub fn parse_to_compact(
        data: &[u8],
        txid: Option<Vec<Vec<u8>>>,
        sapling_commitment_tree_size: u32,
        orchard_commitment_tree_size: u32,
    ) -> Result<CompactBlock, ParseError> {
        Self::parse_full_block(data, txid)?
            .to_compact(sapling_commitment_tree_size, orchard_commitment_tree_size)
    }
}

/// Returns a compact block.
///
/// Retrieves a full block from zebrad/zcashd using 2 get_block calls.
/// This is because a get_block verbose = 1 call is require to fetch txids.
/// TODO: Save retrieved CompactBlock to the BlockCache.
/// TODO: Return more representative error type.
pub async fn get_block_from_node(
    zebra_uri: &http::Uri,
    height: &u32,
) -> Result<CompactBlock, BlockCacheError> {
    let zebrad_client = JsonRpcConnector::new(
        zebra_uri.clone(),
        Some("xxxxxx".to_string()),
        Some("xxxxxx".to_string()),
    )
    .await?;
    let block_1 = zebrad_client.get_block(height.to_string(), Some(1)).await;
    match block_1 {
        Ok(GetBlockResponse::Object {
            hash,
            confirmations: _,
            height: _,
            time: _,
            tx,
            trees,
        }) => {
            let block_0 = zebrad_client.get_block(hash.0.to_string(), Some(0)).await;
            match block_0 {
                Ok(GetBlockResponse::Object {
                    hash: _,
                    confirmations: _,
                    height: _,
                    time: _,
                    tx: _,
                    trees: _,
                }) => Err(BlockCacheError::ParseError(ParseError::InvalidData(
                    "Received object block type, this should not be possible here.".to_string(),
                ))),
                Ok(GetBlockResponse::Raw(block_hex)) => Ok(FullBlock::parse_to_compact(
                    block_hex.as_ref(),
                    Some(display_txids_to_server(tx)?),
                    trees.sapling() as u32,
                    trees.orchard() as u32,
                )?),
                Err(e) => Err(e.into()),
            }
        }
        Ok(GetBlockResponse::Raw(_)) => Err(BlockCacheError::ParseError(ParseError::InvalidData(
            "Received raw block type, this should not be possible here.".to_string(),
        ))),
        Err(e) => Err(e.into()),
    }
}

/// Returns a compact block holding only action nullifiers.
///
/// Retrieves a full block from zebrad/zcashd using 2 get_block calls.
/// This is because a get_block verbose = 1 call is require to fetch txids.
///
/// TODO / NOTE: This should be rewritten when the BlockCache is added.
pub async fn get_nullifiers_from_node(
    zebra_uri: &http::Uri,
    height: &u32,
) -> Result<CompactBlock, BlockCacheError> {
    match get_block_from_node(zebra_uri, height).await {
        Ok(block) => Ok(CompactBlock {
            proto_version: block.proto_version,
            height: block.height,
            hash: block.hash,
            prev_hash: block.prev_hash,
            time: block.time,
            header: block.header,
            vtx: block
                .vtx
                .into_iter()
                .map(|tx| CompactTx {
                    index: tx.index,
                    hash: tx.hash,
                    fee: tx.fee,
                    spends: tx.spends,
                    outputs: Vec::new(),
                    actions: tx
                        .actions
                        .into_iter()
                        .map(|action| CompactOrchardAction {
                            nullifier: action.nullifier,
                            cmx: Vec::new(),
                            ephemeral_key: Vec::new(),
                            ciphertext: Vec::new(),
                        })
                        .collect(),
                })
                .collect(),
            chain_metadata: Some(ChainMetadata {
                sapling_commitment_tree_size: 0,
                orchard_commitment_tree_size: 0,
            }),
        }),
        Err(e) => Err(e.into()),
    }
}