Skip to content
Snippets Groups Projects
Commit ea65c9ec authored by vinithk2's avatar vinithk2
Browse files

completed part3

parent 29445987
No related branches found
No related tags found
No related merge requests found
block is generated
block is generated
difficulty 00087718210e0b3b608814e04e61fde06d0df794319a12162f287412df3ec920
BLocks = 227
time = 7.181
rate = 31.61 blocks/sec
difficulty = 00007718210e0b3b608814e04e61fde06d0df794319a12162f287412df3ec920
blocks = 37
time = 16.399
rate = 2.25
difficulty = 00000718210e0b3b608814e04e61fde06d0df794319a12162f287412df3ec920
blocks = 2
time = 21.859
rate = .091
\ No newline at end of file
......@@ -43,7 +43,7 @@ pub fn generate_random_block(parent: &H256) -> Block {
let r1:u32 = rng.gen();
let r2:u128 = rng.gen();
//let mut buffer: [u8; 32] = [0; 32];
let b:H256 = hex!("00087718210e0b3b608814e04e61fde06d0df794319a12162f287412df3ec920").into();
let b:H256 = hex!("00001718210e0b3b608814e04e61fde06d0df794319a12162f287412df3ec920").into();
let h:Header = Header{parenthash:*parent,nonce:r1,difficulty:b,timestamp:r2,merkle_root:b};
let t = transaction::generate_random_transaction();
//transaction::pr();
......@@ -53,3 +53,17 @@ pub fn generate_random_block(parent: &H256) -> Block {
let b:Block = Block{header:h,content:c};
b
}
pub fn generate_genesis_block(parent: &H256) -> Block {
let b:H256 = hex!("00001718210e0b3b608814e04e61fde06d0df794319a12162f287412df3ec920").into();
let r1:u32 = 0;
let r2:u128 = 0;
let h:Header = Header{parenthash:*parent,nonce:r1,difficulty:b,timestamp:r2,merkle_root:b};
let t = transaction::generate_genesis_transaction();
//transaction::pr();
let mut vect:Vec<Transaction> = vec![];
vect.push(t);
let c:Content = Content{data:vect};
let b:Block = Block{header:h,content:c};
b
}
......@@ -6,8 +6,8 @@ use std::collections::HashMap;
pub struct Blockchain {
pub chain:HashMap<H256,Block>,
pub tiphash:H256,
heights:HashMap<H256,u8>,
buffer:HashMap<H256,Block>,
pub heights:HashMap<H256,u8>,
pub buffer:HashMap<H256,Block>,
}
impl Blockchain {
......@@ -15,7 +15,7 @@ impl Blockchain {
pub fn new() -> Self {
let mut buffer: [u8; 32] = [0; 32];
let b:H256 = buffer.into();
let mut genesis:Block = block::generate_random_block(&b);
let mut genesis:Block = block::generate_genesis_block(&b);
let mut genhash:H256 = genesis.hash();
let mut chainmap:HashMap<H256,Block> = HashMap::new();
let mut heightsmap:HashMap<H256,u8> = HashMap::new();
......@@ -50,8 +50,8 @@ impl Blockchain {
if blck.header.parenthash == h {
flag = true;
bhash_copy = *bhash;
self.chain.insert(h,block.clone());
let len = self.heights[&block.header.parenthash]+1;
self.chain.insert(h,blck.clone());
let len = self.heights[&blck.header.parenthash]+1;
self.heights.insert(h,len);
if(len>self.heights[&self.tiphash]){
self.tiphash = h;
......
......@@ -61,10 +61,20 @@ fn main() {
// create channels between server and worker
let (msg_tx, msg_rx) = channel::unbounded();
// start the p2p server
let (server_ctx, server) = server::new(p2p_addr, msg_tx).unwrap();
server_ctx.start().unwrap();
// start the miner
let blockchain = Arc::new(Mutex::new(blockchain::Blockchain::new()));
let (miner_ctx, miner) = miner::new(
&server,
&blockchain,
);
miner_ctx.start();
// start the worker
let p2p_workers = matches
.value_of("p2p_workers")
......@@ -78,16 +88,11 @@ fn main() {
p2p_workers,
msg_rx,
&server,
&blockchain,
);
worker_ctx.start();
// start the miner
let blockchain = Arc::new(Mutex::new(blockchain::Blockchain::new()));
let (miner_ctx, miner) = miner::new(
&server,
&blockchain,
);
miner_ctx.start();
// connect to known peers
if let Some(known_peers) = matches.values_of("known_peer") {
......
......@@ -3,7 +3,7 @@ use crate::blockchain::Blockchain;
use crate::block::*;
use crate::transaction::{self, Transaction};
use crate::crypto::hash::{H256, Hashable};
use crate::network::message::Message;
use log::info;
use rand::Rng;
use crossbeam::channel::{unbounded, Receiver, Sender, TryRecvError};
......@@ -28,13 +28,15 @@ pub struct Context {
control_chan: Receiver<ControlSignal>,
operating_state: OperatingState,
server: ServerHandle,
blockchain: Arc<Mutex<Blockchain>>
blockchain: Arc<Mutex<Blockchain>>,
num_mined:u8,
}
#[derive(Clone)]
pub struct Handle {
/// Channel for sending signal to the miner thread
control_chan: Sender<ControlSignal>,
}
pub fn new(
......@@ -47,7 +49,8 @@ pub fn new(
control_chan: signal_chan_receiver,
operating_state: OperatingState::Paused,
server: server.clone(),
blockchain: Arc::clone(blockchain)
blockchain: Arc::clone(blockchain),
num_mined:0,
};
let handle = Handle {
......@@ -67,7 +70,6 @@ impl Handle {
.send(ControlSignal::Start(lambda))
.unwrap();
}
}
impl Context {
......@@ -120,23 +122,23 @@ impl Context {
}
// actual mining
// create Block
//TODO: Put this in a function
//Creating Header fields
let mut locked_blockchain = self.blockchain.lock().unwrap();
let phash = locked_blockchain.tiphash;
let mut rng = rand::thread_rng();
let nonce = rng.gen();
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis();
let difficulty = locked_blockchain.chain.get(&locked_blockchain.tiphash)
.unwrap()
.header
.difficulty ;
//Creating Content
//It will also be used for Merkel Root for the Header
let t = transaction::generate_random_transaction();
......@@ -144,7 +146,7 @@ impl Context {
vect.push(t);
let content: Content = Content{data:vect};
let merkle_root = H256::from([0; 32]);
let merkle_root = H256::from([0; 32]);
//Putting all together
let header = Header{
......@@ -155,12 +157,17 @@ impl Context {
merkle_root: merkle_root
};
let new_block = Block{header: header, content: content};
//Check whether block solved the puzzle
//If passed, add it to blockchain
if new_block.hash() <= difficulty {
print!("block is generated\n");
print!("block with hash:{} generated\n",new_block.hash());
print!("Number of blocks mined until now:{}\n",self.num_mined+1);
locked_blockchain.insert(&new_block);
print!("Total number of blocks in blockchain:{}\n",locked_blockchain.chain.len());
self.num_mined = self.num_mined + 1;
let mut new_block_hash : Vec<H256> = vec![];
new_block_hash.push(new_block.hash());
self.server.broadcast(Message::NewBlockHashes(new_block_hash));
}
if let OperatingState::Run(i) = self.operating_state {
......
use serde::{Serialize, Deserialize};
use crate::crypto::hash::{H256, Hashable};
use crate::block::{self, *};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum Message {
Ping(String),
Pong(String),
NewBlockHashes(Vec<H256>),
GetBlocks(Vec<H256>),
Blocks(Vec<Block>),
}
......@@ -3,25 +3,31 @@ use super::peer;
use crate::network::server::Handle as ServerHandle;
use crossbeam::channel;
use log::{debug, warn};
use crate::blockchain::Blockchain;
use crate::block::*;
use std::sync::{Arc, Mutex};
use std::thread;
use crate::crypto::hash::{H256, Hashable};
#[derive(Clone)]
pub struct Context {
msg_chan: channel::Receiver<(Vec<u8>, peer::Handle)>,
num_worker: usize,
server: ServerHandle,
blockchain: Arc<Mutex<Blockchain>>,
}
pub fn new(
num_worker: usize,
msg_src: channel::Receiver<(Vec<u8>, peer::Handle)>,
server: &ServerHandle,
blockchain: &Arc<Mutex<Blockchain>>
) -> Context {
Context {
msg_chan: msg_src,
num_worker,
server: server.clone(),
blockchain: Arc::clone(blockchain),
}
}
......@@ -42,6 +48,7 @@ impl Context {
let msg = self.msg_chan.recv().unwrap();
let (msg, peer) = msg;
let msg: Message = bincode::deserialize(&msg).unwrap();
let mut locked_blockchain = self.blockchain.lock().unwrap();
match msg {
Message::Ping(nonce) => {
debug!("Ping: {}", nonce);
......@@ -50,6 +57,69 @@ impl Context {
Message::Pong(nonce) => {
debug!("Pong: {}", nonce);
}
Message::NewBlockHashes(vec_hashes) => {
let mut required_blocks:Vec<H256> = vec![];
debug!("Received New Block Hashes");
let mut flag:bool = false;
for recv_hash in vec_hashes {
flag = false;
for (bhash,blck) in locked_blockchain.chain.iter(){
if *bhash == recv_hash{
debug!("Block that hashes to {} already present", bhash);
flag = true;
}
}
for (bhash,blck) in locked_blockchain.buffer.iter(){
if *bhash == recv_hash {
debug!("Block that hashes to {} already present", bhash);
flag = true;
}
}
if !flag {
required_blocks.push(recv_hash);
}
}
if required_blocks.len()!= 0 {
debug!("Sending getBlocks Message");
peer.write(Message::GetBlocks(required_blocks));
}
}
Message::GetBlocks(vec_hashes) => {
let mut give_blocks:Vec<Block> = vec![];
debug!("Received GetBlocks");
for getblock_hash in vec_hashes {
for (bhash,blck) in locked_blockchain.chain.iter(){
if *bhash == getblock_hash{
debug!("Adding block with hash {} to give_blocks", bhash);
give_blocks.push(blck.clone());
}
}
for (bhash,blck) in locked_blockchain.buffer.iter(){
if *bhash == getblock_hash {
debug!("Adding block with hash {} to give_blocks", bhash);
give_blocks.push(blck.clone());
}
}
}
if give_blocks.len()!=0 {
debug!("Sending Blocks message");
peer.write(Message::Blocks(give_blocks));
}
}
Message::Blocks(vec_blocks) => {
for blck in vec_blocks {
locked_blockchain.insert(&blck);
debug!("Adding block with hash {} to chain",blck.hash());
print!("Total number of blocks in blockchain:{}\n",locked_blockchain.chain.len());
let mut new_block_hash : Vec<H256> = vec![];
new_block_hash.push(blck.hash());
self.server.broadcast(Message::NewBlockHashes(new_block_hash));
}
}
}
}
}
......
......@@ -51,6 +51,15 @@ pub fn generate_random_transaction() -> Transaction {
Transaction{input : input_bytes,output : output_bytes}
}
pub fn generate_genesis_transaction() -> Transaction {
/*Default::default();*/
let zero_bytes1: Vec<u8> = vec![0,32];
let zero_bytes2: Vec<u8> = vec![0;32];
Transaction{input : zero_bytes1,output : zero_bytes2}
}
#[cfg(any(test, test_utilities))]
pub mod tests {
use super::*;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment