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

91 lines
2.7 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;
2024-06-11 17:06:49 +01:00
use crate::{crdt::TransactionList, utils};
pub(crate) struct SideNode {
crdt: BaseCrdt<TransactionList>,
2024-06-07 17:35:38 +01:00
keys: fastcrypto::ed25519::Ed25519KeyPair,
incoming_receiver: mpsc::Receiver<SignedOp>,
stdin_receiver: std::sync::mpsc::Receiver<String>,
2024-06-11 18:13:51 +01:00
network_sender: mpsc::Sender<SignedOp>,
}
impl SideNode {
2024-06-07 17:35:38 +01:00
pub(crate) fn new(
crdt: BaseCrdt<TransactionList>,
keys: Ed25519KeyPair,
incoming_receiver: mpsc::Receiver<SignedOp>,
stdin_receiver: std::sync::mpsc::Receiver<String>,
2024-06-11 18:13:51 +01:00
network_sender: mpsc::Sender<SignedOp>,
2024-06-07 17:35:38 +01:00
) -> Self {
let node = Self {
crdt,
2024-06-07 17:35:38 +01:00
keys,
incoming_receiver,
stdin_receiver,
2024-06-11 18:13:51 +01:00
network_sender,
};
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) => {
println!("Received stdin input: {:?}", stdin);
2024-06-11 17:06:49 +01:00
let transaction = utils::fake_transaction(stdin);
let json = serde_json::to_value(transaction).unwrap();
2024-06-11 18:13:51 +01:00
let signed_op = self.add_transaction_local(json);
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) => {
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) {
2024-06-11 17:06:49 +01:00
println!("sending to network: {:?}", signed_op);
2024-06-11 18:13:51 +01:00
self.network_sender.send(signed_op).await.unwrap();
2024-06-11 17:06:49 +01:00
}
fn handle_incoming(&mut self, incoming: &SignedOp) {
println!("WINNNINGINGINGINGINGIGNIGN");
self.crdt.apply(incoming.clone());
}
2024-06-07 17:35:38 +01:00
2024-06-11 18:13:51 +01:00
pub(crate) 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.keys);
signed_op
}
/// Print the current state of the CRDT, can be used to debug
2024-06-10 16:43:45 +01:00
pub(crate) fn _trace_crdt(&self) {
println!("{:?}", self.crdt.doc.list);
}
}