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 13 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};
edytapawlak marked this conversation as resolved.
Show resolved Hide resolved
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));
}
15 changes: 4 additions & 11 deletions src/event/event_data/delegated/mod.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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)]
35359595 marked this conversation as resolved.
Show resolved Hide resolved
pub rotation_data: RotationEvent,

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

impl DelegatedInceptionEvent {
Expand Down Expand Up @@ -58,17 +55,13 @@ 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()))
}
}
}
115 changes: 115 additions & 0 deletions src/event_message/attachement.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 Attachement {
edytapawlak marked this conversation as resolved.
Show resolved Hide resolved
SealSourceCouplets(Vec<SorceSeal>),
}

impl Attachement {
pub fn serialize(&self) -> Result<Vec<u8>, Error> {
match self {
Attachement::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 Attachement {
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()))
}
}
_ => todo!(),
35359595 marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SorceSeal {
edytapawlak marked this conversation as resolved.
Show resolved Hide resolved
pub sn: u64,
pub digest: SelfAddressingPrefix,
}

impl SorceSeal {
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 achive expected base64 string
edytapawlak marked this conversation as resolved.
Show resolved Hide resolved
// 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> {
edytapawlak marked this conversation as resolved.
Show resolved Hide resolved
let attached_str = "-GAC0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII0AAAAAAAAAAAAAAAAAAAAAAQE3fUycq1G-P1K1pL2OhvY6ZU-9otSa3hXiCcrxuhjyII";
let attached_sn_dig: Attachement = attached_str.parse()?;
assert_eq!(
attached_str,
String::from_utf8(attached_sn_dig.serialize()?).unwrap()
);
match attached_sn_dig {
Attachement::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(())
}
22 changes: 6 additions & 16 deletions src/event_message/event_msg_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
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,7 +68,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,
})
Expand Down Expand Up @@ -107,9 +98,9 @@ impl EventMsgBuilder {
EventMsgBuilder { ..self }
}

pub fn with_delegating_seal(self, seal: LocationSeal) -> Self {
pub fn with_delegator(self, delegator: IdentifierPrefix) -> Self {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this take ownership on delegator or ref + clone? how's calling code uses it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this also applyes to below SignatureThreshold too?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated it for both. Now delegator prefix and signature threshold are passed by ref :)

EventMsgBuilder {
delegating_seal: seal,
delegator,
..self
}
}
Expand Down Expand Up @@ -187,7 +178,7 @@ impl EventMsgBuilder {
};
DelegatedInceptionEvent {
inception_data: icp_data,
seal: self.delegating_seal,
delegator: self.delegator,
}
.incept_self_addressing(self.derivation, self.format)?
}
Expand All @@ -203,7 +194,6 @@ impl EventMsgBuilder {
sn: self.sn,
event_data: EventData::Drt(DelegatedRotationEvent {
rotation_data,
seal: self.delegating_seal,
}),
}
.to_message(self.format)?
Expand Down
Loading