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
use crate::parser::errors::OpResult;
use crate::parser::reader::BlockchainRead;
use bitcoin::hashes::hex::ToHex;
use bitcoin::BlockHeader;
use leveldb::database::iterator::LevelDBIterator;
use leveldb::database::Database;
use leveldb::iterator::Iterable;
use leveldb::options::{Options, ReadOptions};
use log::info;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
use std::io::Cursor;
use std::path::Path;

const BLOCK_VALID_HEADER: u32 = 1;
const BLOCK_VALID_TREE: u32 = 2;
const BLOCK_VALID_TRANSACTIONS: u32 = 3;
const BLOCK_VALID_CHAIN: u32 = 4;
const BLOCK_VALID_SCRIPTS: u32 = 5;
const BLOCK_VALID_MASK: u32 = BLOCK_VALID_HEADER
    | BLOCK_VALID_TREE
    | BLOCK_VALID_TRANSACTIONS
    | BLOCK_VALID_CHAIN
    | BLOCK_VALID_SCRIPTS;
const BLOCK_HAVE_DATA: u32 = 8;
const BLOCK_HAVE_UNDO: u32 = 16;

// BLOCK_INDEX RECORD

#[derive(Serialize, Clone)]
pub struct BlockIndexRecord {
    pub n_version: i32,
    pub n_height: i32,
    pub n_status: u32,
    pub n_tx: u32,
    pub n_file: i32,
    pub n_data_pos: u32,
    pub n_undo_pos: u32,
    pub block_header: BlockHeader,
}

impl BlockIndexRecord {
    fn from(values: &[u8]) -> OpResult<Self> {
        let mut reader = Cursor::new(values);

        let n_version = reader.read_varint()? as i32;
        let n_height = reader.read_varint()? as i32;
        let n_status = reader.read_varint()? as u32;
        let n_tx = reader.read_varint()? as u32;
        let n_file = if n_status & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO) > 0 {
            reader.read_varint()? as i32
        } else {
            -1
        };
        let n_data_pos = if n_status & BLOCK_HAVE_DATA > 0 {
            reader.read_varint()? as u32
        } else {
            u32::MAX
        };
        let n_undo_pos = if n_status & BLOCK_HAVE_UNDO > 0 {
            reader.read_varint()? as u32
        } else {
            u32::MAX
        };
        let block_header = reader.read_block_header()?;

        Ok(BlockIndexRecord {
            n_version,
            n_height,
            n_status,
            n_tx,
            n_file,
            n_data_pos,
            n_undo_pos,
            block_header,
        })
    }
}

impl fmt::Debug for BlockIndexRecord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BlockIndexRecord")
            .field("version", &self.n_version)
            .field("height", &self.n_height)
            .field("status", &self.n_status)
            .field("n_tx", &self.n_tx)
            .field("n_file", &self.n_file)
            .field("n_data_pos", &self.n_data_pos)
            .field("header", &self.block_header)
            .finish()
    }
}

#[inline]
fn is_block_index_record(data: &[u8]) -> bool {
    *data.get(0).unwrap() == b'b'
}

#[derive(Clone)]
pub struct BlockIndex {
    pub records: Vec<BlockIndexRecord>,
    pub hash_to_height: HashMap<String, i32>,
}

impl BlockIndex {
    pub(crate) fn new(p: &Path) -> OpResult<BlockIndex> {
        let records = load_block_index(p)?;
        let mut hash_to_height = HashMap::with_capacity(records.len());
        for b in &records {
            let this_block_hash = b.block_header.block_hash();
            hash_to_height.insert(this_block_hash.to_hex(), b.n_height);
        }
        hash_to_height.shrink_to_fit();
        Ok(BlockIndex {
            records,
            hash_to_height,
        })
    }
}

struct BlockKey {
    key: Vec<u8>,
}

impl db_key::Key for BlockKey {
    fn from_u8(key: &[u8]) -> Self {
        BlockKey {
            key: Vec::from(key),
        }
    }

    fn as_slice<T, F: Fn(&[u8]) -> T>(&self, f: F) -> T {
        f(&self.key)
    }
}

/// load all block index in memory from disk (i.e. `blocks/index` path)
pub fn load_block_index(path: &Path) -> OpResult<Vec<BlockIndexRecord>> {
    let mut block_index = Vec::with_capacity(800000);

    info!("Start loading block_index");
    let mut options = Options::new();
    options.create_if_missing = false;
    let db: Database<BlockKey> = Database::open(path, options)?;
    let options = ReadOptions::new();
    let mut iter = db.iter(options);

    while iter.advance() {
        let k = iter.key();
        let v = iter.value();
        if is_block_index_record(&k.key) {
            let record = BlockIndexRecord::from(&v)?;
            if record.n_status & (BLOCK_VALID_MASK | BLOCK_HAVE_DATA) > 0 {
                block_index.push(record);
            }
        }
    }
    block_index.sort_by_key(|b| b.n_height);
    info!("Longest chain: {}", &block_index.len());
    Ok(block_index)
}