solana/src/accountant_skel.rs

76 lines
2.3 KiB
Rust
Raw Normal View History

2018-02-28 09:07:54 -08:00
use std::io;
use accountant::Accountant;
use transaction::Transaction;
use signature::PublicKey;
2018-03-06 16:20:37 -08:00
use hash::Sha256Hash;
use log::Entry;
2018-03-04 06:28:51 -08:00
use std::net::UdpSocket;
use bincode::{deserialize, serialize};
2018-02-28 09:07:54 -08:00
pub struct AccountantSkel {
pub acc: Accountant,
2018-02-28 09:07:54 -08:00
}
2018-02-28 13:16:50 -08:00
#[derive(Serialize, Deserialize, Debug)]
2018-02-28 09:07:54 -08:00
pub enum Request {
Transaction(Transaction<i64>),
GetBalance { key: PublicKey },
GetEntries { last_id: Sha256Hash },
GetId { is_last: bool },
2018-02-28 09:07:54 -08:00
}
2018-02-28 13:16:50 -08:00
#[derive(Serialize, Deserialize, Debug)]
2018-02-28 09:07:54 -08:00
pub enum Response {
Balance { key: PublicKey, val: Option<i64> },
Entries { entries: Vec<Entry<i64>> },
Id { id: Sha256Hash, is_last: bool },
2018-02-28 09:07:54 -08:00
}
impl AccountantSkel {
pub fn new(acc: Accountant) -> Self {
AccountantSkel { acc }
2018-02-28 13:16:50 -08:00
}
2018-02-28 17:04:35 -08:00
pub fn process_request(self: &mut Self, msg: Request) -> Option<Response> {
2018-02-28 09:07:54 -08:00
match msg {
Request::Transaction(tr) => {
if let Err(err) = self.acc.process_transaction(tr) {
eprintln!("Transaction error: {:?}", err);
}
2018-02-28 09:07:54 -08:00
None
}
Request::GetBalance { key } => {
let val = self.acc.get_balance(&key);
2018-02-28 09:07:54 -08:00
Some(Response::Balance { key, val })
}
2018-03-05 10:11:00 -08:00
Request::GetEntries { .. } => Some(Response::Entries { entries: vec![] }),
Request::GetId { is_last } => Some(Response::Id {
id: if is_last {
self.acc.sync();
self.acc.last_id
} else {
self.acc.first_id
},
is_last,
}),
2018-02-28 09:07:54 -08:00
}
}
/// UDP Server that forwards messages to Accountant methods.
2018-02-28 09:07:54 -08:00
pub fn serve(self: &mut Self, addr: &str) -> io::Result<()> {
let socket = UdpSocket::bind(addr)?;
2018-02-28 13:16:50 -08:00
let mut buf = vec![0u8; 1024];
2018-02-28 09:07:54 -08:00
loop {
//println!("skel: Waiting for incoming packets...");
let (_sz, src) = socket.recv_from(&mut buf)?;
2018-02-28 09:07:54 -08:00
// TODO: Return a descriptive error message if deserialization fails.
2018-02-28 13:16:50 -08:00
let req = deserialize(&buf).expect("deserialize request");
2018-02-28 17:04:35 -08:00
if let Some(resp) = self.process_request(req) {
socket.send_to(&serialize(&resp).expect("serialize response"), &src)?;
2018-02-28 09:07:54 -08:00
}
}
}
}