|
| 1 | +use crate::block::Block; |
| 2 | + |
| 3 | +#[derive(Debug)] |
| 4 | +pub struct Chain { |
| 5 | + block_chain: Vec<Block>, |
| 6 | +} |
| 7 | + |
| 8 | +impl Chain { |
| 9 | + pub fn new() -> Result<Chain, String> { |
| 10 | + Block::new_genesis().map(|b| Chain { |
| 11 | + block_chain: vec![b], |
| 12 | + }) |
| 13 | + } |
| 14 | + |
| 15 | + pub fn get_length(&self) -> usize { |
| 16 | + self.block_chain.len() |
| 17 | + } |
| 18 | + |
| 19 | + pub fn get_lastest_block(&self) -> Option<&Block> { |
| 20 | + self.block_chain.last() |
| 21 | + } |
| 22 | + |
| 23 | + pub fn add_block(&mut self, data: &Vec<String>) -> Result<&Chain, String> { |
| 24 | + let previous_block = self |
| 25 | + .get_lastest_block() |
| 26 | + .ok_or("previous_block not exist.")?; |
| 27 | + let new_block = Block::new(previous_block, 0, data)?; |
| 28 | + |
| 29 | + self.block_chain.push(new_block); // TODO : 안전할까? |
| 30 | + Ok(self) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +#[cfg(test)] |
| 35 | +mod tests { |
| 36 | + |
| 37 | + use super::*; |
| 38 | + |
| 39 | + #[test] |
| 40 | + fn create_chain() { |
| 41 | + let chain = Chain::new().unwrap(); |
| 42 | + |
| 43 | + assert_eq!(chain.block_chain.len(), 1); |
| 44 | + } |
| 45 | + |
| 46 | + #[test] |
| 47 | + fn get_length() { |
| 48 | + let chain = Chain::new().unwrap(); |
| 49 | + |
| 50 | + assert_eq!(chain.get_length(), 1); |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn get_lastest_block() { |
| 55 | + let first_block = Block::new_genesis().unwrap(); |
| 56 | + let second_block = Block::new(&first_block, 0, &vec!["data".to_string()]).unwrap(); |
| 57 | + |
| 58 | + let chain = Chain { |
| 59 | + block_chain: vec![first_block, second_block.clone()], |
| 60 | + }; |
| 61 | + |
| 62 | + assert_eq!(*chain.get_lastest_block().unwrap(), second_block); |
| 63 | + } |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn add_block_to_empty_chain() { |
| 67 | + let mut empty_chain = Chain { |
| 68 | + block_chain: Vec::new(), |
| 69 | + }; |
| 70 | + let result = empty_chain.add_block(&vec!["data".to_string()]); |
| 71 | + |
| 72 | + assert_eq!(result.is_err(), true); |
| 73 | + assert_eq!(empty_chain.block_chain.len(), 0); |
| 74 | + } |
| 75 | + |
| 76 | + #[test] |
| 77 | + fn add_block() { |
| 78 | + let mut chain = Chain::new().unwrap(); |
| 79 | + let added_chain = chain.add_block(&vec!["data".to_string()]).unwrap(); |
| 80 | + |
| 81 | + assert_eq!(added_chain.block_chain.len(), 2); |
| 82 | + } |
| 83 | +} |
0 commit comments