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) anduse crate::
(absolute path). It was confusing at first! - I’m getting used to writing
struct
and adding functions withimpl
. Sometimes I forgetpub
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;
}
}
}
- Yesterday, I coded a Softmax backward function, so
Vec
is my friend now (maybe one-sided love?).iter
,map
, andzip
are buddies too, though I didn’t usezip
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!
Top comments (1)
Anyway, Grok helps me write English.
First I wrote it by myself.
↓↓
Then Grok fixed my English.
I want to learn a lot from sentences rewrited.
Thank you.