Basic Blockchain Example Code

struct Block {
    nonce: u64,
    prev_hash: String,
    transactions: Vec<String>,
}

struct Blockchain {
    blocks: Vec<Block>,
}

impl Blockchain {
    fn new() -> Blockchain {
        let mut blockchain = Blockchain { blocks: Vec::new() };
        blockchain.add_block(0, "0".to_string());
        blockchain
    }

    fn add_block(&mut self, nonce: u64, prev_hash: String) -> &Block {
        let block = Block {
            nonce,
            prev_hash,
            transactions: Vec::new(),
        };
        self.blocks.push(block);
        &self.blocks[self.blocks.len() - 1]
    }
}

fn main() {
    let mut chain = Blockchain::new();
    chain.add_block(5, "hash for 0".to_string());
    chain.add_block(6, "hash for 1".to_string());

    for (i, block) in chain.blocks.iter().enumerate() {
        println!("block {}", i);
        println!("nonce: {}", block.nonce);
        println!("prev_hash: {}", block.prev_hash);
        println!("transactions: {:?} \r\n", block.transactions);
    }
}

This code defines a Block struct using the Rust Programming Language with fields for the nonce, previous hash, and transactions, and a Blockchain struct with a field for a list of blocks. The Blockchain struct has an implementation with a new method that creates a new empty blockchain and adds a block with a nonce of 0 and a previous hash of “0” and an add_block method that adds a new block to the chain with a specified nonce and previous hash.

In the main function, we create a new blockchain, add two blocks to it, and then iterate over the blocks in the chain, printing the nonce, previous hash, and transactions for each block.

Output:

block 0
nonce: 0
prev_hash: 0
transactions: [] 

block 1
nonce: 5
prev_hash: hash for 0
transactions: [] 

block 2
nonce: 6
prev_hash: hash for 1
transactions: []

rust playground

By Burt Snyder

Writing about interesting things and sharing ideas.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.