2019-12-02 16:33:19 +01:00
|
|
|
use chrono::Utc;
|
2021-02-05 22:24:28 +01:00
|
|
|
use sqlite::{Connection, Error, Readable, State, Statement};
|
|
|
|
|
|
|
|
|
|
use crate::{Block, Bytes, Keystore, Transaction};
|
2021-01-20 19:23:41 +01:00
|
|
|
|
|
|
|
|
const DB_NAME: &str = "blockchain.db";
|
2019-12-01 22:45:25 +01:00
|
|
|
|
|
|
|
|
pub struct Blockchain {
|
2021-02-13 23:37:44 +01:00
|
|
|
origin: String,
|
|
|
|
|
pub version: u32,
|
2019-12-01 22:45:25 +01:00
|
|
|
pub blocks: Vec<Block>,
|
2021-01-20 19:23:41 +01:00
|
|
|
last_block: Option<Block>,
|
|
|
|
|
db: Connection,
|
2019-12-01 22:45:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Blockchain {
|
2021-02-13 23:37:44 +01:00
|
|
|
pub fn new(origin: String, version: u32) -> Self {
|
2021-01-20 19:23:41 +01:00
|
|
|
let db = sqlite::open(DB_NAME).expect("Unable to open blockchain DB");
|
2021-02-13 23:37:44 +01:00
|
|
|
let mut blockchain = Blockchain{ origin, version, blocks: Vec::new(), last_block: None, db};
|
2021-01-20 19:23:41 +01:00
|
|
|
blockchain.init_db();
|
2019-12-01 22:45:25 +01:00
|
|
|
blockchain
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-20 19:23:41 +01:00
|
|
|
/// Reads options from DB or initializes and writes them to DB if not found
|
|
|
|
|
fn init_db(&mut self) {
|
|
|
|
|
match self.db.prepare("SELECT * FROM blocks ORDER BY id DESC LIMIT 1;") {
|
|
|
|
|
Ok(mut statement) => {
|
|
|
|
|
while statement.next().unwrap() == State::Row {
|
2021-01-30 14:18:37 +01:00
|
|
|
match Self::get_block_from_statement(&mut statement) {
|
2021-01-20 19:23:41 +01:00
|
|
|
None => { println!("Something wrong with block in DB!"); }
|
|
|
|
|
Some(block) => {
|
|
|
|
|
println!("Loaded last block: {:?}", &block);
|
2021-02-13 23:37:44 +01:00
|
|
|
self.version = block.version;
|
2021-01-20 19:23:41 +01:00
|
|
|
self.last_block = Some(block);
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-02-13 23:37:44 +01:00
|
|
|
println!("Blockchain version from DB = {}", self.version);
|
2021-01-20 19:23:41 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Err(_) => {
|
|
|
|
|
println!("No blockchain database found. Creating new.");
|
|
|
|
|
self.db.execute("
|
|
|
|
|
CREATE TABLE blocks (
|
|
|
|
|
'id' BIGINT,
|
|
|
|
|
'timestamp' BIGINT,
|
2021-02-13 23:37:44 +01:00
|
|
|
'version' TEXT,
|
2021-01-20 19:23:41 +01:00
|
|
|
'difficulty' INTEGER,
|
|
|
|
|
'random' INTEGER,
|
|
|
|
|
'nonce' INTEGER,
|
|
|
|
|
'transaction' TEXT,
|
|
|
|
|
'prev_block_hash' BINARY,
|
|
|
|
|
'hash' BINARY
|
|
|
|
|
);
|
2021-01-30 14:18:37 +01:00
|
|
|
CREATE INDEX block_index ON blocks (id);
|
2021-02-13 23:37:44 +01:00
|
|
|
CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, identity BINARY, confirmation BINARY, method TEXT, data TEXT, pub_key BINARY, signature BINARY);
|
2021-01-30 14:18:37 +01:00
|
|
|
CREATE INDEX ids ON transactions (identity);"
|
2021-01-20 19:23:41 +01:00
|
|
|
).expect("Error creating blocks table");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-01 22:45:25 +01:00
|
|
|
pub fn add_block(&mut self, block: Block) {
|
2021-01-20 19:23:41 +01:00
|
|
|
if self.check_block(&block, &self.last_block) {
|
2019-12-01 22:45:25 +01:00
|
|
|
println!("Adding block:\n{:?}", &block);
|
2021-01-20 19:23:41 +01:00
|
|
|
self.blocks.push(block.clone());
|
|
|
|
|
self.last_block = Some(block.clone());
|
2021-01-30 14:18:37 +01:00
|
|
|
let transaction = block.transaction.clone();
|
|
|
|
|
|
|
|
|
|
{
|
|
|
|
|
// Adding block to DB
|
|
|
|
|
let mut statement = self.db.prepare("INSERT INTO blocks (\
|
2021-02-13 23:37:44 +01:00
|
|
|
id, timestamp, version, difficulty, random,\
|
|
|
|
|
nonce, 'transaction', prev_block_hash, hash)\
|
|
|
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);").unwrap();
|
2021-01-30 14:18:37 +01:00
|
|
|
statement.bind(1, block.index as i64);
|
|
|
|
|
statement.bind(2, block.timestamp as i64);
|
2021-02-13 23:37:44 +01:00
|
|
|
statement.bind(3, block.version as i64);
|
|
|
|
|
statement.bind(4, block.difficulty as i64);
|
|
|
|
|
statement.bind(5, block.random as i64);
|
|
|
|
|
statement.bind(6, block.nonce as i64);
|
2021-01-30 14:18:37 +01:00
|
|
|
match &transaction {
|
2021-02-13 23:37:44 +01:00
|
|
|
None => { statement.bind(7, ""); }
|
2021-01-30 14:18:37 +01:00
|
|
|
Some(transaction) => {
|
2021-02-13 23:37:44 +01:00
|
|
|
statement.bind(7, transaction.to_string().as_ref() as &str);
|
2021-01-30 14:18:37 +01:00
|
|
|
}
|
|
|
|
|
}
|
2021-02-13 23:37:44 +01:00
|
|
|
statement.bind(8, block.prev_block_hash.as_bytes());
|
|
|
|
|
statement.bind(9, block.hash.as_bytes());
|
2021-01-30 14:18:37 +01:00
|
|
|
statement.next().expect("Error adding block to DB");
|
|
|
|
|
}
|
2021-01-20 19:23:41 +01:00
|
|
|
|
2021-01-30 14:18:37 +01:00
|
|
|
match &transaction {
|
|
|
|
|
None => {}
|
|
|
|
|
Some(transaction) => {
|
|
|
|
|
self.add_transaction(transaction);
|
|
|
|
|
}
|
2021-01-20 19:23:41 +01:00
|
|
|
}
|
2019-12-01 22:45:25 +01:00
|
|
|
} else {
|
|
|
|
|
println!("Bad block found, ignoring:\n{:?}", &block);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-30 14:18:37 +01:00
|
|
|
fn add_transaction(&mut self, t: &Transaction) {
|
2021-02-13 23:37:44 +01:00
|
|
|
let mut statement = self.db.prepare("INSERT INTO transactions (identity, confirmation, method, data, pub_key, signature) VALUES (?, ?, ?, ?, ?, ?)").unwrap();
|
2021-01-30 14:18:37 +01:00
|
|
|
statement.bind(1, t.identity.as_bytes());
|
2021-02-13 23:37:44 +01:00
|
|
|
statement.bind(2, t.confirmation.as_bytes());
|
|
|
|
|
statement.bind(3, t.method.as_ref() as &str);
|
|
|
|
|
statement.bind(4, t.data.as_ref() as &str);
|
|
|
|
|
statement.bind(5, t.pub_key.as_bytes());
|
|
|
|
|
statement.bind(6, t.signature.as_bytes());
|
2021-01-30 14:18:37 +01:00
|
|
|
statement.next().expect("Error adding transaction to DB");
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-05 22:24:28 +01:00
|
|
|
pub fn get_block(&self, index: u64) -> Option<Block> {
|
|
|
|
|
match self.db.prepare("SELECT * FROM blocks WHERE id=? LIMIT 1;") {
|
|
|
|
|
Ok(mut statement) => {
|
|
|
|
|
statement.bind(1, index as i64);
|
|
|
|
|
while statement.next().unwrap() == State::Row {
|
|
|
|
|
return match Self::get_block_from_statement(&mut statement) {
|
|
|
|
|
None => {
|
|
|
|
|
println!("Something wrong with block in DB!");
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
Some(block) => {
|
|
|
|
|
println!("Loaded block: {:?}", &block);
|
|
|
|
|
Some(block)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
Err(_) => {
|
|
|
|
|
println!("Can't find block {}", index);
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-30 14:18:37 +01:00
|
|
|
pub fn is_domain_available(&self, domain: &str, keystore: &Keystore) -> bool {
|
|
|
|
|
if domain.is_empty() {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
let identity_hash = Transaction::hash_identity(domain);
|
|
|
|
|
let mut statement = self.db.prepare("SELECT pub_key FROM transactions WHERE identity = ? ORDER BY id DESC LIMIT 1;").unwrap();
|
|
|
|
|
statement.bind(1, identity_hash.as_bytes());
|
|
|
|
|
while let State::Row = statement.next().unwrap() {
|
|
|
|
|
let pub_key = Bytes::from_bytes(statement.read::<Vec<u8>>(0).unwrap().as_slice());
|
|
|
|
|
if !pub_key.eq(&keystore.get_public()) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let parts: Vec<&str> = domain.rsplitn(2, ".").collect();
|
|
|
|
|
if parts.len() > 1 {
|
|
|
|
|
// We do not support third level domains
|
|
|
|
|
if parts.last().unwrap().contains(".") {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
// Checking for available zone, for this domain
|
|
|
|
|
let identity_hash = Transaction::hash_identity(parts.first().unwrap());
|
|
|
|
|
let mut statement = self.db.prepare("SELECT identity FROM transactions WHERE identity = ? ORDER BY id DESC LIMIT 1;").unwrap();
|
|
|
|
|
statement.bind(1, identity_hash.as_bytes());
|
|
|
|
|
while let State::Row = statement.next().unwrap() {
|
|
|
|
|
// If there is such a zone
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
true
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-05 22:24:28 +01:00
|
|
|
pub fn last_block(&self) -> Option<Block> {
|
2021-01-20 19:23:41 +01:00
|
|
|
self.last_block.clone()
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-05 22:24:28 +01:00
|
|
|
pub fn height(&self) -> u64 {
|
|
|
|
|
match self.last_block {
|
|
|
|
|
None => { 0u64 }
|
|
|
|
|
Some(ref block) => {
|
|
|
|
|
block.index
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-20 19:23:41 +01:00
|
|
|
/*pub fn check(&self) -> bool {
|
2019-12-01 22:45:25 +01:00
|
|
|
let mut prev_block = None;
|
|
|
|
|
for block in self.blocks.iter() {
|
2021-01-20 19:23:41 +01:00
|
|
|
if !self.check_block(block, &prev_block) {
|
2019-12-01 22:45:25 +01:00
|
|
|
println!("Block {:?} is bad", block);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
prev_block = Some(block);
|
|
|
|
|
}
|
|
|
|
|
true
|
2021-01-20 19:23:41 +01:00
|
|
|
}*/
|
2019-12-01 22:45:25 +01:00
|
|
|
|
2021-01-20 19:23:41 +01:00
|
|
|
fn check_block(&self, block: &Block, prev_block: &Option<Block>) -> bool {
|
2021-02-05 22:24:28 +01:00
|
|
|
// TODO check if it is already stored, or its height is more than we need
|
2019-12-01 22:45:25 +01:00
|
|
|
if !Self::check_block_hash(block) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
if prev_block.is_none() {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-20 19:23:41 +01:00
|
|
|
return block.prev_block_hash == prev_block.as_ref().unwrap().hash;
|
2019-12-01 22:45:25 +01:00
|
|
|
}
|
|
|
|
|
|
2021-01-30 14:18:37 +01:00
|
|
|
fn get_block_from_statement(statement: &mut Statement) -> Option<Block> {
|
|
|
|
|
let index = statement.read::<i64>(0).unwrap() as u64;
|
|
|
|
|
let timestamp = statement.read::<i64>(1).unwrap();
|
2021-02-13 23:37:44 +01:00
|
|
|
let version = statement.read::<i64>(2).unwrap() as u32;
|
|
|
|
|
let difficulty = statement.read::<i64>(3).unwrap() as usize;
|
|
|
|
|
let random = statement.read::<i64>(4).unwrap() as u32;
|
|
|
|
|
let nonce = statement.read::<i64>(5).unwrap() as u64;
|
|
|
|
|
let transaction = Transaction::from_json(&statement.read::<String>(6).unwrap());
|
|
|
|
|
let prev_block_hash = Bytes::from_bytes(statement.read::<Vec<u8>>(7).unwrap().as_slice());
|
|
|
|
|
let hash = Bytes::from_bytes(statement.read::<Vec<u8>>(8).unwrap().as_slice());
|
|
|
|
|
Some(Block::from_all_params(index, timestamp, version, difficulty, random, nonce, prev_block_hash, hash, transaction))
|
2021-01-30 14:18:37 +01:00
|
|
|
}
|
|
|
|
|
|
2019-12-01 22:45:25 +01:00
|
|
|
pub fn check_block_hash(block: &Block) -> bool {
|
|
|
|
|
// We need to clear Hash value to rehash it without it for check :(
|
|
|
|
|
let mut copy: Block = block.clone();
|
2021-01-18 00:18:35 +01:00
|
|
|
copy.hash = Bytes::default();
|
2019-12-01 22:45:25 +01:00
|
|
|
let data = serde_json::to_string(©).unwrap();
|
|
|
|
|
Block::hash(data.as_bytes()) == block.hash
|
|
|
|
|
}
|
2021-02-05 22:24:28 +01:00
|
|
|
}
|