Skip to content
Snippets Groups Projects
Commit 678722eb authored by qh11's avatar qh11
Browse files

Update mod.rs

parent afc206f4
No related branches found
No related tags found
No related merge requests found
use crate::types::block::Block;
use crate::types::hash::H256;
use crate::types::block::{Block,generate_genesis_block};
use crate::types::hash::{H256,Hashable};
use std::collections::HashMap;
pub struct Blockchain {
pub blocks: HashMap<H256, Block>,
pub blocks_lens: HashMap<H256, usize>,
pub latest: H256,
}
impl Blockchain {
/// Create a new blockchain, only containing the genesis block
pub fn new() -> Self {
Self {}
let genesis_block : Block = generate_genesis_block();
let mut blocks = HashMap::new();
let mut blocks_lens = HashMap::new();
let latest = genesis_block.hash();
blocks.insert(latest, genesis_block);
blocks_lens.insert(latest, 0);
Blockchain{
blocks: blocks,
latest: latest,
blocks_lens: blocks_lens,
}
}
/// Insert a block into blockchain
pub fn insert(&mut self, block: &Block) {
unimplemented!()
pub fn insert(&mut self, block: &Block) -> bool{
let parent = block.get_parent();
let block_hash = block.hash();
if self.blocks.contains_key(&parent) {
self.blocks.insert(block_hash, block.clone());
let clen = self.blocks_lens[&parent] + 1;
self.blocks_lens.insert(block_hash, clen);
if self.blocks_lens[&self.latest] < clen {
self.latest = block_hash;
}
true
} else {
false
}
}
/// Get the last block's hash of the longest chain
pub fn tip(&self) -> H256 {
unimplemented!()
self.latest
}
/// Get all blocks' hashes of the longest chain, ordered from genesis to the tip
pub fn all_blocks_in_longest_chain(&self) -> Vec<H256> {
// unimplemented!()
vec![]
let gen_parent = H256::from([0;32]); // gen_block_parent
let mut result = Vec::new();
let mut curr = self.latest;
while curr != gen_parent {
result.push(curr);
curr = self.blocks[&curr].get_parent();
}
return result;
}
}
......@@ -46,4 +79,4 @@ mod tests {
}
}
// DO NOT CHANGE THIS COMMENT, IT IS FOR AUTOGRADER. AFTER TEST
\ No newline at end of file
// DO NOT CHANGE THIS COMMENT, IT IS FOR AUTOGRADER. AFTER TEST
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