Skip to content
This repository has been archived by the owner on Apr 21, 2023. It is now read-only.

Update delegation #80

Merged
merged 17 commits into from
Oct 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/database/sled/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 3 additions & 20 deletions src/derivation/attached_signature_code.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -93,25 +93,8 @@ pub fn b64_to_num(b64: &[u8]) -> Result<u16, Error> {
}))
}

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!("AE", num_to_b64(64));
}
28 changes: 5 additions & 23 deletions src/event/event_data/delegated/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{super::sections::seal::LocationSeal, DummyEvent, EventData};
use super::{InceptionEvent, RotationEvent};
use super::{DummyEvent, EventData};
use super::InceptionEvent;
use crate::{
derivation::self_addressing::SelfAddressing,
error::Error,
Expand All @@ -14,17 +14,8 @@ pub struct DelegatedInceptionEvent {
#[serde(flatten)]
pub inception_data: InceptionEvent,

#[serde(rename = "da")]
pub seal: LocationSeal,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct DelegatedRotationEvent {
#[serde(flatten)]
pub rotation_data: RotationEvent,

#[serde(rename = "da")]
pub seal: LocationSeal,
#[serde(rename = "di")]
pub delegator: IdentifierPrefix,
}

impl DelegatedInceptionEvent {
Expand Down Expand Up @@ -58,17 +49,8 @@ impl DelegatedInceptionEvent {
impl EventSemantics for DelegatedInceptionEvent {
fn apply_to(&self, state: IdentifierState) -> Result<IdentifierState, Error> {
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<IdentifierState, Error> {
if state.delegator == Some(self.seal.prefix.clone()) {
self.rotation_data.apply_to(state)
} else {
Err(Error::SemanticError("Wrong delegator".into()))
}
}
}
4 changes: 2 additions & 2 deletions src/event/event_data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -31,7 +31,7 @@ pub enum EventData {
Rot(RotationEvent),
Ixn(InteractionEvent),
Dip(DelegatedInceptionEvent),
Drt(DelegatedRotationEvent),
Drt(RotationEvent),
Rct(Receipt),
}

Expand Down
115 changes: 115 additions & 0 deletions src/event_message/attachment.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
use std::str::FromStr;

use base64::URL_SAFE_NO_PAD;
use serde::{Deserialize, Serialize};

use crate::{
error::Error,
prefix::{Prefix, SelfAddressingPrefix},
};

use super::{parse::counter, payload_size::PayloadType};

#[derive(Debug, Clone, Deserialize, PartialEq)]
pub enum Attachment {
SealSourceCouplets(Vec<SourceSeal>),
}

impl Attachment {
pub fn serialize(&self) -> Result<Vec<u8>, Error> {
match self {
Attachment::SealSourceCouplets(sources) => {
let payload_type = PayloadType::MG;
let serialzied_sources = sources
.into_iter()
.map(|s| s.serialize().unwrap())
.flatten();
Ok(payload_type
.adjust_with_num(sources.len() as u16)
.as_bytes()
.to_vec()
.into_iter()
.chain(serialzied_sources)
.collect::<Vec<_>>())
}
}
}
}

impl FromStr for Attachment {
type Err = Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match &s[0..2] {
"-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 {
Err(Error::SemanticError("Can't parse counter".into()))
}
}
_ => Err(Error::DeserializeError("Unknown counter code".into())),
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SourceSeal {
pub sn: u64,
pub digest: SelfAddressingPrefix,
}

impl SourceSeal {
pub fn new(sn: u64, digest: SelfAddressingPrefix) -> Self {
Self { sn, digest }
}
pub fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok([pack_sn(self.sn), self.digest.to_str()]
.join("")
.as_bytes()
.to_vec())
}
}

fn pack_sn(sn: u64) -> String {
let payload_type = PayloadType::OA;
let sn_raw: Vec<u8> = sn.to_be_bytes().into();
// 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<u8> = std::iter::repeat(0).take(missing_zeros).chain(sn_raw).collect();
[
payload_type.to_string(),
base64::encode_config(sn_vec, URL_SAFE_NO_PAD),
]
.join("")
}

#[test]
fn test_parse_attachement() -> Result<(), Error> {
let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII";
let attached_sn_dig: Attachment = attached_str.parse()?;
assert_eq!(
attached_str,
String::from_utf8(attached_sn_dig.serialize()?).unwrap()
);
match attached_sn_dig {
Attachment::SealSourceCouplets(sources) => {
let s1 = sources[0].clone();
let s2 = sources[1].clone();
assert_eq!(s1.sn, 1);
assert_eq!(
s1.digest.to_str(),
"E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"
);
assert_eq!(s2.sn, 1);
assert_eq!(
s2.digest.to_str(),
"E3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII"
);
}
};
Ok(())
}
46 changes: 20 additions & 26 deletions src/event_message/event_msg_builder.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
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,
},
sections::{threshold::SignatureThreshold, seal::LocationSeal, WitnessConfig},
sections::{threshold::SignatureThreshold, WitnessConfig},
SerializationFormats,
}, event::{
event_data::{inception::InceptionEvent, EventData},
Expand All @@ -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,
Expand All @@ -26,7 +25,7 @@ pub struct EventMsgBuilder {
next_keys: Vec<BasicPrefix>,
prev_event: SelfAddressingPrefix,
data: Vec<Seal>,
delegating_seal: LocationSeal,
delegator: IdentifierPrefix,
format: SerializationFormats,
derivation: SelfAddressing,
}
Expand Down Expand Up @@ -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(),
Expand All @@ -77,14 +68,17 @@ 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,
})
}

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<BasicPrefix>) -> Self {
Expand All @@ -98,25 +92,28 @@ 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<Seal>) -> Self {
self.data.extend(seals);
EventMsgBuilder { ..self }
}

pub fn with_delegating_seal(self, seal: LocationSeal) -> Self {
pub fn with_delegator(self, delegator: &IdentifierPrefix) -> Self {
EventMsgBuilder {
delegating_seal: seal,
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
}
}
Expand Down Expand Up @@ -187,7 +184,7 @@ impl EventMsgBuilder {
};
DelegatedInceptionEvent {
inception_data: icp_data,
seal: self.delegating_seal,
delegator: self.delegator,
}
.incept_self_addressing(self.derivation, self.format)?
}
Expand All @@ -201,10 +198,7 @@ impl EventMsgBuilder {
Event {
prefix,
sn: self.sn,
event_data: EventData::Drt(DelegatedRotationEvent {
rotation_data,
seal: self.delegating_seal,
}),
event_data: EventData::Drt(rotation_data),
}
.to_message(self.format)?
}
Expand Down
Loading