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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Common types needed in concordium.

use super::{
    deserial_string, serial_string, Buffer, Deserial, Get, ParseResult, SerdeDeserialize,
    SerdeSerialize, Serial,
};
use crate::common::Serialize;
use byteorder::{BigEndian, ReadBytesExt};
use concordium_contracts_common::{
    self as concordium_std, ContractAddress, ContractName, OwnedContractName, OwnedParameter,
    OwnedReceiveName, Parameter, ReceiveName,
};
pub use concordium_contracts_common::{AccountAddress, Address, Amount, ACCOUNT_ADDRESS_SIZE};
use derive_more::{Display, From, FromStr, Into};
use std::{collections::BTreeMap, num::ParseIntError, str::FromStr};
/// Index of an account key that is to be used.
#[derive(
    Debug,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Clone,
    Copy,
    Hash,
    Serialize,
    Display,
    From,
    Into,
    concordium_std::Serialize,
)]
#[repr(transparent)]
#[derive(SerdeSerialize)]
#[serde(transparent)]
pub struct KeyIndex(pub u8);

#[derive(
    SerdeSerialize,
    SerdeDeserialize,
    Serialize,
    Copy,
    Clone,
    Eq,
    PartialEq,
    Ord,
    PartialOrd,
    Debug,
    FromStr,
    Display,
    From,
    Into,
    concordium_std::Serialize,
)]
#[serde(transparent)]
/// Index of the credential that is to be used.
pub struct CredentialIndex {
    pub index: u8,
}

impl Serial for Amount {
    fn serial<B: super::Buffer>(&self, out: &mut B) { self.micro_ccd().serial(out) }
}

impl Deserial for Amount {
    fn deserial<R: byteorder::ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let micro_ccd = source.get()?;
        Ok(Amount::from_micro_ccd(micro_ccd))
    }
}

impl Serial for Address {
    fn serial<B: Buffer>(&self, out: &mut B) {
        match self {
            Address::Account(acc) => {
                0u8.serial(out);
                acc.serial(out)
            }
            Address::Contract(ca) => {
                1u8.serial(out);
                ca.serial(out)
            }
        }
    }
}

impl Deserial for Address {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        match u8::deserial(source)? {
            0u8 => Ok(Self::Account(source.get()?)),
            1u8 => Ok(Self::Contract(source.get()?)),
            _ => anyhow::bail!("Unsupported address type."),
        }
    }
}

impl Serial for AccountAddress {
    #[inline]
    fn serial<B: Buffer>(&self, x: &mut B) {
        x.write_all(&self.0)
            .expect("Writing to buffer should succeed.")
    }
}

impl Deserial for AccountAddress {
    #[inline]
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let mut buf = [0u8; ACCOUNT_ADDRESS_SIZE];
        source.read_exact(&mut buf)?;
        Ok(AccountAddress(buf))
    }
}

impl Serial for ContractAddress {
    #[inline]
    fn serial<B: Buffer>(&self, x: &mut B) {
        x.write_u64::<BigEndian>(self.index)
            .expect("Writing to buffer should succeed.");
        x.write_u64::<BigEndian>(self.subindex)
            .expect("Writing to buffer should succeed.");
    }
}

impl Deserial for ContractAddress {
    #[inline]
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let index = source.read_u64::<BigEndian>()?;
        let subindex = source.read_u64::<BigEndian>()?;
        Ok(ContractAddress::new(index, subindex))
    }
}

impl Serial for ReceiveName<'_> {
    #[inline]
    fn serial<B: Buffer>(&self, out: &mut B) {
        let string = self.get_chain_name();
        (string.len() as u16).serial(out);
        serial_string(string, out)
    }
}

impl Serial for OwnedReceiveName {
    #[inline]
    fn serial<B: Buffer>(&self, x: &mut B) { self.as_receive_name().serial(x) }
}

impl Deserial for OwnedReceiveName {
    #[inline]
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len: u16 = source.get()?;
        let name = deserial_string(source, len.into())?;
        Ok(OwnedReceiveName::new(name)?)
    }
}

impl Serial for ContractName<'_> {
    #[inline]
    fn serial<B: Buffer>(&self, out: &mut B) {
        let string = self.get_chain_name();
        (string.len() as u16).serial(out);
        serial_string(string, out)
    }
}

impl Serial for OwnedContractName {
    #[inline]
    fn serial<B: Buffer>(&self, x: &mut B) { self.as_contract_name().serial(x) }
}

impl Deserial for OwnedContractName {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len: u16 = source.get()?;
        let name = deserial_string(source, len.into())?;
        Ok(OwnedContractName::new(name)?)
    }
}

impl Serial for Parameter<'_> {
    fn serial<B: Buffer>(&self, out: &mut B) {
        let bytes = self.as_ref();
        (bytes.len() as u16).serial(out);
        out.write_all(bytes)
            .expect("Writing to buffer should succeed.")
    }
}

impl Serial for OwnedParameter {
    #[inline]
    fn serial<B: Buffer>(&self, out: &mut B) { self.as_parameter().serial(out) }
}

impl Deserial for OwnedParameter {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        // Since `MAX_PARAMETER_LEN == u16::MAX`, we don't need to check it explicitly.
        // The constant exists in concordium_contracts_common::constants.
        let len: u16 = source.get()?;
        let mut bytes = vec![0u8; len.into()]; // Safe to preallocate since len fits `u16`.
        source.read_exact(&mut bytes)?;
        Ok(OwnedParameter::new_unchecked(bytes))
    }
}

/// A ratio between two `u64` integers.
///
/// It should be safe to assume the denominator is not zero and that numerator
/// and denominator are coprime.
///
/// This type is introduced (over using `num::rational::Ratio<u64>`) to add the
/// above requirements and to provide implementations for `serde::Serialize` and
/// `serde::Deserialize`.
#[derive(Debug, SerdeDeserialize, SerdeSerialize, Serial, Clone, Copy)]
#[serde(try_from = "rust_decimal::Decimal", into = "rust_decimal::Decimal")]
pub struct Ratio {
    numerator:   u64,
    denominator: u64,
}

/// Error during creating a new ratio.
#[derive(Debug, Clone, thiserror::Error)]
pub enum NewRatioError {
    #[error("Denominator cannot be 0.")]
    ZeroDenominator,
    #[error("Numerator and denominator must be coprime.")]
    NotCoprime,
}

impl Ratio {
    /// Construct a new ratio. Returns an error if denominator is non-zero or
    /// numerator and denominator are not coprime.
    pub fn new(numerator: u64, denominator: u64) -> Result<Self, NewRatioError> {
        if denominator == 0 {
            return Err(NewRatioError::ZeroDenominator);
        }
        if num::Integer::gcd(&numerator, &denominator) != 1 {
            return Err(NewRatioError::NotCoprime);
        }
        Ok(Self {
            numerator,
            denominator,
        })
    }

    /// Construct a new ratio without checking anything.
    ///
    /// It is up to the caller to ensure the denominator is not zero and that
    /// numerator and denominator are coprime.
    pub fn new_unchecked(numerator: u64, denominator: u64) -> Self {
        Self {
            numerator,
            denominator,
        }
    }

    /// Get the numerator of the ratio.
    pub fn numerator(&self) -> u64 { self.numerator }

    /// Get the denominator of the ratio.
    pub fn denominator(&self) -> u64 { self.denominator }
}

impl Deserial for Ratio {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let numerator: u64 = source.get()?;
        let denominator: u64 = source.get()?;
        Ok(Self::new(numerator, denominator)?)
    }
}

impl From<Ratio> for rust_decimal::Decimal {
    fn from(ratio: Ratio) -> rust_decimal::Decimal {
        rust_decimal::Decimal::from(ratio.numerator)
            / rust_decimal::Decimal::from(ratio.denominator)
    }
}

/// Error from converting a decimal to a [`Ratio`].
#[derive(Debug, Clone, thiserror::Error)]
#[error("Unrepresentable number.")]
pub struct RatioFromDecimalError;

impl TryFrom<rust_decimal::Decimal> for Ratio {
    type Error = RatioFromDecimalError;

    fn try_from(mut value: rust_decimal::Decimal) -> Result<Self, Self::Error> {
        value.normalize_assign();
        let mantissa = value.mantissa();
        let scale = value.scale();
        let denominator = 10u64.checked_pow(scale).ok_or(RatioFromDecimalError)?;
        let numerator: u64 = mantissa.try_into().map_err(|_| RatioFromDecimalError)?;
        let g = num::Integer::gcd(&numerator, &denominator);
        let numerator = numerator / g;
        let denominator = denominator / g;
        Ok(Self {
            numerator,
            denominator,
        })
    }
}

impl From<Ratio> for num::rational::Ratio<u64> {
    fn from(ratio: Ratio) -> Self { Self::new_raw(ratio.numerator, ratio.denominator) }
}

#[derive(Clone, PartialEq, Eq, Debug)]
/// A single signature. Using the same binary and JSON serialization as the
/// Haskell counterpart. In particular this means encoding the length as 2
/// bytes, and thus the largest size is 65535 bytes.
pub struct Signature {
    pub sig: Vec<u8>,
}

impl Serial for Signature {
    fn serial<B: Buffer>(&self, out: &mut B) {
        (self.sig.len() as u16).serial(out);
        out.write_all(&self.sig)
            .expect("Writing to buffer should succeed.");
    }
}

impl Deserial for Signature {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len: u16 = source.get()?;
        // allocating is safe because len is a u16
        let mut sig = vec![0; len as usize];
        source.read_exact(&mut sig)?;
        Ok(Signature { sig })
    }
}

impl SerdeSerialize for Signature {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer, {
        serializer.serialize_str(&hex::encode(&self.sig))
    }
}

impl<'de> SerdeDeserialize<'de> for Signature {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>, {
        let s = String::deserialize(deserializer)?;
        let sig = hex::decode(s).map_err(|e| serde::de::Error::custom(format!("{}", e)))?;
        if sig.len() <= 65535 {
            Ok(Signature { sig })
        } else {
            Err(serde::de::Error::custom("Signature length out of bounds."))
        }
    }
}

impl AsRef<[u8]> for Signature {
    fn as_ref(&self) -> &[u8] { &self.sig }
}

/// Transaction signature structure, to match the one on the Haskell side.
#[derive(SerdeDeserialize, SerdeSerialize, Clone, PartialEq, Eq, Debug, derive_more::AsRef)]
#[serde(transparent)]
pub struct TransactionSignature {
    pub signatures: BTreeMap<CredentialIndex, BTreeMap<KeyIndex, Signature>>,
}

impl TransactionSignature {
    /// The total number of signatures.
    pub fn num_signatures(&self) -> u32 {
        // Since there are at most 256 credential indices, and at most 256 key indices
        // using `as` is safe.
        let x: usize = self.signatures.values().map(|sigs| sigs.len()).sum();
        x as u32
    }
}

impl Serial for TransactionSignature {
    fn serial<B: Buffer>(&self, out: &mut B) {
        let l = self.signatures.len() as u8;
        l.serial(out);
        for (idx, map) in self.signatures.iter() {
            idx.serial(out);
            (map.len() as u8).serial(out);
            super::serial_map_no_length(map, out);
        }
    }
}

impl Deserial for TransactionSignature {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let num_creds: u8 = source.get()?;
        anyhow::ensure!(num_creds > 0, "Number of signatures must not be 0.");
        let mut out = BTreeMap::new();
        let mut last = None;
        for _ in 0..num_creds {
            let idx = source.get()?;
            anyhow::ensure!(
                last < Some(idx),
                "Credential indices must be strictly increasing."
            );
            last = Some(idx);
            let inner_len: u8 = source.get()?;
            anyhow::ensure!(
                inner_len > 0,
                "Each credential must have at least one signature."
            );
            let inner_map = super::deserial_map_no_length(source, inner_len.into())?;
            out.insert(idx, inner_map);
        }
        Ok(TransactionSignature { signatures: out })
    }
}

/// Datatype used to indicate transaction expiry.
#[derive(
    SerdeDeserialize, SerdeSerialize, PartialEq, Eq, Debug, Serialize, Clone, Copy, PartialOrd, Ord,
)]
#[serde(transparent)]
pub struct TransactionTime {
    /// Seconds since the unix epoch.
    pub seconds: u64,
}

impl TransactionTime {
    /// Construct a timestamp from seconds since the unix epoch.
    pub fn from_seconds(seconds: u64) -> Self { Self { seconds } }

    /// Construct a timestamp that is the given amount of seconds in the future.
    pub fn seconds_after(seconds: u32) -> Self {
        Self::from_seconds(chrono::offset::Utc::now().timestamp() as u64 + u64::from(seconds))
    }

    /// Construct a timestamp that is the given amount of minutes in the future.
    pub fn minutes_after(minutes: u32) -> Self { Self::seconds_after(minutes * 60) }

    /// Construct a timestamp that is the given amount of hours in the future.
    pub fn hours_after(hours: u32) -> Self { Self::minutes_after(hours * 60) }
}

impl From<u64> for TransactionTime {
    fn from(seconds: u64) -> Self { Self { seconds } }
}

impl FromStr for TransactionTime {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let seconds = u64::from_str(s)?;
        Ok(Self { seconds })
    }
}

/// Datatype used to indicate a timestamp in milliseconds.
#[derive(
    SerdeDeserialize, SerdeSerialize, PartialEq, Eq, Debug, Serialize, Clone, Copy, PartialOrd, Ord,
)]
#[serde(transparent)]
pub struct Timestamp {
    /// Milliseconds since the unix epoch.
    pub millis: u64,
}

impl Timestamp {
    pub fn now() -> Self { (chrono::Utc::now().timestamp_millis() as u64).into() }
}

impl From<u64> for Timestamp {
    fn from(millis: u64) -> Self { Self { millis } }
}

impl FromStr for Timestamp {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let millis = u64::from_str(s)?;
        Ok(Self { millis })
    }
}

/// A ed25519 keypair. This is available in the `ed25519::dalek` crate, but the
/// JSON serialization there is not compatible with what we use, so we redefine
/// it there.
#[derive(Debug, SerdeSerialize, SerdeDeserialize)]
pub struct KeyPair {
    #[serde(
        rename = "signKey",
        serialize_with = "crate::common::base16_encode",
        deserialize_with = "crate::common::base16_decode"
    )]
    pub secret: ed25519_dalek::SecretKey,
    #[serde(
        rename = "verifyKey",
        serialize_with = "crate::common::base16_encode",
        deserialize_with = "crate::common::base16_decode"
    )]
    pub public: ed25519_dalek::PublicKey,
}

impl KeyPair {
    pub fn generate<R: rand::CryptoRng + rand::Rng>(rng: &mut R) -> Self {
        Self::from(ed25519_dalek::Keypair::generate(rng))
    }
}

impl From<ed25519_dalek::Keypair> for KeyPair {
    fn from(kp: ed25519_dalek::Keypair) -> Self {
        Self {
            secret: kp.secret,
            public: kp.public,
        }
    }
}

impl KeyPair {
    /// Sign the given message with the keypair.
    pub fn sign(&self, msg: &[u8]) -> Signature {
        let expanded = ed25519_dalek::ExpandedSecretKey::from(&self.secret);
        let sig = expanded.sign(msg, &self.public);
        Signature {
            sig: sig.to_bytes().to_vec(),
        }
    }
}

impl From<KeyPair> for ed25519_dalek::Keypair {
    fn from(kp: KeyPair) -> ed25519_dalek::Keypair {
        ed25519_dalek::Keypair {
            secret: kp.secret,
            public: kp.public,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::{
        distributions::{Distribution, Uniform},
        Rng,
    };

    #[test]
    fn transaction_signature_serialization() {
        let mut rng = rand::thread_rng();
        for _ in 0..100 {
            let num_creds = rng.gen_range(1, 30);
            let mut signatures = BTreeMap::new();
            for _ in 0..num_creds {
                let num_keys = rng.gen_range(1, 20);
                let mut cred_sigs = BTreeMap::new();
                for _ in 0..num_keys {
                    let num_elems = rng.gen_range(0, 200);
                    let sig = Signature {
                        sig: Uniform::new_inclusive(0, 255u8)
                            .sample_iter(rng)
                            .take(num_elems)
                            .collect(),
                    };
                    cred_sigs.insert(KeyIndex(rng.gen()), sig);
                }
                signatures.insert(CredentialIndex { index: rng.gen() }, cred_sigs);
            }
            let signatures = TransactionSignature { signatures };
            let js = serde_json::to_string(&signatures).expect("Serialization should succeed.");
            match serde_json::from_str::<TransactionSignature>(&js) {
                Ok(s) => assert_eq!(s, signatures, "Deserialized incorrect value."),
                Err(e) => panic!("{}", e),
            }

            let binary_result = crate::common::serialize_deserialize(&signatures)
                .expect("Binary signature serialization is not invertible.");
            assert_eq!(
                binary_result, signatures,
                "Binary signature parses incorrectly."
            );
        }
    }

    #[test]
    fn amount_json_serialization() {
        let mut rng = rand::thread_rng();
        for _ in 0..1000 {
            let amount = Amount::from_micro_ccd(rng.gen::<u64>());
            let s = serde_json::to_string(&amount).expect("Could not serialize");
            assert_eq!(
                amount,
                serde_json::from_str(&s).unwrap(),
                "Could not deserialize amount."
            );
        }

        let amount = Amount::from_micro_ccd(12345);
        let s = serde_json::to_string(&amount).expect("Could not serialize");
        assert_eq!(s, r#""12345""#, "Could not deserialize amount.");

        assert!(
            serde_json::from_str::<Amount>(r#""""#).is_err(),
            "Parsed empty string, but should not."
        );
        assert!(
            serde_json::from_str::<Amount>(r#""12f""#).is_err(),
            "Parsed string with corrupt data at end, but should not."
        );
        assert!(
            serde_json::from_str::<Amount>(r#""12345612312315415123123""#).is_err(),
            "Parsed overflowing amount, but should not."
        );
    }
}