Custom Implementation of Blockchain In Rust(Part 1)

Table of contents
Reading Time: 3 minutes

Hello folks, in this blog, we will be learning how to create our own Blockchain, which is a technology behind Bitcoin. Blockchain technology has been called the greatest innovation since the internet.

A Blockchain is a chain of blocks which contain information. A block contains the following:-
1) Transaction Data:- This contains information about the Sender, Receiver, number of bitcoins to be transferred.

2) PreviousHash:- Hash of previous block, if the previous block data is changed then the previous block hash will also change.

3) Hash:- own hash created using transaction data and previous hash. Hash is basically a Digital Signature.

The first block in the chain is called the Genesis block. Each new block in the chain is linked to the previous block.

Let’s start coding

  1. Create Block and Transaction model
#[derive(Debug)]
pub struct Block {
    pub timestamp: i64,
    pub hash: String,
    pub pre_hash: String,
    pub transaction: Vec<Transaction>,
}

pub struct Transaction {
    pub sender: String,
    pub receiver: String,
    pub amount: f32,
}

2. Implement Digital Signature

As I mentioned above, each block has its own hash. This hash is a digital signature, which is unique to each block and used to validate authenticity and integrity of block content. There are many cryptographic algorithms are available but we will be using SHA-256 for out application.

Add crypto-hash in cargo.toml

[dependencies]
crypto-hash = "0.3.4"

Add calculate_hash in lib.rs

pub fn calculate_hash(
    pre_hash: &String,
    transactions: &Vec<Transaction>,
    timestamp: i64,
) -> String {
    let mut bytes = vec![];
    bytes.extend(&timestamp.to_ne_bytes());
    bytes.extend(
        transactions
            .iter()
            .flat_map(|transaction| transaction.bytes())
            .collect::<Vec<u8>>(),
    );
    bytes.extend(pre_hash.as_bytes());

    crypto_hash::hex_digest(crypto_hash::Algorithm::SHA256, &bytes)
}

3. Build Blockchain

So we are done with Blocks and Digital Signature. Lets now join block together and create our blockchain class.

#[derive(Debug)]
pub struct Blockchain {
    pub blocks: Vec<Block>,
}

impl Blockchain {
    pub fn new() -> Self {
        Blockchain { blocks: vec![] }
    }

    pub fn add_block(&mut self, block: Block) {
        self.blocks.push(block)
    }
}

To test our changes, let’s create couple of blocks and print blockchain.

fn main() {
    let mut blockchain = Blockchain::new();

    let genesis_block = Block::new(
        "0".to_owned(),
        vec![Transaction {
            sender: String::from("Ryan"),
            receiver: String::from("Dan"),
            amount: 2000.0,
        }],
    );

    let first_block = Block::new(
        genesis_block.hash.to_owned(),
        vec![Transaction {
            sender: String::from("Sam"),
            receiver: String::from("Michal"),
            amount: 2500.0,
        }],
    );

    let second_block = Block::new(
        first_block.hash.to_owned(),
        vec![Transaction {
            sender: String::from("Michal"),
            receiver: String::from("Dan"),
            amount: 1000.0,
        }],
    );

    blockchain.add_block(genesis_block);
    blockchain.add_block(first_block);
    blockchain.add_block(second_block);

    println!("{:#?}", blockchain);
}

After executing cargo run we will get a blockchain similar to below JSON.

Blockchain {
    blocks: [
        Block {
            timestamp: 1574012427,
            hash: "2a6da9a14b1ef3101026d94ccf594cac2f91a8d7d9d6d98cb86b416e75c1ecc9",
            pre_hash: "0",
            transaction: [
                Transaction {
                    sender: "Ryan",
                    receiver: "Dan",
                    amount: 2000.0,
                },
            ],
        },
        Block {
            timestamp: 1574012427,
            hash: "e7a765acae3c758bd0403c1728e45a7460c9c3d5d5e1ff0203d52f303290f87f",
            pre_hash: "2a6da9a14b1ef3101026d94ccf594cac2f91a8d7d9d6d98cb86b416e75c1ecc9",
            transaction: [
                Transaction {
                    sender: "Sam",
                    receiver: "Michal",
                    amount: 2500.0,
                },
            ],
        },
        Block {
            timestamp: 1574012427,
            hash: "57be20d1ac9b7e27c6849428fed4d144bc09cab268083bb69419dc4ea69b26bf",
            pre_hash: "e7a765acae3c758bd0403c1728e45a7460c9c3d5d5e1ff0203d52f303290f87f",
            transaction: [
                Transaction {
                    sender: "Michal",
                    receiver: "Dan",
                    amount: 1000.0,
                },
            ],
        },
    ],
}

Now we have got a working chain of block. But we haven’t covered validation, mining, proof of work. We will cover them in next blog. You can find code here rust_blockchain.

Thank you for reading the blog!!


Knoldus-blog-footer-image

Written by 

Ayush is the Sr. Lead Consultant @ Knoldus Software LLP. In his 10 years of experience he has become a developer with proven experience in architecting and developing web applications. Ayush has a Masters in Computer Application from U.P. Technical University, Ayush is a strong-willed and self-motivated professional who takes deep care in adhering to quality norms within projects. He is capable of managing challenging projects with remarkable deadline sensitivity without compromising code quality.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading