Files
bft-crdt-experiment/side-node/src/node.rs

100 lines
3.0 KiB
Rust
Raw Normal View History

use bft_json_crdt::json_crdt::{BaseCrdt, SignedOp};
2024-06-07 17:35:38 +01:00
use fastcrypto::ed25519::Ed25519KeyPair;
use tokio::sync::mpsc;
use crate::{crdt::TransactionList, utils, websocket::WebSocketClient};
pub struct SideNode {
crdt: BaseCrdt<TransactionList>,
bft_crdt_keys: fastcrypto::ed25519::Ed25519KeyPair,
2024-06-18 16:56:24 +01:00
bitcoin_keys: bitcoin::secp256k1::Keypair,
incoming_receiver: mpsc::Receiver<SignedOp>,
stdin_receiver: std::sync::mpsc::Receiver<String>,
handle: ezsockets::Client<WebSocketClient>,
}
impl SideNode {
pub fn new(
2024-06-07 17:35:38 +01:00
crdt: BaseCrdt<TransactionList>,
2024-06-18 16:56:24 +01:00
bft_crdt_keys: Ed25519KeyPair,
bitcoin_keys: bitcoin::secp256k1::Keypair,
incoming_receiver: mpsc::Receiver<SignedOp>,
stdin_receiver: std::sync::mpsc::Receiver<String>,
handle: ezsockets::Client<WebSocketClient>,
2024-06-07 17:35:38 +01:00
) -> Self {
let node = Self {
crdt,
2024-06-18 16:56:24 +01:00
bft_crdt_keys,
bitcoin_keys,
incoming_receiver,
stdin_receiver,
handle,
};
node
}
pub(crate) async fn start(&mut self) {
println!("Starting node...");
loop {
2024-06-11 18:13:51 +01:00
match self.stdin_receiver.try_recv() {
Ok(stdin) => {
let transaction = utils::fake_generic_transaction_json(stdin);
2024-06-11 17:06:49 +01:00
let json = serde_json::to_value(transaction).unwrap();
2024-06-11 18:13:51 +01:00
let signed_op = self.add_transaction_local(json);
println!("STDIN: {}", utils::shappy(signed_op.clone()));
2024-06-11 18:13:51 +01:00
self.send_to_network(signed_op).await;
}
2024-06-11 18:13:51 +01:00
Err(_) => {} // ignore empty channel errors in this PoC
}
match self.incoming_receiver.try_recv() {
Ok(incoming) => {
println!("INCOMING: {}", utils::shappy(incoming.clone()));
2024-06-11 18:42:13 +01:00
self.handle_incoming(incoming);
}
2024-06-11 18:13:51 +01:00
Err(_) => {} // ignore empty channel errors in this PoC
}
}
}
2024-06-11 18:13:51 +01:00
async fn send_to_network(&self, signed_op: SignedOp) {
let to_send = serde_json::to_string(&signed_op).unwrap();
self.handle.call(to_send).unwrap();
2024-06-11 17:06:49 +01:00
}
pub fn handle_incoming(&mut self, incoming: SignedOp) {
2024-06-11 18:42:13 +01:00
self.crdt.apply(incoming);
// self.trace_crdt();
}
2024-06-07 17:35:38 +01:00
pub fn add_transaction_local(
2024-06-07 17:35:38 +01:00
&mut self,
transaction: serde_json::Value,
) -> bft_json_crdt::json_crdt::SignedOp {
let last = self
.crdt
.doc
.list
.ops
.last()
.expect("couldn't find last op");
let signed_op = self
.crdt
.doc
.list
.insert(last.id, transaction)
.sign(&self.bft_crdt_keys);
// self.trace_crdt();
2024-06-07 17:35:38 +01:00
signed_op
}
/// Print the current state of the CRDT, can be used to debug
pub fn trace_crdt(&self) {
2024-06-11 19:16:36 +01:00
println!("{:?}", self.crdt.doc.view_sha());
}
pub fn current_sha(&self) -> String {
self.crdt.doc.view_sha()
}
}