Files
solana/src/accountant_skel.rs

99 lines
2.7 KiB
Rust
Raw Normal View History

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