Rust 实现简单区块链
Posted 广州吴彦祖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rust 实现简单区块链相关的知识,希望对你有一定的参考价值。
85 行 Rust 实现一个简单的区块链
概述
这篇文章只是把之前写的 C 语言区块链用 Rust 实现了下,并且使用了 md5 作为哈希函数。本文只是为了 Rust 练手,不得不说这语言学起来难但是用起来真爽哈哈哈
区块链 = 由区块顺次连接形成的链
Cargo.toml
[dependencies]
chrono = "*"
rust-crypto = "^0.2"
组成
-
区块
#[derive(Debug)] struct Block prevHash: String, timeStamp: i64, hash: String, body: String,
-
区块链
struct BlockChain block: Vec<Block>, height: i64,
完整代码
use std::os::unix::raw::time_t;
use chrono::prelude::*;
use crypto::digest::Digest;
use crypto::md5::Md5;
#[derive(Debug)]
struct Block
prevHash: String,
timeStamp: i64,
hash: String,
body: String,
struct BlockChain
block: Vec<Block>,
height: i64,
impl Block
fn new(prevHash: String, body: String) -> Block
let timeStamp = Block::timeStamp();
let hash = Block::md5(format!("--", prevHash, timeStamp, body).as_str());
Block
prevHash,
timeStamp: timeStamp,
hash: hash,
body,
fn timeStamp() -> i64
(Local::now()).timestamp_millis()
fn md5(input: &str) -> String
let mut md5 = Md5::new();
md5.input_str(input);
md5.result_str()
impl BlockChain
// 创建区块链对象时自动创建创世区块
fn new() -> BlockChain
let mut blockChain = BlockChain
block: vec![],
height: 0
;
blockChain.block.push(Block::new(
"c87ffbd5d8dabb535b673c5d1b8197d5".to_string(),
"广州吴彦祖 - 创世区块".to_string()
));
blockChain.height += 1;
blockChain
fn addBlock(&mut self, prevHash: String, body: String)
self.block.push(Block::new(
prevHash,
body
));
self.height += 1;
fn main()
let mut blockChain = BlockChain::new();
blockChain.addBlock(
"this is block A".to_string(),
"this is Block A data".to_string(),
);
blockChain.addBlock(
"this is block B".to_string(),
"this is Block B data".to_string(),
);
for x in blockChain.block
println!(":#?", x);
允许结果
Block
prevHash: "c87ffbd5d8dabb535b673c5d1b8197d5",
timeStamp: 1639814280102,
hash: "33ece6ba97133882800a8dd22ac49a19",
body: "广州吴彦祖 - 创世区块",
Block
prevHash: "this is block A",
timeStamp: 1639814280102,
hash: "0565ce1ca7a0adc5a8ec3cad9e7102b4",
body: "this is Block A data",
Block
prevHash: "this is block B",
timeStamp: 1639814280102,
hash: "5774ea1a98ecdd884dd4e58c0168ffa6",
body: "this is Block B data",
以上是关于Rust 实现简单区块链的主要内容,如果未能解决你的问题,请参考以下文章