Technology Sep 03, 2026 · 4 min read

🦀 Rust Master Class - Chapter 24: Blockchain

🦀 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 t...

DE
DEV Community
by Oludayo Adeoye
🦀 Rust Master Class - Chapter 24: Blockchain

🦀 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 .

  • Block Fields: Typically include a unique id, a nonce (used for mining), the data payload, the current block's hash, the previous_hash to link it to the chain, and a timestamp .
  • BlockChain Fields: Primarily contains a blocks field, which is a Vec<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 loop is used to repeatedly hash the block's content while incrementing the nonce until the resulting hash meets the "0000" prefix requirement .
  • External Crates: The implementation relies on sha256::digest for hashing and chrono::Utc for 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:
    1. The previous_hash must match the hash of the preceding block .
    2. The current block's hash must start with "0000" .
    3. The id must be exactly one greater than the previous block's ID .
    4. Re-hashing the data must yield the same hash stored in the block .
  • is_chain_valid: Iterates through the entire blocks vector 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 .
  • loop and break: 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

DE
Source

This article was originally published by DEV Community and written by Oludayo Adeoye.

Read original article on DEV Community
Back to Discover

Reading List