luanti-g1/g1bridge/src/main.rs
2025-06-12 20:10:41 +02:00

147 lines
3.6 KiB
Rust

#![feature(try_blocks)]
mod blockchain;
use argp::FromArgs;
use serde::{Deserialize, Serialize, de};
use sp_core::Pair as _;
use std::{
io::{BufRead, Read},
str::FromStr,
sync::Arc,
};
use subxt::{
ext::sp_core::ed25519::{Pair, Public},
utils::{AccountId32, MultiAddress},
};
use tiny_http::{Response, ResponseBox, Server, ServerConfig};
use tokio::sync::mpsc::{Sender, channel};
use typed_sled::Tree;
/// Game to Blockchain
const TREE_DEBT_G2B: &'static str = "debt_g2b";
/// Blob
#[derive(FromArgs)]
struct Opt {
/// path to the database
#[argp(option, short = 'd')]
db: String,
/// secret key is legacy (two passwords on the two first lines)
#[argp(switch, short = 'l')]
legacy: bool,
/// path to the file containing the secret key in Substrate format
#[argp(option, short = 's')]
secret_key: String,
/// duniter node URL (default: ws://127.0.0.1:9944)
#[argp(option, short = 'u', default = "String::from(\"ws://127.0.0.1:9944\")")]
url: String,
}
#[derive(Deserialize, Serialize)]
struct DebtG2B {
address: AccountId32,
amount: u64,
}
#[tokio::main]
async fn main() {
let opt: Opt = argp::parse_args_or_exit(argp::DEFAULT);
let mut sk_file = std::fs::File::open(opt.secret_key).expect("Cannot open secret key file");
let pair: Pair = if opt.legacy {
let sk_reader = std::io::BufReader::new(sk_file);
let mut sk_lines = sk_reader.lines();
let psw1 = sk_lines
.next()
.expect("Secret key file should contain at least 2 lines for the 2 passwords")
.unwrap();
let psw2 = sk_lines
.next()
.expect("Secret key file should contain at least 2 lines for the 2 passwords")
.unwrap();
let params = scrypt::Params::new(12, 16, 1, 32).unwrap();
let mut seed = [0u8; 32];
scrypt::scrypt(
psw2.trim().as_bytes(),
psw1.trim().as_bytes(),
&params,
&mut seed,
)
.unwrap();
Pair::from_seed(&seed)
} else {
let mut sk_content = String::new();
sk_file
.read_to_string(&mut sk_content)
.expect("Cannot read secret key file");
Pair::from_string(sk_content.trim(), None).expect("Cannot decode secret key")
};
simplelog::SimpleLogger::init(log::LevelFilter::Debug, simplelog::Config::default()).unwrap();
let db = typed_sled::open(opt.db).expect("Cannot open database");
let tree_debt_g2b = Tree::<DebtG2B, ()>::open(&db, TREE_DEBT_G2B);
let (bc_send, bc_recv) = channel(128);
tokio::spawn(blockchain::run(
opt.url,
pair,
bc_recv,
tree_debt_g2b.clone(),
));
let server = Server::http("127.0.0.1:30061").expect("Cannot start server");
struct Locals {
tree_debt_g2b: Tree<DebtG2B, ()>,
bc_send: Sender<DebtG2B>,
}
tokio::task_local! {
static LOCALS: Arc<Locals>;
};
LOCALS.scope(
Arc::new(Locals {
tree_debt_g2b,
bc_send,
}),
async move {
for request in server.incoming_requests() {
let locals = LOCALS.get();
tokio::spawn(async move {
let url = request.url();
let mut url_items = url.split('/').filter(|item| !item.is_empty());
let resp: Option<ResponseBox> = try {
match url_items.next() {
Some("send") => {
let address = AccountId32::from_str(url_items.next()?).ok()?;
let amount = url_items.next()?.parse::<u64>().ok()?;
println!("{address} {amount}");
let debt = DebtG2B { address, amount };
locals.tree_debt_g2b.insert(&debt, &()).ok()?;
locals.bc_send.send(debt).await.ok()?;
Response::empty(200).boxed()
}
_ => None?,
}
};
if let Some(resp) = resp {
request.respond(resp).ok();
} else {
request.respond(Response::empty(400)).ok();
}
});
}
},
).await;
}