Implemation Using Rust
A Quick Maintain Of Proof od Work using Rust
// So
extern crate sha2;
use sha2::{Digest, Sha256};
use std::time::Instant;
// The block structure
struct Block {
index: u64,
timestamp: u128,
data: String,
prev_hash: String,
hash: String,
nonce: u64,
}
// The Proof of Work struct
struct ProofOfWork {
target: Vec<u8>,
}
impl ProofOfWork {
// Creates a new Proof of Work with a difficulty level
fn new(difficulty: u32) -> Self {
let mut target = vec![255; 32]; // Initialize target with max values (255)
let shift = difficulty / 8;
target[shift as usize] = 255 >> (difficulty % 8); // Adjust the target based on the difficulty level
ProofOfWork { target }
}
// This method calculates the hash of the block with a specific nonce
fn calculate_hash(block: &Block, nonce: u64) -> Vec<u8> {
let data = format!(
"{}{}{}{}{}",
block.index, block.timestamp, block.data, block.prev_hash, nonce
);
let mut hasher = Sha256::new();
hasher.update(data);
hasher.finalize().to_vec()
}
// Perform the proof of work, return the valid hash and nonce
fn mine(&self, block: &Block) -> (Vec<u8>, u64) {
let mut nonce = 0;
let start = Instant::now();
loop {
let hash = ProofOfWork::calculate_hash(block, nonce);
if hash <= self.target {
println!("Block mined! Nonce: {}, Hash: {:x?}", nonce, hash);
println!("Mining took: {:?}", start.elapsed());
return (hash, nonce);
}
nonce += 1;
}
}
}
impl Block {
// Creates a new block
fn new(index: u64, timestamp: u128, data: String, prev_hash: String) -> Self {
Block {
index,
timestamp,
data,
prev_hash,
hash: String::new(),
nonce: 0,
}
}
// Starts mining and returns the mined block
fn mine_block(&mut self, difficulty: u32) {
let pow = ProofOfWork::new(difficulty);
let (hash, nonce) = pow.mine(self);
self.hash = format!("{:x?}", hash);
self.nonce = nonce;
}
}
fn main() {
let mut block = Block::new(1, 1234567890, "Test Block".to_string(), "0".to_string());
// Set the difficulty level (e.g., 16)
let difficulty = 16;
println!("Mining block...");
block.mine_block(difficulty);
// Display the block information
println!("Block mined:");
println!("Index: {}", block.index);
println!("Timestamp: {}", block.timestamp);
println!("Data: {}", block.data);
println!("Prev Hash: {}", block.prev_hash);
println!("Hash: {}", block.hash);
println!("Nonce: {}", block.nonce);
}
Output
Mining block...
Block mined! Nonce: 0, Hash: [78, 7c, ee, 8c, 46, b3, bd, 48, aa, 2b, 85, 25, d6, 30, a9, 96, cc, b0, b9, 81, cf, c2, 6, ca, 71, 53, 33, d3, 32, 2c, 84, 52]
Mining took: 20.417µs
Block mined:
Index: 1
Timestamp: 1234567890
Data: Test Block
Prev Hash: 0
Hash: [78, 7c, ee, 8c, 46, b3, bd, 48, aa, 2b, 85, 25, d6, 30, a9, 96, cc, b0, b9, 81, cf, c2, 6, ca, 71, 53, 33, d3, 32, 2c, 84, 52]
Nonce: 0
Last updated