Skip to content
This repository has been archived by the owner on Jun 25, 2021. It is now read-only.

Commit

Permalink
Merge 074cf03 into 606bf96
Browse files Browse the repository at this point in the history
  • Loading branch information
oetyng committed Feb 22, 2021
2 parents 606bf96 + 074cf03 commit 62c4e71
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 68 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ version = "0.3.3"

[dependencies]
bincode = "1.2.1"
sn_data_types = "~0.14.0"
sn_data_types = "~0.15.0"
thiserror = "1.0.23"
crdts = "4.3.0"
threshold_crypto = "~0.4.0"
Expand Down
74 changes: 41 additions & 33 deletions src/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::StateSynched;

use super::{
wallet::{Wallet, WalletSnapshot},
ActorEvent, Error, Outcome, ReplicaValidator, Result, TernaryResult, TransferInitiated,
TransferRegistrationSent, TransferValidated, TransferValidationReceived, TransfersSynched,
wallet::Wallet, ActorEvent, Error, Outcome, ReplicaValidator, Result, TernaryResult,
TransferInitiated, TransferRegistrationSent, TransferValidated, TransferValidationReceived,
TransfersSynched,
};
use crdts::Dot;
use itertools::Itertools;
Expand Down Expand Up @@ -45,6 +47,8 @@ pub struct Actor<V: ReplicaValidator, S: Signing> {
/// The passed in replica_validator, contains the logic from upper layers
/// for determining if a remote group of Replicas, represented by a PublicKey, is indeed valid.
replica_validator: V,
/// A log of applied events.
history: ActorHistory,
}

impl<V: ReplicaValidator, S: Signing> Actor<V, S> {
Expand All @@ -67,22 +71,13 @@ impl<V: ReplicaValidator, S: Signing> Actor<V, S> {
wallet,
next_expected_debit: 0,
accumulating_validations: Default::default(),
history: ActorHistory::empty(),
}
}

///
pub fn from_info(signing: S, info: WalletInfo, replica_validator: V) -> Result<Actor<V, S>> {
let id = signing.id();
let wallet = Wallet::new(id.clone());
let mut actor = Actor {
id,
signing,
replicas: info.replicas,
replica_validator,
wallet,
next_expected_debit: 0,
accumulating_validations: Default::default(),
};
let mut actor = Self::new(signing, info.replicas, replica_validator);
if let Some(e) = actor.from_history(info.history)? {
actor.apply(ActorEvent::TransfersSynched(e))?;
}
Expand All @@ -105,6 +100,7 @@ impl<V: ReplicaValidator, S: Signing> Actor<V, S> {
wallet,
next_expected_debit: 0,
accumulating_validations: Default::default(),
history: ActorHistory::empty(),
}
}

Expand All @@ -128,10 +124,20 @@ impl<V: ReplicaValidator, S: Signing> Actor<V, S> {
}

///
pub fn replicas(&self) -> PublicKey {
pub fn replicas_public_key(&self) -> PublicKey {
PublicKey::Bls(self.replicas.public_key())
}

///
pub fn replicas_key_set(&self) -> PublicKeySet {
self.replicas.clone()
}

/// History of credits and debits
pub fn history(&self) -> ActorHistory {
self.history.clone()
}

/// -----------------------------------------------------------------
/// ---------------------- Cmds -------------------------------------
/// -----------------------------------------------------------------
Expand Down Expand Up @@ -318,9 +324,9 @@ impl<V: ReplicaValidator, S: Signing> Actor<V, S> {
balance: Token,
debit_version: u64,
credit_ids: HashSet<CreditId>,
) -> Outcome<TransfersSynched> {
) -> Outcome<StateSynched> {
// todo: use WalletSnapshot, aggregate sigs
Outcome::success(TransfersSynched {
Outcome::success(StateSynched {
id: self.id(),
balance,
debit_version,
Expand Down Expand Up @@ -354,21 +360,7 @@ impl<V: ReplicaValidator, S: Signing> Actor<V, S> {
let credits = self.validate_credits(&history.credits);
let debits = self.validate_debits(&history.debits);
if !credits.is_empty() || !debits.is_empty() {
let mut wallet = self.wallet.clone();
for credit in credits {
// append credits _before_ debits
wallet.apply_credit(credit.signed_credit.credit)?;
}
for proof in debits {
// append debits _after_ credits
wallet.apply_debit(proof.signed_debit.debit)?;
}
let snapshot: WalletSnapshot = wallet.into();
self.synch(
snapshot.balance,
snapshot.debit_version,
snapshot.credit_ids,
)
Outcome::success(TransfersSynched(ActorHistory { credits, debits }))
} else {
Err(Error::NothingToSync) // TODO: the error is actually that credits and/or debits failed validation..
}
Expand Down Expand Up @@ -453,11 +445,27 @@ impl<V: ReplicaValidator, S: Signing> Actor<V, S> {
}
ActorEvent::TransferRegistrationSent(e) => {
self.wallet
.apply_debit(e.transfer_proof.signed_debit.debit)?;
.apply_debit(e.transfer_proof.signed_debit.debit.clone())?;
self.accumulating_validations.clear();
self.history.debits.push(e.transfer_proof);
Ok(())
}
ActorEvent::TransfersSynched(e) => {
for credit in e.0.credits {
// append credits _before_ debits
self.wallet
.apply_credit(credit.signed_credit.credit.clone())?;
self.history.credits.push(credit);
}
for debit in e.0.debits {
// append debits _after_ credits
self.wallet.apply_debit(debit.signed_debit.debit.clone())?;
self.history.debits.push(debit);
}
self.next_expected_debit = self.wallet.next_debit();
Ok(())
}
ActorEvent::StateSynched(e) => {
self.wallet = Wallet::from(
self.owner().clone(),
e.balance,
Expand Down
41 changes: 17 additions & 24 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ pub use self::{

use serde::{Deserialize, Serialize};
use sn_data_types::{
CreditId, DebitId, PublicKey, SignedCredit, SignedDebit, Token, TransferAgreementProof,
TransferValidated,
ActorHistory, CreditId, DebitId, PublicKey, SignedCredit, SignedDebit, Token,
TransferAgreementProof, TransferValidated,
};
use std::collections::HashSet;

Expand Down Expand Up @@ -93,6 +93,9 @@ pub enum ActorEvent {
/// Raised when the Actor has received
/// unknown credits on querying Replicas.
TransfersSynched(TransfersSynched),
/// Raised when the Actor has received
/// unknown credits on querying Replicas.
StateSynched(StateSynched),
}

/// Raised when the Actor has received
Expand All @@ -102,13 +105,22 @@ pub enum ActorEvent {
/// upon the registration of them from another
/// instance of the same Actor.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct TransfersSynched {
pub struct StateSynched {
id: PublicKey,
balance: Token,
debit_version: u64,
credit_ids: HashSet<CreditId>,
}

/// Raised when the Actor has received
/// f.ex. credits that its Replicas were holding upon
/// the propagation of them from a remote group of Replicas,
/// or unknown debits that its Replicas were holding
/// upon the registration of them from another
/// instance of the same Actor.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct TransfersSynched(ActorHistory);

/// This event is raised by the Actor after having
/// successfully created a transfer cmd to send to the
/// Replicas for validation.
Expand Down Expand Up @@ -214,10 +226,6 @@ mod test {

let event = ReplicaEvent::TransferPropagated(sn_data_types::TransferPropagated {
credit_proof: genesis_credit.clone(),
crediting_replica_keys: PublicKey::Bls(
genesis_elder.signing.replicas_pk_set().public_key(),
),
crediting_replica_sig: genesis_elder.signing.sign_credit_proof(&genesis_credit)?,
});
wallet_replica.apply(event)?;

Expand Down Expand Up @@ -276,10 +284,6 @@ mod test {
wallet_replica.apply(ReplicaEvent::TransferPropagated(
sn_data_types::TransferPropagated {
credit_proof: genesis_credit.clone(),
crediting_replica_keys: PublicKey::Bls(
genesis_elder.signing.replicas_pk_set().public_key(),
),
crediting_replica_sig: genesis_elder.signing.sign_credit_proof(&genesis_credit)?,
},
))?;
let balance = wallet_replica.balance();
Expand Down Expand Up @@ -311,10 +315,6 @@ mod test {
wallet_replica.apply(ReplicaEvent::TransferPropagated(
sn_data_types::TransferPropagated {
credit_proof: genesis_credit.clone(),
crediting_replica_keys: PublicKey::Bls(
genesis_elder.signing.replicas_pk_set().public_key(),
),
crediting_replica_sig: genesis_elder.signing.sign_credit_proof(&genesis_credit)?,
},
))?;

Expand Down Expand Up @@ -507,13 +507,8 @@ mod test {
.receive_propagated(&credit_proof, || past_key)?
.ok_or(Error::UnexpectedOutcome)?;

let crediting_replica_sig = replica.signing.sign_credit_proof(&credit_proof)?;
let propagated = sn_data_types::TransferPropagated {
credit_proof: credit_proof.clone(),
crediting_replica_keys: PublicKey::Bls(
replica.signing.replicas_pk_set().public_key(),
),
crediting_replica_sig,
};
// then apply to inmem state
wallet_replica.apply(ReplicaEvent::TransferPropagated(propagated.clone()))?;
Expand All @@ -534,17 +529,15 @@ mod test {
.get(&recipient.actor.id())
.ok_or(Error::UnexpectedOutcome)?;
let snapshot = wallet.wallet().ok_or(Error::UnexpectedOutcome)?;
let transfers = recipient
let state = recipient
.actor
.synch(
snapshot.balance,
snapshot.debit_version,
snapshot.credit_ids,
)?
.ok_or(Error::UnexpectedOutcome)?;
recipient
.actor
.apply(ActorEvent::TransfersSynched(transfers))
recipient.actor.apply(ActorEvent::StateSynched(state))
}

// ------------------------------------------------------------------------
Expand Down
11 changes: 1 addition & 10 deletions src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ impl ReplicaSigning {
}

/// Get the replica's PK set
#[allow(unused)]
pub fn replicas_pk_set(&self) -> &PublicKeySet {
&self.peer_replicas
}
Expand Down Expand Up @@ -285,14 +286,4 @@ impl ReplicaSigning {
}),
}
}

pub fn sign_credit_proof(&self, proof: &CreditAgreementProof) -> Result<SignatureShare> {
match bincode::serialize(proof) {
Err(_) => Err(Error::Serialisation("Could not serialise proof".into())),
Ok(data) => Ok(SignatureShare {
index: self.key_index,
share: self.secret_key.sign(data),
}),
}
}
}

0 comments on commit 62c4e71

Please sign in to comment.