Skip to content

Commit

Permalink
Merge pull request #12 from freenet/185999014-fix-simulation
Browse files Browse the repository at this point in the history
185999014 - Fix simulation
  • Loading branch information
iduartgomez committed Oct 24, 2023
2 parents 0cd6ba8 + e6b4b32 commit f364755
Show file tree
Hide file tree
Showing 12 changed files with 294 additions and 139 deletions.
2 changes: 1 addition & 1 deletion rust-macros/src/common.rs
Expand Up @@ -2,7 +2,7 @@ use proc_macro2::TokenStream;
use quote::quote;

pub fn set_logger() -> TokenStream {
// TODO: add log level as a parameter to the macro
// TODO: add env_filter as a parameter to the macro
quote! {
#[cfg(feature = "trace")]
{
Expand Down
35 changes: 4 additions & 31 deletions rust/src/client_api/client_events.rs
@@ -1,7 +1,7 @@
use flatbuffers::WIPOffset;
use std::fmt::Display;

use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::client_api::TryFromFbs;
use crate::client_request_generated::client_request::{
Expand Down Expand Up @@ -413,7 +413,7 @@ impl<'a> From<DelegateRequest<'a>> for ClientRequest<'a> {
pub enum DelegateRequest<'a> {
ApplicationMessages {
key: DelegateKey,
#[serde(deserialize_with = "DelegateRequest::deser_params")]
#[serde(deserialize_with = "Parameters::deser_params")]
params: Parameters<'a>,
#[serde(borrow)]
inbound: Vec<InboundDelegateMsg<'a>>,
Expand Down Expand Up @@ -484,14 +484,6 @@ impl DelegateRequest<'_> {
DelegateRequest::UnregisterDelegate(key) => key,
}
}

fn deser_params<'de, 'a, D>(deser: D) -> Result<Parameters<'a>, D::Error>
where
D: Deserializer<'de>,
{
let bytes_vec: Vec<u8> = Deserialize::deserialize(deser)?;
Ok(Parameters::from(bytes_vec))
}
}

impl Display for ClientRequest<'_> {
Expand Down Expand Up @@ -1292,7 +1284,6 @@ impl std::fmt::Display for HostResponse {
}
}

// todo: add a `AsBytes` trait for state representations
#[derive(Clone, Serialize, Deserialize, Debug)]
#[non_exhaustive]
pub enum ContractResponse<T = WrappedState> {
Expand All @@ -1308,35 +1299,17 @@ pub enum ContractResponse<T = WrappedState> {
/// Message sent when there is an update to a subscribed contract.
UpdateNotification {
key: ContractKey,
#[serde(deserialize_with = "ContractResponse::<T>::deser_update_data")]
#[serde(deserialize_with = "UpdateData::deser_update_data")]
update: UpdateData<'static>,
},
/// Successful update
UpdateResponse {
key: ContractKey,
#[serde(deserialize_with = "ContractResponse::<T>::deser_state")]
#[serde(deserialize_with = "StateSummary::deser_state_summary")]
summary: StateSummary<'static>,
},
}

impl<T> ContractResponse<T> {
fn deser_update_data<'de, D>(deser: D) -> Result<UpdateData<'static>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = <UpdateData as Deserialize>::deserialize(deser)?;
Ok(value.into_owned())
}

fn deser_state<'de, D>(deser: D) -> Result<StateSummary<'static>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = <StateSummary as Deserialize>::deserialize(deser)?;
Ok(value.into_owned())
}
}

impl<T> From<ContractResponse<T>> for HostResponse<T> {
fn from(value: ContractResponse<T>) -> HostResponse<T> {
HostResponse::ContractResponse(value)
Expand Down
104 changes: 85 additions & 19 deletions rust/src/contract_composition.rs
Expand Up @@ -11,17 +11,17 @@ impl<'a> From<&'a State<'static>> for State<'static> {
}
}

pub trait ParametersComponent {
pub trait ComponentParameter {
fn contract_id(&self) -> Option<ContractInstanceId>;
}

pub trait SummaryComponent<ChildSummary> {
fn merge(&mut self, _child_summary: ChildSummary);
pub trait Mergeable<Other> {
fn merge(&mut self, other: Other);
}

pub trait ContractComponent: std::any::Any + Sized {
type Context;
type Parameters: ParametersComponent;
type Parameters: ComponentParameter;
type Delta;
type Summary;

Expand Down Expand Up @@ -59,7 +59,7 @@ pub trait ContractComponent: std::any::Any + Sized {
summary: &mut ParentSummary,
) -> Result<(), ContractError>
where
ParentSummary: SummaryComponent<<Self as ContractComponent>::Summary>;
ParentSummary: Mergeable<<Self as ContractComponent>::Summary>;

/// Corresponds to ContractInterface `delta`
fn delta(
Expand All @@ -76,24 +76,48 @@ pub enum TypedUpdateData<T: ContractComponent> {
}

impl<T: ContractComponent> TypedUpdateData<T> {
pub fn from_other<Parent>(_value: &TypedUpdateData<Parent>) -> Self
pub fn from_other<Parent>(value: &TypedUpdateData<Parent>) -> Self
where
Parent: ContractComponent,
<T as ContractComponent>::Delta: for<'x> From<&'x Parent::Delta>,
T: for<'x> From<&'x Parent>,
{
todo!()
match value {
TypedUpdateData::RelatedState { state } => {
let state = T::from(state);
TypedUpdateData::RelatedState { state }
}
TypedUpdateData::RelatedDelta { delta } => {
let delta: T::Delta = <T as ContractComponent>::Delta::from(delta);
TypedUpdateData::RelatedDelta { delta }
}
TypedUpdateData::RelatedStateAndDelta { state, delta } => {
let state = T::from(state);
let delta: T::Delta = <T as ContractComponent>::Delta::from(delta);
TypedUpdateData::RelatedStateAndDelta { state, delta }
}
}
}
}

impl<T: ContractComponent> From<(Option<T>, Option<T::Delta>)> for TypedUpdateData<T> {
fn from((_state, _delta): (Option<T>, Option<T::Delta>)) -> Self {
todo!()
impl<T: ContractComponent> TryFrom<(Option<T>, Option<T::Delta>)> for TypedUpdateData<T> {
type Error = ContractError;
fn try_from((state, delta): (Option<T>, Option<T::Delta>)) -> Result<Self, Self::Error> {
match (state, delta) {
(None, None) => Err(ContractError::InvalidState),
(None, Some(delta)) => Ok(Self::RelatedDelta { delta }),
(Some(state), None) => Ok(Self::RelatedState { state }),
(Some(state), Some(delta)) => Ok(Self::RelatedStateAndDelta { state, delta }),
}
}
}

#[allow(unused)]
impl<T: ContractComponent> ContractComponent for Vec<T> {
impl<T> ContractComponent for Vec<T>
where
T: ContractComponent + Clone,
<T as ContractComponent>::Delta: Clone + Mergeable<<T as ContractComponent>::Delta>,
{
type Context = T::Context;
type Parameters = T::Parameters;
type Delta = T::Delta;
Expand All @@ -109,7 +133,16 @@ impl<T: ContractComponent> ContractComponent for Vec<T> {
Child: ContractComponent,
Self::Context: for<'x> From<&'x Ctx>,
{
todo!()
for v in self {
match v.verify::<Child, Ctx>(parameters, context, related)? {
ValidateResult::Invalid => return Ok(ValidateResult::Invalid),
ValidateResult::RequestRelated(related) => {
return Ok(ValidateResult::RequestRelated(related))
}
ValidateResult::Valid => {}
}
}
Ok(ValidateResult::Valid)
}

fn verify_delta<Child>(
Expand All @@ -119,7 +152,7 @@ impl<T: ContractComponent> ContractComponent for Vec<T> {
where
Child: ContractComponent,
{
todo!()
<T as ContractComponent>::verify_delta::<Child>(parameters, delta)
}

fn merge(
Expand All @@ -128,7 +161,28 @@ impl<T: ContractComponent> ContractComponent for Vec<T> {
update: &TypedUpdateData<Self>,
related: &RelatedContractsContainer,
) -> MergeResult {
todo!()
for v in self {
let update = match update {
TypedUpdateData::RelatedState { state } => TypedUpdateData::RelatedState {
state: state[0].clone(),
},
TypedUpdateData::RelatedDelta { delta } => TypedUpdateData::RelatedDelta {
delta: delta.clone(),
},
TypedUpdateData::RelatedStateAndDelta { state, delta } => {
TypedUpdateData::RelatedStateAndDelta {
state: state[0].clone(),
delta: delta.clone(),
}
}
};
match v.merge(parameters, &update, related) {
MergeResult::RequestRelated(req) => return MergeResult::RequestRelated(req),
MergeResult::Error(err) => return MergeResult::Error(err),
MergeResult::Success => {}
}
}
MergeResult::Success
}

fn summarize<ParentSummary>(
Expand All @@ -137,17 +191,29 @@ impl<T: ContractComponent> ContractComponent for Vec<T> {
summary: &mut ParentSummary,
) -> Result<(), ContractError>
where
ParentSummary: SummaryComponent<<Self as ContractComponent>::Summary>,
ParentSummary: Mergeable<<Self as ContractComponent>::Summary>,
{
todo!()
for v in self {
v.summarize(parameters, summary);
}
Ok(())
}

fn delta(
&self,
parameters: &Self::Parameters,
summary: &Self::Summary,
) -> Result<Self::Delta, ContractError> {
todo!()
let mut delta: Option<<T as ContractComponent>::Delta> = None;
for v in self {
let other_delta = v.delta(parameters, summary)?;
if let Some(delta) = &mut delta {
delta.merge(other_delta);
} else {
delta = Some(other_delta)
}
}
delta.ok_or(ContractError::InvalidDelta)
}
}

Expand Down Expand Up @@ -274,7 +340,7 @@ pub mod from_bytes {
<<T as EncodingAdapter>::DeltaEncoder>::deserialize(d.as_ref()).map(Into::into)
})
.transpose()?;
let typed_update = TypedUpdateData::from((state, delta));
let typed_update = TypedUpdateData::try_from((state, delta))?;
match typed_state.merge(&typed_params, &typed_update, &related_container) {
MergeResult::Success => {}
MergeResult::RequestRelated(req) => {
Expand All @@ -295,7 +361,7 @@ pub mod from_bytes {
T: ContractComponent + EncodingAdapter,
<T as EncodingAdapter>::Parameters: Into<<T as ContractComponent>::Parameters>,
<T as ContractComponent>::Summary:
for<'x> From<&'x T> + SummaryComponent<<T as ContractComponent>::Summary>,
for<'x> From<&'x T> + Mergeable<<T as ContractComponent>::Summary>,
ContractError: From<
<<T as EncodingAdapter>::ParametersEncoder as Encoder<
<T as EncodingAdapter>::Parameters,
Expand Down

0 comments on commit f364755

Please sign in to comment.