【Rust】PoWをしてBlockを生成しよう

fn main(){
    let previous_hash = "b9b9ee9ffc95fa4956b63b6043a99d0a8f04e0e52e687fc1958d3c6dff885f01";
    let mut num = rand::thread_rng().gen_range(0..1000000);
    let mut hash_num = format!("{}{}", previous_hash, num.to_string());
    let mut header = Sha256::digest(hash_num);
    let mut target: String  = (&hex::encode(header)[..4]).to_string();
    
    let mut cnt = 1;
    println!("count: {} {:x}", cnt, header);

    while target != "0000" {
        println!("count: {} {:x}", cnt, header);
        num = rand::thread_rng().gen_range(0..1000000);
        hash_num = format!("{}{}", previous_hash, num.to_string());
        header = Sha256::digest(hash_num);
        target = (&hex::encode(header)[..4]).to_string();
        cnt += 1;
    }
    println!("count: {} {:x}", cnt, header);

    let t = vec!["sender".to_string(), "receiver".to_string(), "amount".to_string()];
    let utc_datetime: DateTime<Utc> = Utc::now();
    let b = Block{time:utc_datetime.to_string(), transactions: t, hash: hex::encode(header).to_string(), nonce:num.to_string()};
    println!("{:?}", b);
}

$ cargo run

Block { time: “2025-01-04 00:22:15.386703002 UTC”, transactions: [“sender”, “receiver”, “amount”], hash: “0000cef5d82d7d11f5e90aab7439a128e5877ee6e6b8da31301a6359d74b5503”, nonce: “494683” }

なるほど、こういう仕組みなのか!
うん、悪くないかも
これで、トランザクションの箇所を、Postされてきたデータの構造体に置き換えると…

#[derive(Debug, Serialize, Clone, Deserialize)]
struct Block {
    time: String,
    transactions: Vec<SignedTransaction>,
    hash: String,
    nonce: String,
}

$ cargo run

Block { time: “2025-01-04 00:31:53.015599503 UTC”, transactions: [SignedTransaction { time: “2024-12-25 22:53:36.824066840 UTC”, sender: “5bac6cb0f4ad6397752c3d73b88c5c86e3d88ac695118494a1732e2abd16c76acad3d6586c37c8db7e69c2f812f99275198936957d72c38d71981991123”, receiver: “4bac6cb0f4ad6397752c3d73b88c5c86e3d88ac695118494a1732e2abd16c76acad3d6586c37c8db7e69c2f812f99275198936957d72c38d71981991124”, amount: 10, signature: “8000E340A55A517D0F27F3A63FBE39ED576BA491DFAC89B44654AB147EC66B206B054BAAF53E318EB2721DC892B4736630F400547989AE9F7C069034ECB4DF98” }, SignedTransaction { time: “2024-12-25 22:53:36.824066840 UTC”, sender: “4bac6cb0f4ad6397752c3d73b88c5c86e3d88ac695118494a1732e2abd16c76acad3d6586c37c8db7e69c2f812f99275198936957d72c38d71981991123”, receiver: “4bac6cb0f4ad6397752c3d73b88c5c86e3d88ac695118494a1732e2abd16c76acad3d6586c37c8db7e69c2f812f99275198936957d72c38d71981991124”, amount: 10, signature: “8000E340A55A517D0F27F3A63FBE39ED576BA491DFAC89B44654AB147EC66B206B054BAAF53E318EB2721DC892B4736630F400547989AE9F7C069034ECB4DF98” }], hash: “0000f5b116872033b276499b3e039b03fc4753aaa4e400f2cce856c358d2d51f”, nonce: “4961” }
blockを作成しました。

SignedTransactionがvectorとしてblockの中に入ります。
おおおおおおおおおおおおおお
基本的な形はできたやん
次の課題として、
– blockをjsonデータとして保存する
– genesis blockと生成したblockを繋げていく処理を検討する

【Rust】構造体(struct)の要素にvector

#[derive(Debug, Serialize, Clone, Deserialize)]
struct Name {
    family: String,
    first: String,
    age: u32,
    hobby: Vec<String>,
}

fn main(){
    let n1 = Name {family: "yamada".to_string(), first: "taro".to_string(), age: 20, hobby: vec!["サッカー".to_string(), "旅行".to_string()]};

    println!("{:?}", n1);
}

$ cargo run
Compiling sample v0.1.0 (/home/vagrant/dev/rust/sample)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.34s
Running `target/debug/sample`
Name { family: “yamada”, first: “taro”, age: 20, hobby: [“サッカー”, “旅行”] }

VecのところをVec<(構造体名)>でもできる。ちょっとややこしいけど…

use serde::{Serialize, Deserialize};
use once_cell::sync::Lazy;
use std::sync::Mutex;
use std::ops::DerefMut;


#[derive(Debug, Serialize, Clone, Deserialize)]
struct Name {
    family: String,
    first: String,
    age: u32,
    note: String,
}

#[derive(Debug, Serialize, Clone, Deserialize)]
struct list {
    family: String,
    first: String,
    age: u32,
    note: Vec<Name>,
}

static VECT: Lazy<Mutex<Vec<Name>>> = Lazy::new(|| Mutex::new(vec![]));

fn push_name() {
    let n1 = Name {family: "yamada".to_string(), first: "taro".to_string(), age: 20, note: "AAA".to_string()};
    VECT.lock().unwrap().push(n1);
    let n2 = Name {family: "tanaka".to_string(), first: "kazuo".to_string(), age: 18, note: "BBB".to_string()};
    VECT.lock().unwrap().push(n2);
    let n3 = Name {family: "sato".to_string(), first: "hanako".to_string(), age: 22, note: "CCC".to_string()};
    VECT.lock().unwrap().push(n3);
}

fn main(){
    push_name();

    let mut binding = VECT.lock().unwrap();
    let objs = binding.deref_mut();

    let l1 = list {family: "yamada".to_string(), first: "taro".to_string(), age: 20, note: objs.to_vec()};

    println!("{:?}", l1);
}

$ cargo run
Compiling sample v0.1.0 (/home/vagrant/dev/rust/sample)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/sample`
Name2 { family: “yamada”, first: “taro”, age: 20, note: [Name { family: “yamada”, first: “taro”, age: 20, note: “AAA” }, Name { family: “tanaka”, first: “kazuo”, age: 18, note: “BBB” }, Name { family: “sato”, first: “hanako”, age: 22, note: “CCC” }] }

うむ、普通に出来ますね。これをマイニング終了のタイミングでBlockとトランザクションで作りたい。

use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Clone, Deserialize)]
struct Block {
    time: String,
    transactions: Vec<String>,
    hash: String,
    nonce: String,
}

fn main(){
    let t = vec!["sender".to_string(), "receiver".to_string(), "amount".to_string()];
    let b = Block{time:"a".to_string(), transactions: t, hash:"aaa".to_string(), nonce:"aaa".to_string()};
    println!("{:?}", b);
}

$ cargo run
Compiling sample v0.1.0 (/home/vagrant/dev/rust/sample)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/sample`
Block { time: “a”, transactions: [“sender”, “receiver”, “amount”], hash: “aaa”, nonce: “aaa” }

これを作っていきます!

【C++】構造体の中にvectorを定義

### 構造体(struct)の中にVectorを入れようとすると

#include <iostream>
using namespace std;

struct PERSON {
    int age;
    float weight;
    vector<int> id;
} family_member;

int main() {

    PERSON brother;
    brother.age = 20;
    brother.weight = 60.5;
    brother.id =  {7, 4, 0, 8};

    cout << brother.id[0] << endl;
}

$ g++ -o test test.cpp && ./test
test.cpp:7:5: error: ‘vector’ does not name a type
7 | vector id;
| ^~~~~~
test.cpp: In function ‘int main()’:

書き方が間違っていたみたい。以下のように書くと、、、

#include <iostream>
#include <vector>
using namespace std;

struct PERSON {
    int age;
    float weight;
    std::vector<int> id;
} family_member;

int main() {

    PERSON brother;
    brother.age = 20;
    brother.weight = 60.5;
    brother.id =  {7, 4, 0, 8};

    cout << brother.id[0] << endl;
}

$ g++ -o test test.cpp && ./test
7

うん、出来ますね♪ これをRustで書いていきたい。

【C++】多重ベクタ(多次元配列)

#include <iostream>
#include <vector>
using namespace std;

int main() {

    vector<vector<int>> data = {
        {7, 4, 0, 8},
        {2, 0, 3, 5},
        {6, 1, 7, 0},
    };

    int count = 0;

    for(int i=0; i < 3; i++){
        for(int j=0; j < 4; j++) {
            if(data.at(i).at(j) == 0) {
                count++;
            }
        }
    }

    cout << count << endl;
}

$ g++ -o test test.cpp && ./test
3

【Rust】axumでPOSTされたデータをreqwestで外部にPOSTする

axum::routing::postでPOSTデータを受け取って、そのデータをクローンしたものをシリアライズしてstring型にし、reqwestで外部に送る。
なお、reqwestで外部に送る処理は関数にして外出しする。

    let app = axum::Router::new()
        .route("/", axum::routing::get(handle_index))
        .route("/home", axum::routing::get(handle_top))
        .route("/account", axum::routing::get(handle_account))
        .route("/withdrawal", axum::routing::get(handle_withdrawal))
        .route("/sent", axum::routing::post(handle_sent))
        .route("/post", axum::routing::post(handle_post));

//

async fn handle_sent(axum::Form(unsignedtransaction): axum::Form<UnsignedTransaction>)
    -> axum::response::Html<String> {

    let s: UnsignedTransaction = unsignedtransaction.clone();
    post(s).await;
    let tera = tera::Tera::new("templates/*").unwrap();

    let mut context = tera::Context::new();
    context.insert("time", &unsignedtransaction.time);
    context.insert("receiver", &unsignedtransaction.receiver);
    context.insert("amount", &unsignedtransaction.amount);

    let output = tera.render("sent.html", &context);
    axum::response::Html(output.unwrap())

}

async fn post(unsignedtransaction: UnsignedTransaction) -> Result<(), Box<dyn std::error::Error>> {

    let serialized: String = serde_json::to_string(&unsignedtransaction).unwrap();

    let client = reqwest::Client::new();
    let resp = client.post("http://httpbin.org/post")
        .body(serialized)
        .send()
        .await?;
    
    let body = resp.text().await?;    
    let json: serde_json::Value = serde_json::from_str(&body)?;
    let obj = json.as_object().unwrap();
    
    for (key,value) in obj.iter() {
        println!("{}\t{}",key,value);
        }
    Ok(())
}

$ cargo run
//
Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.81s
Running `target/debug/axum_basic`
args {}
data “{\”time\”:\”2025-01-02T10:53:00.295Z\”,\”sender\”:\”12sSVCmfi7kgsdG4ZmaargPppDRvkE5zvD\”,\”receiver\”:\”12sSVCmfi7kgsdG4ZmaargPppDRvkE5zvD\”,\”amount\”:1000}”
files {}
form {}
headers {“Accept”:”*/*”,”Content-Length”:”143″,”Host”:”httpbin.org”,”X-Amzn-Trace-Id”:”Root=1-67767470-5a86f0272c93fb6a0a20a060″}
json {“amount”:1000,”receiver”:”12sSVCmfi7kgsdG4ZmaargPppDRvkE5zvD”,”sender”:”12sSVCmfi7kgsdG4ZmaargPppDRvkE5zvD”,”time”:”2025-01-02T10:53:00.295Z”}
origin “*.*.*”
url “http://httpbin.org/post”

うん、ちゃんとエラーなく送れてますね。
OK, wallet側はアドレスの作成とコインのPOST処理ができてある程度形になってきたので、一旦トランザクションからBlockを作成するところに戻ります。やっぱりUIがあると楽しいですな。。

【Rust】axumでformの送信とトランザクションのPostを実装したい

templates/withdrawal.html

<form action="/sent" method="post" class="">
            <input type="hidden" name="time" id="time" value="">
            <input type="hidden" name="sender" value="{{address}}">
            <div class="mb-3">
                <label for="receiver" class="form-label">送付先アドレス</label>
                <input type="text" class="form-control" id="receiver" name="receiver" placeholder="送付先のアドレスを入力してください">
              </div>
              <div class="mb-3">
                <label for="amount" class="form-label">送付コイン量</label>
                <input type="text" class="form-control" id="amount" name="amount" placeholder="数量を半角数字で入力してください。e.g. 1000">
              </div>
              <input type="submit" value="送信" class="btn btn-primary"/>
        </form>
#[derive(Serialize, Deserialize, Debug)]
struct UnsignedTransaction {
    time: String,
    sender: String,
    receiver: String,
    amount: i32,
}
// 
async fn handle_sent(axum::Form(unsignedtransaction): axum::Form<UnsignedTransaction>)
    -> axum::response::Html<String> {

    let tera = tera::Tera::new("templates/*").unwrap();

    let mut context = tera::Context::new();
    context.insert("time", &unsignedtransaction.time);
    context.insert("receiver", &unsignedtransaction.receiver);
    context.insert("amount", &unsignedtransaction.amount);

    let output = tera.render("sent.html", &context);
    axum::response::Html(output.unwrap())
}

formのPOSTはできました。
このデータを受け取ったタイミングで、外部のIP(node)に合わせてPOSTしたい。

【Rust】秘密鍵・公開鍵・アドレスの作成をaxumを使ってWebで表現

templates/account.html

   <body class="container">
        <h1 class="display-6 my-2">Crypt Wallet</h1>
        <hr>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="/">Home</a></li>
              <li class="breadcrumb-item"><a href="/account">アカウント情報</a></li>
            </ol>
          </nav>
        <div class="alert alert-primary">
            <p class="my-2">秘密鍵、公開鍵、アドレスを生成しました。</p>
        </div>
        <dl class="row">
            <dt class="col-sm-3">秘密鍵</dt>
            <dd class="col-sm-9">{{private_key}}</dd>
          
            <dt class="col-sm-3">公開鍵</dt>
            <dd class="col-sm-9">{{public_key}}</dd>
          
            <dt class="col-sm-3">アドレス</dt>
            <dd class="col-sm-9">{{address}}</dd>
          
          </dl>
        <br><br>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
    </body>
async fn handle_account()-> axum::response::Html<String> {

    let signing_key = SigningKey::random(&mut OsRng);
    let private_key = hex::encode(signing_key.to_bytes());
    let verifying_key = signing_key.verifying_key();
    let public_key = hex::encode(verifying_key.to_sec1_bytes());
    let address = new_address(&verifying_key);    

    let tera = tera::Tera::new("templates/*").unwrap();
    let mut context = tera::Context::new();
    context.insert("private_key", &private_key);
    context.insert("public_key", &public_key);
    context.insert("address", &address);

    let output = tera.render("account.html", &context);
    axum::response::Html(output.unwrap())
}

リファクタリングが必要だけど、やりたいことは大体できている^^

【Rust】axumでget, post, psql

まずテーブル作成
$ sudo -u postgres psql
$ CREATE TABLE “todo” (
id UUID primary key,
description varchar(100) not null,
deadline_at timestamp not null
);

postgres=# \dt
List of relations
Schema | Name | Type | Owner
——–+——–+——-+———-
public | todo | table | postgres

chrono = "0.4.31"
sqlx = { version = "0.7.2", features = ["runtime-tokio-native-tls", "chrono", "uuid"]}
uuid = { version = "1.6.1", fatures = ["v4", "serde"] }
use axum::{Router, extract::State, response::Html, routing::get};
use tera::{Context, Tera};
use serde::{Serialize, Deserialize};
use sqlx::{FromRow, PgPool};
use uuid::Uuid;

//

#[derive(Clone)]
struct ServiceState {
    tera: Tera,
    pool: PgPool,
}

//

#[tokio::main]
async fn main() {

    let pool = PgPool::connect("postgres://postgres:password@localhost:5432/postgres").await.unwrap();

    let tera = match Tera::new("templates/**/*.html"){
        Ok(t) => t,
        Err(e) => {
            println!("Parsing error(s): {}", e);
            ::std::process::exit(1);
        }
    };

    
    let app = Router::new()
        .route("/", get(index))
        .with_state(ServiceState {tera, pool});
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

http://192.168.33.10:3000/create_todo

### 入力結果の表示
templates/todos.html

<a href="/create_todo">Todoを作成</a>
<table>
    <thread>
        <tr>
            <th scope="col">description</th>
            <th scope="col">deadline at</th>
        </tr>
    </thread>
    <tbody>
        {% for todo in todos %}
        <tr id="{{ todo.id }}">
            <td>{{ todo.description }}</td>
            <td>{{ todo.deadline_at }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>
use axum::{Router, extract::State, response::{Redirect, Html}, Form, routing::get};
use chrono::NaiveDateTime;
use tera::{Context, Tera};
use serde::{Serialize, Deserialize};
use sqlx::{FromRow, PgPool};
use uuid::Uuid;

pub fn deserialize_date<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<NaiveDateTime, D::Error> {
    let s = String::deserialize(deserializer)?;
    NaiveDateTime::parse_from_str(&s, "%Y-%m-%dT%H:%M")
        .map_err(serde::de::Error::custom)
}

#[derive(Serialize)]
struct Index {
    name: String
}

#[derive(Clone)]
struct ServiceState {
    tera: Tera,
    pool: PgPool,
}

#[derive(Debug, Serialize, FromRow)]
struct Todo {
    id: Uuid,
    description: String,
    deadline_at: NaiveDateTime,
}

#[derive(Debug, Deserialize)]
struct CreateTodo {
    description: String,
    #[serde(deserialize_with = "deserialize_date")]
    deadline_at: NaiveDateTime,
}

async fn index(State(state): State<ServiceState>) -> Html<String> {
    let index = Index { name: String::from("test") };
    let page = state.tera.render("index.html", &Context::from_serialize(&index).unwrap()).unwrap();
    Html(page.to_owned())
}

async fn get_create_todo(State(state): State<ServiceState>) -> Html<String> {
    let page = state.tera.render("create_todo.html", &Context::new()).unwrap();
    Html(page.to_owned())
}

async fn post_create_todo(
    State(state): State<ServiceState>,
    Form(todo): Form<CreateTodo>,
) -> Redirect {
    let todo = Todo {
        id: Uuid::new_v4(),
        description: todo.description,
        deadline_at: todo.deadline_at,
    };

    sqlx::query("INSERT INTO todo VALUES ($1, $2, $3);")
        .bind(todo.id)
        .bind(todo.description)
        .bind(todo.deadline_at)
        .execute(&state.pool)
        .await
        .expect("todoの取得に失敗しました");

    Redirect::to("/todos")
}

async fn get_todos(
    State(state): State<ServiceState>,
) -> Html<String> {
    let todos = sqlx::query_as::<_, Todo>("SELECT * FROM todo")
        .fetch_all(&state.pool)
        .await
        .expect("todoの取得に失敗しました");
    let mut context = Context::new();
    context.insert("todos", &todos);

    let page = state.tera.render("todos.html", &context).expect("todoの描画に失敗しました");
    Html(page)
}

#[tokio::main]
async fn main() {

    let pool = PgPool::connect("postgres://postgres:password@localhost:5432/postgres").await.unwrap();

    let tera = match Tera::new("templates/**/*.html"){
        Ok(t) => t,
        Err(e) => {
            println!("Parsing error(s): {}", e);
            ::std::process::exit(1);
        }
    };

    
    let app = Router::new()
        .route("/", get(index))
        .route("/todos", get(get_todos))
        .route("/create_todo", get(get_create_todo).post(post_create_todo))
        .with_state(ServiceState {tera, pool});
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

http://192.168.33.10:3000/todos
Todoを作成
description deadline at
test 2025-01-01T15:54:00
aaa 2025-01-01T15:57:00

なんだこれは…

【Rust】#[derive]アトリビュートとは?

derive: 導出
#[derive]アトリビュートを用いることで、型に対して特定のトレイトの標準的な実装を提供する

比較: Eq, PartialEq, Ord, PartialOrd コンパイルの条件分岐
Clone: &TからT
Copy: to give a type copy semantic
Hash: ハッシュ値計算
Default: 空のインスタンス
Debug: {:?}

implementation

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

impl Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

fn main(){
    
    let a = Circle{x: 2.0, y: 4.0, radius: 3.0};
    println!("{}", a.area());
}

トレイト

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

trait HasArea {fn area(&self)-> f64;}
impl HasArea for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

fn main(){
    
    let a = Circle{x: 2.0, y: 4.0, radius: 3.0};
    println!("{}", a.area());
}

属性アトリビュートは追加機能
以下のような目的で使用する
– クレート名、バージョン、種類(バイナリか、ライブラリか)の設定
– リントの無効化 (警告の抑止)
– コンパイラ付属の機能(マクロ、glob、インポートなど)の有効化
– 外部ライブラリへのリンク
– ユニットテスト用の関数として明示
– ベンチマーク用の関数として明示
#[test] 単体テスト
#[cfg] 条件を提示し、その条件に応じたコンパイルをする
#[derive] トレイトの実装を自動的に構造体や列挙型に実装できる
 #[derive(Debug)] の場合は、Debugトレイトのfmt関数が実装される
#[allow]
#[deny]