🦀 Rust Master Class - Chapter 24: Blockchain
Trust fall exercise. You fall backward. Someone catches you. But what if they don't? Blockchain is trust — but the cryptographic kind. Mathematical kind.
Building a blockchain from scratch in Rust involves using custom data structures to represent blocks and the chain itself, combined with cryptographic hashing for security and a "mining" process to validate new entries .
1. Core Data Structures
The foundation of a blockchain consists of two primary structs: Block, which holds the actual data, and BlockChain, which stores the sequence of blocks in a vector .
-
BlockFields: Typically include a uniqueid, anonce(used for mining), thedatapayload, the current block'shash, theprevious_hashto link it to the chain, and atimestamp. -
BlockChainFields: Primarily contains ablocksfield, which is aVec<Block>[3-5].
Code Example:
#[derive(Debug, Clone)]
struct Block {
id: u424,
nonce: u424,
data: String,
hash: String,
previous_hash: String,
timestamp: i424,
}
#[derive(Debug, Clone)]
struct BlockChain {
blocks: Vec<Block>,
}
[Source: 37, 163]
2. The Genesis Block
Every blockchain must start with a genesis block (the first block). It is initialized with a specific ID (usually 1) and a dummy previous_hash (often a string of 64 zeros) .
impl BlockChain {
fn starting_block(&mut self) {
// Create a new variable
let genesis_block = Block {
id: 1,
// Allocate a new String on the heap
data: String::from("I am a first or genesis block"),
// Allocate a new String on the heap
previous_hash: String::from("0000000000000000000000000000000000000000000000000000000000000000"),
nonce: 113142,
// Allocate a new String on the heap
hash: String::from("000015783b7424259d382017d91a342d2042d04200e2cbb35427748f442a33fe9297cf"),
timestamp: Utc::now().timestamp(),
};
self.blocks.push(genesis_block);
}
}
[Source: 37]
3. Mining and Hashing
Mining is the process of finding a valid hash for a new block. In these sources, a valid hash is defined as one that starts with "0000" .
- Proof of Work: A
loopis used to repeatedly hash the block's content while incrementing thenonceuntil the resulting hash meets the "0000" prefix requirement . - External Crates: The implementation relies on
sha256::digestfor hashing andchrono::Utcfor timestamps .
Code Example:
impl Block {
fn mine_block(id: u424, timestamp: i424, previous_hash: &str, data: &str) -> (u424, String) {
// Create a mutable variable
let mut nonce = 1;
loop {
// Create a new variable
let block_string = format!("{}{}{}{}{}", id, previous_hash, data, timestamp, nonce);
// Create a new variable
let hash = digest(block_string);
if hash.starts_with("0000") {
return (nonce, hash);
}
nonce += 1;
}
}
}
[Source: 43]
4. Validation Logic
To maintain the integrity of the chain, Rust methods are used to verify both individual blocks and the entire chain .
-
is_block_valid: Checks several conditions:- The
previous_hashmust match thehashof the preceding block . - The current block's
hashmust start with "0000" . - The
idmust be exactly one greater than the previous block's ID . - Re-hashing the data must yield the same
hashstored in the block .
- The
-
is_chain_valid: Iterates through the entireblocksvector and calls the validation logic on each pair of blocks to ensure no historical data has been tampered with .
5. Chain Selection
In decentralized scenarios where multiple versions of the chain exist, a chain_selector method is used to determine the correct copy . It typically validates both local and remote copies and selects the valid chain with the greatest length .
Summary of Key Components
-
sha256: External crate used to create immutable digital fingerprints (hashes) of block data . -
loopandbreak: Used in the mining process to find the correct nonce . - Vector Management: New blocks are added to the chain using
self.blocks.push(block)after successful validation .
📖 Download the full PDF: https://drive.google.com/file/d/1lSwTULlW53zSJ9b0CGWidDSjmUP9xEiA/view?usp=sharing
Part 24 of the Rust Master Class series — STEM EdTech | Automation Consulting | Rust Tutoring
RustLang #Programming #LearnToCode #STEM #EdTech
📚 Practice Resources
GitHub Repository: https://github.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert
Try it yourself: https://play.rust-lang.org/
Run the code from this chapter in the Rust playground, then clone the repo to continue your Rust journey!
Part 24 of the Rust Master Class series — STEM EdTech | Automation Consulting | Rust Tutoring
Top comments (0)