Last active
June 9, 2025 10:11
-
-
Save brunopgalvao/620924e35525a7375c3eaf8006d1df19 to your computer and use it in GitHub Desktop.
example PoW blockchain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The blockchain itself - a collection of blocks | |
struct Blockchain { | |
chain: Vec<Block>, | |
difficulty: usize, | |
} | |
impl Blockchain { | |
// Create a new blockchain with genesis block | |
fn new() -> Blockchain { | |
let mut blockchain = Blockchain { | |
chain: Vec::new(), | |
difficulty: 2, // Require 2 leading zeros in hash | |
}; | |
// Create the first block (genesis block) | |
blockchain.create_genesis_block(); | |
blockchain | |
} | |
fn create_genesis_block(&mut self) { | |
let mut genesis = Block::new( | |
0, | |
"Genesis Block".to_string(), | |
"0".to_string() | |
); | |
genesis.mine_block(self.difficulty); | |
self.chain.push(genesis); | |
} | |
// Add a new block to the chain | |
fn add_block(&mut self, data: String) { | |
let previous_block = self.chain.last().unwrap(); | |
let mut new_block = Block::new( | |
previous_block.index + 1, | |
data, | |
previous_block.hash.clone() | |
); | |
new_block.mine_block(self.difficulty); | |
self.chain.push(new_block); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment