solana/src/accountant.rs

247 lines
7.5 KiB
Rust
Raw Normal View History

2018-02-23 13:08:19 -08:00
//! The `accountant` is a client of the `historian`. It uses the historian's
//! event log to record transactions. Its users can deposit funds and
//! transfer funds to other users.
use log::{Entry, Sha256Hash};
use event::{Event, PublicKey, Signature};
2018-02-23 13:08:19 -08:00
use historian::Historian;
use ring::signature::Ed25519KeyPair;
use std::sync::mpsc::SendError;
2018-02-23 13:08:19 -08:00
use std::collections::HashMap;
pub struct Accountant {
pub historian: Historian<u64>,
pub balances: HashMap<PublicKey, u64>,
pub end_hash: Sha256Hash,
}
impl Accountant {
pub fn new(start_hash: &Sha256Hash, ms_per_tick: Option<u64>) -> Self {
let hist = Historian::<u64>::new(start_hash, ms_per_tick);
Accountant {
historian: hist,
balances: HashMap::new(),
end_hash: *start_hash,
}
}
pub fn sync(self: &mut Self) -> Vec<Entry<u64>> {
2018-02-28 17:04:35 -08:00
let mut entries = vec![];
2018-02-23 13:08:19 -08:00
while let Ok(entry) = self.historian.receiver.try_recv() {
2018-02-28 17:04:35 -08:00
entries.push(entry);
}
2018-02-28 17:04:35 -08:00
if let Some(last_entry) = entries.last() {
self.end_hash = last_entry.end_hash;
}
entries
2018-02-23 13:08:19 -08:00
}
2018-02-28 09:07:54 -08:00
pub fn deposit_signed(
self: &mut Self,
2018-02-28 09:07:54 -08:00
key: PublicKey,
data: u64,
sig: Signature,
) -> Result<(), SendError<Event<u64>>> {
let event = Event::Claim { key, data, sig };
if !self.historian.verify_event(&event) {
// TODO: Replace the SendError result with a custom one.
println!("Rejecting transaction: Invalid event");
return Ok(());
}
if self.balances.contains_key(&key) {
if let Some(x) = self.balances.get_mut(&key) {
*x += data;
}
} else {
self.balances.insert(key, data);
}
2018-02-28 09:07:54 -08:00
self.historian.sender.send(event)
}
2018-02-23 13:08:19 -08:00
pub fn deposit(
self: &mut Self,
2018-02-23 13:08:19 -08:00
n: u64,
keypair: &Ed25519KeyPair,
) -> Result<Signature, SendError<Event<u64>>> {
use event::{get_pubkey, sign_serialized};
2018-02-28 09:07:54 -08:00
let key = get_pubkey(keypair);
let sig = sign_serialized(&n, keypair);
self.deposit_signed(key, n, sig).map(|_| sig)
2018-02-28 09:07:54 -08:00
}
pub fn transfer_signed(
self: &mut Self,
from: PublicKey,
to: PublicKey,
data: u64,
sig: Signature,
) -> Result<(), SendError<Event<u64>>> {
let event = Event::Transaction {
from,
to,
data,
sig,
};
if !self.historian.verify_event(&event) {
// TODO: Replace the SendError result with a custom one.
println!("Rejecting transaction: Invalid event");
return Ok(());
}
if self.get_balance(&from).unwrap_or(0) < data {
// TODO: Replace the SendError result with a custom one.
println!("Rejecting transaction: Insufficient funds");
return Ok(());
}
if let Some(x) = self.balances.get_mut(&from) {
*x -= data;
}
if self.balances.contains_key(&to) {
if let Some(x) = self.balances.get_mut(&to) {
*x += data;
}
} else {
self.balances.insert(to, data);
}
2018-02-23 13:08:19 -08:00
self.historian.sender.send(event)
}
pub fn transfer(
self: &mut Self,
n: u64,
keypair: &Ed25519KeyPair,
2018-02-28 09:07:54 -08:00
to: PublicKey,
) -> Result<Signature, SendError<Event<u64>>> {
use event::{get_pubkey, sign_transaction_data};
2018-02-28 09:07:54 -08:00
let from = get_pubkey(keypair);
let sig = sign_transaction_data(&n, keypair, &to);
self.transfer_signed(from, to, n, sig).map(|_| sig)
2018-02-23 13:08:19 -08:00
}
pub fn get_balance(self: &Self, pubkey: &PublicKey) -> Option<u64> {
self.balances.get(pubkey).map(|x| *x)
2018-02-23 13:08:19 -08:00
}
pub fn wait_on_signature(self: &mut Self, wait_sig: &Signature) {
use std::thread::sleep;
use std::time::Duration;
let mut entries = self.sync();
let mut found = false;
while !found {
found = entries.iter().any(|e| match e.event {
Event::Claim { sig, .. } => sig == *wait_sig,
Event::Transaction { sig, .. } => sig == *wait_sig,
_ => false,
});
if !found {
sleep(Duration::from_millis(30));
entries = self.sync();
}
}
}
2018-02-23 13:08:19 -08:00
}
#[cfg(test)]
mod tests {
use super::*;
use event::{generate_keypair, get_pubkey};
2018-02-23 13:08:19 -08:00
use historian::ExitReason;
#[test]
fn test_accountant() {
let zero = Sha256Hash::default();
let mut acc = Accountant::new(&zero, Some(2));
let alice_keypair = generate_keypair();
let bob_keypair = generate_keypair();
acc.deposit(10_000, &alice_keypair).unwrap();
let sig = acc.deposit(1_000, &bob_keypair).unwrap();
acc.wait_on_signature(&sig);
2018-02-23 13:08:19 -08:00
2018-02-28 09:07:54 -08:00
let bob_pubkey = get_pubkey(&bob_keypair);
let sig = acc.transfer(500, &alice_keypair, bob_pubkey).unwrap();
acc.wait_on_signature(&sig);
2018-02-23 13:08:19 -08:00
assert_eq!(acc.get_balance(&bob_pubkey).unwrap(), 1_500);
drop(acc.historian.sender);
assert_eq!(
acc.historian.thread_hdl.join().unwrap().1,
ExitReason::RecvDisconnected
);
}
2018-02-27 10:28:10 -08:00
#[test]
fn test_invalid_transfer() {
use std::thread::sleep;
use std::time::Duration;
2018-02-27 10:28:10 -08:00
let zero = Sha256Hash::default();
let mut acc = Accountant::new(&zero, Some(2));
let alice_keypair = generate_keypair();
let bob_keypair = generate_keypair();
acc.deposit(10_000, &alice_keypair).unwrap();
let sig = acc.deposit(1_000, &bob_keypair).unwrap();
acc.wait_on_signature(&sig);
2018-02-27 10:28:10 -08:00
2018-02-28 09:07:54 -08:00
let bob_pubkey = get_pubkey(&bob_keypair);
2018-02-27 10:28:10 -08:00
acc.transfer(10_001, &alice_keypair, bob_pubkey).unwrap();
sleep(Duration::from_millis(30));
2018-02-28 09:07:54 -08:00
let alice_pubkey = get_pubkey(&alice_keypair);
2018-02-27 10:28:10 -08:00
assert_eq!(acc.get_balance(&alice_pubkey).unwrap(), 10_000);
assert_eq!(acc.get_balance(&bob_pubkey).unwrap(), 1_000);
drop(acc.historian.sender);
assert_eq!(
acc.historian.thread_hdl.join().unwrap().1,
ExitReason::RecvDisconnected
);
}
#[test]
2018-02-28 09:07:54 -08:00
fn test_multiple_claims() {
2018-02-27 10:28:10 -08:00
let zero = Sha256Hash::default();
let mut acc = Accountant::new(&zero, Some(2));
let keypair = generate_keypair();
acc.deposit(1, &keypair).unwrap();
let sig = acc.deposit(2, &keypair).unwrap();
acc.wait_on_signature(&sig);
2018-02-27 10:28:10 -08:00
2018-02-28 09:07:54 -08:00
let pubkey = get_pubkey(&keypair);
2018-02-27 10:28:10 -08:00
assert_eq!(acc.get_balance(&pubkey).unwrap(), 3);
drop(acc.historian.sender);
assert_eq!(
acc.historian.thread_hdl.join().unwrap().1,
ExitReason::RecvDisconnected
);
}
#[test]
fn test_transfer_to_newb() {
let zero = Sha256Hash::default();
let mut acc = Accountant::new(&zero, Some(2));
let alice_keypair = generate_keypair();
let bob_keypair = generate_keypair();
let sig = acc.deposit(10_000, &alice_keypair).unwrap();
acc.wait_on_signature(&sig);
2018-02-27 10:28:10 -08:00
2018-02-28 09:07:54 -08:00
let bob_pubkey = get_pubkey(&bob_keypair);
let sig = acc.transfer(500, &alice_keypair, bob_pubkey).unwrap();
acc.wait_on_signature(&sig);
2018-02-27 10:28:10 -08:00
assert_eq!(acc.get_balance(&bob_pubkey).unwrap(), 500);
drop(acc.historian.sender);
assert_eq!(
acc.historian.thread_hdl.join().unwrap().1,
ExitReason::RecvDisconnected
);
}
2018-02-23 13:08:19 -08:00
}