Skip to content
blockchain.rs 7.57 KiB
Newer Older
use std::collections::HashMap;
Marek Kotewicz's avatar
Marek Kotewicz committed
use std::path::Path;
use std::hash::Hash;
use rocksdb::{DB, WriteBatch, Writable};
Marek Kotewicz's avatar
Marek Kotewicz committed
use util::hash::*;
Marek Kotewicz's avatar
Marek Kotewicz committed
use util::uint::*;
Marek Kotewicz's avatar
Marek Kotewicz committed
use util::rlp::*;
use util::hashdb::*;
use util::overlaydb::*;
Marek Kotewicz's avatar
Marek Kotewicz committed
use util::bytes::*;
Marek Kotewicz's avatar
Marek Kotewicz committed
use blockheader::*;
use block::*;
use verifiedblock::*;
use importroute::*;
use account::*;
use genesis::*;
Marek Kotewicz's avatar
Marek Kotewicz committed
use extras::*;
use transaction::*;
Marek Kotewicz's avatar
Marek Kotewicz committed

pub struct BlockChain {
Marek Kotewicz's avatar
Marek Kotewicz committed
	// rlp list of 3
Marek Kotewicz's avatar
Marek Kotewicz committed
	genesis_block: Bytes,
Marek Kotewicz's avatar
Marek Kotewicz committed
	// genesis block header
Marek Kotewicz's avatar
Marek Kotewicz committed
	_genesis_header: Bytes,
	genesis_hash: H256,
Marek Kotewicz's avatar
Marek Kotewicz committed
	_genesis_state: HashMap<Address, Account>,
Marek Kotewicz's avatar
Marek Kotewicz committed

Marek Kotewicz's avatar
Marek Kotewicz committed
	_last_block_number: U256,
Marek Kotewicz's avatar
Marek Kotewicz committed

Marek Kotewicz's avatar
Marek Kotewicz committed
	// block cache
	blocks: RwLock<HashMap<H256, Bytes>>,
Marek Kotewicz's avatar
Marek Kotewicz committed
	// extra caches
Marek Kotewicz's avatar
Marek Kotewicz committed
	block_details: Extras<H256, BlockDetails>,
	block_hashes: Extras<U256, H256>,
	transaction_addresses: Extras<H256, TransactionAddress>,
	block_logs: Extras<H256, BlockLogBlooms>,
	_blocks_blooms: Extras<H256, BlocksBlooms>,
Marek Kotewicz's avatar
Marek Kotewicz committed

	extras_db: DB,
	blocks_db: DB
Marek Kotewicz's avatar
Marek Kotewicz committed
}

impl BlockChain {
	/// Create new instance of blockchain from given Genesis
	/// 
	/// ```rust
	/// extern crate ethcore_util as util;
	/// extern crate ethcore;
Marek Kotewicz's avatar
Marek Kotewicz committed
	/// use std::env;
	/// use std::str::FromStr;
	/// use ethcore::genesis::*;
	/// use ethcore::blockchain::*;
	/// use util::hash::*;
Marek Kotewicz's avatar
Marek Kotewicz committed
	/// use util::uint::*;
	/// 
	/// fn main() {
Marek Kotewicz's avatar
Marek Kotewicz committed
	/// 	let mut dir = env::temp_dir();
	/// 	dir.push(H32::random().hex());
	///
	/// 	let genesis = Genesis::new_frontier();
Marek Kotewicz's avatar
Marek Kotewicz committed
	/// 	let bc = BlockChain::new(genesis, &dir);
	/// 	let genesis_hash = "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3";
	/// 	assert_eq!(bc.genesis_hash(), &H256::from_str(genesis_hash).unwrap());
Marek Kotewicz's avatar
Marek Kotewicz committed
	/// 	assert!(bc.is_known(bc.genesis_hash()));
	/// 	assert_eq!(bc.genesis_hash(), &bc.number_hash(&U256::from(0u8)).unwrap());
	/// }
	/// ```
Marek Kotewicz's avatar
Marek Kotewicz committed
	pub fn new(genesis: Genesis, path: &Path) -> BlockChain {
		let (genesis_block, genesis_state) = genesis.drain();

		let genesis_header = BlockView::new(&genesis_block).header_view().rlp().raw().to_vec();
		let genesis_hash = HeaderView::new(&genesis_header).sha3();
Marek Kotewicz's avatar
Marek Kotewicz committed

		let genesis_details = BlockDetails {
			number: U256::from(0u64),
			total_difficulty: HeaderView::new(&genesis_header).difficulty(),
Marek Kotewicz's avatar
Marek Kotewicz committed
			parent: H256::new(),
			children: vec![]
Marek Kotewicz's avatar
Marek Kotewicz committed
		let mut extras_path = path.to_path_buf();
		extras_path.push("extras");
		let extras_db = DB::open_default(extras_path.to_str().unwrap()).unwrap();

		let mut blocks_path = path.to_path_buf();
		blocks_path.push("blocks");
		let blocks_db = DB::open_default(blocks_path.to_str().unwrap()).unwrap();
Marek Kotewicz's avatar
Marek Kotewicz committed

		{
Marek Kotewicz's avatar
Marek Kotewicz committed
			let batch = WriteBatch::new();
			batch.put(&genesis_hash.to_extras_slice(ExtrasIndex::BlockDetails), &encode(&genesis_details)).unwrap();
			batch.put(&U256::from(0u8).to_extras_slice(ExtrasIndex::BlockHash), &encode(&genesis_hash)).unwrap();
			extras_db.write(batch).unwrap();
Marek Kotewicz's avatar
Marek Kotewicz committed

Marek Kotewicz's avatar
Marek Kotewicz committed
			blocks_db.put(&genesis_hash, &genesis_block).unwrap();
Marek Kotewicz's avatar
Marek Kotewicz committed
		}
Marek Kotewicz's avatar
Marek Kotewicz committed

Marek Kotewicz's avatar
Marek Kotewicz committed
		BlockChain {
			genesis_block: genesis_block,
Marek Kotewicz's avatar
Marek Kotewicz committed
			_genesis_header: genesis_header,
			genesis_hash: genesis_hash,
Marek Kotewicz's avatar
Marek Kotewicz committed
			_genesis_state: genesis_state,
Marek Kotewicz's avatar
Marek Kotewicz committed
			_last_block_number: U256::from(0u8),
Marek Kotewicz's avatar
Marek Kotewicz committed
			blocks: RwLock::new(HashMap::new()),
			block_details: Extras::new(ExtrasIndex::BlockDetails),
			block_hashes: Extras::new(ExtrasIndex::BlockHash),
			transaction_addresses: Extras::new(ExtrasIndex::TransactionAddress),
			block_logs: Extras::new(ExtrasIndex::BlockLogBlooms),
Marek Kotewicz's avatar
Marek Kotewicz committed
			_blocks_blooms: Extras::new(ExtrasIndex::BlocksBlooms),
Marek Kotewicz's avatar
Marek Kotewicz committed
			extras_db: extras_db,
			blocks_db: blocks_db
Marek Kotewicz's avatar
Marek Kotewicz committed
		}
Marek Kotewicz's avatar
Marek Kotewicz committed
	pub fn genesis_block(&self, db: &OverlayDB) -> Block {
		let root = HeaderView::new(&self.genesis_block).state_root();
Marek Kotewicz's avatar
Marek Kotewicz committed
		if db.exists(&root) {
			return Block::new_existing(db.clone(), root)
		}

Marek Kotewicz's avatar
Marek Kotewicz committed
		let _block = Block::new(db.clone());
		// TODO: commit
		//block.mutable_state().insert_accounts(&self.genesis_state);
Marek Kotewicz's avatar
Marek Kotewicz committed
		// block.mutable_state().db().commit();
		// TODO: set previous block
		// TODO: reset current
Marek Kotewicz's avatar
Marek Kotewicz committed
		unimplemented!()
Marek Kotewicz's avatar
Marek Kotewicz committed
	pub fn verify_block<'a>(&self, _block: &'a [u8]) -> VerifiedBlock<'a> {
		unimplemented!()
Marek Kotewicz's avatar
Marek Kotewicz committed
	pub fn import_block(&self, _block: &[u8], _db: &OverlayDB) -> ImportRoute {
		unimplemented!();
	}

	/// Returns true if the given block is known 
	/// (though not necessarily a part of the canon chain).
	pub fn is_known(&self, hash: &H256) -> bool {
Marek Kotewicz's avatar
Marek Kotewicz committed
		// TODO: consider taking into account current block
Marek Kotewicz's avatar
Marek Kotewicz committed
		self.query_extras_exist(hash, &self.block_details)
Marek Kotewicz's avatar
Marek Kotewicz committed
	}

	/// Returns true if transaction is known.
	pub fn is_known_transaction(&self, hash: &H256) -> bool {
		self.query_extras_exist(hash, &self.transaction_addresses)
	}

	/// Returns reference to genesis hash
	pub fn genesis_hash(&self) -> &H256 {
		&self.genesis_hash
	}

	/// Get the partial-header of a block
	pub fn block_header(&self, hash: &H256) -> Option<Header> {
		self.block(hash).map(|bytes| BlockView::new(&bytes).header())
	}

	/// Get a list of transactions for a given block.
	/// Returns None is block deos not exist.
	pub fn transactions(&self, hash: &H256) -> Option<Vec<Transaction>> {
		self.block(hash).map(|bytes| BlockView::new(&bytes).transactions())
	}

	/// Get a list of transaction hashes for a given block.
	/// Returns None if block does not exist.
	pub fn transaction_hashes(&self, hash: &H256) -> Option<Vec<H256>> {
		self.block(hash).map(|bytes| BlockView::new(&bytes).transaction_hashes())
	}

	/// Get a list of uncles for a given block.
	/// Returns None is block deos not exist.
	pub fn uncles(&self, hash: &H256) -> Option<Vec<Header>> {
		self.block(hash).map(|bytes| BlockView::new(&bytes).uncles())
	}

	/// Get a list of uncle hashes for a given block.
	/// Returns None if block does not exist.
	pub fn uncle_hashes(&self, hash: &H256) -> Option<Vec<H256>> {
		self.block(hash).map(|bytes| BlockView::new(&bytes).uncle_hashes())
	}

	/// Get the familial details concerning a block.
	pub fn block_details(&self, hash: &H256) -> Option<BlockDetails> {
		self.query_extras(hash, &self.block_details)
	}

	/// Get the hash of given block's number
	pub fn number_hash(&self, hash: &U256) -> Option<H256> {
		self.query_extras(hash, &self.block_hashes)
	}

	/// Get the transactions' log blooms of a block
	pub fn log_blooms(&self, hash: &H256) -> Option<BlockLogBlooms> {
		self.query_extras(hash, &self.block_logs)
	}

	fn block(&self, hash: &H256) -> Option<Bytes> {
Marek Kotewicz's avatar
Marek Kotewicz committed
		{
			let read = self.blocks.read().unwrap();
			match read.get(hash) {
				Some(v) => return Some(v.clone()),
				None => ()
			}
		}

		let opt = self.blocks_db.get(hash)
			.expect("Low level database error. Some issue with disk?");

		match opt {
			Some(b) => {
				let bytes: Bytes = b.to_vec();
				let mut write = self.blocks.write().unwrap();
				write.insert(hash.clone(), bytes.clone());
				Some(bytes)
			},
			None => None
		}
	}

	fn query_extras<K, T>(&self, hash: &K, cache: &Extras<K, T>) -> Option<T> where 
Marek Kotewicz's avatar
Marek Kotewicz committed
		T: Clone + Decodable, 
		K: ExtrasSliceConvertable + Eq + Hash + Clone {
		{
			let read = cache.read().unwrap();
			match read.get(hash) {
				Some(v) => return Some(v.clone()),
				None => ()
			}
		}

		let opt = self.extras_db.get(&hash.to_extras_slice(cache.index()))
			.expect("Low level database error. Some issue with disk?");

		match opt {
			Some(b) => {
				let t: T = decode(&b);
				let mut write = cache.write().unwrap();
				write.insert(hash.clone(), t.clone());
				Some(t)
			},
			None => None
		}
	}

	fn query_extras_exist<K, T>(&self, hash: &K, cache: &Extras<K, T>) -> bool where 
Marek Kotewicz's avatar
Marek Kotewicz committed
		K: ExtrasSliceConvertable + Eq + Hash + Clone {
		{
			let read = cache.read().unwrap();
			match read.get(hash) {
				Some(_) => return true,
				None => ()
			}
		}

		let opt = self.extras_db.get(&hash.to_extras_slice(cache.index()))
			.expect("Low level database error. Some issue with disk?");

		opt.is_some()
Marek Kotewicz's avatar
Marek Kotewicz committed
	}
}
Marek Kotewicz's avatar
Marek Kotewicz committed