Skip to content

Commit

Permalink
ref(qry): minor refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
edytapawlak committed Dec 16, 2021
1 parent 4627f05 commit b4ac877
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 140 deletions.
3 changes: 0 additions & 3 deletions src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,6 @@ pub enum Error {
#[error("Invalid identifier state")]
InvalidIdentifierStat,

#[error("Event not yet in database")]
MissingEventError,

#[cfg(feature = "async")]
#[error("Zero send error")]
ZeroSendError,
Expand Down
46 changes: 13 additions & 33 deletions src/event_message/event_msg_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ use crate::{
Event, EventMessage,
},
keys::PublicKey,
prefix::{BasicPrefix, IdentifierPrefix, SelfAddressingPrefix},
prefix::{BasicPrefix, IdentifierPrefix, SelfAddressingPrefix}, state::KeyEventType,
};
use ed25519_dalek::Keypair;
use rand::rngs::OsRng;

pub struct EventMsgBuilder {
event_type: EventType,
event_type: KeyEventType,
prefix: IdentifierPrefix,
sn: u64,
key_threshold: SignatureThreshold,
Expand All @@ -42,29 +42,8 @@ pub struct EventMsgBuilder {
derivation: SelfAddressing,
}

#[derive(Clone, Debug)]
pub enum EventType {
Inception,
Rotation,
Interaction,
DelegatedInception,
DelegatedRotation,
}

impl EventType {
pub fn is_establishment_event(&self) -> bool {
match self {
EventType::Inception
| EventType::Rotation
| EventType::DelegatedInception
| EventType::DelegatedRotation => true,
_ => false,
}
}
}

impl EventMsgBuilder {
pub fn new(event_type: EventType) -> Self {
pub fn new(event_type: KeyEventType) -> Self {
let mut rng = OsRng {};
let kp = Keypair::generate(&mut rng);
let nkp = Keypair::generate(&mut rng);
Expand Down Expand Up @@ -151,14 +130,14 @@ impl EventMsgBuilder {

pub fn with_witness_to_add(self, witness_to_add: &[BasicPrefix]) -> Self {
EventMsgBuilder {
witnesses: witness_to_add.to_vec(),
witness_to_add: witness_to_add.to_vec(),
..self
}
}

pub fn with_witness_to_remove(self, witness_to_remove: &[BasicPrefix]) -> Self {
EventMsgBuilder {
witnesses: witness_to_remove.to_vec(),
witness_to_remove: witness_to_remove.to_vec(),
..self
}
}
Expand All @@ -180,7 +159,7 @@ impl EventMsgBuilder {
};

Ok(match self.event_type {
EventType::Inception => {
KeyEventType::Icp => {
let icp_event = InceptionEvent {
key_config,
witness_config: InceptionWitnessConfig { tally: self.witness_threshold, initial_witnesses: self.witnesses },
Expand All @@ -202,7 +181,7 @@ impl EventMsgBuilder {
}
}

EventType::Rotation => Event {
KeyEventType::Rot => Event {
prefix,
sn: self.sn,
event_data: EventData::Rot(RotationEvent {
Expand All @@ -217,7 +196,7 @@ impl EventMsgBuilder {
}),
}
.to_message(self.format)?,
EventType::Interaction => Event {
KeyEventType::Ixn => Event {
prefix,
sn: self.sn,
event_data: EventData::Ixn(InteractionEvent {
Expand All @@ -226,7 +205,7 @@ impl EventMsgBuilder {
}),
}
.to_message(self.format)?,
EventType::DelegatedInception => {
KeyEventType::Dip => {
let icp_data = InceptionEvent {
key_config,
witness_config: InceptionWitnessConfig::default(),
Expand All @@ -239,7 +218,7 @@ impl EventMsgBuilder {
}
.incept_self_addressing(self.derivation, self.format)?
}
EventType::DelegatedRotation => {
KeyEventType::Drt => {
let rotation_data = RotationEvent {
previous_event_hash: self.prev_event,
key_config,
Expand All @@ -253,6 +232,7 @@ impl EventMsgBuilder {
}
.to_message(self.format)?
}
KeyEventType::Rct => Err(Error::SemanticError("Wrong event type".into()))?,
})
}
}
Expand All @@ -265,7 +245,7 @@ pub struct ReceiptBuilder {

impl Default for ReceiptBuilder {
fn default() -> Self {
let default_event = EventMsgBuilder::new(EventType::Inception).build().unwrap();
let default_event = EventMsgBuilder::new(KeyEventType::Icp).build().unwrap();
Self {
format: SerializationFormats::JSON,
derivation: SelfAddressing::Blake3_256,
Expand Down Expand Up @@ -329,7 +309,7 @@ fn test_multisig_prefix_derivation() {
.unwrap(),
];

let msg_builder = EventMsgBuilder::new(EventType::Inception)
let msg_builder = EventMsgBuilder::new(KeyEventType::Icp)
.with_keys(keys)
.with_next_keys(next_keys)
.with_threshold(&SignatureThreshold::Simple(2))
Expand Down
54 changes: 27 additions & 27 deletions src/event_message/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ pub fn verify_identifier_binding(icp_event: &EventMessage<Event>) -> Result<bool
mod tests {
mod test_utils;

use self::{event_msg_builder::EventType, test_utils::test_mock_event_sequence};
use self::{test_utils::test_mock_event_sequence};
use super::*;
use crate::{
derivation::{basic::Basic, self_addressing::SelfAddressing, self_signing::SelfSigning},
Expand All @@ -255,7 +255,7 @@ mod tests {
sections::{threshold::SignatureThreshold, InceptionWitnessConfig},
},
keys::{PrivateKey, PublicKey},
prefix::{AttachedSignaturePrefix, IdentifierPrefix, Prefix},
prefix::{AttachedSignaturePrefix, IdentifierPrefix, Prefix}, state::KeyEventType,
};
use ed25519_dalek::Keypair;
use rand::rngs::OsRng;
Expand Down Expand Up @@ -417,42 +417,42 @@ mod tests {
#[test]
fn test_basic_establishment_sequence() -> Result<(), Error> {
// Sequence should contain Inception Event.
let no_inception_seq = vec![EventType::Rotation, EventType::Rotation];
let no_inception_seq = vec![KeyEventType::Rot, KeyEventType::Rot];
assert!(test_mock_event_sequence(no_inception_seq).is_err());

// Sequence can't start with Rotation Event.
let rotation_first_seq = vec![EventType::Rotation, EventType::Inception];
let rotation_first_seq = vec![KeyEventType::Rot, KeyEventType::Icp];
assert!(test_mock_event_sequence(rotation_first_seq).is_err());

// Sequence should contain exacly one Inception Event.
let wrong_seq = vec![
EventType::Inception,
EventType::Rotation,
EventType::Rotation,
EventType::Inception,
KeyEventType::Icp,
KeyEventType::Rot,
KeyEventType::Rot,
KeyEventType::Icp,
];
assert!(test_mock_event_sequence(wrong_seq).is_err());

let ok_seq = vec![
EventType::Inception,
EventType::Rotation,
EventType::Rotation,
KeyEventType::Icp,
KeyEventType::Rot,
KeyEventType::Rot,
];
assert!(test_mock_event_sequence(ok_seq).is_ok());

// Wrong delegated events sequence.
let wrong_delegated_sequence = vec![
EventType::DelegatedInception,
EventType::DelegatedRotation,
EventType::Rotation,
KeyEventType::Dip,
KeyEventType::Drt,
KeyEventType::Rot,
];
assert!(test_mock_event_sequence(wrong_delegated_sequence).is_err());

// Delegated events sequence.
let delegated_sequence = vec![
EventType::DelegatedInception,
EventType::DelegatedRotation,
EventType::Interaction,
KeyEventType::Dip,
KeyEventType::Drt,
KeyEventType::Ixn,
];
assert!(test_mock_event_sequence(delegated_sequence).is_ok());

Expand All @@ -462,20 +462,20 @@ mod tests {
#[test]
fn test_basic_sequence() -> Result<(), Error> {
let ok_seq = vec![
EventType::Inception,
EventType::Interaction,
EventType::Interaction,
EventType::Interaction,
EventType::Rotation,
EventType::Interaction,
KeyEventType::Icp,
KeyEventType::Ixn,
KeyEventType::Ixn,
KeyEventType::Ixn,
KeyEventType::Rot,
KeyEventType::Ixn,
];
assert!(test_mock_event_sequence(ok_seq).is_ok());

let delegated_sequence = vec![
EventType::DelegatedInception,
EventType::DelegatedRotation,
EventType::Interaction,
EventType::DelegatedRotation,
KeyEventType::Dip,
KeyEventType::Drt,
KeyEventType::Ixn,
KeyEventType::Drt,
];
assert!(test_mock_event_sequence(delegated_sequence).is_ok());

Expand Down
8 changes: 4 additions & 4 deletions src/event_message/tests/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::event_msg_builder::{EventMsgBuilder, EventType};
use crate::{derivation::{basic::Basic, self_addressing::SelfAddressing, self_signing::SelfSigning}, error::Error, event::sections::{key_config::nxt_commitment, threshold::SignatureThreshold}, keys::{PrivateKey, PublicKey}, prefix::{AttachedSignaturePrefix, BasicPrefix, IdentifierPrefix, SelfAddressingPrefix }, state::IdentifierState};
use super::event_msg_builder::EventMsgBuilder;
use crate::{derivation::{basic::Basic, self_addressing::SelfAddressing, self_signing::SelfSigning}, error::Error, event::sections::{key_config::nxt_commitment, threshold::SignatureThreshold}, keys::{PrivateKey, PublicKey}, prefix::{AttachedSignaturePrefix, BasicPrefix, IdentifierPrefix, SelfAddressingPrefix }, state::{IdentifierState, KeyEventType}};
use ed25519_dalek::Keypair;
use rand::rngs::OsRng;

Expand Down Expand Up @@ -38,7 +38,7 @@ fn get_initial_test_data() -> Result<TestStateData, Error> {
/// Construct mock event message from `event_type` and `state_data`, apply it to
/// `IdentifierState` in `state_data.state` and check if it was updated correctly.
fn test_update_identifier_state(
event_type: EventType,
event_type: KeyEventType,
state_data: TestStateData,
) -> Result<TestStateData, Error> {
// Get current and next key_pairs from argument.
Expand Down Expand Up @@ -140,7 +140,7 @@ fn test_update_identifier_state(

/// For given sequence of EventTypes check wheather `IdentifierState` is updated correctly
/// by applying `test_update_identifier_state` sequentially.
pub fn test_mock_event_sequence(sequence: Vec<EventType>) -> Result<TestStateData, Error> {
pub fn test_mock_event_sequence(sequence: Vec<KeyEventType>) -> Result<TestStateData, Error> {
let mut st = get_initial_test_data();

let step = |event_type, state_data: Result<TestStateData, Error>| {
Expand Down
3 changes: 2 additions & 1 deletion src/event_parsing/attachment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,8 @@ fn test_attachement() {
);

let cesr_attachment = "-VAj-HABE4YPqsEOaPNaZxVIbY-Gx2bJgP-c7AH_K7pEE-YfcI9E-AABAAMX88afPpEfF_HF-E-1uZKyv8b_TdILi2x8vC3Yi7Q7yzHn2fR6Bkl2yn-ZxPqmsTfV3f-H_VQwMgk7jYEukVCA";
let (_rest, att) = attachment(cesr_attachment.as_bytes()).unwrap();
let (rest, att) = attachment(cesr_attachment.as_bytes()).unwrap();
assert!(matches!(att, Attachment::Frame(_)));
assert!(rest.is_empty());

}
12 changes: 6 additions & 6 deletions src/keri/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ use crate::{database::sled::SledEventDatabase, derivation::basic::Basic, derivat
},
sections::seal::EventSeal
}, event_message::{signed_event_message::{SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, Message}}, event_message::{
event_msg_builder::{EventMsgBuilder, EventType},
event_msg_builder::EventMsgBuilder,
}, event_parsing::{SignedEventData, message::{signed_event_stream, signed_message}}, keys::PublicKey, prefix::AttachedSignaturePrefix, prefix::{
BasicPrefix,
IdentifierPrefix,
SelfSigningPrefix
}, processor::EventProcessor, signer::KeyManager, state::{
EventSemantics,
IdentifierState
IdentifierState, KeyEventType
}};
#[cfg(feature = "wallet")]
use universal_wallet::prelude::{Content, UnlockedWallet};
Expand Down Expand Up @@ -110,7 +110,7 @@ impl<K: KeyManager> Keri<K> {

pub fn incept(&mut self, initial_witness: Option<Vec<BasicPrefix>>) -> Result<SignedEventMessage, Error> {
let km = self.key_manager.lock().map_err(|_| Error::MutexPoisoned)?;
let icp = EventMsgBuilder::new(EventType::Inception)
let icp = EventMsgBuilder::new(KeyEventType::Icp)
.with_prefix(&self.prefix)
.with_keys(vec![Basic::Ed25519.derive(km.public_key())])
.with_next_keys(vec![Basic::Ed25519.derive(km.next_public_key())])
Expand Down Expand Up @@ -149,7 +149,7 @@ impl<K: KeyManager> Keri<K> {
// Signing key must be first
let km = self.key_manager.lock().map_err(|_| Error::MutexPoisoned)?;
keys.insert(0, Basic::Ed25519.derive(km.public_key()));
let icp = EventMsgBuilder::new(EventType::Inception)
let icp = EventMsgBuilder::new(KeyEventType::Icp)
.with_prefix(&self.prefix)
.with_keys(keys)
.with_next_keys(vec!(Basic::Ed25519.derive(km.next_public_key())))
Expand Down Expand Up @@ -240,7 +240,7 @@ impl<K: KeyManager> Keri<K> {
.compute_state(&self.prefix)?
.ok_or(Error::SemanticError("There is no state".into()))?;
match self.key_manager.lock() {
Ok(kv) => EventMsgBuilder::new(EventType::Rotation)
Ok(kv) => EventMsgBuilder::new(KeyEventType::Rot)
.with_prefix(&self.prefix)
.with_sn(state.sn + 1)
.with_previous_event(&SelfAddressing::Blake3_256.derive(&state.last))
Expand All @@ -265,7 +265,7 @@ impl<K: KeyManager> Keri<K> {
.compute_state(&self.prefix)?
.ok_or(Error::SemanticError("There is no state".into()))?;

let ev = EventMsgBuilder::new(EventType::Interaction)
let ev = EventMsgBuilder::new(KeyEventType::Ixn)
.with_prefix(&self.prefix)
.with_sn(state.sn + 1)
.with_previous_event(&SelfAddressing::Blake3_256.derive(&state.last))
Expand Down
4 changes: 2 additions & 2 deletions src/keri/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ pub fn test_key_state_notice() -> Result<(), Error> {
let res = alice.process_signed_reply(&signed_rpy.clone());
assert!(matches!(
res,
Err(Error::MissingEventError)
Err(Error::QueryError(QueryError::OutOfOrderEventError))
));
alice.process_event(&bob_icp)?;

Expand All @@ -267,7 +267,7 @@ pub fn test_key_state_notice() -> Result<(), Error> {
// Create transferable reply by bob and process it by alice.
let trans_rpy = witness.get_ksn_for_prefix(&bob_pref)?;
let res = alice.process_signed_reply(&trans_rpy.clone());
assert!(matches!(res, Err(Error::MissingEventError)));
assert!(matches!(res, Err(Error::QueryError(QueryError::OutOfOrderEventError))));

// Now update bob's state in alice's db to most recent.
alice.process_event(&new_bob_rot)?;
Expand Down

0 comments on commit b4ac877

Please sign in to comment.