solana/src/event.rs

71 lines
2.1 KiB
Rust
Raw Normal View History

2018-03-30 10:43:38 -07:00
//! The `event` module handles events, which may be a `Transaction`, or a `Witness` used to process a pending
2018-03-29 11:20:54 -07:00
//! Transaction.
use bincode::serialize;
use chrono::prelude::*;
2018-03-08 09:05:00 -08:00
use signature::{KeyPair, KeyPairUtil, PublicKey, Signature, SignatureUtil};
use transaction::Transaction;
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum Event {
Transaction(Transaction),
Signature {
from: PublicKey,
tx_sig: Signature,
sig: Signature,
},
Timestamp {
from: PublicKey,
dt: DateTime<Utc>,
sig: Signature,
},
}
impl Event {
2018-03-29 11:20:54 -07:00
/// Create and sign a new Witness Timestamp. Used for unit-testing.
2018-03-08 09:05:00 -08:00
pub fn new_timestamp(from: &KeyPair, dt: DateTime<Utc>) -> Self {
2018-05-10 16:59:13 -07:00
let sign_data = serialize(&dt).expect("serialize 'dt' in pub fn new_timestamp");
2018-03-08 09:05:00 -08:00
let sig = Signature::clone_from_slice(from.sign(&sign_data).as_ref());
Event::Timestamp {
from: from.pubkey(),
dt,
sig,
}
}
/// Create and sign a new Witness Signature. Used for unit-testing.
pub fn new_signature(from: &KeyPair, tx_sig: Signature) -> Self {
let sig = Signature::clone_from_slice(from.sign(&tx_sig).as_ref());
Event::Signature {
from: from.pubkey(),
tx_sig,
sig,
}
}
2018-03-29 11:20:54 -07:00
/// Verify the Event's signature's are valid and if a transaction, that its
/// spending plan is valid.
pub fn verify(&self) -> bool {
match *self {
2018-03-26 21:07:11 -07:00
Event::Transaction(ref tr) => tr.verify_sig(),
Event::Signature { from, tx_sig, sig } => sig.verify(&from, &tx_sig),
2018-05-11 11:38:52 -07:00
Event::Timestamp { from, dt, sig } => sig.verify(
&from,
&serialize(&dt).expect("serialize 'dt' in pub fn verify"),
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use signature::{KeyPair, KeyPairUtil};
#[test]
fn test_event_verify() {
assert!(Event::new_timestamp(&KeyPair::new(), Utc::now()).verify());
assert!(Event::new_signature(&KeyPair::new(), Signature::default()).verify());
}
}