1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Copyright 2020 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.

use super::{
    keys::{PublicKey, Signature, SignatureShare},
    money::Money,
    utils, Result,
};
use crdts::Dot;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Debug, Display, Formatter};
use threshold_crypto::PublicKeySet;
use tiny_keccak::sha3_256;

/// Debit ID.
pub type DebitId = Dot<PublicKey>;
/// Credit ID is the hash of the DebitId.
pub type CreditId = [u8; 256 / 8];
/// Msg, containing any data to the recipient.
pub type Msg = String;

/// A cmd to transfer of money between two keys.
#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Debug)]
pub struct Transfer {
    /// The amount to transfer.
    pub amount: Money,
    /// The destination to transfer to.
    pub to: PublicKey,
    /// Debit ID, containing source key.
    pub debit_id: DebitId,
    /// Msg, containing any data to the recipient.
    pub msg: Msg,
}

impl Transfer {
    /// The source.
    pub fn debit(&self) -> Debit {
        Debit {
            id: self.debit_id,
            amount: self.amount,
        }
    }

    /// The destination.
    pub fn credit(&self) -> Result<Credit> {
        Ok(Credit {
            id: self.debit().credit_id()?,
            amount: self.amount,
            recipient: self.to,
            msg: self.msg.to_string(),
        })
    }
}

/// A debit of money at a key.
#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Debug)]
pub struct Debit {
    /// Debit ID, containing source key.
    pub id: DebitId,
    /// The amount to debit.
    pub amount: Money,
}

impl Debit {
    /// Get the debit id
    pub fn id(&self) -> DebitId {
        self.id
    }

    /// Get the amount of this debit
    pub fn amount(&self) -> Money {
        self.amount
    }

    /// Get the key to be debited
    pub fn sender(&self) -> PublicKey {
        self.id.actor
    }

    ///
    pub fn credit_id(&self) -> Result<CreditId> {
        Ok(sha3_256(&utils::serialise(&self.id)?))
    }
}

/// A debit of money at a key.
#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Debug)]
pub struct Credit {
    /// Unique id for the credit, being the hash of the DebitId.
    pub id: CreditId,
    /// The amount to credit.
    pub amount: Money,
    /// The recipient key
    pub recipient: PublicKey,
    /// Msg, containing any data to the recipient.
    pub msg: Msg,
}

impl Credit {
    /// Get the credit id
    pub fn id(&self) -> &CreditId {
        &self.id
    }

    /// Get the amount of this credit
    pub fn amount(&self) -> Money {
        self.amount
    }

    /// Get the key to be credited
    pub fn recipient(&self) -> PublicKey {
        self.recipient
    }
}

/// The aggregated Replica signatures of the Actor debit cmd.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CreditAgreementProof {
    /// The cmd generated by sender Actor.
    pub signed_credit: SignedCredit,
    /// Quorum of Replica sigs over the credit.
    pub debiting_replicas_sig: Signature,
    /// PublicKeySet of the replica when it validated the debit.
    pub debiting_replicas_keys: ReplicaPublicKeySet,
}

impl Debug for CreditAgreementProof {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "CreditAgreementProof::")?;
        write!(formatter, "Credit({})", self.signed_credit.amount())?;
        write!(formatter, "ActorSignature::")?;
        Debug::fmt(&self.signed_credit.actor_signature, formatter)?;
        write!(formatter, "ReplicaSignature::")?;
        Debug::fmt(&self.debiting_replicas_sig, formatter)
    }
}

impl Display for CreditAgreementProof {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, formatter)
    }
}

impl CreditAgreementProof {
    /// Get the credit id
    pub fn id(&self) -> &CreditId {
        self.signed_credit.id()
    }

    /// Get the amount of this credit
    pub fn amount(&self) -> Money {
        self.signed_credit.amount()
    }

    /// Get the recipient of this credit
    pub fn recipient(&self) -> PublicKey {
        self.signed_credit.recipient()
    }

    /// Get the PublicKeySet of the replica that validated this credit
    pub fn replica_keys(&self) -> ReplicaPublicKeySet {
        self.debiting_replicas_keys.clone()
    }
}

/// The aggregated Replica signatures of the Actor debit cmd.
#[derive(Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct TransferAgreementProof {
    /// The debit generated by sender Actor.
    pub signed_debit: SignedDebit,
    /// The credit generated by sender Actor.
    pub signed_credit: SignedCredit,
    /// Quorum of Replica sigs over the debit.
    pub debit_sig: Signature,
    /// Quorum of Replica sigs over the credit.
    pub credit_sig: Signature,
    /// PublicKeySet of the replica when it validated the transfer.
    pub debiting_replicas_keys: ReplicaPublicKeySet,
}

impl TransferAgreementProof {
    /// Get the debit id
    pub fn id(&self) -> DebitId {
        self.signed_debit.id()
    }

    /// Get the amount of this transfer
    pub fn amount(&self) -> Money {
        self.signed_debit.amount()
    }

    /// Get the sender of this transfer
    pub fn sender(&self) -> PublicKey {
        self.signed_debit.sender()
    }

    /// Get the recipient of this transfer
    pub fn recipient(&self) -> PublicKey {
        self.signed_credit.recipient()
    }

    /// Get the PublicKeySet of the replica that validated this transfer
    pub fn replica_keys(&self) -> ReplicaPublicKeySet {
        self.debiting_replicas_keys.clone()
    }

    /// Get the corresponding credit agreement proof.
    pub fn credit_proof(&self) -> CreditAgreementProof {
        CreditAgreementProof {
            signed_credit: self.signed_credit.clone(),
            debiting_replicas_sig: self.credit_sig.clone(),
            debiting_replicas_keys: self.replica_keys(),
        }
    }
}

/// An Actor cmd.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct SignedTransfer {
    /// The debit.
    pub debit: SignedDebit,
    /// The credit.
    pub credit: SignedCredit,
}

impl SignedTransfer {
    /// Get the debit id
    pub fn id(&self) -> DebitId {
        self.debit.id()
    }

    /// Get the amount of this transfer
    pub fn amount(&self) -> Money {
        self.debit.amount()
    }

    /// Get the sender of this transfer
    pub fn sender(&self) -> PublicKey {
        self.debit.id().actor
    }

    /// Get the credit id of this debit.
    pub fn credit_id(&self) -> Result<CreditId> {
        self.debit.credit_id()
    }
}

/// An Actor cmd.
#[derive(Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct SignedDebit {
    /// The debit.
    pub debit: Debit,
    /// Actor signature over the debit.
    pub actor_signature: Signature,
}

impl SignedDebit {
    /// Get the debit id
    pub fn id(&self) -> DebitId {
        self.debit.id()
    }

    /// Get the amount of this transfer
    pub fn amount(&self) -> Money {
        self.debit.amount()
    }

    /// Get the sender of this transfer
    pub fn sender(&self) -> PublicKey {
        self.debit.sender()
    }

    /// Get the credit id of this debit.
    pub fn credit_id(&self) -> Result<CreditId> {
        self.debit.credit_id()
    }
}

/// An Actor cmd.
#[derive(Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct SignedCredit {
    /// The credit.
    pub credit: Credit,
    /// Actor signature over the transfer.
    pub actor_signature: Signature,
}

impl SignedCredit {
    /// Get the credit id
    pub fn id(&self) -> &CreditId {
        self.credit.id()
    }

    /// Get the amount of this transfer
    pub fn amount(&self) -> Money {
        self.credit.amount
    }

    /// Get the sender of this transfer
    pub fn recipient(&self) -> PublicKey {
        self.credit.recipient()
    }
}

// ------------------------------------------------------------
//                      Replica
// ------------------------------------------------------------

/// Events raised by the Replica.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub enum ReplicaEvent {
    /// The event raised when
    /// ValidateTransfer cmd has been successful.
    TransferValidated(TransferValidated),
    /// The event raised when
    /// RegisterTransfer cmd has been successful.
    TransferRegistered(TransferRegistered),
    /// The event raised when
    /// PropagateTransfer cmd has been successful.
    TransferPropagated(TransferPropagated),
    // /// The event raised when
    // /// peers changed so that we have a new PublicKeySet.
    // PeersChanged(PeersChanged),
    /// The event raised when
    /// we learn of a new group PK set.
    KnownGroupAdded(KnownGroupAdded),
}

/// The debiting Replica event raised when
/// ValidateTransfer cmd has been successful.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct TransferValidated {
    /// The debit initiated by the Actor.
    pub signed_debit: SignedDebit,
    /// The corresponding credit, signed by the Actor.
    pub signed_credit: SignedCredit,
    /// Replica signature over the debit.
    pub replica_debit_sig: SignatureShare,
    /// Replica signature over the credit.
    pub replica_credit_sig: SignatureShare,
    /// The PK Set of the Replicas
    pub replicas: PublicKeySet,
    // NB: I'm a bit ambivalent to this implicit communication of public key change.
    // I generally prefer an explicit cmd + event for such a significant part of the logic.
    // Including it here minimizes msg types and traffic, and seamlessly - apparently -
    // updates Actors on any public key change, which they can accumulate in order to
    // apply the change to local state.
    // But it inflicts on, and complicates the logic for validating a transfer..
    // Cost / benefit to be discussed..
}

impl TransferValidated {
    /// Get the debit id
    pub fn id(&self) -> DebitId {
        self.signed_debit.id()
    }

    /// Get the amount of this transfer
    pub fn amount(&self) -> Money {
        self.signed_debit.amount()
    }

    /// Get the sender of this transfer
    pub fn sender(&self) -> PublicKey {
        self.signed_debit.sender()
    }

    /// Get the recipient of this transfer
    pub fn recipient(&self) -> PublicKey {
        self.signed_credit.recipient()
    }
}

/// The debiting Replica event raised when
/// RegisterTransfer cmd has been successful.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct TransferRegistered {
    /// The transfer proof.
    pub transfer_proof: TransferAgreementProof,
}

impl TransferRegistered {
    /// Get the debit id
    pub fn id(&self) -> DebitId {
        self.transfer_proof.id()
    }

    /// Get the amount of this transfer
    pub fn amount(&self) -> Money {
        self.transfer_proof.amount()
    }

    /// Get the sender of this transfer
    pub fn sender(&self) -> PublicKey {
        self.transfer_proof.sender()
    }

    /// Get the recipient of this transfer
    pub fn recipient(&self) -> PublicKey {
        self.transfer_proof.recipient()
    }
}

/// The crediting Replica event raised when
/// PropagateTransfer cmd has been successful.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
pub struct TransferPropagated {
    /// The debiting Replicas' proof.
    pub credit_proof: CreditAgreementProof,
    /// The crediting Replica signature.
    pub crediting_replica_sig: SignatureShare,
    /// The pub key of the debiting Replicas.
    pub crediting_replica_keys: PublicKey,
}

impl TransferPropagated {
    /// Get the credit id
    pub fn id(&self) -> &CreditId {
        self.credit_proof.id()
    }

    /// Get the amount of this transfer
    pub fn amount(&self) -> Money {
        self.credit_proof.amount()
    }

    /// Get the recipient of this credit
    pub fn recipient(&self) -> PublicKey {
        self.credit_proof.recipient()
    }
}

/// Public Key Set for a group of transfer replicas.
pub type ReplicaPublicKeySet = PublicKeySet;
/// The Replica event raised when
/// we learn of a new group PK set.
#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Debug)]
pub struct KnownGroupAdded {
    /// The PublicKeySet of the group.
    pub group: PublicKeySet,
}

/// Notification of a credit sent to a recipient.
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct CreditNotification(pub CreditAgreementProof);