DEV Community

tomomomomo
tomomomomo

Posted on

1 1 1

My First Blockchain Code with Rust!

Today I started learning blockchain with Rust, and I’m really excited about it.
Here’s what I learned today:

  • I understood the difference between use super:: (relative path) and use crate:: (absolute path). It was confusing at first!
  • I’m getting used to writing struct and adding functions with impl. Sometimes I forget pub though, oops.
  • I wrote this simple blockchain code with Proof of Work. It mines until the hash starts with "0000".
use super::transaction::Transaction;//相対パス
use sha2::{Digest, Sha256};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone)]
pub struct Block {
    pub index: u64,
    pub timestamp: u128,
    pub transactions: Vec<Transaction>,
    pub previous_hash: String,
    pub hash: String,
    pub nonce: u64,
}

impl Block {
    pub fn new(index: u64, transactions: Vec<Transaction>, previous_hash: String) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis();


        let mut block = Block {
            index,
            timestamp,
            transactions,
            previous_hash,
            hash: String::new(),
            nonce: 0,
        };
        block.hash = block.mine();
        block
    }

    pub fn caluculate_hash(&self)-> String {
        let txs_string: String = self.transactions.iter().map(|tx| tx.to_string()).collect();
        let input = format!(
            "{}{}{}{}{}", 
            self.index, self.timestamp, txs_string, self.previous_hash, self.nonce
        );
        let mut hasher = Sha256::new();
        hasher.update(input);
        let result = hasher.finalize();
        hex::encode(result)
    }


    fn mine(&mut self) -> String {
        loop {
            let hash = self.caluculate_hash();
            if hash.starts_with("0000") {
                return hash;
            }
            self.nonce += 1;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Yesterday, I coded a Softmax backward function, so Vec is my friend now (maybe one-sided love?). iter, map, and zip are buddies too, though I didn’t use zip today.

It’s been less than a week since I started, and I’m proud of this progress. It’s so fun to build something! Any tips or feedback would be awesome. Next, I want to try P2P. Thanks for reading!

Image of Timescale

📊 Benchmarking Databases for Real-Time Analytics Applications

Benchmarking Timescale, Clickhouse, Postgres, MySQL, MongoDB, and DuckDB for real-time analytics. Introducing RTABench 🚀

Read full post →

Top comments (1)

Collapse
 
tomomomomomomomo profile image
tomomomomo • Edited

Anyway, Grok helps me write English.
First I wrote it by myself.
↓↓

”My First Blockchain code
Today I learned the beginning part of blockchain.
I am interested in blockchain.
What I learned today.
I didn’t know the difference “use super::” and “use crates::”.
Now I know the previous one is a relative path and the latter one is an absolute path.
I am getting familiar with how to write struct and implement function to struct.
For less than a week, it is so good progress for me.
Sometimes I forget to put ‘pub’ in front of func.
Yesterday I wrote a Softmax backward function, so Vec is also my friend! It’s a probably one-side love.
Iter, map, and zip (today I didn’t use) are also my friends.
So It was very fun.”

Then Grok fixed my English.
I want to learn a lot from sentences rewrited.
Thank you.

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay