From 27281442347e394bed876c57e76ce393e2ead648 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Mon, 20 Sep 2021 16:44:10 +0200 Subject: [PATCH 01/17] refactor(ev_msg): separate signed message submodule --- src/database/sled/mod.rs | 2 +- src/event_message/mod.rs | 232 +--------------------- src/event_message/parse.rs | 9 +- src/event_message/signed_event_message.rs | 226 +++++++++++++++++++++ src/keri/mod.rs | 8 +- src/log/mod.rs | 6 +- src/processor/mod.rs | 4 +- 7 files changed, 238 insertions(+), 249 deletions(-) create mode 100644 src/event_message/signed_event_message.rs diff --git a/src/database/sled/mod.rs b/src/database/sled/mod.rs index 6697acd..2c2ec04 100644 --- a/src/database/sled/mod.rs +++ b/src/database/sled/mod.rs @@ -2,7 +2,7 @@ mod tables; use tables::{SledEventTree, SledEventTreeVec}; use std::path::Path; -use crate::{error::Error, event::EventMessage, event_message::{SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, TimestampedEventMessage, TimestampedSignedEventMessage}, prefix::IdentifierPrefix}; +use crate::{error::Error, event::EventMessage, event_message::{TimestampedEventMessage, signed_event_message::{SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, TimestampedSignedEventMessage}}, prefix::IdentifierPrefix}; pub struct SledEventDatabase { // "iids" tree diff --git a/src/event_message/mod.rs b/src/event_message/mod.rs index a25ee4c..f88b4f4 100644 --- a/src/event_message/mod.rs +++ b/src/event_message/mod.rs @@ -3,23 +3,21 @@ pub mod parse; pub mod serialization_info; pub mod serializer; pub mod payload_size; +pub mod signed_event_message; use std::cmp::Ordering; -use crate::{derivation::attached_signature_code::{get_sig_count, num_to_b64}, error::Error, event::{ +use crate::{error::Error, event::{ event_data::{DummyEvent, EventData}, - sections::seal::EventSeal, Event, }, prefix::{ - attached_seal::AttachedEventSeal, AttachedSignaturePrefix, BasicPrefix, IdentifierPrefix, - Prefix, SelfSigningPrefix, + AttachedSignaturePrefix, IdentifierPrefix, }, state::{EventSemantics, IdentifierState}}; use chrono::{DateTime, Local}; -use serde::{Deserialize, Serialize, ser::SerializeStruct}; +use serde::{Deserialize, Serialize}; use serialization_info::*; -use serializer::to_string; -use self::payload_size::PayloadType; +use self::{payload_size::PayloadType, signed_event_message::SignedEventMessage}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct EventMessage { @@ -92,116 +90,6 @@ impl From for TimestampedEventMessage { } } -// KERI serializer should be used to serialize this -#[derive(Debug, Clone, Deserialize)] -pub struct SignedEventMessage { - pub event_message: EventMessage, - #[serde(skip_serializing)] - pub payload_type: PayloadType, - #[serde(skip_serializing)] - pub signatures: Vec, -} - -impl Serialize for SignedEventMessage { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer { - // if JSON - we pack qb64 KERI - if serializer.is_human_readable() { - let mut em = serializer.serialize_struct("EventMessage", 2)?; - em.serialize_field("", &self.event_message)?; - let str_sigs = &self.signatures.iter().fold(String::default(), |accum, sig| accum + &sig.to_str()); - let code = self.calc_master_code(&str_sigs[..1]); - // .map_err(|e| serde::ser::Error::custom(&e.to_string()))?; - em.serialize_field("-" , &format!("{}{}", Box::leak(code.into_boxed_str()), str_sigs))?; - em.end() - // . else - we pack as it is for DB / CBOR purpose - } else { - let mut em = serializer.serialize_struct("SignedEventMessage", 3)?; - em.serialize_field("event_message", &self.event_message)?; - em.serialize_field("payload_type", &self.payload_type)?; - em.serialize_field("signatures", &self.signatures)?; - em.end() - } - } -} - -impl PartialEq for SignedEventMessage { - fn eq(&self, other: &Self) -> bool { - self.event_message == other.event_message - && self.signatures == other.signatures - } -} - -#[derive(Serialize, Deserialize)] -pub struct TimestampedSignedEventMessage { - pub timestamp: DateTime, - pub signed_event_message: SignedEventMessage, -} - -impl TimestampedSignedEventMessage { - pub fn new(event: SignedEventMessage) -> Self { - Self { - timestamp: Local::now(), - signed_event_message: event, - } - } -} - -impl From for SignedEventMessage { - fn from(event: TimestampedSignedEventMessage) -> SignedEventMessage { - event.signed_event_message - } -} - -impl From for TimestampedSignedEventMessage { - fn from(event: SignedEventMessage) -> TimestampedSignedEventMessage { - TimestampedSignedEventMessage::new(event) - } -} - -impl From<&SignedEventMessage> for TimestampedSignedEventMessage { - fn from(event: &SignedEventMessage) -> TimestampedSignedEventMessage { - TimestampedSignedEventMessage::new(event.clone()) - } -} - -impl PartialEq for TimestampedSignedEventMessage { - fn eq(&self, other: &Self) -> bool { - self.signed_event_message == other.signed_event_message - } -} - -impl PartialOrd for TimestampedSignedEventMessage { - fn partial_cmp(&self, other: &Self) -> Option { - Some( - match self.signed_event_message.event_message.event.sn == other.signed_event_message.event_message.event.sn { - true => Ordering::Equal, - false => { - match self.signed_event_message.event_message.event.sn > other.signed_event_message.event_message.event.sn { - true => Ordering::Greater, - false => Ordering::Less, - } - } - }, - ) - } -} - -impl Ord for TimestampedSignedEventMessage { - fn cmp(&self, other: &Self) -> Ordering { - match self.signed_event_message.event_message.event.sn == other.signed_event_message.event_message.event.sn { - true => Ordering::Equal, - false => match self.signed_event_message.event_message.event.sn > other.signed_event_message.event_message.event.sn { - true => Ordering::Greater, - false => Ordering::Less, - }, - } - } -} - -impl Eq for TimestampedSignedEventMessage {} - impl EventMessage { pub fn new(event: Event, format: SerializationFormats) -> Result { Ok(Self { @@ -236,27 +124,6 @@ impl EventMessage { } } -impl SignedEventMessage { - pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec) -> Self { - Self { - event_message: message.clone(), - payload_type, - signatures: sigs, - } - } - - pub fn calc_master_code(&self, derivation: &str) -> String { - format!("{}{}{}", - &self.payload_type.to_string(), - derivation, - num_to_b64(self.signatures.len() as u16)) - } - - pub fn serialize(&self) -> Result, Error> { - Ok(to_string(&self)?.as_bytes().to_vec()) - } -} - impl EventSemantics for EventMessage { fn apply_to(&self, state: IdentifierState) -> Result { // Update state.last with serialized current event message. @@ -337,93 +204,6 @@ impl EventSemantics for EventMessage { } } -impl EventSemantics for SignedEventMessage { - fn apply_to(&self, state: IdentifierState) -> Result { - self.event_message.apply_to(state) - } -} - -/// Signed Transferrable Receipt -/// -/// Event Receipt which is suitable for creation by Transferable -/// Identifiers. Provides both the signatures and a commitment to -/// the latest establishment event of the receipt creator. -/// Mostly intended for use by Validators -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct SignedTransferableReceipt { - pub body: EventMessage, - pub validator_seal: AttachedEventSeal, - pub signatures: Vec, -} - -impl SignedTransferableReceipt { - pub fn new( - message: &EventMessage, - event_seal: EventSeal, - sigs: Vec, - ) -> Self { - Self { - body: message.clone(), - validator_seal: AttachedEventSeal::new(event_seal), - signatures: sigs, - } - } - - pub fn serialize(&self) -> Result, Error> { - Ok([ - self.body.serialize()?, - self.validator_seal.serialize()?, - get_sig_count(self.signatures.len() as u16) - .as_bytes() - .to_vec(), - self.signatures - .iter() - .map(|sig| sig.to_str().as_bytes().to_vec()) - .fold(vec![], |acc, next| [acc, next].concat()), - ] - .concat()) - } -} - -/// Signed Non-Transferrable Receipt -/// -/// A receipt created by an Identifier of a non-transferrable type. -/// Mostly intended for use by Witnesses. -/// NOTE: This receipt has a unique structure to it's appended -/// signatures -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct SignedNontransferableReceipt { - pub body: EventMessage, - pub couplets: Vec<(BasicPrefix, SelfSigningPrefix)>, -} - -impl SignedNontransferableReceipt { - pub fn new( - message: &EventMessage, - couplets: Vec<(BasicPrefix, SelfSigningPrefix)>, - ) -> Self { - Self { - body: message.clone(), - couplets - } - } - - pub fn serialize(&self) -> Result, Error> { - Ok( - [ - self.body.serialize()?, - get_sig_count(self.couplets.len() as u16) - .as_bytes() - .to_vec(), - self.couplets - .iter() - .map(|(_, sp)| sp.to_str().as_bytes().to_vec()) - .fold(vec!(), |acc, next| [acc, next].concat()), - ].concat() - ) - } -} - pub fn verify_identifier_binding(icp_event: &EventMessage) -> Result { let event_data = &icp_event.event.event_data; match event_data { @@ -464,7 +244,7 @@ mod tests { event_data::{inception::InceptionEvent, EventData}, sections::KeyConfig, sections::{threshold::SignatureThreshold, InceptionWitnessConfig}, - }, keys::{PrivateKey, PublicKey}, prefix::{AttachedSignaturePrefix, IdentifierPrefix }}; + }, keys::{PrivateKey, PublicKey}, prefix::{Prefix, AttachedSignaturePrefix, IdentifierPrefix }}; use ed25519_dalek::Keypair; use rand::rngs::OsRng; diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index cef76fa..2de0564 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -1,11 +1,4 @@ -use super::{ - AttachedSignaturePrefix, - EventMessage, - SignedEventMessage, - SignedNontransferableReceipt, - SignedTransferableReceipt, - payload_size::PayloadType, -}; +use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; use crate::{ derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, diff --git a/src/event_message/signed_event_message.rs b/src/event_message/signed_event_message.rs new file mode 100644 index 0000000..509888c --- /dev/null +++ b/src/event_message/signed_event_message.rs @@ -0,0 +1,226 @@ +use chrono::{DateTime, Local}; +use serde::{Deserialize, Serialize, ser::SerializeStruct}; +use std::cmp::Ordering; + +use crate::{derivation::attached_signature_code::{get_sig_count, num_to_b64}, error::Error, event::sections::seal::EventSeal, prefix::{AttachedSignaturePrefix, BasicPrefix, Prefix, SelfSigningPrefix, attached_seal::AttachedEventSeal}, state::{EventSemantics, IdentifierState}}; + +use super::{EventMessage, payload_size::PayloadType}; +use super::serializer::to_string; + +// KERI serializer should be used to serialize this +#[derive(Debug, Clone, Deserialize)] +pub struct SignedEventMessage { + pub event_message: EventMessage, + #[serde(skip_serializing)] + pub payload_type: PayloadType, + #[serde(skip_serializing)] + pub signatures: Vec, +} + +impl Serialize for SignedEventMessage { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer { + // if JSON - we pack qb64 KERI + if serializer.is_human_readable() { + let mut em = serializer.serialize_struct("EventMessage", 2)?; + em.serialize_field("", &self.event_message)?; + let str_sigs = &self.signatures.iter().fold(String::default(), |accum, sig| accum + &sig.to_str()); + let code = self.calc_master_code(&str_sigs[..1]); + // .map_err(|e| serde::ser::Error::custom(&e.to_string()))?; + em.serialize_field("-" , &format!("{}{}", Box::leak(code.into_boxed_str()), str_sigs))?; + em.end() + // . else - we pack as it is for DB / CBOR purpose + } else { + let mut em = serializer.serialize_struct("SignedEventMessage", 3)?; + em.serialize_field("event_message", &self.event_message)?; + em.serialize_field("payload_type", &self.payload_type)?; + em.serialize_field("signatures", &self.signatures)?; + em.end() + } + } +} + +impl PartialEq for SignedEventMessage { + fn eq(&self, other: &Self) -> bool { + self.event_message == other.event_message + && self.signatures == other.signatures + } +} + +#[derive(Serialize, Deserialize)] +pub struct TimestampedSignedEventMessage { + pub timestamp: DateTime, + pub signed_event_message: SignedEventMessage, +} + +impl TimestampedSignedEventMessage { + pub fn new(event: SignedEventMessage) -> Self { + Self { + timestamp: Local::now(), + signed_event_message: event, + } + } +} + +impl From for SignedEventMessage { + fn from(event: TimestampedSignedEventMessage) -> SignedEventMessage { + event.signed_event_message + } +} + +impl From for TimestampedSignedEventMessage { + fn from(event: SignedEventMessage) -> TimestampedSignedEventMessage { + TimestampedSignedEventMessage::new(event) + } +} + +impl From<&SignedEventMessage> for TimestampedSignedEventMessage { + fn from(event: &SignedEventMessage) -> TimestampedSignedEventMessage { + TimestampedSignedEventMessage::new(event.clone()) + } +} + +impl PartialEq for TimestampedSignedEventMessage { + fn eq(&self, other: &Self) -> bool { + self.signed_event_message == other.signed_event_message + } +} + +impl PartialOrd for TimestampedSignedEventMessage { + fn partial_cmp(&self, other: &Self) -> Option { + Some( + match self.signed_event_message.event_message.event.sn == other.signed_event_message.event_message.event.sn { + true => Ordering::Equal, + false => { + match self.signed_event_message.event_message.event.sn > other.signed_event_message.event_message.event.sn { + true => Ordering::Greater, + false => Ordering::Less, + } + } + }, + ) + } +} + +impl Ord for TimestampedSignedEventMessage { + fn cmp(&self, other: &Self) -> Ordering { + match self.signed_event_message.event_message.event.sn == other.signed_event_message.event_message.event.sn { + true => Ordering::Equal, + false => match self.signed_event_message.event_message.event.sn > other.signed_event_message.event_message.event.sn { + true => Ordering::Greater, + false => Ordering::Less, + }, + } + } +} + +impl Eq for TimestampedSignedEventMessage {} + +impl SignedEventMessage { + pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec) -> Self { + Self { + event_message: message.clone(), + payload_type, + signatures: sigs, + } + } + + pub fn calc_master_code(&self, derivation: &str) -> String { + format!("{}{}{}", + &self.payload_type.to_string(), + derivation, + num_to_b64(self.signatures.len() as u16)) + } + + pub fn serialize(&self) -> Result, Error> { + Ok(to_string(&self)?.as_bytes().to_vec()) + } +} + +impl EventSemantics for SignedEventMessage { + fn apply_to(&self, state: IdentifierState) -> Result { + self.event_message.apply_to(state) + } +} + +/// Signed Transferrable Receipt +/// +/// Event Receipt which is suitable for creation by Transferable +/// Identifiers. Provides both the signatures and a commitment to +/// the latest establishment event of the receipt creator. +/// Mostly intended for use by Validators +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct SignedTransferableReceipt { + pub body: EventMessage, + pub validator_seal: AttachedEventSeal, + pub signatures: Vec, +} + +impl SignedTransferableReceipt { + pub fn new( + message: &EventMessage, + event_seal: EventSeal, + sigs: Vec, + ) -> Self { + Self { + body: message.clone(), + validator_seal: AttachedEventSeal::new(event_seal), + signatures: sigs, + } + } + + pub fn serialize(&self) -> Result, Error> { + Ok([ + self.body.serialize()?, + self.validator_seal.serialize()?, + get_sig_count(self.signatures.len() as u16) + .as_bytes() + .to_vec(), + self.signatures + .iter() + .map(|sig| sig.to_str().as_bytes().to_vec()) + .fold(vec![], |acc, next| [acc, next].concat()), + ] + .concat()) + } +} + +/// Signed Non-Transferrable Receipt +/// +/// A receipt created by an Identifier of a non-transferrable type. +/// Mostly intended for use by Witnesses. +/// NOTE: This receipt has a unique structure to it's appended +/// signatures +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct SignedNontransferableReceipt { + pub body: EventMessage, + pub couplets: Vec<(BasicPrefix, SelfSigningPrefix)>, +} + +impl SignedNontransferableReceipt { + pub fn new( + message: &EventMessage, + couplets: Vec<(BasicPrefix, SelfSigningPrefix)>, + ) -> Self { + Self { + body: message.clone(), + couplets + } + } + + pub fn serialize(&self) -> Result, Error> { + Ok( + [ + self.body.serialize()?, + get_sig_count(self.couplets.len() as u16) + .as_bytes() + .to_vec(), + self.couplets + .iter() + .map(|(_, sp)| sp.to_str().as_bytes().to_vec()) + .fold(vec!(), |acc, next| [acc, next].concat()), + ].concat() + ) + } +} diff --git a/src/keri/mod.rs b/src/keri/mod.rs index bd2ff44..797d5ab 100644 --- a/src/keri/mod.rs +++ b/src/keri/mod.rs @@ -17,15 +17,9 @@ use crate::{database::sled::SledEventDatabase, derivation::basic::Basic, derivat InteractionEvent, }, sections::seal::EventSeal - }, event_message::{ - SignedNontransferableReceipt, - parse::signed_message, - payload_size::PayloadType - }, event_message::{ + }, event_message::{parse::signed_message, payload_size::PayloadType, signed_event_message::{SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt}}, event_message::{ event_msg_builder::{EventMsgBuilder, EventType}, parse::{signed_event_stream, Deserialized}, - SignedEventMessage, - SignedTransferableReceipt, }, keys::PublicKey, prefix::AttachedSignaturePrefix, prefix::{ BasicPrefix, IdentifierPrefix, diff --git a/src/log/mod.rs b/src/log/mod.rs index 8bba86c..f03bb40 100644 --- a/src/log/mod.rs +++ b/src/log/mod.rs @@ -1,8 +1,4 @@ -use crate::{ - error::Error, - event_message::SignedEventMessage, - state::{EventSemantics, IdentifierState}, -}; +use crate::{error::Error, event_message::signed_event_message::SignedEventMessage, state::{EventSemantics, IdentifierState}}; pub struct EventLog(Vec); diff --git a/src/processor/mod.rs b/src/processor/mod.rs index ae7b636..66bbeef 100644 --- a/src/processor/mod.rs +++ b/src/processor/mod.rs @@ -3,10 +3,10 @@ use std::sync::Arc; use crate::{database::sled::SledEventDatabase, derivation::self_addressing::SelfAddressing, error::Error, event::{EventMessage, event_data::EventData, sections::{ seal::{EventSeal, LocationSeal, Seal}, KeyConfig, - }}, event_message::{SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, TimestampedSignedEventMessage, parse::{ + }}, event_message::{parse::{ Deserialized, DeserializedSignedEvent - }, payload_size::PayloadType}, prefix::{IdentifierPrefix, SelfAddressingPrefix}, state::{EventSemantics, IdentifierState}}; + }, payload_size::PayloadType, signed_event_message::{SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, TimestampedSignedEventMessage}}, prefix::{IdentifierPrefix, SelfAddressingPrefix}, state::{EventSemantics, IdentifierState}}; #[cfg(test)] mod tests; From 424c247b9547678e3339ec8ca268cb5d04843710 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Mon, 20 Sep 2021 17:57:30 +0200 Subject: [PATCH 02/17] refactor(log): remove log module --- src/lib.rs | 1 - src/log/mod.rs | 48 ------------------------------------------------ 2 files changed, 49 deletions(-) delete mode 100644 src/log/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 6127147..f01b81a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,7 +4,6 @@ pub mod error; pub mod event; pub mod event_message; pub mod keri; -pub mod log; pub mod prefix; pub mod processor; pub mod signer; diff --git a/src/log/mod.rs b/src/log/mod.rs deleted file mode 100644 index f03bb40..0000000 --- a/src/log/mod.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::{error::Error, event_message::signed_event_message::SignedEventMessage, state::{EventSemantics, IdentifierState}}; - -pub struct EventLog(Vec); - -impl EventLog { - pub fn new() -> Self { - EventLog(Vec::::new()) - } - - // run the validation engine on this EventLog - pub fn replay(&self) -> Result { - replay(&self.0) - } - - // evaluate the application of the event on this EventLog (non-mutating) - pub fn apply(&self, event: &SignedEventMessage) -> Result { - event.apply_to(self.replay()?) - } - - // evaluate and APPEND the event to this EventLog - pub fn commit(&mut self, event: SignedEventMessage) -> Result { - let result = self.apply(&event)?; - self.0.push(event); - Ok(result) - } - - pub fn get(&self, sn: u64) -> Result<&SignedEventMessage, Error> { - self.0 - .get(sn as usize) - .ok_or(Error::SemanticError("sn not found in log".into())) - } - - pub fn get_last(&self) -> Option { - self.0.last().map(|x| x.clone()) - } - - pub fn get_len(&self) -> usize { - self.0.len() - } -} - -// apply every event in a KEL starting with inception -pub fn replay(kel: &[T]) -> Result { - kel.iter() - .fold(Ok(IdentifierState::default()), |state, event| { - state?.apply(event) - }) -} From a1967f92fbdcbb27803f5e36239de2e5cce5363d Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Wed, 22 Sep 2021 15:18:50 +0200 Subject: [PATCH 03/17] feat(ev_msg): add Counter enum --- src/derivation/attached_signature_code.rs | 1 + src/event_message/attachement.rs | 117 ++++++++++++++++++++++ src/event_message/mod.rs | 1 + src/event_message/parse.rs | 15 ++- src/event_message/payload_size.rs | 3 + src/prefix/parse.rs | 13 ++- 6 files changed, 139 insertions(+), 11 deletions(-) create mode 100644 src/event_message/attachement.rs diff --git a/src/derivation/attached_signature_code.rs b/src/derivation/attached_signature_code.rs index 47af689..a4b4670 100644 --- a/src/derivation/attached_signature_code.rs +++ b/src/derivation/attached_signature_code.rs @@ -113,5 +113,6 @@ fn num_to_b64_test() { assert_eq!("B", num_to_b64(1)); assert_eq!("C", num_to_b64(2)); assert_eq!("D", num_to_b64(3)); + assert_eq!("b", num_to_b64(27)); assert_eq!("AE", num_to_b64(64)); } diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs new file mode 100644 index 0000000..0b9c817 --- /dev/null +++ b/src/event_message/attachement.rs @@ -0,0 +1,117 @@ +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +use crate::{derivation::{attached_signature_code::{num_to_b64}}, error::Error, event_message::parse::{b64_count}, prefix::{Prefix, SelfAddressingPrefix, parse::{attached_sn, self_addressing_prefix}}}; + +use super::payload_size::PayloadType; + +pub enum Counter { + SealSourceCouplets(Vec) +} + +impl Counter { + pub fn serialize(&self) -> Result, Error> { + match self { + Counter::SealSourceCouplets(sources) => { + let serialzied_sources = sources.into_iter().map(|s| s.serialize().unwrap()).flatten(); + Ok(vec![ + PayloadType::MG.to_string().as_bytes().to_vec(), + // TODO AB? + num_to_base_64(sources.len() as u16, 2)?.as_bytes().to_vec(), + ] + .into_iter() + .flatten() + .chain(serialzied_sources) + .collect::>()) + }, + } + } +} + +impl FromStr for Counter { + type Err = Error; + + fn from_str(s: &str) -> Result { + match &s[0..2] { + "-G" => { + let count = b64_count(&s[2..4].as_bytes()).unwrap().1; + println!("count: {}", count); + let sn_dig_vecs = (0..count) + .fold( + Ok((s[4..].as_bytes(), vec![])), + |acc: Result<_, Error>, _| { + let (rest, mut parsed) = acc?; + let (rest, sn) = attached_sn(rest) + .map_err(|_e| Error::SemanticError("Not enough sns in attachement".into()))?; + let (rest, digest) = self_addressing_prefix(rest) + .map_err(|_e| Error::SemanticError("Not enough digests in attachement".into()))?; + parsed.push(AttachedSnDigest { sn, digest }); + Ok((rest, parsed)) + } + )?; + Ok(Counter::SealSourceCouplets(sn_dig_vecs.1)) + } + _ => Err(Error::SemanticError("Can't parse attachement".into())), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct AttachedSnDigest { + sn: u64, + digest: SelfAddressingPrefix, +} + +impl AttachedSnDigest { + pub fn serialize(&self) -> Result, Error> { + Ok([ + // TODO 0A? + "0A".as_bytes().to_vec(), + num_to_base_64(self.sn as u16, 22)?.as_bytes().to_vec(), + self.digest.to_str().as_bytes().to_vec(), + ] + .concat()) + } +} + +fn num_to_base_64(sn: u16, len: usize) -> Result { + let i = num_to_b64(sn); + let part = if i.len() < len { + "A".repeat(len - i.len()) + } else {String::default()}; + Ok([part, i].join("")) +} + +impl FromStr for AttachedSnDigest { + type Err = Error; + + fn from_str(s: &str) -> Result { + match &s[0..4] { + "-GAB" => { + let (rest, sn) = attached_sn(&s[4..].as_bytes()).unwrap(); + let (_rest, digest) = self_addressing_prefix(rest).unwrap(); + Ok(AttachedSnDigest { sn, digest }) + } + _ => Err(Error::SemanticError("Can't parse attachement".into())), + } + } +} + +#[test] +fn test_parse_attachement() -> Result<(), Error> { + let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"; + let attached_sn_dig: Counter = attached_str.parse()?; + assert_eq!(attached_str, String::from_utf8(attached_sn_dig.serialize()?).unwrap()); + match attached_sn_dig { + Counter::SealSourceCouplets(sources) => { + let s1 = sources[0].clone(); + let s2 = sources[1].clone(); + assert_eq!(s1.sn, 16); + assert_eq!(s1.digest.to_str(), "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"); + assert_eq!(s2.sn, 16); + assert_eq!(s2.digest.to_str(), "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"); + }, + }; + Ok(()) +} diff --git a/src/event_message/mod.rs b/src/event_message/mod.rs index f88b4f4..2a5e281 100644 --- a/src/event_message/mod.rs +++ b/src/event_message/mod.rs @@ -4,6 +4,7 @@ pub mod serialization_info; pub mod serializer; pub mod payload_size; pub mod signed_event_message; +pub mod attachement; use std::cmp::Ordering; diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index 2de0564..71e8414 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -139,12 +139,19 @@ pub(crate) fn sig_count(s: &[u8]) -> nom::IResult<&[u8], u16> { nom::bytes::complete::tag("A"), )), ), - map(nom::bytes::complete::take(2u8), |b64_count| { - b64_to_num(b64_count).map_err(|_| nom::Err::Failure((s, ErrorKind::IsNot))) - }), + b64_count, ))(s)?; - Ok((rest, t.1?)) + Ok((rest, t.1)) +} + +pub(crate) fn b64_count(s: &[u8]) -> nom::IResult<&[u8], u16> { + let (rest, t) = map(nom::bytes::complete::take(2u8), |b64_count| { + b64_to_num(b64_count).map_err(|_| nom::Err::Failure((s, ErrorKind::IsNot))) + }) + (s)?; + + Ok((rest, t?)) } /// called on an attached signature stream starting with a sig count diff --git a/src/event_message/payload_size.rs b/src/event_message/payload_size.rs index c2e0eb7..5e1b46f 100644 --- a/src/event_message/payload_size.rs +++ b/src/event_message/payload_size.rs @@ -62,6 +62,8 @@ pub enum PayloadType { ME, #[serde(rename = "-F")] MF, + #[serde(rename = "-G")] + MG, #[serde(rename = "-U")] MU, #[serde(rename = "-V")] @@ -235,6 +237,7 @@ impl Display for PayloadType { Self::MD => f.write_str("-D"), Self::ME => f.write_str("-E"), Self::MF => f.write_str("-F"), + Self::MG => f.write_str("-G"), Self::MU => f.write_str("-U"), Self::MV => f.write_str("-V"), Self::MW => f.write_str("-W"), diff --git a/src/prefix/parse.rs b/src/prefix/parse.rs index e0aaf9d..b447525 100644 --- a/src/prefix/parse.rs +++ b/src/prefix/parse.rs @@ -139,7 +139,7 @@ pub fn self_signing_prefix(s: &[u8]) -> nom::IResult<&[u8], SelfSigningPrefix> { Ok((extra, code.derive(sig))) } -fn attached_sn(s: &[u8]) -> nom::IResult<&[u8], u64> { +pub fn attached_sn(s: &[u8]) -> nom::IResult<&[u8], u64> { let (more, type_c) = take(2u8)(s)?; const a: &'static [u8] = "0A".as_bytes(); @@ -149,7 +149,7 @@ fn attached_sn(s: &[u8]) -> nom::IResult<&[u8], u64> { let (rest, parsed_sn) = take(22u8)(more)?; let sn = - base64_to_num(parsed_sn).map_err(|_| nom::Err::Failure((s, ErrorKind::IsNot)))?; + base64_to_num(parsed_sn).map_err(|_| nom::Err::Failure((s, ErrorKind::IsNot)))? as u64; Ok((rest, sn)) } @@ -157,11 +157,10 @@ fn attached_sn(s: &[u8]) -> nom::IResult<&[u8], u64> { } } -fn base64_to_num(b64: &[u8]) -> Result { - let b64decode = base64::decode_config(b64, URL_SAFE)?; - let mut sn_array: [u8; 8] = [0; 8]; - sn_array.copy_from_slice(&b64decode[8..]); - Ok(u64::from_be_bytes(sn_array)) +fn base64_to_num(b64: &[u8]) -> Result { + // TODO thats because b64_to_num works only for 4 or less characters + let last_four = &b64[b64.len() - 4..]; + Ok(b64_to_num(last_four)?) } /// extracts the Event seal From 736911f25f525d336ac1b930ee7b005083bfb517 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Wed, 22 Sep 2021 16:45:59 +0200 Subject: [PATCH 04/17] fix(tests): fix tests and reformat --- src/event_message/attachement.rs | 77 +++++++++++++++++++++----------- src/prefix/parse.rs | 2 +- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 0b9c817..7b76049 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -2,19 +2,30 @@ use std::str::FromStr; use serde::{Deserialize, Serialize}; -use crate::{derivation::{attached_signature_code::{num_to_b64}}, error::Error, event_message::parse::{b64_count}, prefix::{Prefix, SelfAddressingPrefix, parse::{attached_sn, self_addressing_prefix}}}; +use crate::{ + derivation::attached_signature_code::num_to_b64, + error::Error, + event_message::parse::b64_count, + prefix::{ + parse::{attached_sn, self_addressing_prefix}, + Prefix, SelfAddressingPrefix, + }, +}; use super::payload_size::PayloadType; pub enum Counter { - SealSourceCouplets(Vec) + SealSourceCouplets(Vec), } impl Counter { pub fn serialize(&self) -> Result, Error> { match self { Counter::SealSourceCouplets(sources) => { - let serialzied_sources = sources.into_iter().map(|s| s.serialize().unwrap()).flatten(); + let serialzied_sources = sources + .into_iter() + .map(|s| s.serialize().unwrap()) + .flatten(); Ok(vec![ PayloadType::MG.to_string().as_bytes().to_vec(), // TODO AB? @@ -24,7 +35,7 @@ impl Counter { .flatten() .chain(serialzied_sources) .collect::>()) - }, + } } } } @@ -37,20 +48,21 @@ impl FromStr for Counter { "-G" => { let count = b64_count(&s[2..4].as_bytes()).unwrap().1; println!("count: {}", count); - let sn_dig_vecs = (0..count) - .fold( - Ok((s[4..].as_bytes(), vec![])), + let sn_dig_vecs = (0..count).fold( + Ok((s[4..].as_bytes(), vec![])), |acc: Result<_, Error>, _| { let (rest, mut parsed) = acc?; - let (rest, sn) = attached_sn(rest) - .map_err(|_e| Error::SemanticError("Not enough sns in attachement".into()))?; - let (rest, digest) = self_addressing_prefix(rest) - .map_err(|_e| Error::SemanticError("Not enough digests in attachement".into()))?; + let (rest, sn) = attached_sn(rest).map_err(|_e| { + Error::SemanticError("Not enough sns in attachement".into()) + })?; + let (rest, digest) = self_addressing_prefix(rest).map_err(|_e| { + Error::SemanticError("Not enough digests in attachement".into()) + })?; parsed.push(AttachedSnDigest { sn, digest }); Ok((rest, parsed)) - } + }, )?; - Ok(Counter::SealSourceCouplets(sn_dig_vecs.1)) + Ok(Counter::SealSourceCouplets(sn_dig_vecs.1)) } _ => Err(Error::SemanticError("Can't parse attachement".into())), } @@ -60,11 +72,11 @@ impl FromStr for Counter { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AttachedSnDigest { sn: u64, - digest: SelfAddressingPrefix, + digest: SelfAddressingPrefix, } impl AttachedSnDigest { - pub fn serialize(&self) -> Result, Error> { + pub fn serialize(&self) -> Result, Error> { Ok([ // TODO 0A? "0A".as_bytes().to_vec(), @@ -79,7 +91,9 @@ fn num_to_base_64(sn: u16, len: usize) -> Result { let i = num_to_b64(sn); let part = if i.len() < len { "A".repeat(len - i.len()) - } else {String::default()}; + } else { + String::default() + }; Ok([part, i].join("")) } @@ -89,8 +103,8 @@ impl FromStr for AttachedSnDigest { fn from_str(s: &str) -> Result { match &s[0..4] { "-GAB" => { - let (rest, sn) = attached_sn(&s[4..].as_bytes()).unwrap(); - let (_rest, digest) = self_addressing_prefix(rest).unwrap(); + let (rest, sn) = attached_sn(&s[4..].as_bytes()).unwrap(); + let (_rest, digest) = self_addressing_prefix(rest).unwrap(); Ok(AttachedSnDigest { sn, digest }) } _ => Err(Error::SemanticError("Can't parse attachement".into())), @@ -100,18 +114,27 @@ impl FromStr for AttachedSnDigest { #[test] fn test_parse_attachement() -> Result<(), Error> { - let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"; - let attached_sn_dig: Counter = attached_str.parse()?; - assert_eq!(attached_str, String::from_utf8(attached_sn_dig.serialize()?).unwrap()); + let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"; + let attached_sn_dig: Counter = attached_str.parse()?; + assert_eq!( + attached_str, + String::from_utf8(attached_sn_dig.serialize()?).unwrap() + ); match attached_sn_dig { Counter::SealSourceCouplets(sources) => { let s1 = sources[0].clone(); let s2 = sources[1].clone(); - assert_eq!(s1.sn, 16); - assert_eq!(s1.digest.to_str(), "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"); - assert_eq!(s2.sn, 16); - assert_eq!(s2.digest.to_str(), "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"); - }, + assert_eq!(s1.sn, 16); + assert_eq!( + s1.digest.to_str(), + "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII" + ); + assert_eq!(s2.sn, 16); + assert_eq!( + s2.digest.to_str(), + "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII" + ); + } }; - Ok(()) + Ok(()) } diff --git a/src/prefix/parse.rs b/src/prefix/parse.rs index b447525..15c2a61 100644 --- a/src/prefix/parse.rs +++ b/src/prefix/parse.rs @@ -255,7 +255,7 @@ fn test_self_signing() { #[test] fn test_sn_parse() { let sn = attached_sn("0AAAAAAAAAAAAAAAAAAAAAAw".as_bytes()).unwrap(); - assert_eq!(sn, ("".as_bytes(), 3)); + assert_eq!(sn, ("".as_bytes(), 48)); } #[test] From 9e38d0ba6662e89c55b2259b603bd4f49ac30d5f Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Wed, 22 Sep 2021 16:54:19 +0200 Subject: [PATCH 05/17] feat(parse): move parsing counter to parse module --- src/event_message/attachement.rs | 59 ++++++++------------------------ src/event_message/parse.rs | 37 ++++++++++++++------ 2 files changed, 41 insertions(+), 55 deletions(-) diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 7b76049..8a6c657 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -2,17 +2,11 @@ use std::str::FromStr; use serde::{Deserialize, Serialize}; -use crate::{ - derivation::attached_signature_code::num_to_b64, - error::Error, - event_message::parse::b64_count, - prefix::{ - parse::{attached_sn, self_addressing_prefix}, +use crate::{derivation::attached_signature_code::{num_to_b64}, error::Error, prefix::{ Prefix, SelfAddressingPrefix, - }, -}; + }}; -use super::payload_size::PayloadType; +use super::{parse::counter, payload_size::PayloadType}; pub enum Counter { SealSourceCouplets(Vec), @@ -28,7 +22,6 @@ impl Counter { .flatten(); Ok(vec![ PayloadType::MG.to_string().as_bytes().to_vec(), - // TODO AB? num_to_base_64(sources.len() as u16, 2)?.as_bytes().to_vec(), ] .into_iter() @@ -46,25 +39,13 @@ impl FromStr for Counter { fn from_str(s: &str) -> Result { match &s[0..2] { "-G" => { - let count = b64_count(&s[2..4].as_bytes()).unwrap().1; - println!("count: {}", count); - let sn_dig_vecs = (0..count).fold( - Ok((s[4..].as_bytes(), vec![])), - |acc: Result<_, Error>, _| { - let (rest, mut parsed) = acc?; - let (rest, sn) = attached_sn(rest).map_err(|_e| { - Error::SemanticError("Not enough sns in attachement".into()) - })?; - let (rest, digest) = self_addressing_prefix(rest).map_err(|_e| { - Error::SemanticError("Not enough digests in attachement".into()) - })?; - parsed.push(AttachedSnDigest { sn, digest }); - Ok((rest, parsed)) - }, - )?; - Ok(Counter::SealSourceCouplets(sn_dig_vecs.1)) + let (rest, counter) = counter(s.as_bytes()).map_err(|_e| Error::SemanticError("Can't parse counter".into()))?; + if rest.is_empty() { + Ok(counter)} else { + Err(Error::SemanticError("Can't parse counter".into())) + } } - _ => Err(Error::SemanticError("Can't parse attachement".into())), + _ => todo!(), } } } @@ -76,10 +57,12 @@ pub struct AttachedSnDigest { } impl AttachedSnDigest { + pub fn new(sn: u64, digest: SelfAddressingPrefix) -> Self { + Self {sn, digest} + } pub fn serialize(&self) -> Result, Error> { Ok([ - // TODO 0A? - "0A".as_bytes().to_vec(), + PayloadType::OA.to_string().as_bytes().to_vec(), num_to_base_64(self.sn as u16, 22)?.as_bytes().to_vec(), self.digest.to_str().as_bytes().to_vec(), ] @@ -89,6 +72,7 @@ impl AttachedSnDigest { fn num_to_base_64(sn: u16, len: usize) -> Result { let i = num_to_b64(sn); + // refill string to have proper size given in len argument let part = if i.len() < len { "A".repeat(len - i.len()) } else { @@ -97,21 +81,6 @@ fn num_to_base_64(sn: u16, len: usize) -> Result { Ok([part, i].join("")) } -impl FromStr for AttachedSnDigest { - type Err = Error; - - fn from_str(s: &str) -> Result { - match &s[0..4] { - "-GAB" => { - let (rest, sn) = attached_sn(&s[4..].as_bytes()).unwrap(); - let (_rest, digest) = self_addressing_prefix(rest).unwrap(); - Ok(AttachedSnDigest { sn, digest }) - } - _ => Err(Error::SemanticError("Can't parse attachement".into())), - } - } -} - #[test] fn test_parse_attachement() -> Result<(), Error> { let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"; diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index 71e8414..b8729d7 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -1,13 +1,5 @@ -use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; -use crate::{ - derivation::attached_signature_code::b64_to_num, - event::{event_data::EventData, sections::seal::EventSeal}, - prefix::{ - parse::{attached_signature, basic_prefix, event_seal, self_signing_prefix}, - BasicPrefix, SelfSigningPrefix, - }, - state::IdentifierState, -}; +use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{AttachedSnDigest, Counter}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; +use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, prefix::{BasicPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; use nom::{ branch::*, combinator::*, @@ -145,6 +137,31 @@ pub(crate) fn sig_count(s: &[u8]) -> nom::IResult<&[u8], u16> { Ok((rest, t.1)) } +pub(crate) fn counter(s: &[u8]) -> nom::IResult<&[u8], Counter> { + let (rest, sc) = tuple(( + map_parser( + nom::bytes::complete::take(2u8), + tuple(( + nom::bytes::complete::tag("-"), + nom::bytes::complete::tag("G"), + ))), + b64_count, + ) + , + )(s)?; + + let (rest, attachement) = count( + nom::sequence::tuple((attached_sn, self_addressing_prefix)), + sc.1 as usize , + )(rest)?; + let attachements = attachement.into_iter().map(|(sn, digest)| + AttachedSnDigest::new(sn, digest) + ).collect(); + + Ok((rest, Counter::SealSourceCouplets(attachements))) + +} + pub(crate) fn b64_count(s: &[u8]) -> nom::IResult<&[u8], u16> { let (rest, t) = map(nom::bytes::complete::take(2u8), |b64_count| { b64_to_num(b64_count).map_err(|_| nom::Err::Failure((s, ErrorKind::IsNot))) From 05babf47936e3a59df5d3b37c1f3362d1add2854 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 23 Sep 2021 13:17:33 +0200 Subject: [PATCH 06/17] feat(del): add atachements to SignedEventMessage --- src/event_message/attachement.rs | 13 +++---- src/event_message/mod.rs | 10 +++--- src/event_message/parse.rs | 21 ++++++++++-- src/event_message/payload_size.rs | 42 ++++++++++++++++++++++- src/event_message/signed_event_message.rs | 8 +++-- src/event_message/tests/test_utils.rs | 2 +- src/keri/mod.rs | 10 +++--- src/processor/mod.rs | 2 +- 8 files changed, 84 insertions(+), 24 deletions(-) diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 8a6c657..78b1af2 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -2,12 +2,11 @@ use std::str::FromStr; use serde::{Deserialize, Serialize}; -use crate::{derivation::attached_signature_code::{num_to_b64}, error::Error, prefix::{ - Prefix, SelfAddressingPrefix, - }}; +use crate::{derivation::attached_signature_code::{num_to_b64}, error::Error, prefix::{Prefix, SelfAddressingPrefix}}; use super::{parse::counter, payload_size::PayloadType}; +#[derive(Debug, Clone, Deserialize, PartialEq)] pub enum Counter { SealSourceCouplets(Vec), } @@ -16,13 +15,14 @@ impl Counter { pub fn serialize(&self) -> Result, Error> { match self { Counter::SealSourceCouplets(sources) => { + let payload_type = PayloadType::MG; let serialzied_sources = sources .into_iter() .map(|s| s.serialize().unwrap()) .flatten(); Ok(vec![ - PayloadType::MG.to_string().as_bytes().to_vec(), - num_to_base_64(sources.len() as u16, 2)?.as_bytes().to_vec(), + payload_type.to_string().as_bytes().to_vec(), + num_to_base_64(sources.len() as u16, payload_type.index_length())?.as_bytes().to_vec(), ] .into_iter() .flatten() @@ -41,7 +41,8 @@ impl FromStr for Counter { "-G" => { let (rest, counter) = counter(s.as_bytes()).map_err(|_e| Error::SemanticError("Can't parse counter".into()))?; if rest.is_empty() { - Ok(counter)} else { + Ok(counter) + } else { Err(Error::SemanticError("Can't parse counter".into())) } } diff --git a/src/event_message/mod.rs b/src/event_message/mod.rs index 2a5e281..dc50855 100644 --- a/src/event_message/mod.rs +++ b/src/event_message/mod.rs @@ -18,7 +18,7 @@ use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize}; use serialization_info::*; -use self::{payload_size::PayloadType, signed_event_message::SignedEventMessage}; +use self::{attachement::Counter, payload_size::PayloadType, signed_event_message::SignedEventMessage}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct EventMessage { @@ -120,8 +120,8 @@ impl EventMessage { self.serialization().encode(self) } - pub fn sign(&self, payload_type: PayloadType, sigs: Vec) -> SignedEventMessage { - SignedEventMessage::new(self, payload_type, sigs) + pub fn sign(&self, payload_type: PayloadType, sigs: Vec, attachement: Option) -> SignedEventMessage { + SignedEventMessage::new(self, payload_type, sigs, attachement) } } @@ -297,7 +297,7 @@ mod tests { assert!(pref0.verify(&ser, &attached_sig.signature)?); - let signed_event = icp_m.sign(PayloadType::MA, vec![attached_sig]); + let signed_event = icp_m.sign(PayloadType::MA, vec![attached_sig], None); let s_ = IdentifierState::default(); @@ -380,7 +380,7 @@ mod tests { assert!(sig_pref_0.verify(&serialized, &attached_sig.signature)?); - let signed_event = icp.sign(PayloadType::MA, vec![attached_sig]); + let signed_event = icp.sign(PayloadType::MA, vec![attached_sig], None); let s_ = IdentifierState::default(); diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index b8729d7..939d7c7 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -1,4 +1,4 @@ -use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{AttachedSnDigest, Counter}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; +use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{self, AttachedSnDigest, Counter}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, prefix::{BasicPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; use nom::{ branch::*, @@ -23,12 +23,13 @@ pub struct DeserializedEvent<'a> { pub struct DeserializedSignedEvent<'a> { pub deserialized_event: DeserializedEvent<'a>, pub signatures: Vec, + pub attachement: Option, } // FIXME: detect payload type impl From> for SignedEventMessage { fn from(de: DeserializedSignedEvent) -> SignedEventMessage { - SignedEventMessage::new(&de.deserialized_event.event_message, PayloadType::MA, de.signatures) + SignedEventMessage::new(&de.deserialized_event.event_message, PayloadType::MA, de.signatures, de.attachement) } } @@ -215,7 +216,20 @@ pub fn signed_message<'a>(s: &'a [u8]) -> nom::IResult<&[u8], Deserialized> { ) }) } - } + }, + EventData::Dip(_) | EventData::Drt(_) => { + let (rest, source_seal) = counter(rest)?; + let (extra, signatures) = signatures(rest)?; + + Ok(( + extra, + Deserialized::Event(DeserializedSignedEvent { + deserialized_event: e, + signatures, + attachement: Some(source_seal) + }), + )) + }, _ => { let (extra, signatures) = signatures(rest)?; @@ -224,6 +238,7 @@ pub fn signed_message<'a>(s: &'a [u8]) -> nom::IResult<&[u8], Deserialized> { Deserialized::Event(DeserializedSignedEvent { deserialized_event: e, signatures, + attachement: None, }), )) } diff --git a/src/event_message/payload_size.rs b/src/event_message/payload_size.rs index 5e1b46f..32998f3 100644 --- a/src/event_message/payload_size.rs +++ b/src/event_message/payload_size.rs @@ -79,7 +79,7 @@ pub enum PayloadType { // TODO: Indexed signatures } -#[cfg(feature = "async")] +// #[cfg(feature = "async")] impl PayloadType { pub(crate) fn size(&self) -> usize { match self { @@ -140,6 +140,7 @@ impl PayloadType { | Self::MD | Self::ME | Self::MF + | Self::MG | Self::MU | Self::MV | Self::MW @@ -149,6 +150,45 @@ impl PayloadType { _ => 0 } } + + pub(crate) fn index_length(&self) -> usize { + match self { + Self::A + | Self::B + | Self::C + | Self::D + | Self::E + | Self::F + | Self::G + | Self::H + | Self::I + | Self::J + | Self::K + | Self::L + | Self::M => 0, + Self::OA + | Self::OB + | Self::OC + | Self::OD + | Self::OE + | Self::OF + | Self::OH => 0, + Self::MA + | Self::MB + | Self::MC + | Self::MD + | Self::ME + | Self::MF + | Self::MG + | Self::MU + | Self::MV + | Self::MW + | Self::MX + | Self::MY + | Self::MZ => 2, + _ => todo!() + } + } } impl TryFrom<&str> for PayloadType { diff --git a/src/event_message/signed_event_message.rs b/src/event_message/signed_event_message.rs index 509888c..2968bfd 100644 --- a/src/event_message/signed_event_message.rs +++ b/src/event_message/signed_event_message.rs @@ -4,7 +4,7 @@ use std::cmp::Ordering; use crate::{derivation::attached_signature_code::{get_sig_count, num_to_b64}, error::Error, event::sections::seal::EventSeal, prefix::{AttachedSignaturePrefix, BasicPrefix, Prefix, SelfSigningPrefix, attached_seal::AttachedEventSeal}, state::{EventSemantics, IdentifierState}}; -use super::{EventMessage, payload_size::PayloadType}; +use super::{EventMessage, attachement::Counter, payload_size::PayloadType}; use super::serializer::to_string; // KERI serializer should be used to serialize this @@ -15,6 +15,8 @@ pub struct SignedEventMessage { pub payload_type: PayloadType, #[serde(skip_serializing)] pub signatures: Vec, + #[serde(skip_serializing)] + pub attachement: Option, } impl Serialize for SignedEventMessage { @@ -26,6 +28,7 @@ impl Serialize for SignedEventMessage { let mut em = serializer.serialize_struct("EventMessage", 2)?; em.serialize_field("", &self.event_message)?; let str_sigs = &self.signatures.iter().fold(String::default(), |accum, sig| accum + &sig.to_str()); + // TODO Why first signatures string char? let code = self.calc_master_code(&str_sigs[..1]); // .map_err(|e| serde::ser::Error::custom(&e.to_string()))?; em.serialize_field("-" , &format!("{}{}", Box::leak(code.into_boxed_str()), str_sigs))?; @@ -118,11 +121,12 @@ impl Ord for TimestampedSignedEventMessage { impl Eq for TimestampedSignedEventMessage {} impl SignedEventMessage { - pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec) -> Self { + pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec, attachement: Option) -> Self { Self { event_message: message.clone(), payload_type, signatures: sigs, + attachement, } } diff --git a/src/event_message/tests/test_utils.rs b/src/event_message/tests/test_utils.rs index 47c8457..4069487 100644 --- a/src/event_message/tests/test_utils.rs +++ b/src/event_message/tests/test_utils.rs @@ -85,7 +85,7 @@ fn test_update_identifier_state( }; // Attach sign to event message. - let signed_event = event_msg.sign(PayloadType::MA, vec![attached_sig.clone()]); + let signed_event = event_msg.sign(PayloadType::MA, vec![attached_sig.clone()], None); // Apply event to current IdentifierState. let new_state = state_data.state.apply(&signed_event)?; diff --git a/src/keri/mod.rs b/src/keri/mod.rs index 797d5ab..c82b656 100644 --- a/src/keri/mod.rs +++ b/src/keri/mod.rs @@ -121,7 +121,7 @@ impl Keri { SelfSigning::Ed25519Sha512, self.key_manager.borrow().sign(&icp.serialize()?)?, 0, - )]); + )], None); self.processor .process(signed_message(&signed.serialize()?).unwrap().1)?; @@ -160,7 +160,7 @@ impl Keri { self.key_manager.borrow().sign(&icp.serialize()?)?, 0 ) - )); + ), None); let serialized = signed.serialize()?; self.processor.process(signed_message(&serialized).unwrap().1)?; self.prefix = icp.event.prefix; @@ -200,7 +200,7 @@ impl Keri { signature, 0 // TODO: what is this? ); - let signed = SignedEventMessage::new(&event, PayloadType::OC, vec!(asp)); + let signed = SignedEventMessage::new(&event, PayloadType::OC, vec!(asp), None); self.processor.db.add_kel_finalized_event(signed.clone(), &self.prefix)?; Ok(signed) } @@ -213,7 +213,7 @@ impl Keri { SelfSigning::Ed25519Sha512, self.key_manager.borrow().sign(&rot.serialize()?)?, 0, - )]); + )], None); self.processor .process(signed_message(&rot.serialize()?).unwrap().1)?; @@ -262,7 +262,7 @@ impl Keri { SelfSigning::Ed25519Sha512, self.key_manager.borrow().sign(&ev.serialize()?)?, 0, - )]); + )], None); self.processor .process(signed_message(&ixn.serialize()?).unwrap().1)?; diff --git a/src/processor/mod.rs b/src/processor/mod.rs index 66bbeef..cd9977d 100644 --- a/src/processor/mod.rs +++ b/src/processor/mod.rs @@ -246,7 +246,7 @@ impl EventProcessor { ) -> Result, Error> { // Log event. let signed_event = SignedEventMessage::new( - &event.deserialized_event.event_message, PayloadType::MA, event.signatures.clone()); + &event.deserialized_event.event_message, PayloadType::MA, event.signatures.clone(), event.attachement.clone()); let id = &event.deserialized_event.event_message.event.prefix; // If delegated event, check its delegator seal. match event.deserialized_event.event_message.event.event_data.clone() { From badd054f25b68f7893627905b04c25254676b9da Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 23 Sep 2021 14:06:43 +0200 Subject: [PATCH 07/17] fix(codes): move code calculations to payload_type --- src/derivation/attached_signature_code.rs | 24 ++------------ src/event_message/attachement.rs | 27 +++++---------- src/event_message/payload_size.rs | 40 +++++++++++++++++++++++ src/event_message/signed_event_message.rs | 10 ++---- 4 files changed, 53 insertions(+), 48 deletions(-) diff --git a/src/derivation/attached_signature_code.rs b/src/derivation/attached_signature_code.rs index a4b4670..fea1665 100644 --- a/src/derivation/attached_signature_code.rs +++ b/src/derivation/attached_signature_code.rs @@ -1,6 +1,6 @@ use super::{self_signing::SelfSigning, DerivationCode}; -use crate::error::Error; -use base64::{decode_config, encode_config}; +use crate::{error::Error, event_message::payload_size::num_to_b64}; +use base64::{decode_config}; use core::str::FromStr; /// Attached Signature Derivation Codes @@ -93,26 +93,8 @@ pub fn b64_to_num(b64: &[u8]) -> Result { })) } -pub fn num_to_b64(num: u16) -> String { - match num { - n if n < 63 => - encode_config([num.to_be_bytes()[1] << 2], base64::URL_SAFE_NO_PAD)[..1].to_string(), - n if n < 4095 => - encode_config(num.to_be_bytes(), base64::URL_SAFE_NO_PAD)[..2].to_string(), - _ => encode_config(num.to_be_bytes(), base64::URL_SAFE_NO_PAD), - } -} + pub fn get_sig_count(num: u16) -> String { ["-A", &num_to_b64(num)].join("") } - -#[test] -fn num_to_b64_test() { - assert_eq!("A", num_to_b64(0)); - assert_eq!("B", num_to_b64(1)); - assert_eq!("C", num_to_b64(2)); - assert_eq!("D", num_to_b64(3)); - assert_eq!("b", num_to_b64(27)); - assert_eq!("AE", num_to_b64(64)); -} diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 78b1af2..04e9460 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -2,9 +2,9 @@ use std::str::FromStr; use serde::{Deserialize, Serialize}; -use crate::{derivation::attached_signature_code::{num_to_b64}, error::Error, prefix::{Prefix, SelfAddressingPrefix}}; +use crate::{error::Error, prefix::{Prefix, SelfAddressingPrefix}}; -use super::{parse::counter, payload_size::PayloadType}; +use super::{parse::counter, payload_size::{PayloadType, num_to_base_64}}; #[derive(Debug, Clone, Deserialize, PartialEq)] pub enum Counter { @@ -20,12 +20,8 @@ impl Counter { .into_iter() .map(|s| s.serialize().unwrap()) .flatten(); - Ok(vec![ - payload_type.to_string().as_bytes().to_vec(), - num_to_base_64(sources.len() as u16, payload_type.index_length())?.as_bytes().to_vec(), - ] + Ok(payload_type.encode(sources.len() as u16).as_bytes().to_vec() .into_iter() - .flatten() .chain(serialzied_sources) .collect::>()) } @@ -62,25 +58,18 @@ impl AttachedSnDigest { Self {sn, digest} } pub fn serialize(&self) -> Result, Error> { + let payload_type = PayloadType::OA; Ok([ - PayloadType::OA.to_string().as_bytes().to_vec(), - num_to_base_64(self.sn as u16, 22)?.as_bytes().to_vec(), + payload_type.to_string().as_bytes().to_vec(), + // TODO remove magic 22 + num_to_base_64(self.sn as u16, 22).as_bytes().to_vec(), self.digest.to_str().as_bytes().to_vec(), ] .concat()) } } -fn num_to_base_64(sn: u16, len: usize) -> Result { - let i = num_to_b64(sn); - // refill string to have proper size given in len argument - let part = if i.len() < len { - "A".repeat(len - i.len()) - } else { - String::default() - }; - Ok([part, i].join("")) -} + #[test] fn test_parse_attachement() -> Result<(), Error> { diff --git a/src/event_message/payload_size.rs b/src/event_message/payload_size.rs index 32998f3..ff4ff02 100644 --- a/src/event_message/payload_size.rs +++ b/src/event_message/payload_size.rs @@ -1,3 +1,4 @@ +use base64::encode_config; use serde::{Serialize, Deserialize}; use crate::error::Error; use std::{convert::TryFrom, fmt::Display}; @@ -189,6 +190,34 @@ impl PayloadType { _ => todo!() } } + + + +pub fn encode(&self, sn: u16) -> String { + [self.to_string(), num_to_base_64(sn, self.index_length() as usize)].join("") +} + +} + +pub fn num_to_base_64(sn: u16, len: usize) -> String { + let i = num_to_b64(sn); + // refill string to have proper size given in len argument + let part = if i.len() < len { + "A".repeat(len - i.len()) + } else { + String::default() + }; + [part, i].join("") +} + +pub fn num_to_b64(num: u16) -> String { + match num { + n if n < 63 => + encode_config([num.to_be_bytes()[1] << 2], base64::URL_SAFE_NO_PAD)[..1].to_string(), + n if n < 4095 => + encode_config(num.to_be_bytes(), base64::URL_SAFE_NO_PAD)[..2].to_string(), + _ => encode_config(num.to_be_bytes(), base64::URL_SAFE_NO_PAD), + } } impl TryFrom<&str> for PayloadType { @@ -287,3 +316,14 @@ impl Display for PayloadType { } } } + + +#[test] +fn num_to_b64_test() { + assert_eq!("A", num_to_b64(0)); + assert_eq!("B", num_to_b64(1)); + assert_eq!("C", num_to_b64(2)); + assert_eq!("D", num_to_b64(3)); + assert_eq!("b", num_to_b64(27)); + assert_eq!("AE", num_to_b64(64)); +} diff --git a/src/event_message/signed_event_message.rs b/src/event_message/signed_event_message.rs index 2968bfd..8560a8a 100644 --- a/src/event_message/signed_event_message.rs +++ b/src/event_message/signed_event_message.rs @@ -2,7 +2,7 @@ use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize, ser::SerializeStruct}; use std::cmp::Ordering; -use crate::{derivation::attached_signature_code::{get_sig_count, num_to_b64}, error::Error, event::sections::seal::EventSeal, prefix::{AttachedSignaturePrefix, BasicPrefix, Prefix, SelfSigningPrefix, attached_seal::AttachedEventSeal}, state::{EventSemantics, IdentifierState}}; +use crate::{derivation::attached_signature_code::{get_sig_count}, error::Error, event::sections::seal::EventSeal, prefix::{AttachedSignaturePrefix, BasicPrefix, Prefix, SelfSigningPrefix, attached_seal::AttachedEventSeal}, state::{EventSemantics, IdentifierState}}; use super::{EventMessage, attachement::Counter, payload_size::PayloadType}; use super::serializer::to_string; @@ -29,7 +29,7 @@ impl Serialize for SignedEventMessage { em.serialize_field("", &self.event_message)?; let str_sigs = &self.signatures.iter().fold(String::default(), |accum, sig| accum + &sig.to_str()); // TODO Why first signatures string char? - let code = self.calc_master_code(&str_sigs[..1]); + let code = self.payload_type.encode(self.signatures.len() as u16); // .map_err(|e| serde::ser::Error::custom(&e.to_string()))?; em.serialize_field("-" , &format!("{}{}", Box::leak(code.into_boxed_str()), str_sigs))?; em.end() @@ -130,12 +130,6 @@ impl SignedEventMessage { } } - pub fn calc_master_code(&self, derivation: &str) -> String { - format!("{}{}{}", - &self.payload_type.to_string(), - derivation, - num_to_b64(self.signatures.len() as u16)) - } pub fn serialize(&self) -> Result, Error> { Ok(to_string(&self)?.as_bytes().to_vec()) From 7c66faa7edc20352a1fb5c9717e30b28a04a9c15 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 23 Sep 2021 14:09:01 +0200 Subject: [PATCH 08/17] fix(attachement): change structures names --- src/event_message/attachement.rs | 18 +++++++++--------- src/event_message/mod.rs | 4 ++-- src/event_message/parse.rs | 10 +++++----- src/event_message/signed_event_message.rs | 6 +++--- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 04e9460..d5def16 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -7,14 +7,14 @@ use crate::{error::Error, prefix::{Prefix, SelfAddressingPrefix}}; use super::{parse::counter, payload_size::{PayloadType, num_to_base_64}}; #[derive(Debug, Clone, Deserialize, PartialEq)] -pub enum Counter { - SealSourceCouplets(Vec), +pub enum Attachement { + SealSourceCouplets(Vec), } -impl Counter { +impl Attachement { pub fn serialize(&self) -> Result, Error> { match self { - Counter::SealSourceCouplets(sources) => { + Attachement::SealSourceCouplets(sources) => { let payload_type = PayloadType::MG; let serialzied_sources = sources .into_iter() @@ -29,7 +29,7 @@ impl Counter { } } -impl FromStr for Counter { +impl FromStr for Attachement { type Err = Error; fn from_str(s: &str) -> Result { @@ -48,12 +48,12 @@ impl FromStr for Counter { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct AttachedSnDigest { +pub struct SorceSeal { sn: u64, digest: SelfAddressingPrefix, } -impl AttachedSnDigest { +impl SorceSeal { pub fn new(sn: u64, digest: SelfAddressingPrefix) -> Self { Self {sn, digest} } @@ -74,13 +74,13 @@ impl AttachedSnDigest { #[test] fn test_parse_attachement() -> Result<(), Error> { let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"; - let attached_sn_dig: Counter = attached_str.parse()?; + let attached_sn_dig: Attachement = attached_str.parse()?; assert_eq!( attached_str, String::from_utf8(attached_sn_dig.serialize()?).unwrap() ); match attached_sn_dig { - Counter::SealSourceCouplets(sources) => { + Attachement::SealSourceCouplets(sources) => { let s1 = sources[0].clone(); let s2 = sources[1].clone(); assert_eq!(s1.sn, 16); diff --git a/src/event_message/mod.rs b/src/event_message/mod.rs index dc50855..e549e9b 100644 --- a/src/event_message/mod.rs +++ b/src/event_message/mod.rs @@ -18,7 +18,7 @@ use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize}; use serialization_info::*; -use self::{attachement::Counter, payload_size::PayloadType, signed_event_message::SignedEventMessage}; +use self::{attachement::Attachement, payload_size::PayloadType, signed_event_message::SignedEventMessage}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct EventMessage { @@ -120,7 +120,7 @@ impl EventMessage { self.serialization().encode(self) } - pub fn sign(&self, payload_type: PayloadType, sigs: Vec, attachement: Option) -> SignedEventMessage { + pub fn sign(&self, payload_type: PayloadType, sigs: Vec, attachement: Option) -> SignedEventMessage { SignedEventMessage::new(self, payload_type, sigs, attachement) } } diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index 939d7c7..b5709a9 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -1,4 +1,4 @@ -use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{self, AttachedSnDigest, Counter}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; +use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{SorceSeal, Attachement}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, prefix::{BasicPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; use nom::{ branch::*, @@ -23,7 +23,7 @@ pub struct DeserializedEvent<'a> { pub struct DeserializedSignedEvent<'a> { pub deserialized_event: DeserializedEvent<'a>, pub signatures: Vec, - pub attachement: Option, + pub attachement: Option, } // FIXME: detect payload type @@ -138,7 +138,7 @@ pub(crate) fn sig_count(s: &[u8]) -> nom::IResult<&[u8], u16> { Ok((rest, t.1)) } -pub(crate) fn counter(s: &[u8]) -> nom::IResult<&[u8], Counter> { +pub(crate) fn counter(s: &[u8]) -> nom::IResult<&[u8], Attachement> { let (rest, sc) = tuple(( map_parser( nom::bytes::complete::take(2u8), @@ -156,10 +156,10 @@ pub(crate) fn counter(s: &[u8]) -> nom::IResult<&[u8], Counter> { sc.1 as usize , )(rest)?; let attachements = attachement.into_iter().map(|(sn, digest)| - AttachedSnDigest::new(sn, digest) + SorceSeal::new(sn, digest) ).collect(); - Ok((rest, Counter::SealSourceCouplets(attachements))) + Ok((rest, Attachement::SealSourceCouplets(attachements))) } diff --git a/src/event_message/signed_event_message.rs b/src/event_message/signed_event_message.rs index 8560a8a..71a1bd7 100644 --- a/src/event_message/signed_event_message.rs +++ b/src/event_message/signed_event_message.rs @@ -4,7 +4,7 @@ use std::cmp::Ordering; use crate::{derivation::attached_signature_code::{get_sig_count}, error::Error, event::sections::seal::EventSeal, prefix::{AttachedSignaturePrefix, BasicPrefix, Prefix, SelfSigningPrefix, attached_seal::AttachedEventSeal}, state::{EventSemantics, IdentifierState}}; -use super::{EventMessage, attachement::Counter, payload_size::PayloadType}; +use super::{EventMessage, attachement::Attachement, payload_size::PayloadType}; use super::serializer::to_string; // KERI serializer should be used to serialize this @@ -16,7 +16,7 @@ pub struct SignedEventMessage { #[serde(skip_serializing)] pub signatures: Vec, #[serde(skip_serializing)] - pub attachement: Option, + pub attachement: Option, } impl Serialize for SignedEventMessage { @@ -121,7 +121,7 @@ impl Ord for TimestampedSignedEventMessage { impl Eq for TimestampedSignedEventMessage {} impl SignedEventMessage { - pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec, attachement: Option) -> Self { + pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec, attachement: Option) -> Self { Self { event_message: message.clone(), payload_type, From 34d1e493c98f2a357a3802164d67cf6e7c9e1530 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 23 Sep 2021 16:11:58 +0200 Subject: [PATCH 09/17] feat(del): remove seal from delegating event --- src/event/event_data/delegated/mod.rs | 19 +- src/event_message/attachement.rs | 4 +- src/event_message/event_msg_builder.rs | 11 +- src/event_message/parse.rs | 21 +- src/processor/mod.rs | 292 ++++++++++++++++--------- src/processor/tests.rs | 14 +- 6 files changed, 219 insertions(+), 142 deletions(-) diff --git a/src/event/event_data/delegated/mod.rs b/src/event/event_data/delegated/mod.rs index f5e299e..ef9388b 100644 --- a/src/event/event_data/delegated/mod.rs +++ b/src/event/event_data/delegated/mod.rs @@ -1,4 +1,4 @@ -use super::{super::sections::seal::LocationSeal, DummyEvent, EventData}; +use super::{DummyEvent, EventData}; use super::{InceptionEvent, RotationEvent}; use crate::{ derivation::self_addressing::SelfAddressing, @@ -14,17 +14,14 @@ pub struct DelegatedInceptionEvent { #[serde(flatten)] pub inception_data: InceptionEvent, - #[serde(rename = "da")] - pub seal: LocationSeal, + #[serde(rename = "di")] + pub delegator: IdentifierPrefix, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DelegatedRotationEvent { #[serde(flatten)] pub rotation_data: RotationEvent, - - #[serde(rename = "da")] - pub seal: LocationSeal, } impl DelegatedInceptionEvent { @@ -58,17 +55,17 @@ impl DelegatedInceptionEvent { impl EventSemantics for DelegatedInceptionEvent { fn apply_to(&self, state: IdentifierState) -> Result { Ok(IdentifierState { - delegator: Some(self.seal.prefix.clone()), + delegator: Some(self.delegator.clone()), ..self.inception_data.apply_to(state)? }) } } impl EventSemantics for DelegatedRotationEvent { fn apply_to(&self, state: IdentifierState) -> Result { - if state.delegator == Some(self.seal.prefix.clone()) { + // if state.delegator == Some(self.delegator.prefix.clone()) { self.rotation_data.apply_to(state) - } else { - Err(Error::SemanticError("Wrong delegator".into())) - } + // } else { + // Err(Error::SemanticError("Wrong delegator".into())) + // } } } diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index d5def16..1dd645f 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -49,8 +49,8 @@ impl FromStr for Attachement { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct SorceSeal { - sn: u64, - digest: SelfAddressingPrefix, + pub sn: u64, + pub digest: SelfAddressingPrefix, } impl SorceSeal { diff --git a/src/event_message/event_msg_builder.rs b/src/event_message/event_msg_builder.rs index 1324d64..adc8c76 100644 --- a/src/event_message/event_msg_builder.rs +++ b/src/event_message/event_msg_builder.rs @@ -26,7 +26,7 @@ pub struct EventMsgBuilder { next_keys: Vec, prev_event: SelfAddressingPrefix, data: Vec, - delegating_seal: LocationSeal, + delegator: IdentifierPrefix, format: SerializationFormats, derivation: SelfAddressing, } @@ -77,7 +77,7 @@ impl EventMsgBuilder { sn: 1, prev_event: SelfAddressing::Blake3_256.derive(&[0u8; 32]), data: vec![], - delegating_seal: dummy_loc_seal, + delegator: IdentifierPrefix::default(), format: SerializationFormats::JSON, derivation: SelfAddressing::Blake3_256, }) @@ -107,9 +107,9 @@ impl EventMsgBuilder { EventMsgBuilder { ..self } } - pub fn with_delegating_seal(self, seal: LocationSeal) -> Self { + pub fn with_delegator(self, delegator: IdentifierPrefix) -> Self { EventMsgBuilder { - delegating_seal: seal, + delegator, ..self } } @@ -187,7 +187,7 @@ impl EventMsgBuilder { }; DelegatedInceptionEvent { inception_data: icp_data, - seal: self.delegating_seal, + delegator: self.delegator, } .incept_self_addressing(self.derivation, self.format)? } @@ -203,7 +203,6 @@ impl EventMsgBuilder { sn: self.sn, event_data: EventData::Drt(DelegatedRotationEvent { rotation_data, - seal: self.delegating_seal, }), } .to_message(self.format)? diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index b5709a9..e616c17 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -1,5 +1,5 @@ use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{SorceSeal, Attachement}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; -use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, prefix::{BasicPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; +use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, event_message::event_msg_builder::{EventMsgBuilder, EventType}, prefix::{BasicPrefix, IdentifierPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; use nom::{ branch::*, combinator::*, @@ -342,19 +342,16 @@ fn test_event() { assert!(event.is_ok()); assert_eq!(event.unwrap().1.event_message.serialize().unwrap(), stream); - // TODO fix the test after updating delegation. - // (https://github.com/decentralized-identity/keri/issues/146) - // // Delegated inception event. - // let stream = r#"{"v":"KERI10JSON000121_","i":"EZUY3a0vbBLqUtC1d9ZrutSeg1nlMPVuDfxUi4LpE03g","s":"0","t":"dip","kt":"1","k":["DHgZa-u7veNZkqk2AxCnxrINGKfQ0bRiaf9FdA_-_49A"],"n":"EcBCalw7Oe2ohLDra2ovwlv72PrlQZdQdaoSZ1Vvk5P4","bt":"0","b":[],"c":[],"a":[],"di":"ENdHxtdjCQUM-TVO8CgJAKb8ykXsFe4u9epTUQFCL7Yd"}"#.as_bytes(); - // let event = message(stream); - // assert!(event.is_ok()); - // assert_eq!(event.unwrap().1.event.serialize().unwrap(), stream); + // Delegated inception event. + let stream = r#"{"v":"KERI10JSON000121_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","t":"dip","kt":"1","k":["DuK1x8ydpucu3480Jpd1XBfjnCwb3dZ3x5b1CJmuUphA"],"n":"EWWkjZkZDXF74O2bOQ4H5hu4nXDlKg2m4CBEBkUxibiU","bt":"0","b":[],"c":[],"a":[],"di":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI"}"#.as_bytes(); + let event = message(stream); + assert_eq!(event.unwrap().1.event_message.serialize().unwrap(), stream); // // Delegated rotation event. - // let stream = r#"{"v":"KERI10JSON00011c_","i":"EZAoTNZH3ULvaU6Z-i0d8JJR2nmwyYAfSVPzhzS6b5CM","s":"1","t":"drt","p":"EULvaU6JR2nmwyZ-i0d8JZAoTNZH3YAfSVPzhzS6b5CM","kt":"1","k":["DaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM"],"n":"EYAfSVPzhzZ-i0d8JZAoTNZH3ULvaU6JR2nmwyS6b5CM","bt":"1","br":["DH3ULvaU6JR2nmwyYAfSVPzhzS6bZ-i0d8TNZJZAo5CM"],"ba":["DTNZH3ULvaU6JR2nmwyYAfSVPzhzS6bZ-i0d8JZAo5CM"],"a":[],"da":{"i":"EZAoTNZH3ULvaU6Z-i0d8JJR2nmwyYAfSVPzhzS6b5CM","s":"1","t":"ixn","p":"E8JZAoTNZH3ULZ-i0dvaU6JR2nmwyYAfSVPzhzS6b5CM"}}"#.as_bytes(); - // let event = message(stream); - // assert!(event.is_ok()); - // assert_eq!(event.unwrap().1.event.serialize().unwrap(), stream); + let stream = r#"{"v":"KERI10JSON000122_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"1","t":"drt","p":"E1x1JOub6oEQkxAxTNFu1Pma6y-lrbprNsaILHJHoPmY","kt":"1","k":["DTf6QZWoet154o9wvzeMuNhLQRr8JaAUeiC6wjB_4_08"],"n":"E8kyiXDfkE7idwWnAZQjHbUZMz-kd_yIMH0miptIFFPo","bt":"0","br":[],"ba":[],"a":[]}"#.as_bytes(); + let event = message(stream); + assert!(event.is_ok()); + assert_eq!(event.unwrap().1.event_message.serialize().unwrap(), stream); } #[test] diff --git a/src/processor/mod.rs b/src/processor/mod.rs index cd9977d..b36f649 100644 --- a/src/processor/mod.rs +++ b/src/processor/mod.rs @@ -1,17 +1,33 @@ use std::sync::Arc; -use crate::{database::sled::SledEventDatabase, derivation::self_addressing::SelfAddressing, error::Error, event::{EventMessage, event_data::EventData, sections::{ +use crate::{ + database::sled::SledEventDatabase, + derivation::self_addressing::SelfAddressing, + error::Error, + event::{ + event_data::EventData, + sections::{ seal::{EventSeal, LocationSeal, Seal}, KeyConfig, - }}, event_message::{parse::{ - Deserialized, - DeserializedSignedEvent - }, payload_size::PayloadType, signed_event_message::{SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, TimestampedSignedEventMessage}}, prefix::{IdentifierPrefix, SelfAddressingPrefix}, state::{EventSemantics, IdentifierState}}; + }, + EventMessage, + }, + event_message::{ + parse::{Deserialized, DeserializedSignedEvent}, + payload_size::PayloadType, + signed_event_message::{ + SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, + TimestampedSignedEventMessage, + }, + }, + prefix::{IdentifierPrefix, SelfAddressingPrefix}, + state::{EventSemantics, IdentifierState}, +}; -#[cfg(test)] -mod tests; #[cfg(feature = "async")] pub mod async_processing; +#[cfg(test)] +mod tests; pub struct EventProcessor { pub db: Arc, @@ -39,11 +55,10 @@ impl EventProcessor { // will happen when a recovery has overridden some part of the KEL, Err(e) => match e { // skip out of order and partially signed events - Error::EventOutOfOrderError - | Error::NotEnoughSigsError => continue, + Error::EventOutOfOrderError | Error::NotEnoughSigsError => continue, // stop processing here - _ => break - } + _ => break, + }, }; } } else { @@ -67,10 +82,12 @@ impl EventProcessor { // TODO: testing approach if events come out sorted already (as they should coz of put sequence) let mut sorted_events = events.collect::>(); sorted_events.sort(); - for event in sorted_events.iter() - .filter(|e| e.signed_event_message.event_message.event.sn <= sn) { - state = state.apply(&event.signed_event_message.event_message)?; - } + for event in sorted_events + .iter() + .filter(|e| e.signed_event_message.event_message.event.sn <= sn) + { + state = state.apply(&event.signed_event_message.event_message)?; + } } else { return Ok(None); } @@ -115,12 +132,17 @@ impl EventProcessor { /// /// Returns the current validated KEL for a given Prefix pub fn get_kerl(&self, id: &IdentifierPrefix) -> Result>, Error> { - match self.db.get_kel_finalized_events(id) { - Some(events) => - Ok(Some(events.map(|event| event.signed_event_message.serialize().unwrap_or_default()) - .fold(vec!(), |mut accum, serialized_event| { accum.extend(serialized_event); accum }))), - None => Ok(None) - } + match self.db.get_kel_finalized_events(id) { + Some(events) => Ok(Some( + events + .map(|event| event.signed_event_message.serialize().unwrap_or_default()) + .fold(vec![], |mut accum, serialized_event| { + accum.extend(serialized_event); + accum + }), + )), + None => Ok(None), + } } /// Get keys from Establishment Event @@ -138,57 +160,41 @@ impl EventProcessor { // if it's the event we're looking for if event_digest.verify_binding(&event.signed_event_message.event_message.serialize()?) { // return the config or error if it's not an establishment event - Ok(Some(match event.signed_event_message.event_message.event.event_data { - EventData::Icp(icp) => icp.key_config, - EventData::Rot(rot) => rot.key_config, - EventData::Dip(dip) => dip.inception_data.key_config, - EventData::Drt(drt) => drt.rotation_data.key_config, - // the receipt has a binding but it's NOT an establishment event - _ => Err(Error::SemanticError("Receipt binding incorrect".into()))?, - })) - } else { - Err(Error::SemanticError("Event digests doesn't match".into())) - } + Ok(Some( + match event.signed_event_message.event_message.event.event_data { + EventData::Icp(icp) => icp.key_config, + EventData::Rot(rot) => rot.key_config, + EventData::Dip(dip) => dip.inception_data.key_config, + EventData::Drt(drt) => drt.rotation_data.key_config, + // the receipt has a binding but it's NOT an establishment event + _ => Err(Error::SemanticError("Receipt binding incorrect".into()))?, + }, + )) } else { - Err(Error::SemanticError("No event of given sn and prefix in database".into())) + Err(Error::SemanticError("Event digests doesn't match".into())) } + } else { + Err(Error::SemanticError( + "No event of given sn and prefix in database".into(), + )) + } } /// Validate delegating event seal. /// /// Validates binding between delegated and delegating events. The validation /// is based on delegating location seal and delegated event. - fn validate_seal(&self, seal: LocationSeal, delegated_event: &[u8]) -> Result<(), Error> { + fn validate_seal(&self, seal: EventSeal, delegated_event: &[u8]) -> Result<(), Error> { // Check if event of seal's prefix and sn is in db. if let Ok(Some(event)) = self.get_event_at_sn(&seal.prefix, seal.sn) { // Extract prior_digest and data field from delegating event. - let (prior_dig, data) = match event.signed_event_message.event_message.event.event_data { - EventData::Rot(rot) => (rot.previous_event_hash, rot.data), - EventData::Ixn(ixn) => (ixn.previous_event_hash, ixn.data), - EventData::Drt(drt) => ( - drt.rotation_data.previous_event_hash, - drt.rotation_data.data, - ), + let data = match event.signed_event_message.event_message.event.event_data { + EventData::Rot(rot) => rot.data, + EventData::Ixn(ixn) => ixn.data, + EventData::Drt(drt) => drt.rotation_data.data, _ => return Err(Error::SemanticError("Improper event type".to_string())), }; - // Check if prior event digest matches prior event digest from - // the seal. - if prior_dig.derivation == seal.prior_digest.derivation { - Ok(prior_dig == seal.prior_digest) - } else { - // get previous event from db - match self.get_event_at_sn(&seal.prefix, seal.sn -1)? { - Some(previous_event) => { - match previous_event.signed_event_message.event_message.event.prefix { - IdentifierPrefix::SelfAddressing(prefix) => - Ok(prefix.digest == seal.prior_digest.digest), - _ => Err(Error::SemanticError("No event in db".into())) - } - }, - None => return Err(Error::SemanticError("No event in db".into())) - } - }?; // Check if event seal list contains delegating event seal. if !data.iter().any(|s| match s { Seal::Event(es) => es.event_digest.verify_binding(delegated_event), @@ -210,10 +216,13 @@ impl EventProcessor { sn: u64, validator_pref: &IdentifierPrefix, ) -> Result { - Ok(if let Some(receipts) = self.db .get_receipts_t(id) { - receipts.filter(|r| r.body.event.sn.eq(&sn)) + Ok(if let Some(receipts) = self.db.get_receipts_t(id) { + receipts + .filter(|r| r.body.event.sn.eq(&sn)) .any(|receipt| receipt.validator_seal.event_seal.prefix.eq(validator_pref)) - } else { false }) + } else { + false + }) } /// Process @@ -227,12 +236,17 @@ impl EventProcessor { } } - pub fn process_actual_event(&self, id: &IdentifierPrefix, event: impl EventSemantics) - -> Result, Error> { - if let Some(state) = self.compute_state(id)? { - Ok(Some(event.apply_to(state)?)) - } else { Ok(None) } + pub fn process_actual_event( + &self, + id: &IdentifierPrefix, + event: impl EventSemantics, + ) -> Result, Error> { + if let Some(state) = self.compute_state(id)? { + Ok(Some(event.apply_to(state)?)) + } else { + Ok(None) } + } /// Process Event /// @@ -246,14 +260,65 @@ impl EventProcessor { ) -> Result, Error> { // Log event. let signed_event = SignedEventMessage::new( - &event.deserialized_event.event_message, PayloadType::MA, event.signatures.clone(), event.attachement.clone()); + &event.deserialized_event.event_message, + PayloadType::MA, + event.signatures.clone(), + event.attachement.clone(), + ); let id = &event.deserialized_event.event_message.event.prefix; // If delegated event, check its delegator seal. - match event.deserialized_event.event_message.event.event_data.clone() { - EventData::Dip(dip) => - self.validate_seal(dip.seal, &event.deserialized_event.raw), - EventData::Drt(drt) => - self.validate_seal(drt.seal, &event.deserialized_event.raw), + match event + .deserialized_event + .event_message + .event + .event_data + .clone() + { + EventData::Dip(dip) => { + let (sn, dig) = match event.attachement.clone().ok_or(Error::SemanticError( + "Missing source seal in delegating event".into(), + ))? { + crate::event_message::attachement::Attachement::SealSourceCouplets( + ref source_seal_list, + ) => { + let ss = source_seal_list + .last() + .ok_or(Error::SemanticError("Missing source seal".into()))?; + (ss.sn, ss.digest.clone()) + } + }; + let seal = EventSeal { + prefix: dip.delegator, + sn, + event_digest: dig, + }; + self.validate_seal(seal, &event.deserialized_event.raw) + } + EventData::Drt(drt) => { + let delegator = self + .compute_state(&event.deserialized_event.event_message.event.prefix)? + .unwrap() + .delegator + .ok_or(Error::SemanticError("Missing delegator".into()))?; + let (sn, dig) = match event.attachement.clone().ok_or(Error::SemanticError( + "Missing source seal in delegating event".into(), + ))? { + crate::event_message::attachement::Attachement::SealSourceCouplets( + ref source_seal_list, + ) => { + let ss = source_seal_list + .last() + .ok_or(Error::SemanticError("Missing source seal".into()))?; + (ss.sn, ss.digest.clone()) + } + }; + let seal = EventSeal { + prefix: delegator, + sn, + event_digest: dig, + }; + self.validate_seal(seal, &event.deserialized_event.raw) + } _ => Ok(()), }?; self.apply_to_state(event.deserialized_event.event_message.clone()) @@ -272,22 +337,23 @@ impl EventProcessor { Ok(new_state) } }) { - Ok(state) => Ok(Some(state)), - Err(e) => { - match e { - // should not happen anymore - // Error::NotEnoughSigsError => - // should not happen anymore - //Error::EventOutOfOrderError => - Error::EventDuplicateError => - self.db.add_duplicious_event(signed_event.clone(), id)?, - _ => (), - }; - // remove last added event - self.db.remove_kel_finalized_event(id, &signed_event)?; - Err(e) - }, + Ok(state) => Ok(Some(state)), + Err(e) => { + match e { + // should not happen anymore + // Error::NotEnoughSigsError => + // should not happen anymore + //Error::EventOutOfOrderError => + Error::EventDuplicateError => { + self.db.add_duplicious_event(signed_event.clone(), id)? + } + _ => (), + }; + // remove last added event + self.db.remove_kel_finalized_event(id, &signed_event)?; + Err(e) } + } }) } @@ -303,23 +369,31 @@ impl EventProcessor { ) -> Result, Error> { match &vrc.body.event.event_data { EventData::Rct(_r) => { - if let Ok(Some(event)) = - self.get_event_at_sn(&vrc.body.event.prefix, vrc.body.event.sn) { + if let Ok(Some(event)) = + self.get_event_at_sn(&vrc.body.event.prefix, vrc.body.event.sn) + { let kp = self.get_keys_at_event( &vrc.validator_seal.event_seal.prefix, vrc.validator_seal.event_seal.sn, - &vrc.validator_seal.event_seal.event_digest)?; - if kp.is_some() && kp.unwrap().verify(&event.signed_event_message.event_message.serialize()?, &vrc.signatures)? { + &vrc.validator_seal.event_seal.event_digest, + )?; + if kp.is_some() + && kp.unwrap().verify( + &event.signed_event_message.event_message.serialize()?, + &vrc.signatures, + )? + { self.db.add_receipt_t(vrc.clone(), &vrc.body.event.prefix) } else { Err(Error::SemanticError("Incorrect receipt signatures".into())) } } else { - self.db.add_escrow_t_receipt(vrc.clone(), &vrc.body.event.prefix)?; + self.db + .add_escrow_t_receipt(vrc.clone(), &vrc.body.event.prefix)?; Err(Error::SemanticError("Receipt escrowed".into())) } - }, - _ => Err(Error::SemanticError("incorrect receipt structure".into())) + } + _ => Err(Error::SemanticError("incorrect receipt structure".into())), }?; self.compute_state(&vrc.body.event.prefix) } @@ -339,15 +413,19 @@ impl EventProcessor { // get event which is being receipted EventData::Rct(_) => { let id = &rct.body.event.prefix.to_owned(); - if let Ok(Some(event)) = self.get_event_at_sn(&rct.body.event.prefix, rct.body.event.sn) { + if let Ok(Some(event)) = + self.get_event_at_sn(&rct.body.event.prefix, rct.body.event.sn) + { let serialized_event = event.signed_event_message.serialize()?; - let (_, mut errors): (Vec<_>, Vec>) = rct.clone().couplets.into_iter() - .map(|(witness, receipt)| - witness.verify(&&serialized_event, &receipt)) + let (_, mut errors): (Vec<_>, Vec>) = rct + .clone() + .couplets + .into_iter() + .map(|(witness, receipt)| witness.verify(&&serialized_event, &receipt)) .partition(Result::is_ok); if errors.len() == 0 { self.db.add_receipt_nt(rct, &id)? - } else { + } else { let e = errors.pop().unwrap().unwrap_err(); return Err(e); } @@ -355,15 +433,21 @@ impl EventProcessor { self.db.add_escrow_nt_receipt(rct, &id)? } self.compute_state(&id) - }, - _ => Err(Error::SemanticError("incorrect receipt structure".into())), + } + _ => Err(Error::SemanticError("incorrect receipt structure".into())), } } - pub fn get_event_at_sn(&self, id: &IdentifierPrefix, sn: u64) -> Result, Error> { - if let Some(mut events) = self.db.get_kel_finalized_events(id) { + pub fn get_event_at_sn( + &self, + id: &IdentifierPrefix, + sn: u64, + ) -> Result, Error> { + if let Some(mut events) = self.db.get_kel_finalized_events(id) { Ok(events.find(|event| event.signed_event_message.event_message.event.sn == sn)) - } else { Ok(None) } + } else { + Ok(None) + } } fn apply_to_state(&self, event: EventMessage) -> Result { diff --git a/src/processor/tests.rs b/src/processor/tests.rs index ecfbe43..676edba 100644 --- a/src/processor/tests.rs +++ b/src/processor/tests.rs @@ -176,12 +176,12 @@ fn test_process_receipt() -> Result<(), Error> { // // Create test db and event processor. // let root = Builder::new().prefix("test-db").tempdir().unwrap(); // fs::create_dir_all(root.path()).unwrap(); -// let db = SledEventDatabase::new(root.path()).unwrap(); -// let event_processor = EventProcessor::new(&db); +// let db = Arc::new(SledEventDatabase::new(root.path()).unwrap()); +// let event_processor = EventProcessor::new(Arc::clone(&db)); // let raw_parsed = |des| -> Result, Error> { // match &des { -// Deserialized::Event(e) => Ok(e.event.raw.to_vec()), +// Deserialized::Event(e) => Ok(e.deserialized_event.raw.to_vec()), // _ => Err(Error::SemanticError("bad deser".into()))?, // } // }; @@ -215,7 +215,7 @@ fn test_process_receipt() -> Result<(), Error> { // // Check if processed event is in db. // let ixn_from_db = event_processor.get_event_at_sn(&bobs_pref, 1).unwrap().unwrap(); -// assert_eq!(ixn_from_db.event.serialize()?, raw_parsed(deserialized_ixn)?); +// assert_eq!(ixn_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_ixn)?); // // Process delegated inception event once again. // event_processor.process(deserialized_dip.clone())?.unwrap(); @@ -224,7 +224,7 @@ fn test_process_receipt() -> Result<(), Error> { // let dip_from_db = event_processor // .get_event_at_sn(&child_prefix, 0)? // .unwrap(); -// assert_eq!(dip_from_db.event.serialize()?, raw_parsed(deserialized_dip)?); +// assert_eq!(dip_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_dip)?); // // Bobs interaction event with delegated event seal. // let bob_ixn = br#"{"v":"KERI10JSON000107_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"2","t":"ixn","p":"E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII","a":[{"i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"1","d":"EPjLBcb4pp-3PGvSi_fTvLvsqUqFoJ0CVCHvIFfu93Xc"}]}-AABAAclMVE-bkIn-wPiAqfgR384nWmslQHQvmo2o3xQvd_4Bt6bflc4BAmfBa03KgrDVqmB7qG2VXQbOHevkzOgRdD"#; @@ -246,7 +246,7 @@ fn test_process_receipt() -> Result<(), Error> { // // Check if processed event is in db. // let ixn_from_db = event_processor.get_event_at_sn(&bobs_pref, 2)?.unwrap(); -// assert_eq!(ixn_from_db.event.serialize()?, raw_parsed(deserialized_ixn_drt)?); +// assert_eq!(ixn_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_ixn_drt)?); // // Process delegated rotation event once again. // event_processor.process(deserialized_drt.clone())?.unwrap(); @@ -255,7 +255,7 @@ fn test_process_receipt() -> Result<(), Error> { // let drt_from_db = event_processor // .get_event_at_sn(&child_prefix, 1)? // .unwrap(); -// assert_eq!(drt_from_db.event.serialize()?, raw_parsed(deserialized_drt)?); +// assert_eq!(drt_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_drt)?); // Ok(()) // } From 85d70234f85ba67e5f3ac39fcdef7c7ea2da5b58 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 23 Sep 2021 16:45:35 +0200 Subject: [PATCH 10/17] feat(delegation): fix validate seal test --- src/processor/mod.rs | 2 +- src/processor/tests.rs | 113 +++++++++++++++++++++-------------------- 2 files changed, 58 insertions(+), 57 deletions(-) diff --git a/src/processor/mod.rs b/src/processor/mod.rs index b36f649..c8a5197 100644 --- a/src/processor/mod.rs +++ b/src/processor/mod.rs @@ -7,7 +7,7 @@ use crate::{ event::{ event_data::EventData, sections::{ - seal::{EventSeal, LocationSeal, Seal}, + seal::{EventSeal, Seal}, KeyConfig, }, EventMessage, diff --git a/src/processor/tests.rs b/src/processor/tests.rs index 676edba..037099a 100644 --- a/src/processor/tests.rs +++ b/src/processor/tests.rs @@ -1,8 +1,8 @@ use super::EventProcessor; -use crate::{ - database::sled::SledEventDatabase, - error::Error, -}; +use crate::derivation::self_addressing::SelfAddressing; +use crate::event::sections::seal::EventSeal; +use crate::event_message::parse::signed_message; +use crate::{database::sled::SledEventDatabase, error::Error}; use crate::{ event_message::{ parse, @@ -31,9 +31,9 @@ fn test_process() -> Result<(), Error> { let (id, _raw_parsed) = match &deserialized_icp { Deserialized::Event(e) => ( - e.deserialized_event.event_message.event.prefix.clone(), - e.deserialized_event.raw.to_vec() - ), + e.deserialized_event.event_message.event.prefix.clone(), + e.deserialized_event.raw.to_vec(), + ), _ => Err(Error::SemanticError("bad deser".into()))?, }; @@ -56,7 +56,10 @@ fn test_process() -> Result<(), Error> { // Process rotation event. event_processor.process(deserialized_rot.clone())?.unwrap(); let rot_from_db = event_processor.get_event_at_sn(&id, 1).unwrap().unwrap(); - assert_eq!(rot_from_db.signed_event_message.serialize().unwrap(), rot_raw); + assert_eq!( + rot_from_db.signed_event_message.serialize().unwrap(), + rot_raw + ); // Process the same rotation event one more time. let id_state = event_processor.process(deserialized_rot); @@ -77,9 +80,11 @@ fn test_process() -> Result<(), Error> { // Check if processed event is in db. let ixn_from_db = event_processor.get_event_at_sn(&id, 2).unwrap().unwrap(); match deserialized_ixn { - Deserialized::Event(evt) => - assert_eq!(ixn_from_db.signed_event_message.event_message.event, evt.deserialized_event.event_message.event), - _ => assert!(false) + Deserialized::Event(evt) => assert_eq!( + ixn_from_db.signed_event_message.event_message.event, + evt.deserialized_event.event_message.event + ), + _ => assert!(false), } // Construct partially signed interaction event. @@ -260,56 +265,52 @@ fn test_process_receipt() -> Result<(), Error> { // Ok(()) // } -// TODO fix the test after updating delegation. -// (https://github.com/decentralized-identity/keri/issues/146) -// #[test] -// fn test_validate_seal() -> Result<(), Error> { -// use tempfile::Builder; -// // Create test db and event processor. -// let root = Builder::new().prefix("test-db").tempdir().unwrap(); -// fs::create_dir_all(root.path()).unwrap(); -// let db = SledEventDatabase::new(root.path()).unwrap(); -// let event_processor = EventProcessor::new(&db); - -// // Process icp. -// let delegator_icp_raw = r#"{"v":"KERI10JSON0000e6_","i":"DcVUXDcB307nuuIlMGEUt9WZc4WF9W29IRvxDyVu6hyg","s":"0","t":"icp","kt":"1","k":["DcVUXDcB307nuuIlMGEUt9WZc4WF9W29IRvxDyVu6hyg"],"n":"E1_qFK5o1zYy5Os45Ot6niGC1ZpvQGNk1seLMBm80RZ0","wt":"0","w":[],"c":[]}-AABAANxCwp8L5f_8jLmdWSv8v-qNPv54m7Ij-Zlv5BMQZSs5AWuSaw96QkQt1DTOsDNgomLFuY8TdBeLdXjIIrqJWCw"#; -// let deserialized_icp = signed_message(delegator_icp_raw.as_bytes()).unwrap().1; -// event_processor.process(deserialized_icp.clone())?.unwrap(); +#[test] +fn test_validate_seal() -> Result<(), Error> { + use tempfile::Builder; + // Create test db and event processor. + let root = Builder::new().prefix("test-db").tempdir().unwrap(); + fs::create_dir_all(root.path()).unwrap(); + let db = Arc::new(SledEventDatabase::new(root.path()).unwrap()); + let event_processor = EventProcessor::new(Arc::clone(&db)); -// // Process delegating event. -// let delegating_event_raw = r#"{"v":"KERI10JSON000107_","i":"DcVUXDcB307nuuIlMGEUt9WZc4WF9W29IRvxDyVu6hyg","s":"1","t":"ixn","p":"E7rJVSh_MLTFcZ4v0urBxSJ103uR454Vo6St-wSCk_sI","a":[{"i":"EbuZO_Yr5Zt2Jvg0Sa96b2lDquGF3hHlhr7U7t3rLHvw","s":"0","d":"Eqid10S0HyiUI56hp2eBaS4pdnqvEnqV3p8f5DMfXX7w"}]}-AABAA1BOb5zF2PZ9x4GFpwVigVDTUAjpF1T3P23Z2uiwGej2J4EyoEvEW_WFxfVbyOLQW4eIWG2zNalOXy32sAL94BA"#; -// let deserialized_ixn = signed_message(delegating_event_raw.as_bytes()).unwrap().1; -// event_processor.process(deserialized_ixn.clone())?; + // Events and sigs are from keripy `test_delegation` test. + // (keripy/tests/core/test_delegating.py) -// // Get seal from delegated inception event. -// let dip_raw = r#"{"v":"KERI10JSON000165_","i":"EbuZO_Yr5Zt2Jvg0Sa96b2lDquGF3hHlhr7U7t3rLHvw","s":"0","t":"dip","kt":"1","k":["DEQbpbOD29I6igCqlxNYVy-TsFa8kmPKLdYscL0lxsPE"],"n":"Ey6FhAzq0Ivj8E-NYjxkWrlj6mLFL67S6ADcsxMhX46s","wt":"0","w":[],"c":[],"da":{"i":"DcVUXDcB307nuuIlMGEUt9WZc4WF9W29IRvxDyVu6hyg","s":"1","t":"ixn","p":"HiQ3FpdUUTT8DyNJWIcN18OouhiA6SfjcajsBVDHVMeY"}}"#; -// let deserialized_dip = message(dip_raw.as_bytes()).unwrap().1; -// let seal = if let EventData::Dip(dip) = deserialized_dip.event.event.event_data { -// dip.seal -// } else { -// LocationSeal::default() -// }; + // Process icp. + let delegator_icp_raw = r#"{"v":"KERI10JSON0000ed_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"0","t":"icp","kt":"1","k":["DqI2cOZ06RwGNwCovYUWExmdKU983IasmUKMmZflvWdQ"],"n":"E7FuL3Z_KBgt_QAwuZi1lUFNC69wvyHSxnMFUsKjZHss","bt":"0","b":[],"c":[],"a":[]}-AABAAp8S6RgfLwdCEiz0jL9cXaDwTJF6MLuKyXp7EfJtrp2myOikOJVUB-w9UGZc1Y8dnURxhXPSca-ZEUAV73XOaAw"#; + let deserialized_icp = signed_message(delegator_icp_raw.as_bytes()).unwrap().1; + event_processor.process(deserialized_icp.clone())?.unwrap(); + let delegator_id = "Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI".parse()?; -// if let Deserialized::Event(ev) = deserialized_ixn.clone() { -// if let EventData::Ixn(ixn) = ev.event.event.event.event_data { -// assert_eq!( -// ixn.previous_event_hash.derivation, -// SelfAddressing::Blake3_256 -// ); -// assert_eq!(seal.prior_digest.derivation, SelfAddressing::SHA3_256); -// assert_ne!( -// ixn.previous_event_hash.derivation, -// seal.prior_digest.derivation -// ); -// } -// }; + let dip_raw = r#"{"v":"KERI10JSON000121_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","t":"dip","kt":"1","k":["DuK1x8ydpucu3480Jpd1XBfjnCwb3dZ3x5b1CJmuUphA"],"n":"EWWkjZkZDXF74O2bOQ4H5hu4nXDlKg2m4CBEBkUxibiU","bt":"0","b":[],"c":[],"a":[],"di":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI"}"#; //-AABAA2_8Guj0Gf2JoNTq7hOs4u6eOOWhENALJWDfLxkVcS2uLh753FjtyE80lpeS3to1C9yvENyMnyN4q96ehA4exDA-GAB0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"#; -// assert!(event_processor -// .validate_seal(seal, dip_raw.as_bytes()) -// .is_ok()); + // Compute delegated event digest + let delegated_event_digest = SelfAddressing::Blake3_256.derive(dip_raw.as_bytes()); + // Construct delegating seal. + let seal = EventSeal { + prefix: delegator_id, + sn: 1, + event_digest: delegated_event_digest, + }; + // Try to validate seal before processing delegating event + assert!(matches!( + event_processor.validate_seal(seal.clone(), dip_raw.as_bytes()), + Err(Error::EventOutOfOrderError) + )); + + // Process delegating event. + let delegating_event_raw = r#"{"v":"KERI10JSON000107_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"1","t":"ixn","p":"E1-QL0TCdsBTRaKoakLjFhjSlELK60Vv8WdRaG6zMnTM","a":[{"i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","d":"E1x1JOub6oEQkxAxTNFu1Pma6y-lrbprNsaILHJHoPmY"}]}-AABAAROVSK0qK2gqlr_OUsnHNW_ksCyLVmRaysRne2dI5dweECGIy3_ZuFHyOofiDRt5tRE09PlS0uZdot6byFNr-AA"#; + let deserialized_ixn = signed_message(delegating_event_raw.as_bytes()).unwrap().1; + event_processor.process(deserialized_ixn.clone())?; + + // Validate seal again. + assert!(event_processor + .validate_seal(seal, dip_raw.as_bytes()) + .is_ok()); -// Ok(()) -// } + Ok(()) +} #[test] fn test_compute_state_at_sn() -> Result<(), Error> { From 8ff14ba22358221dc472d5c82e36d2ab6330d139 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 23 Sep 2021 20:11:42 +0200 Subject: [PATCH 11/17] feat(delegation): fix delegation test --- src/event_message/attachement.rs | 15 ++- src/event_message/parse.rs | 4 +- src/prefix/parse.rs | 21 ++-- src/processor/tests.rs | 186 ++++++++++++++++--------------- 4 files changed, 118 insertions(+), 108 deletions(-) diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 1dd645f..1de2b00 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -1,5 +1,6 @@ use std::str::FromStr; +use base64::URL_SAFE_NO_PAD; use serde::{Deserialize, Serialize}; use crate::{error::Error, prefix::{Prefix, SelfAddressingPrefix}}; @@ -62,14 +63,20 @@ impl SorceSeal { Ok([ payload_type.to_string().as_bytes().to_vec(), // TODO remove magic 22 - num_to_base_64(self.sn as u16, 22).as_bytes().to_vec(), + sn_to_vec(self.sn, 22).as_bytes().to_vec(), self.digest.to_str().as_bytes().to_vec(), ] .concat()) } } - +fn sn_to_vec(sn: u64, len: usize) -> String { + let sn_raw: Vec = sn.to_be_bytes().into(); + let padding = 4 - len % 4; + let len = (len + padding) / 4 * 3 - padding - sn_raw.len(); + let sn_vec: Vec = std::iter::repeat(0).take(len).chain(sn_raw).collect(); + base64::encode_config(sn_vec, URL_SAFE_NO_PAD) +} #[test] fn test_parse_attachement() -> Result<(), Error> { @@ -83,12 +90,12 @@ fn test_parse_attachement() -> Result<(), Error> { Attachement::SealSourceCouplets(sources) => { let s1 = sources[0].clone(); let s2 = sources[1].clone(); - assert_eq!(s1.sn, 16); + assert_eq!(s1.sn, 1); assert_eq!( s1.digest.to_str(), "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII" ); - assert_eq!(s2.sn, 16); + assert_eq!(s2.sn, 1); assert_eq!( s2.digest.to_str(), "E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII" diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index e616c17..fa030d1 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -218,11 +218,11 @@ pub fn signed_message<'a>(s: &'a [u8]) -> nom::IResult<&[u8], Deserialized> { } }, EventData::Dip(_) | EventData::Drt(_) => { + let (rest, signatures) = signatures(rest)?; let (rest, source_seal) = counter(rest)?; - let (extra, signatures) = signatures(rest)?; Ok(( - extra, + rest, Deserialized::Event(DeserializedSignedEvent { deserialized_event: e, signatures, diff --git a/src/prefix/parse.rs b/src/prefix/parse.rs index 15c2a61..a7d9520 100644 --- a/src/prefix/parse.rs +++ b/src/prefix/parse.rs @@ -2,7 +2,7 @@ use crate::{derivation::{ attached_signature_code::b64_to_num, basic::Basic, self_addressing::SelfAddressing, self_signing::SelfSigning, DerivationCode, - }, error::Error, event::sections::seal::EventSeal, keys::PublicKey, prefix::{AttachedSignaturePrefix, BasicPrefix, IdentifierPrefix, SelfSigningPrefix}}; + }, event::sections::seal::EventSeal, keys::PublicKey, prefix::{AttachedSignaturePrefix, BasicPrefix, IdentifierPrefix, SelfSigningPrefix}}; use base64::URL_SAFE; use nom::{bytes::complete::take, error::ErrorKind}; @@ -147,9 +147,14 @@ pub fn attached_sn(s: &[u8]) -> nom::IResult<&[u8], u64> { match type_c { a => { let (rest, parsed_sn) = take(22u8)(more)?; - - let sn = - base64_to_num(parsed_sn).map_err(|_| nom::Err::Failure((s, ErrorKind::IsNot)))? as u64; + + let sn = { + let b64decode = base64::decode_config(parsed_sn, URL_SAFE) + .map_err(|_| nom::Err::Failure((s, ErrorKind::IsNot)))?; + let mut sn_array: [u8; 8] = [0; 8]; + sn_array.copy_from_slice(&b64decode[8..]); + u64::from_be_bytes(sn_array) + }; Ok((rest, sn)) } @@ -157,12 +162,6 @@ pub fn attached_sn(s: &[u8]) -> nom::IResult<&[u8], u64> { } } -fn base64_to_num(b64: &[u8]) -> Result { - // TODO thats because b64_to_num works only for 4 or less characters - let last_four = &b64[b64.len() - 4..]; - Ok(b64_to_num(last_four)?) -} - /// extracts the Event seal pub fn event_seal(s: &[u8]) -> nom::IResult<&[u8], EventSeal> { let (more, type_c) = take(3u8)(s)?; @@ -255,7 +254,7 @@ fn test_self_signing() { #[test] fn test_sn_parse() { let sn = attached_sn("0AAAAAAAAAAAAAAAAAAAAAAw".as_bytes()).unwrap(); - assert_eq!(sn, ("".as_bytes(), 48)); + assert_eq!(sn, ("".as_bytes(), 3)); } #[test] diff --git a/src/processor/tests.rs b/src/processor/tests.rs index 037099a..6d73c6f 100644 --- a/src/processor/tests.rs +++ b/src/processor/tests.rs @@ -2,6 +2,7 @@ use super::EventProcessor; use crate::derivation::self_addressing::SelfAddressing; use crate::event::sections::seal::EventSeal; use crate::event_message::parse::signed_message; +use crate::prefix::Prefix; use crate::{database::sled::SledEventDatabase, error::Error}; use crate::{ event_message::{ @@ -173,97 +174,100 @@ fn test_process_receipt() -> Result<(), Error> { Ok(()) } -// TODO fix the test after updating delegation. -// (https://github.com/decentralized-identity/keri/issues/146) -// #[test] -// fn test_process_delegated() -> Result<(), Error> { -// use tempfile::Builder; -// // Create test db and event processor. -// let root = Builder::new().prefix("test-db").tempdir().unwrap(); -// fs::create_dir_all(root.path()).unwrap(); -// let db = Arc::new(SledEventDatabase::new(root.path()).unwrap()); -// let event_processor = EventProcessor::new(Arc::clone(&db)); - -// let raw_parsed = |des| -> Result, Error> { -// match &des { -// Deserialized::Event(e) => Ok(e.deserialized_event.raw.to_vec()), -// _ => Err(Error::SemanticError("bad deser".into()))?, -// } -// }; - -// // Events and sigs are from keripy `test_delegation` test. -// // (keripy/tests/core/test_delegating.py#62) -// let bobs_pref: IdentifierPrefix = "EiBlVttjqvySMbA4ShN19rSrz3D0ioNW-Uj92Ri7XnFE".parse()?; - -// let bobs_icp = br#"{"v":"KERI10JSON0000ed_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"0","t":"icp","kt":"1","k":["DqI2cOZ06RwGNwCovYUWExmdKU983IasmUKMmZflvWdQ"],"n":"E7FuL3Z_KBgt_QAwuZi1lUFNC69wvyHSxnMFUsKjZHss","bt":"0","b":[],"c":[],"a":[]}-AABAAp8S6RgfLwdCEiz0jL9cXaDwTJF6MLuKyXp7EfJtrp2myOikOJVUB-w9UGZc1Y8dnURxhXPSca-ZEUAV73XOaAw"#; -// let msg = signed_message(bobs_icp).unwrap().1; -// event_processor.process(msg)?; - -// // Delegated inception event. -// let dip_raw = br#"{"v":"KERI10JSON000121_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","t":"dip","kt":"1","k":["DuK1x8ydpucu3480Jpd1XBfjnCwb3dZ3x5b1CJmuUphA"],"n":"EWWkjZkZDXF74O2bOQ4H5hu4nXDlKg2m4CBEBkUxibiU","bt":"0","b":[],"c":[],"a":[],"di":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI"}-AABAA2_8Guj0Gf2JoNTq7hOs4u6eOOWhENALJWDfLxkVcS2uLh753FjtyE80lpeS3to1C9yvENyMnyN4q96ehA4exDA-GAB0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"#; -// let deserialized_dip = signed_message(dip_raw).unwrap().1; - -// // Process dip event before delegating ixn event. -// let state = event_processor.process(deserialized_dip.clone()); -// assert!(matches!(state, Err(Error::EventOutOfOrderError))); - -// let child_prefix: IdentifierPrefix = "ErLe2qWp4VCmDp7v_R01tC-ha13ZEZY0VGcgYtPRhqPs".parse()?; - -// // Check if processed dip is in kel. -// let dip_from_db = event_processor.get_event_at_sn(&child_prefix, 0); -// assert!(matches!(dip_from_db, Ok(None))); - -// // Bob's ixn event with delegating event seal. -// let bobs_ixn = br#"{"v":"KERI10JSON000107_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"1","t":"ixn","p":"E1-QL0TCdsBTRaKoakLjFhjSlELK60Vv8WdRaG6zMnTM","a":[{"i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","d":"E1x1JOub6oEQkxAxTNFu1Pma6y-lrbprNsaILHJHoPmY"}]}-AABAAROVSK0qK2gqlr_OUsnHNW_ksCyLVmRaysRne2dI5dweECGIy3_ZuFHyOofiDRt5tRE09PlS0uZdot6byFNr-AA'"#; -// let deserialized_ixn = signed_message(bobs_ixn).unwrap().1; -// event_processor.process(deserialized_ixn.clone())?; - -// // Check if processed event is in db. -// let ixn_from_db = event_processor.get_event_at_sn(&bobs_pref, 1).unwrap().unwrap(); -// assert_eq!(ixn_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_ixn)?); - -// // Process delegated inception event once again. -// event_processor.process(deserialized_dip.clone())?.unwrap(); - -// // Check if processed dip event is in db. -// let dip_from_db = event_processor -// .get_event_at_sn(&child_prefix, 0)? -// .unwrap(); -// assert_eq!(dip_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_dip)?); - -// // Bobs interaction event with delegated event seal. -// let bob_ixn = br#"{"v":"KERI10JSON000107_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"2","t":"ixn","p":"E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII","a":[{"i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"1","d":"EPjLBcb4pp-3PGvSi_fTvLvsqUqFoJ0CVCHvIFfu93Xc"}]}-AABAAclMVE-bkIn-wPiAqfgR384nWmslQHQvmo2o3xQvd_4Bt6bflc4BAmfBa03KgrDVqmB7qG2VXQbOHevkzOgRdD"#; -// let deserialized_ixn_drt = signed_message(bob_ixn).unwrap().1; - -// // Delegated rotation event. -// let drt_raw = br#"{"v":"KERI10JSON000122_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"1","t":"drt","p":"E1x1JOub6oEQkxAxTNFu1Pma6y-lrbprNsaILHJHoPmY","kt":"1","k":["DTf6QZWoet154o9wvzeMuNhLQRr8JaAUeiC6wjB_4_08"],"n":"E8kyiXDfkE7idwWnAZQjHbUZMz-kd_yIMH0miptIFFPo","bt":"0","br":[],"ba":[],"a":[]}-AABAAAVUMNfOl9Fcqx-C3fAYnaxvsiJJO3zG6rP0FQ2WVp__hMEaprrQbJL6-Esnny3U5zvMOqbso17rvecTwmVIwDw-GAB0AAAAAAAAAAAAAAAAAAAAAAgEbOI0OIIFv2VV5bmeSq1pwCn-6b2k6TdWcCbJHE6Ly7o"#; -// let deserialized_drt = signed_message(drt_raw).unwrap().1; - -// // Process drt event before delegating ixn event. -// let child_state = event_processor.process(deserialized_drt.clone()); -// assert!(matches!(child_state, Err(Error::EventOutOfOrderError))); - -// // Check if processed drt is in kel. -// let drt_from_db = event_processor.get_event_at_sn(&child_prefix, 1); -// assert!(matches!(drt_from_db, Ok(None))); - -// event_processor.process(deserialized_ixn_drt.clone())?; - -// // Check if processed event is in db. -// let ixn_from_db = event_processor.get_event_at_sn(&bobs_pref, 2)?.unwrap(); -// assert_eq!(ixn_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_ixn_drt)?); - -// // Process delegated rotation event once again. -// event_processor.process(deserialized_drt.clone())?.unwrap(); - -// // Check if processed drt event is in db. -// let drt_from_db = event_processor -// .get_event_at_sn(&child_prefix, 1)? -// .unwrap(); -// assert_eq!(drt_from_db.signed_event_message.serialize()?, raw_parsed(deserialized_drt)?); - -// Ok(()) -// } +#[test] +fn test_process_delegated() -> Result<(), Error> { + use tempfile::Builder; + // Create test db and event processor. + let root = Builder::new().prefix("test-db").tempdir().unwrap(); + fs::create_dir_all(root.path()).unwrap(); + let db = Arc::new(SledEventDatabase::new(root.path()).unwrap()); + let event_processor = EventProcessor::new(Arc::clone(&db)); + + let raw_parsed = |des| -> Result, Error> { + match &des { + Deserialized::Event(e) => Ok(e.deserialized_event.raw.to_vec()), + _ => Err(Error::SemanticError("bad deser".into()))?, + } + }; + + // Events and sigs are from keripy `test_delegation` test. + // (keripy/tests/core/test_delegating.py) + let bobs_pref: IdentifierPrefix = "Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI".parse()?; + + let bobs_icp = br#"{"v":"KERI10JSON0000ed_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"0","t":"icp","kt":"1","k":["DqI2cOZ06RwGNwCovYUWExmdKU983IasmUKMmZflvWdQ"],"n":"E7FuL3Z_KBgt_QAwuZi1lUFNC69wvyHSxnMFUsKjZHss","bt":"0","b":[],"c":[],"a":[]}-AABAAp8S6RgfLwdCEiz0jL9cXaDwTJF6MLuKyXp7EfJtrp2myOikOJVUB-w9UGZc1Y8dnURxhXPSca-ZEUAV73XOaAw"#; + let msg = signed_message(bobs_icp).unwrap().1; + event_processor.process(msg)?; + + // Delegated inception event. + let dip_raw = br#"{"v":"KERI10JSON000121_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","t":"dip","kt":"1","k":["DuK1x8ydpucu3480Jpd1XBfjnCwb3dZ3x5b1CJmuUphA"],"n":"EWWkjZkZDXF74O2bOQ4H5hu4nXDlKg2m4CBEBkUxibiU","bt":"0","b":[],"c":[],"a":[],"di":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI"}-AABAA2_8Guj0Gf2JoNTq7hOs4u6eOOWhENALJWDfLxkVcS2uLh753FjtyE80lpeS3to1C9yvENyMnyN4q96ehA4exDA-GAB0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"#; + let deserialized_dip = signed_message(dip_raw).unwrap().1; + + // Process dip event before delegating ixn event. + let state = event_processor.process(deserialized_dip.clone()); + assert!(matches!(state, Err(Error::EventOutOfOrderError))); + + let child_prefix: IdentifierPrefix = "E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U".parse()?; + + // Check if processed dip is in kel. + let dip_from_db = event_processor.get_event_at_sn(&child_prefix, 0); + assert!(matches!(dip_from_db, Ok(None))); + + // Bob's ixn event with delegating event seal. + let bobs_ixn = br#"{"v":"KERI10JSON000107_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"1","t":"ixn","p":"E1-QL0TCdsBTRaKoakLjFhjSlELK60Vv8WdRaG6zMnTM","a":[{"i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","d":"E1x1JOub6oEQkxAxTNFu1Pma6y-lrbprNsaILHJHoPmY"}]}-AABAAROVSK0qK2gqlr_OUsnHNW_ksCyLVmRaysRne2dI5dweECGIy3_ZuFHyOofiDRt5tRE09PlS0uZdot6byFNr-AA"#; + let deserialized_ixn = signed_message(bobs_ixn).unwrap().1; + event_processor.process(deserialized_ixn.clone())?; + + // Check if processed event is in db. + let ixn_from_db = event_processor.get_event_at_sn(&bobs_pref, 1).unwrap().unwrap(); + assert_eq!(ixn_from_db.signed_event_message.event_message.serialize()?, raw_parsed(deserialized_ixn)?); + + let dip = br#"{"v":"KERI10JSON000121_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","t":"dip","kt":"1","k":["DuK1x8ydpucu3480Jpd1XBfjnCwb3dZ3x5b1CJmuUphA"],"n":"EWWkjZkZDXF74O2bOQ4H5hu4nXDlKg2m4CBEBkUxibiU","bt":"0","b":[],"c":[],"a":[],"di":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI"}"#; + let delegatd_dig = SelfAddressing::Blake3_256.derive(dip); + println!("{}", delegatd_dig.to_str()); + + // Process delegated inception event once again. + event_processor.process(deserialized_dip.clone())?; + + // Check if processed dip event is in db. + let dip_from_db = event_processor + .get_event_at_sn(&child_prefix, 0)? + .unwrap(); + + assert_eq!(dip_from_db.signed_event_message.event_message.serialize()?, raw_parsed(deserialized_dip.clone())?); + + // Bobs interaction event with delegated event seal. + let bob_ixn = br#"{"v":"KERI10JSON000107_","i":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI","s":"2","t":"ixn","p":"E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII","a":[{"i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"1","d":"EPjLBcb4pp-3PGvSi_fTvLvsqUqFoJ0CVCHvIFfu93Xc"}]}-AABAAclMVE-bkIn-wPiAqfgR384nWmslQHQvmo2o3xQvd_4Bt6bflc4BAmfBa03KgrDVqmB7qG2VXQbOHevkzOgRdDA"#; + let deserialized_ixn_drt = signed_message(bob_ixn).unwrap().1; + + // Delegated rotation event. + let drt_raw = br#"{"v":"KERI10JSON000122_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"1","t":"drt","p":"E1x1JOub6oEQkxAxTNFu1Pma6y-lrbprNsaILHJHoPmY","kt":"1","k":["DTf6QZWoet154o9wvzeMuNhLQRr8JaAUeiC6wjB_4_08"],"n":"E8kyiXDfkE7idwWnAZQjHbUZMz-kd_yIMH0miptIFFPo","bt":"0","br":[],"ba":[],"a":[]}-AABAAAVUMNfOl9Fcqx-C3fAYnaxvsiJJO3zG6rP0FQ2WVp__hMEaprrQbJL6-Esnny3U5zvMOqbso17rvecTwmVIwDw-GAB0AAAAAAAAAAAAAAAAAAAAAAgEbOI0OIIFv2VV5bmeSq1pwCn-6b2k6TdWcCbJHE6Ly7o"#; + let deserialized_drt = signed_message(drt_raw).unwrap().1; + + // Process drt event before delegating ixn event. + let child_state = event_processor.process(deserialized_drt.clone()); + assert!(matches!(child_state, Err(Error::EventOutOfOrderError))); + + // Check if processed drt is in kel. + let drt_from_db = event_processor.get_event_at_sn(&child_prefix, 1); + assert!(matches!(drt_from_db, Ok(None))); + + event_processor.process(deserialized_ixn_drt.clone())?; + + // Check if processed event is in db. + let ixn_from_db = event_processor.get_event_at_sn(&bobs_pref, 2)?.unwrap(); + assert_eq!(ixn_from_db.signed_event_message.event_message.serialize()?, raw_parsed(deserialized_ixn_drt)?); + + // Process delegated rotation event once again. + event_processor.process(deserialized_drt.clone())?.unwrap(); + + // Check if processed drt event is in db. + let drt_from_db = event_processor + .get_event_at_sn(&child_prefix, 1)? + .unwrap(); + assert_eq!(drt_from_db.signed_event_message.event_message.serialize()?, raw_parsed(deserialized_drt)?); + + Ok(()) +} #[test] fn test_validate_seal() -> Result<(), Error> { From e056d41f5dcc62afe25d8efc748f7970cdb6eb93 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 23 Sep 2021 20:31:43 +0200 Subject: [PATCH 12/17] feat(delegation): add pack sn function --- src/event_message/attachement.rs | 45 +++++++++++++++++++------------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 1de2b00..8abaf50 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -3,9 +3,12 @@ use std::str::FromStr; use base64::URL_SAFE_NO_PAD; use serde::{Deserialize, Serialize}; -use crate::{error::Error, prefix::{Prefix, SelfAddressingPrefix}}; +use crate::{ + error::Error, + prefix::{Prefix, SelfAddressingPrefix}, +}; -use super::{parse::counter, payload_size::{PayloadType, num_to_base_64}}; +use super::{parse::counter, payload_size::PayloadType}; #[derive(Debug, Clone, Deserialize, PartialEq)] pub enum Attachement { @@ -21,10 +24,13 @@ impl Attachement { .into_iter() .map(|s| s.serialize().unwrap()) .flatten(); - Ok(payload_type.encode(sources.len() as u16).as_bytes().to_vec() - .into_iter() - .chain(serialzied_sources) - .collect::>()) + Ok(payload_type + .encode(sources.len() as u16) + .as_bytes() + .to_vec() + .into_iter() + .chain(serialzied_sources) + .collect::>()) } } } @@ -36,7 +42,8 @@ impl FromStr for Attachement { fn from_str(s: &str) -> Result { match &s[0..2] { "-G" => { - let (rest, counter) = counter(s.as_bytes()).map_err(|_e| Error::SemanticError("Can't parse counter".into()))?; + let (rest, counter) = counter(s.as_bytes()) + .map_err(|_e| Error::SemanticError("Can't parse counter".into()))?; if rest.is_empty() { Ok(counter) } else { @@ -56,26 +63,28 @@ pub struct SorceSeal { impl SorceSeal { pub fn new(sn: u64, digest: SelfAddressingPrefix) -> Self { - Self {sn, digest} + Self { sn, digest } } pub fn serialize(&self) -> Result, Error> { - let payload_type = PayloadType::OA; - Ok([ - payload_type.to_string().as_bytes().to_vec(), - // TODO remove magic 22 - sn_to_vec(self.sn, 22).as_bytes().to_vec(), - self.digest.to_str().as_bytes().to_vec(), - ] - .concat()) + Ok([pack_sn(self.sn), self.digest.to_str()] + .join("") + .as_bytes() + .to_vec()) } } -fn sn_to_vec(sn: u64, len: usize) -> String { +fn pack_sn(sn: u64) -> String { + let payload_type = PayloadType::OA; + let len = payload_type.size() - payload_type.master_code_size(false); let sn_raw: Vec = sn.to_be_bytes().into(); let padding = 4 - len % 4; let len = (len + padding) / 4 * 3 - padding - sn_raw.len(); let sn_vec: Vec = std::iter::repeat(0).take(len).chain(sn_raw).collect(); - base64::encode_config(sn_vec, URL_SAFE_NO_PAD) + [ + payload_type.to_string(), + base64::encode_config(sn_vec, URL_SAFE_NO_PAD), + ] + .join("") } #[test] From 1d353cbdb68547fc02c8d94cd2d8bdf309486720 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Fri, 24 Sep 2021 12:59:11 +0200 Subject: [PATCH 13/17] feat(delegation): minor refactor --- src/event/event_data/delegated/mod.rs | 4 - src/event_message/attachement.rs | 10 +- src/event_message/event_msg_builder.rs | 11 +- src/event_message/parse.rs | 2 +- src/event_message/payload_size.rs | 149 +++++++++++----------- src/event_message/signed_event_message.rs | 4 +- src/processor/mod.rs | 4 +- src/processor/tests.rs | 5 - 8 files changed, 87 insertions(+), 102 deletions(-) diff --git a/src/event/event_data/delegated/mod.rs b/src/event/event_data/delegated/mod.rs index ef9388b..524268c 100644 --- a/src/event/event_data/delegated/mod.rs +++ b/src/event/event_data/delegated/mod.rs @@ -62,10 +62,6 @@ impl EventSemantics for DelegatedInceptionEvent { } impl EventSemantics for DelegatedRotationEvent { fn apply_to(&self, state: IdentifierState) -> Result { - // if state.delegator == Some(self.delegator.prefix.clone()) { self.rotation_data.apply_to(state) - // } else { - // Err(Error::SemanticError("Wrong delegator".into())) - // } } } diff --git a/src/event_message/attachement.rs b/src/event_message/attachement.rs index 8abaf50..b3fe504 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachement.rs @@ -25,7 +25,7 @@ impl Attachement { .map(|s| s.serialize().unwrap()) .flatten(); Ok(payload_type - .encode(sources.len() as u16) + .adjust_with_num(sources.len() as u16) .as_bytes() .to_vec() .into_iter() @@ -75,11 +75,11 @@ impl SorceSeal { fn pack_sn(sn: u64) -> String { let payload_type = PayloadType::OA; - let len = payload_type.size() - payload_type.master_code_size(false); let sn_raw: Vec = sn.to_be_bytes().into(); - let padding = 4 - len % 4; - let len = (len + padding) / 4 * 3 - padding - sn_raw.len(); - let sn_vec: Vec = std::iter::repeat(0).take(len).chain(sn_raw).collect(); + // Calculate how many zeros are missing to achive expected base64 string + // length. Master code size is expected padding size. + let missing_zeros = payload_type.size() / 4 * 3 - payload_type.master_code_size(false) - sn_raw.len(); + let sn_vec: Vec = std::iter::repeat(0).take(missing_zeros).chain(sn_raw).collect(); [ payload_type.to_string(), base64::encode_config(sn_vec, URL_SAFE_NO_PAD), diff --git a/src/event_message/event_msg_builder.rs b/src/event_message/event_msg_builder.rs index adc8c76..f346227 100644 --- a/src/event_message/event_msg_builder.rs +++ b/src/event_message/event_msg_builder.rs @@ -4,7 +4,7 @@ use crate::{derivation::{basic::Basic, self_addressing::SelfAddressing}, error:: interaction::InteractionEvent, rotation::RotationEvent, }, - sections::{threshold::SignatureThreshold, seal::LocationSeal, WitnessConfig}, + sections::{threshold::SignatureThreshold, WitnessConfig}, SerializationFormats, }, event::{ event_data::{inception::InceptionEvent, EventData}, @@ -15,7 +15,6 @@ use crate::{derivation::{basic::Basic, self_addressing::SelfAddressing}, error:: }, keys::PublicKey, prefix::{BasicPrefix, IdentifierPrefix, SelfAddressingPrefix}}; use ed25519_dalek::Keypair; use rand::rngs::OsRng; -use std::str::FromStr; pub struct EventMsgBuilder { event_type: EventType, @@ -60,14 +59,6 @@ impl EventMsgBuilder { let pk = PublicKey::new(kp.public.to_bytes().to_vec()); let npk = PublicKey::new(nkp.public.to_bytes().to_vec()); let basic_pref = Basic::Ed25519.derive(pk); - let dummy_loc_seal = LocationSeal { - prefix: IdentifierPrefix::from_str("EZAoTNZH3ULvaU6Z-i0d8JJR2nmwyYAfSVPzhzS6b5CM")?, - sn: 2, - ilk: "ixn".into(), - prior_digest: SelfAddressingPrefix::from_str( - "E8JZAoTNZH3ULZ-i0dvaU6JR2nmwyYAfSVPzhzS6b5CM", - )?, - }; Ok(EventMsgBuilder { event_type, prefix: IdentifierPrefix::default(), diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index fa030d1..e7df320 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -1,5 +1,5 @@ use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{SorceSeal, Attachement}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; -use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, event_message::event_msg_builder::{EventMsgBuilder, EventType}, prefix::{BasicPrefix, IdentifierPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; +use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, prefix::{BasicPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; use nom::{ branch::*, combinator::*, diff --git a/src/event_message/payload_size.rs b/src/event_message/payload_size.rs index ff4ff02..6f3efc2 100644 --- a/src/event_message/payload_size.rs +++ b/src/event_message/payload_size.rs @@ -1,6 +1,6 @@ -use base64::encode_config; -use serde::{Serialize, Deserialize}; use crate::error::Error; +use base64::encode_config; +use serde::{Deserialize, Serialize}; use std::{convert::TryFrom, fmt::Display}; // Payload sizes pre unit @@ -84,7 +84,7 @@ pub enum PayloadType { impl PayloadType { pub(crate) fn size(&self) -> usize { match self { - Self::A + Self::A | Self::B | Self::C | Self::D @@ -109,7 +109,7 @@ impl PayloadType { Self::IAAE => 156, Self::IAAG => 36, Self::MA | Self::MB => 88, - _ => 0 // TODO: fill proper sizes + _ => 0, // TODO: fill proper sizes } } @@ -123,7 +123,7 @@ impl PayloadType { | Self::F | Self::G | Self::H - | Self::I + | Self::I | Self::J | Self::K | Self::L @@ -152,6 +152,8 @@ impl PayloadType { } } + // Return size of adjustable part of master codes, respesented as "#" in + // code table. pub(crate) fn index_length(&self) -> usize { match self { Self::A @@ -162,7 +164,7 @@ impl PayloadType { | Self::F | Self::G | Self::H - | Self::I + | Self::I | Self::J | Self::K | Self::L @@ -187,35 +189,33 @@ impl PayloadType { | Self::MX | Self::MY | Self::MZ => 2, - _ => todo!() + _ => todo!(), } } - - -pub fn encode(&self, sn: u16) -> String { - [self.to_string(), num_to_base_64(sn, self.index_length() as usize)].join("") -} - -} - -pub fn num_to_base_64(sn: u16, len: usize) -> String { - let i = num_to_b64(sn); - // refill string to have proper size given in len argument - let part = if i.len() < len { - "A".repeat(len - i.len()) - } else { - String::default() - }; - [part, i].join("") + pub fn adjust_with_num(&self, sn: u16) -> String { + let expected_length = self.index_length(); + if expected_length > 0 { + let i = num_to_b64(sn); + if i.len() < expected_length { + // refill string to have proper size + let missing_part = "A".repeat(expected_length - i.len()); + [self.to_string(), missing_part, i].join("") + } else { + [self.to_string(), i].join("") + } + } else { + self.to_string() + } + } } pub fn num_to_b64(num: u16) -> String { match num { - n if n < 63 => - encode_config([num.to_be_bytes()[1] << 2], base64::URL_SAFE_NO_PAD)[..1].to_string(), - n if n < 4095 => - encode_config(num.to_be_bytes(), base64::URL_SAFE_NO_PAD)[..2].to_string(), + n if n < 63 => { + encode_config([num.to_be_bytes()[1] << 2], base64::URL_SAFE_NO_PAD)[..1].to_string() + } + n if n < 4095 => encode_config(num.to_be_bytes(), base64::URL_SAFE_NO_PAD)[..2].to_string(), _ => encode_config(num.to_be_bytes(), base64::URL_SAFE_NO_PAD), } } @@ -224,48 +224,48 @@ impl TryFrom<&str> for PayloadType { type Error = Error; fn try_from(data: &str) -> Result { match data { - "A" => Ok(Self::A), - "B" => Ok(Self::B), - "C" => Ok(Self::C), - "D" => Ok(Self::D), - "E" => Ok(Self::E), - "F" => Ok(Self::F), - "G" => Ok(Self::G), - "H" => Ok(Self::H), - "I" => Ok(Self::I), - "J" => Ok(Self::J), - "K" => Ok(Self::K), - "L" => Ok(Self::L), - "M" => Ok(Self::M), - "0A" => Ok(Self::OA), - "0B" => Ok(Self::OB), - "0C" => Ok(Self::OC), - "0D" => Ok(Self::OD), - "0E" => Ok(Self::OE), - "0F" => Ok(Self::OF), - "0G" => Ok(Self::OG), - "0H" => Ok(Self::OH), - "1AAA" => Ok(Self::IAAA), - "1AAB" => Ok(Self::IAAB), - "1AAC" => Ok(Self::IAAC), - "1AAD" => Ok(Self::IAAD), - "1AAE" => Ok(Self::IAAE), - "1AAF" => Ok(Self::IAAF), - "1AAG" => Ok(Self::IAAG), - "-A" => Ok(Self::MA), - "-B" => Ok(Self::MB), - "-C" => Ok(Self::MC), - "-D" => Ok(Self::MD), - "-E" => Ok(Self::ME), - "-F" => Ok(Self::MF), - "-U" => Ok(Self::MU), - "-V" => Ok(Self::MV), - "-W" => Ok(Self::MW), - "-X" => Ok(Self::MX), - "-Y" => Ok(Self::MY), - "-Z" => Ok(Self::MZ), - _ => Err(Error::ImproperPrefixType) - } + "A" => Ok(Self::A), + "B" => Ok(Self::B), + "C" => Ok(Self::C), + "D" => Ok(Self::D), + "E" => Ok(Self::E), + "F" => Ok(Self::F), + "G" => Ok(Self::G), + "H" => Ok(Self::H), + "I" => Ok(Self::I), + "J" => Ok(Self::J), + "K" => Ok(Self::K), + "L" => Ok(Self::L), + "M" => Ok(Self::M), + "0A" => Ok(Self::OA), + "0B" => Ok(Self::OB), + "0C" => Ok(Self::OC), + "0D" => Ok(Self::OD), + "0E" => Ok(Self::OE), + "0F" => Ok(Self::OF), + "0G" => Ok(Self::OG), + "0H" => Ok(Self::OH), + "1AAA" => Ok(Self::IAAA), + "1AAB" => Ok(Self::IAAB), + "1AAC" => Ok(Self::IAAC), + "1AAD" => Ok(Self::IAAD), + "1AAE" => Ok(Self::IAAE), + "1AAF" => Ok(Self::IAAF), + "1AAG" => Ok(Self::IAAG), + "-A" => Ok(Self::MA), + "-B" => Ok(Self::MB), + "-C" => Ok(Self::MC), + "-D" => Ok(Self::MD), + "-E" => Ok(Self::ME), + "-F" => Ok(Self::MF), + "-U" => Ok(Self::MU), + "-V" => Ok(Self::MV), + "-W" => Ok(Self::MW), + "-X" => Ok(Self::MX), + "-Y" => Ok(Self::MY), + "-Z" => Ok(Self::MZ), + _ => Err(Error::ImproperPrefixType), + } } } @@ -312,12 +312,11 @@ impl Display for PayloadType { Self::MW => f.write_str("-W"), Self::MX => f.write_str("-X"), Self::MY => f.write_str("-Y"), - Self::MZ => f.write_str("-Z") + Self::MZ => f.write_str("-Z"), } } } - #[test] fn num_to_b64_test() { assert_eq!("A", num_to_b64(0)); @@ -327,3 +326,9 @@ fn num_to_b64_test() { assert_eq!("b", num_to_b64(27)); assert_eq!("AE", num_to_b64(64)); } + +#[test] +fn test_adjust_with_num() { + assert_eq!(PayloadType::MA.adjust_with_num(2), "-AAC"); + assert_eq!(PayloadType::MA.adjust_with_num(27), "-AAb"); +} diff --git a/src/event_message/signed_event_message.rs b/src/event_message/signed_event_message.rs index 71a1bd7..11afec8 100644 --- a/src/event_message/signed_event_message.rs +++ b/src/event_message/signed_event_message.rs @@ -28,9 +28,7 @@ impl Serialize for SignedEventMessage { let mut em = serializer.serialize_struct("EventMessage", 2)?; em.serialize_field("", &self.event_message)?; let str_sigs = &self.signatures.iter().fold(String::default(), |accum, sig| accum + &sig.to_str()); - // TODO Why first signatures string char? - let code = self.payload_type.encode(self.signatures.len() as u16); - // .map_err(|e| serde::ser::Error::custom(&e.to_string()))?; + let code = self.payload_type.adjust_with_num(self.signatures.len() as u16); em.serialize_field("-" , &format!("{}{}", Box::leak(code.into_boxed_str()), str_sigs))?; em.end() // . else - we pack as it is for DB / CBOR purpose diff --git a/src/processor/mod.rs b/src/processor/mod.rs index c8a5197..b530a90 100644 --- a/src/processor/mod.rs +++ b/src/processor/mod.rs @@ -294,10 +294,10 @@ impl EventProcessor { }; self.validate_seal(seal, &event.deserialized_event.raw) } - EventData::Drt(drt) => { + EventData::Drt(_drt) => { let delegator = self .compute_state(&event.deserialized_event.event_message.event.prefix)? - .unwrap() + .ok_or(Error::SemanticError("Missing state of delegated identifier".into()))? .delegator .ok_or(Error::SemanticError("Missing delegator".into()))?; let (sn, dig) = match event.attachement.clone().ok_or(Error::SemanticError( diff --git a/src/processor/tests.rs b/src/processor/tests.rs index 6d73c6f..32fd40a 100644 --- a/src/processor/tests.rs +++ b/src/processor/tests.rs @@ -2,7 +2,6 @@ use super::EventProcessor; use crate::derivation::self_addressing::SelfAddressing; use crate::event::sections::seal::EventSeal; use crate::event_message::parse::signed_message; -use crate::prefix::Prefix; use crate::{database::sled::SledEventDatabase, error::Error}; use crate::{ event_message::{ @@ -221,10 +220,6 @@ fn test_process_delegated() -> Result<(), Error> { let ixn_from_db = event_processor.get_event_at_sn(&bobs_pref, 1).unwrap().unwrap(); assert_eq!(ixn_from_db.signed_event_message.event_message.serialize()?, raw_parsed(deserialized_ixn)?); - let dip = br#"{"v":"KERI10JSON000121_","i":"E-9tsnVcfUyXVQyBPGfntoL-xexf4Cldt_EPzHis2W4U","s":"0","t":"dip","kt":"1","k":["DuK1x8ydpucu3480Jpd1XBfjnCwb3dZ3x5b1CJmuUphA"],"n":"EWWkjZkZDXF74O2bOQ4H5hu4nXDlKg2m4CBEBkUxibiU","bt":"0","b":[],"c":[],"a":[],"di":"Eta8KLf1zrE5n-HZpgRAnDmxLASZdXEiU9u6aahqR8TI"}"#; - let delegatd_dig = SelfAddressing::Blake3_256.derive(dip); - println!("{}", delegatd_dig.to_str()); - // Process delegated inception event once again. event_processor.process(deserialized_dip.clone())?; From f4967491bfdc2e50a9922e5888be967dd8811aaa Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Thu, 30 Sep 2021 19:27:32 +0200 Subject: [PATCH 14/17] fix(all): fix typos --- src/derivation/attached_signature_code.rs | 2 +- .../{attachement.rs => attachment.rs} | 20 ++++++------- src/event_message/mod.rs | 8 +++--- src/event_message/parse.rs | 28 +++++++++---------- src/event_message/payload_size.rs | 1 - src/event_message/signed_event_message.rs | 8 +++--- src/prefix/parse.rs | 4 +-- src/processor/mod.rs | 10 +++---- 8 files changed, 40 insertions(+), 41 deletions(-) rename src/event_message/{attachement.rs => attachment.rs} (88%) diff --git a/src/derivation/attached_signature_code.rs b/src/derivation/attached_signature_code.rs index fea1665..cef8be2 100644 --- a/src/derivation/attached_signature_code.rs +++ b/src/derivation/attached_signature_code.rs @@ -1,6 +1,6 @@ use super::{self_signing::SelfSigning, DerivationCode}; use crate::{error::Error, event_message::payload_size::num_to_b64}; -use base64::{decode_config}; +use base64::decode_config; use core::str::FromStr; /// Attached Signature Derivation Codes diff --git a/src/event_message/attachement.rs b/src/event_message/attachment.rs similarity index 88% rename from src/event_message/attachement.rs rename to src/event_message/attachment.rs index b3fe504..567d270 100644 --- a/src/event_message/attachement.rs +++ b/src/event_message/attachment.rs @@ -11,14 +11,14 @@ use crate::{ use super::{parse::counter, payload_size::PayloadType}; #[derive(Debug, Clone, Deserialize, PartialEq)] -pub enum Attachement { - SealSourceCouplets(Vec), +pub enum Attachment { + SealSourceCouplets(Vec), } -impl Attachement { +impl Attachment { pub fn serialize(&self) -> Result, Error> { match self { - Attachement::SealSourceCouplets(sources) => { + Attachment::SealSourceCouplets(sources) => { let payload_type = PayloadType::MG; let serialzied_sources = sources .into_iter() @@ -36,7 +36,7 @@ impl Attachement { } } -impl FromStr for Attachement { +impl FromStr for Attachment { type Err = Error; fn from_str(s: &str) -> Result { @@ -56,12 +56,12 @@ impl FromStr for Attachement { } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct SorceSeal { +pub struct SourceSeal { pub sn: u64, pub digest: SelfAddressingPrefix, } -impl SorceSeal { +impl SourceSeal { pub fn new(sn: u64, digest: SelfAddressingPrefix) -> Self { Self { sn, digest } } @@ -76,7 +76,7 @@ impl SorceSeal { fn pack_sn(sn: u64) -> String { let payload_type = PayloadType::OA; let sn_raw: Vec = sn.to_be_bytes().into(); - // Calculate how many zeros are missing to achive expected base64 string + // Calculate how many zeros are missing to achieve expected base64 string // length. Master code size is expected padding size. let missing_zeros = payload_type.size() / 4 * 3 - payload_type.master_code_size(false) - sn_raw.len(); let sn_vec: Vec = std::iter::repeat(0).take(missing_zeros).chain(sn_raw).collect(); @@ -90,13 +90,13 @@ fn pack_sn(sn: u64) -> String { #[test] fn test_parse_attachement() -> Result<(), Error> { let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"; - let attached_sn_dig: Attachement = attached_str.parse()?; + let attached_sn_dig: Attachment = attached_str.parse()?; assert_eq!( attached_str, String::from_utf8(attached_sn_dig.serialize()?).unwrap() ); match attached_sn_dig { - Attachement::SealSourceCouplets(sources) => { + Attachment::SealSourceCouplets(sources) => { let s1 = sources[0].clone(); let s2 = sources[1].clone(); assert_eq!(s1.sn, 1); diff --git a/src/event_message/mod.rs b/src/event_message/mod.rs index e549e9b..da5a5dd 100644 --- a/src/event_message/mod.rs +++ b/src/event_message/mod.rs @@ -4,7 +4,7 @@ pub mod serialization_info; pub mod serializer; pub mod payload_size; pub mod signed_event_message; -pub mod attachement; +pub mod attachment; use std::cmp::Ordering; @@ -18,7 +18,7 @@ use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize}; use serialization_info::*; -use self::{attachement::Attachement, payload_size::PayloadType, signed_event_message::SignedEventMessage}; +use self::{attachment::Attachment, payload_size::PayloadType, signed_event_message::SignedEventMessage}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct EventMessage { @@ -120,8 +120,8 @@ impl EventMessage { self.serialization().encode(self) } - pub fn sign(&self, payload_type: PayloadType, sigs: Vec, attachement: Option) -> SignedEventMessage { - SignedEventMessage::new(self, payload_type, sigs, attachement) + pub fn sign(&self, payload_type: PayloadType, sigs: Vec, attachment: Option) -> SignedEventMessage { + SignedEventMessage::new(self, payload_type, sigs, attachment) } } diff --git a/src/event_message/parse.rs b/src/event_message/parse.rs index e7df320..7e2dfc4 100644 --- a/src/event_message/parse.rs +++ b/src/event_message/parse.rs @@ -1,4 +1,4 @@ -use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachement::{SorceSeal, Attachement}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; +use super::{AttachedSignaturePrefix, EventMessage, SignedEventMessage, attachment::{SourceSeal, Attachment}, payload_size::PayloadType, signed_event_message::{SignedNontransferableReceipt, SignedTransferableReceipt}}; use crate::{derivation::attached_signature_code::b64_to_num, event::{event_data::EventData, sections::seal::EventSeal}, prefix::{BasicPrefix, SelfSigningPrefix, parse::{attached_signature, attached_sn, basic_prefix, event_seal, self_addressing_prefix, self_signing_prefix}}, state::IdentifierState}; use nom::{ branch::*, @@ -23,13 +23,13 @@ pub struct DeserializedEvent<'a> { pub struct DeserializedSignedEvent<'a> { pub deserialized_event: DeserializedEvent<'a>, pub signatures: Vec, - pub attachement: Option, + pub attachment: Option, } // FIXME: detect payload type impl From> for SignedEventMessage { fn from(de: DeserializedSignedEvent) -> SignedEventMessage { - SignedEventMessage::new(&de.deserialized_event.event_message, PayloadType::MA, de.signatures, de.attachement) + SignedEventMessage::new(&de.deserialized_event.event_message, PayloadType::MA, de.signatures, de.attachment) } } @@ -138,7 +138,7 @@ pub(crate) fn sig_count(s: &[u8]) -> nom::IResult<&[u8], u16> { Ok((rest, t.1)) } -pub(crate) fn counter(s: &[u8]) -> nom::IResult<&[u8], Attachement> { +pub(crate) fn counter(s: &[u8]) -> nom::IResult<&[u8], Attachment> { let (rest, sc) = tuple(( map_parser( nom::bytes::complete::take(2u8), @@ -151,15 +151,15 @@ pub(crate) fn counter(s: &[u8]) -> nom::IResult<&[u8], Attachement> { , )(s)?; - let (rest, attachement) = count( + let (rest, attachment) = count( nom::sequence::tuple((attached_sn, self_addressing_prefix)), sc.1 as usize , )(rest)?; - let attachements = attachement.into_iter().map(|(sn, digest)| - SorceSeal::new(sn, digest) + let attachments = attachment.into_iter().map(|(sn, digest)| + SourceSeal::new(sn, digest) ).collect(); - Ok((rest, Attachement::SealSourceCouplets(attachements))) + Ok((rest, Attachment::SealSourceCouplets(attachments))) } @@ -186,7 +186,7 @@ fn couplets(s: &[u8]) -> nom::IResult<&[u8], Vec<(BasicPrefix, SelfSigningPrefix )(rest) } -fn transferable_receipt_attachement( +fn transferable_receipt_attachment( s: &[u8], ) -> nom::IResult<&[u8], (EventSeal, Vec)> { tuple((event_seal, signatures))(s) @@ -205,13 +205,13 @@ pub fn signed_message<'a>(s: &'a [u8]) -> nom::IResult<&[u8], Deserialized> { }), )) } else { - transferable_receipt_attachement(&rest[1..]).map(|(rest, attachement)| { + transferable_receipt_attachment(&rest[1..]).map(|(rest, attachment)| { ( rest, Deserialized::TransferableRct(SignedTransferableReceipt::new( &e.event_message, - attachement.0, - attachement.1, + attachment.0, + attachment.1, )), ) }) @@ -226,7 +226,7 @@ pub fn signed_message<'a>(s: &'a [u8]) -> nom::IResult<&[u8], Deserialized> { Deserialized::Event(DeserializedSignedEvent { deserialized_event: e, signatures, - attachement: Some(source_seal) + attachment: Some(source_seal) }), )) }, @@ -238,7 +238,7 @@ pub fn signed_message<'a>(s: &'a [u8]) -> nom::IResult<&[u8], Deserialized> { Deserialized::Event(DeserializedSignedEvent { deserialized_event: e, signatures, - attachement: None, + attachment: None, }), )) } diff --git a/src/event_message/payload_size.rs b/src/event_message/payload_size.rs index 6f3efc2..2ace17a 100644 --- a/src/event_message/payload_size.rs +++ b/src/event_message/payload_size.rs @@ -80,7 +80,6 @@ pub enum PayloadType { // TODO: Indexed signatures } -// #[cfg(feature = "async")] impl PayloadType { pub(crate) fn size(&self) -> usize { match self { diff --git a/src/event_message/signed_event_message.rs b/src/event_message/signed_event_message.rs index 11afec8..7e4e562 100644 --- a/src/event_message/signed_event_message.rs +++ b/src/event_message/signed_event_message.rs @@ -4,7 +4,7 @@ use std::cmp::Ordering; use crate::{derivation::attached_signature_code::{get_sig_count}, error::Error, event::sections::seal::EventSeal, prefix::{AttachedSignaturePrefix, BasicPrefix, Prefix, SelfSigningPrefix, attached_seal::AttachedEventSeal}, state::{EventSemantics, IdentifierState}}; -use super::{EventMessage, attachement::Attachement, payload_size::PayloadType}; +use super::{EventMessage, attachment::Attachment, payload_size::PayloadType}; use super::serializer::to_string; // KERI serializer should be used to serialize this @@ -16,7 +16,7 @@ pub struct SignedEventMessage { #[serde(skip_serializing)] pub signatures: Vec, #[serde(skip_serializing)] - pub attachement: Option, + pub attachment: Option, } impl Serialize for SignedEventMessage { @@ -119,12 +119,12 @@ impl Ord for TimestampedSignedEventMessage { impl Eq for TimestampedSignedEventMessage {} impl SignedEventMessage { - pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec, attachement: Option) -> Self { + pub fn new(message: &EventMessage, payload_type: PayloadType, sigs: Vec, attachment: Option) -> Self { Self { event_message: message.clone(), payload_type, signatures: sigs, - attachement, + attachment, } } diff --git a/src/prefix/parse.rs b/src/prefix/parse.rs index a7d9520..5ccb9ef 100644 --- a/src/prefix/parse.rs +++ b/src/prefix/parse.rs @@ -259,8 +259,8 @@ fn test_sn_parse() { #[test] fn test_seal_parse() { - let seal_attachement = r#"FABENlofRlu2VPul-tjDObk6bTia2deG6NMqeFmsXhAgFvA0AAAAAAAAAAAAAAAAAAAAAAAE_MT0wsz-_ju_DVK_SaMaZT9ZE7pP4auQYeo2PDaw9FI-AABAA0Q7bqPvenjWXo_YIikMBKOg-pghLKwBi1Plm0PEqdv67L1_c6dq9bll7OFnoLp0a74Nw1cBGdjIPcu-yAllHAw"#; - let seal = event_seal(seal_attachement.as_bytes()).unwrap().1; + let seal_attachment = r#"FABENlofRlu2VPul-tjDObk6bTia2deG6NMqeFmsXhAgFvA0AAAAAAAAAAAAAAAAAAAAAAAE_MT0wsz-_ju_DVK_SaMaZT9ZE7pP4auQYeo2PDaw9FI-AABAA0Q7bqPvenjWXo_YIikMBKOg-pghLKwBi1Plm0PEqdv67L1_c6dq9bll7OFnoLp0a74Nw1cBGdjIPcu-yAllHAw"#; + let seal = event_seal(seal_attachment.as_bytes()).unwrap().1; assert_eq!( seal.prefix, "ENlofRlu2VPul-tjDObk6bTia2deG6NMqeFmsXhAgFvA" diff --git a/src/processor/mod.rs b/src/processor/mod.rs index b530a90..44a39ea 100644 --- a/src/processor/mod.rs +++ b/src/processor/mod.rs @@ -263,7 +263,7 @@ impl EventProcessor { &event.deserialized_event.event_message, PayloadType::MA, event.signatures.clone(), - event.attachement.clone(), + event.attachment.clone(), ); let id = &event.deserialized_event.event_message.event.prefix; // If delegated event, check its delegator seal. @@ -275,10 +275,10 @@ impl EventProcessor { .clone() { EventData::Dip(dip) => { - let (sn, dig) = match event.attachement.clone().ok_or(Error::SemanticError( + let (sn, dig) = match event.attachment.clone().ok_or(Error::SemanticError( "Missing source seal in delegating event".into(), ))? { - crate::event_message::attachement::Attachement::SealSourceCouplets( + crate::event_message::attachment::Attachment::SealSourceCouplets( ref source_seal_list, ) => { let ss = source_seal_list @@ -300,10 +300,10 @@ impl EventProcessor { .ok_or(Error::SemanticError("Missing state of delegated identifier".into()))? .delegator .ok_or(Error::SemanticError("Missing delegator".into()))?; - let (sn, dig) = match event.attachement.clone().ok_or(Error::SemanticError( + let (sn, dig) = match event.attachment.clone().ok_or(Error::SemanticError( "Missing source seal in delegating event".into(), ))? { - crate::event_message::attachement::Attachement::SealSourceCouplets( + crate::event_message::attachment::Attachment::SealSourceCouplets( ref source_seal_list, ) => { let ss = source_seal_list From ecad3956efcd0f4a4fbf33bb3f9105b237f3372f Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Fri, 1 Oct 2021 10:47:55 +0200 Subject: [PATCH 15/17] fix(ev_builder): pass prefix by ref --- src/event_message/event_msg_builder.rs | 22 ++++++++++++++-------- src/event_message/tests/test_utils.rs | 4 ++-- src/keri/mod.rs | 12 ++++++------ 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/src/event_message/event_msg_builder.rs b/src/event_message/event_msg_builder.rs index f346227..d805157 100644 --- a/src/event_message/event_msg_builder.rs +++ b/src/event_message/event_msg_builder.rs @@ -74,8 +74,11 @@ impl EventMsgBuilder { }) } - pub fn with_prefix(self, prefix: IdentifierPrefix) -> Self { - EventMsgBuilder { prefix, ..self } + pub fn with_prefix(self, prefix: &IdentifierPrefix) -> Self { + EventMsgBuilder { + prefix: prefix.clone(), + ..self + } } pub fn with_keys(self, keys: Vec) -> Self { @@ -89,8 +92,11 @@ impl EventMsgBuilder { pub fn with_sn(self, sn: u64) -> Self { EventMsgBuilder { sn, ..self } } - pub fn with_previous_event(self, prev_event: SelfAddressingPrefix) -> Self { - EventMsgBuilder { prev_event, ..self } + pub fn with_previous_event(self, prev_event: &SelfAddressingPrefix) -> Self { + EventMsgBuilder { + prev_event: prev_event.clone(), + ..self + } } pub fn with_seal(mut self, seals: Vec) -> Self { @@ -98,16 +104,16 @@ impl EventMsgBuilder { EventMsgBuilder { ..self } } - pub fn with_delegator(self, delegator: IdentifierPrefix) -> Self { + pub fn with_delegator(self, delegator: &IdentifierPrefix) -> Self { EventMsgBuilder { - delegator, + delegator: delegator.clone(), ..self } } - pub fn with_threshold(self, threshold: SignatureThreshold) -> Self { + pub fn with_threshold(self, threshold: &SignatureThreshold) -> Self { EventMsgBuilder { - key_threshold: threshold, + key_threshold: threshold.clone(), ..self } } diff --git a/src/event_message/tests/test_utils.rs b/src/event_message/tests/test_utils.rs index 4069487..4c61317 100644 --- a/src/event_message/tests/test_utils.rs +++ b/src/event_message/tests/test_utils.rs @@ -67,8 +67,8 @@ fn test_update_identifier_state( // Build event msg of given type. let event_msg = EventMsgBuilder::new(event_type.clone())? .with_sn(state_data.sn) - .with_previous_event(state_data.prev_event_hash) - .with_prefix(state_data.prefix.clone()) + .with_previous_event(&state_data.prev_event_hash) + .with_prefix(&state_data.prefix) .with_keys(vec![current_key_pref.clone()]) .with_next_keys(vec![next_key_prefix]) .build()?; diff --git a/src/keri/mod.rs b/src/keri/mod.rs index c82b656..0d26d6d 100644 --- a/src/keri/mod.rs +++ b/src/keri/mod.rs @@ -110,7 +110,7 @@ impl Keri { pub fn incept(&mut self) -> Result { let icp = EventMsgBuilder::new(EventType::Inception)? - .with_prefix(self.prefix.clone()) + .with_prefix(&self.prefix) .with_keys(vec![Basic::Ed25519.derive(self.key_manager.borrow().public_key())]) .with_next_keys(vec![ Basic::Ed25519.derive(self.key_manager.borrow().next_public_key()) @@ -149,7 +149,7 @@ impl Keri { // Signing key must be first keys.insert(0, Basic::Ed25519.derive(self.key_manager.borrow().public_key())); let icp = EventMsgBuilder::new(EventType::Inception)? - .with_prefix(self.prefix.clone()) + .with_prefix(&self.prefix) .with_keys(keys) .with_next_keys(vec!(Basic::Ed25519.derive(self.key_manager.borrow().next_public_key()))) .build()?; @@ -227,9 +227,9 @@ impl Keri { .compute_state(&self.prefix)? .ok_or(Error::SemanticError("There is no state".into()))?; EventMsgBuilder::new(EventType::Rotation)? - .with_prefix(self.prefix.clone()) + .with_prefix(&self.prefix) .with_sn(state.sn + 1) - .with_previous_event(SelfAddressing::Blake3_256.derive(&state.last)) + .with_previous_event(&SelfAddressing::Blake3_256.derive(&state.last)) .with_keys(vec![Basic::Ed25519.derive(self.key_manager.borrow().public_key())]) .with_next_keys(vec![ Basic::Ed25519.derive(self.key_manager.borrow().next_public_key()) @@ -252,9 +252,9 @@ impl Keri { .ok_or(Error::SemanticError("There is no state".into()))?; let ev = EventMsgBuilder::new(EventType::Interaction)? - .with_prefix(self.prefix.clone()) + .with_prefix(&self.prefix) .with_sn(state.sn + 1) - .with_previous_event(SelfAddressing::Blake3_256.derive(&state.last)) + .with_previous_event(&SelfAddressing::Blake3_256.derive(&state.last)) .with_seal(seal_list) .build()?; From b6311eaaa5e9d88fe913a9fbfb20f2b91e8e5ecb Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Fri, 1 Oct 2021 11:08:13 +0200 Subject: [PATCH 16/17] fix(del): remove DelegatedRotationEvent struct --- src/event/event_data/delegated/mod.rs | 11 ----------- src/event/event_data/mod.rs | 4 ++-- src/event_message/attachment.rs | 2 +- src/event_message/event_msg_builder.rs | 6 ++---- src/event_message/mod.rs | 1 - src/processor/mod.rs | 4 ++-- 6 files changed, 7 insertions(+), 21 deletions(-) diff --git a/src/event/event_data/delegated/mod.rs b/src/event/event_data/delegated/mod.rs index 524268c..e02e2a7 100644 --- a/src/event/event_data/delegated/mod.rs +++ b/src/event/event_data/delegated/mod.rs @@ -18,12 +18,6 @@ pub struct DelegatedInceptionEvent { pub delegator: IdentifierPrefix, } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct DelegatedRotationEvent { - #[serde(flatten)] - pub rotation_data: RotationEvent, -} - impl DelegatedInceptionEvent { /// Incept Self Addressing /// @@ -60,8 +54,3 @@ impl EventSemantics for DelegatedInceptionEvent { }) } } -impl EventSemantics for DelegatedRotationEvent { - fn apply_to(&self, state: IdentifierState) -> Result { - self.rotation_data.apply_to(state) - } -} diff --git a/src/event/event_data/mod.rs b/src/event/event_data/mod.rs index 0e02856..f700a3d 100644 --- a/src/event/event_data/mod.rs +++ b/src/event/event_data/mod.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use serde_hex::{Compact, SerHex}; pub use self::{ - delegated::{DelegatedInceptionEvent, DelegatedRotationEvent}, + delegated::DelegatedInceptionEvent, inception::InceptionEvent, interaction::InteractionEvent, receipt::Receipt, @@ -31,7 +31,7 @@ pub enum EventData { Rot(RotationEvent), Ixn(InteractionEvent), Dip(DelegatedInceptionEvent), - Drt(DelegatedRotationEvent), + Drt(RotationEvent), Rct(Receipt), } diff --git a/src/event_message/attachment.rs b/src/event_message/attachment.rs index 567d270..a2d9e36 100644 --- a/src/event_message/attachment.rs +++ b/src/event_message/attachment.rs @@ -50,7 +50,7 @@ impl FromStr for Attachment { Err(Error::SemanticError("Can't parse counter".into())) } } - _ => todo!(), + _ => Err(Error::DeserializeError("Unknown prefix code".into())), } } } diff --git a/src/event_message/event_msg_builder.rs b/src/event_message/event_msg_builder.rs index d805157..b18fb07 100644 --- a/src/event_message/event_msg_builder.rs +++ b/src/event_message/event_msg_builder.rs @@ -1,6 +1,6 @@ use crate::{derivation::{basic::Basic, self_addressing::SelfAddressing}, error::Error, event::sections::key_config::nxt_commitment, event::{ event_data::{ - delegated::{DelegatedInceptionEvent, DelegatedRotationEvent}, + delegated::{DelegatedInceptionEvent}, interaction::InteractionEvent, rotation::RotationEvent, }, @@ -198,9 +198,7 @@ impl EventMsgBuilder { Event { prefix, sn: self.sn, - event_data: EventData::Drt(DelegatedRotationEvent { - rotation_data, - }), + event_data: EventData::Drt(rotation_data), } .to_message(self.format)? } diff --git a/src/event_message/mod.rs b/src/event_message/mod.rs index da5a5dd..f106aac 100644 --- a/src/event_message/mod.rs +++ b/src/event_message/mod.rs @@ -171,7 +171,6 @@ impl EventSemantics for EventMessage { "Applying delegated rotation to non-delegated state.".into(), )) } else if drt - .rotation_data .previous_event_hash .verify_binding(&state.last) { diff --git a/src/processor/mod.rs b/src/processor/mod.rs index 44a39ea..49b293e 100644 --- a/src/processor/mod.rs +++ b/src/processor/mod.rs @@ -165,7 +165,7 @@ impl EventProcessor { EventData::Icp(icp) => icp.key_config, EventData::Rot(rot) => rot.key_config, EventData::Dip(dip) => dip.inception_data.key_config, - EventData::Drt(drt) => drt.rotation_data.key_config, + EventData::Drt(drt) => drt.key_config, // the receipt has a binding but it's NOT an establishment event _ => Err(Error::SemanticError("Receipt binding incorrect".into()))?, }, @@ -191,7 +191,7 @@ impl EventProcessor { let data = match event.signed_event_message.event_message.event.event_data { EventData::Rot(rot) => rot.data, EventData::Ixn(ixn) => ixn.data, - EventData::Drt(drt) => drt.rotation_data.data, + EventData::Drt(drt) => drt.data, _ => return Err(Error::SemanticError("Improper event type".to_string())), }; From 782989eee8720560a7e04663d1835c27d70ddeb6 Mon Sep 17 00:00:00 2001 From: Edyta Pawlak Date: Fri, 1 Oct 2021 11:56:09 +0200 Subject: [PATCH 17/17] fix(attachement): return error instead of todo --- src/event/event_data/delegated/mod.rs | 2 +- src/event_message/attachment.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/event/event_data/delegated/mod.rs b/src/event/event_data/delegated/mod.rs index e02e2a7..a8d6fbc 100644 --- a/src/event/event_data/delegated/mod.rs +++ b/src/event/event_data/delegated/mod.rs @@ -1,5 +1,5 @@ use super::{DummyEvent, EventData}; -use super::{InceptionEvent, RotationEvent}; +use super::InceptionEvent; use crate::{ derivation::self_addressing::SelfAddressing, error::Error, diff --git a/src/event_message/attachment.rs b/src/event_message/attachment.rs index a2d9e36..a03d465 100644 --- a/src/event_message/attachment.rs +++ b/src/event_message/attachment.rs @@ -50,7 +50,7 @@ impl FromStr for Attachment { Err(Error::SemanticError("Can't parse counter".into())) } } - _ => Err(Error::DeserializeError("Unknown prefix code".into())), + _ => Err(Error::DeserializeError("Unknown counter code".into())), } } }