casper-binary-port 1.1.1

Types for the casper node binary port
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use core::{convert::TryFrom, num::TryFromIntError, time::Duration};
use std::collections::BTreeMap;

use casper_types::{
    bytesrepr::{self, Bytes, FromBytes, ToBytes},
    contracts::ContractHash,
    global_state::TrieMerkleProof,
    system::auction::DelegationRate,
    Account, AddressableEntity, BlockHash, ByteCode, Contract, ContractWasm, EntityAddr, EraId,
    ExecutionInfo, Key, PublicKey, StoredValue, TimeDiff, Timestamp, Transaction, ValidatorChange,
    U512,
};
use serde::Serialize;

use super::GlobalStateQueryResult;

// `bytesrepr` implementations for type wrappers are repetitive, hence this macro helper. We should
// get rid of this after we introduce the proper "bytesrepr-derive" proc macro.
macro_rules! impl_bytesrepr_for_type_wrapper {
    ($t:ident) => {
        impl ToBytes for $t {
            fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
                self.0.to_bytes()
            }

            fn serialized_length(&self) -> usize {
                self.0.serialized_length()
            }

            fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
                self.0.write_bytes(writer)
            }
        }

        impl FromBytes for $t {
            fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
                let (inner, remainder) = FromBytes::from_bytes(bytes)?;
                Ok(($t(inner), remainder))
            }
        }
    };
}

/// Type representing uptime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Uptime(u64);

impl Uptime {
    /// Constructs new uptime.
    pub fn new(value: u64) -> Self {
        Self(value)
    }

    /// Retrieve the inner value.
    pub fn into_inner(self) -> u64 {
        self.0
    }
}

impl From<Uptime> for Duration {
    fn from(uptime: Uptime) -> Self {
        Duration::from_secs(uptime.0)
    }
}

impl TryFrom<Uptime> for TimeDiff {
    type Error = TryFromIntError;

    fn try_from(uptime: Uptime) -> Result<Self, Self::Error> {
        u32::try_from(uptime.0).map(TimeDiff::from_seconds)
    }
}

/// Type representing changes in consensus validators.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct ConsensusValidatorChanges(BTreeMap<PublicKey, Vec<(EraId, ValidatorChange)>>);

impl ConsensusValidatorChanges {
    /// Constructs new consensus validator changes.
    pub fn new(value: BTreeMap<PublicKey, Vec<(EraId, ValidatorChange)>>) -> Self {
        Self(value)
    }

    /// Retrieve the inner value.
    pub fn into_inner(self) -> BTreeMap<PublicKey, Vec<(EraId, ValidatorChange)>> {
        self.0
    }
}

impl From<ConsensusValidatorChanges> for BTreeMap<PublicKey, Vec<(EraId, ValidatorChange)>> {
    fn from(consensus_validator_changes: ConsensusValidatorChanges) -> Self {
        consensus_validator_changes.0
    }
}

/// Type representing network name.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct NetworkName(String);

impl NetworkName {
    /// Constructs new network name.
    pub fn new(value: impl ToString) -> Self {
        Self(value.to_string())
    }

    /// Retrieve the inner value.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl From<NetworkName> for String {
    fn from(network_name: NetworkName) -> Self {
        network_name.0
    }
}

/// Type representing the reactor state name.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct ReactorStateName(String);

impl ReactorStateName {
    /// Constructs new reactor state name.
    pub fn new(value: impl ToString) -> Self {
        Self(value.to_string())
    }

    /// Retrieve the name as a `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl From<ReactorStateName> for String {
    fn from(reactor_state: ReactorStateName) -> Self {
        reactor_state.0
    }
}

/// Type representing last progress of the sync process.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct LastProgress(Timestamp);

impl LastProgress {
    /// Constructs new last progress.
    pub fn new(value: Timestamp) -> Self {
        Self(value)
    }

    /// Retrieve the inner value.
    pub fn into_inner(self) -> Timestamp {
        self.0
    }
}

impl From<LastProgress> for Timestamp {
    fn from(last_progress: LastProgress) -> Self {
        last_progress.0
    }
}

/// Type representing results of the get full trie request.
#[derive(Debug, PartialEq, Eq)]
pub struct GetTrieFullResult(Option<Bytes>);

impl GetTrieFullResult {
    /// Constructs new get trie result.
    pub fn new(value: Option<Bytes>) -> Self {
        Self(value)
    }

    /// Returns the inner value.
    pub fn into_inner(self) -> Option<Bytes> {
        self.0
    }
}

/// Type representing the reward of a validator or a delegator.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct RewardResponse {
    amount: U512,
    era_id: EraId,
    delegation_rate: DelegationRate,
    switch_block_hash: BlockHash,
}

impl RewardResponse {
    /// Constructs new reward response.
    pub fn new(
        amount: U512,
        era_id: EraId,
        delegation_rate: DelegationRate,
        switch_block_hash: BlockHash,
    ) -> Self {
        Self {
            amount,
            era_id,
            delegation_rate,
            switch_block_hash,
        }
    }

    /// Returns the amount of the reward.
    pub fn amount(&self) -> U512 {
        self.amount
    }

    /// Returns the era ID.
    pub fn era_id(&self) -> EraId {
        self.era_id
    }

    /// Returns the delegation rate of the validator.
    pub fn delegation_rate(&self) -> DelegationRate {
        self.delegation_rate
    }

    /// Returns the switch block hash at which the reward was distributed.
    pub fn switch_block_hash(&self) -> BlockHash {
        self.switch_block_hash
    }
}

impl ToBytes for RewardResponse {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn serialized_length(&self) -> usize {
        self.amount.serialized_length()
            + self.era_id.serialized_length()
            + self.delegation_rate.serialized_length()
            + self.switch_block_hash.serialized_length()
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.amount.write_bytes(writer)?;
        self.era_id.write_bytes(writer)?;
        self.delegation_rate.write_bytes(writer)?;
        self.switch_block_hash.write_bytes(writer)
    }
}

impl FromBytes for RewardResponse {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (amount, remainder) = FromBytes::from_bytes(bytes)?;
        let (era_id, remainder) = FromBytes::from_bytes(remainder)?;
        let (delegation_rate, remainder) = FromBytes::from_bytes(remainder)?;
        let (switch_block_hash, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((
            RewardResponse::new(amount, era_id, delegation_rate, switch_block_hash),
            remainder,
        ))
    }
}

/// Describes the consensus status.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct ConsensusStatus {
    validator_public_key: PublicKey,
    round_length: Option<TimeDiff>,
}

impl ConsensusStatus {
    /// Constructs new consensus status.
    pub fn new(validator_public_key: PublicKey, round_length: Option<TimeDiff>) -> Self {
        Self {
            validator_public_key,
            round_length,
        }
    }

    /// Returns the validator public key.
    pub fn validator_public_key(&self) -> &PublicKey {
        &self.validator_public_key
    }

    /// Returns the round length.
    pub fn round_length(&self) -> Option<TimeDiff> {
        self.round_length
    }
}

impl ToBytes for ConsensusStatus {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn serialized_length(&self) -> usize {
        self.validator_public_key.serialized_length() + self.round_length.serialized_length()
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.validator_public_key.write_bytes(writer)?;
        self.round_length.write_bytes(writer)
    }
}

impl FromBytes for ConsensusStatus {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (validator_public_key, remainder) = FromBytes::from_bytes(bytes)?;
        let (round_length, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((
            ConsensusStatus::new(validator_public_key, round_length),
            remainder,
        ))
    }
}

/// A transaction with execution info.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct TransactionWithExecutionInfo {
    transaction: Transaction,
    execution_info: Option<ExecutionInfo>,
}

impl TransactionWithExecutionInfo {
    /// Constructs new transaction with execution info.
    pub fn new(transaction: Transaction, execution_info: Option<ExecutionInfo>) -> Self {
        Self {
            transaction,
            execution_info,
        }
    }

    /// Converts `self` into the transaction and execution info.
    pub fn into_inner(self) -> (Transaction, Option<ExecutionInfo>) {
        (self.transaction, self.execution_info)
    }
}

impl ToBytes for TransactionWithExecutionInfo {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn serialized_length(&self) -> usize {
        self.transaction.serialized_length() + self.execution_info.serialized_length()
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.transaction.write_bytes(writer)?;
        self.execution_info.write_bytes(writer)
    }
}

impl FromBytes for TransactionWithExecutionInfo {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (transaction, remainder) = FromBytes::from_bytes(bytes)?;
        let (execution_info, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((
            TransactionWithExecutionInfo::new(transaction, execution_info),
            remainder,
        ))
    }
}

/// A query result for a dictionary item, contains the dictionary item key and a global state query
/// result.
#[derive(Debug, Clone, PartialEq)]
pub struct DictionaryQueryResult {
    key: Key,
    query_result: GlobalStateQueryResult,
}

impl DictionaryQueryResult {
    /// Constructs new dictionary query result.
    pub fn new(key: Key, query_result: GlobalStateQueryResult) -> Self {
        Self { key, query_result }
    }

    /// Converts `self` into the dictionary item key and global state query result.
    pub fn into_inner(self) -> (Key, GlobalStateQueryResult) {
        (self.key, self.query_result)
    }
}

impl ToBytes for DictionaryQueryResult {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.key.write_bytes(writer)?;
        self.query_result.write_bytes(writer)
    }

    fn serialized_length(&self) -> usize {
        self.key.serialized_length() + self.query_result.serialized_length()
    }
}

impl FromBytes for DictionaryQueryResult {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (key, remainder) = FromBytes::from_bytes(bytes)?;
        let (query_result, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((DictionaryQueryResult::new(key, query_result), remainder))
    }
}

/// An account with its associated merkle proof.
#[derive(Debug, PartialEq)]
pub struct AccountInformation {
    account: Account,
    merkle_proof: Vec<TrieMerkleProof<Key, StoredValue>>,
}

impl AccountInformation {
    /// Constructs a new `AccountResponse`.
    pub fn new(account: Account, merkle_proof: Vec<TrieMerkleProof<Key, StoredValue>>) -> Self {
        Self {
            account,
            merkle_proof,
        }
    }

    /// Returns the inner `Account`.
    pub fn account(&self) -> &Account {
        &self.account
    }

    /// Returns the merkle proof.
    pub fn merkle_proof(&self) -> &Vec<TrieMerkleProof<Key, StoredValue>> {
        &self.merkle_proof
    }

    /// Converts `self` into the account and merkle proof.
    pub fn into_inner(self) -> (Account, Vec<TrieMerkleProof<Key, StoredValue>>) {
        (self.account, self.merkle_proof)
    }
}

impl ToBytes for AccountInformation {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.account.write_bytes(writer)?;
        self.merkle_proof.write_bytes(writer)
    }

    fn serialized_length(&self) -> usize {
        self.account.serialized_length() + self.merkle_proof.serialized_length()
    }
}

impl FromBytes for AccountInformation {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (account, remainder) = FromBytes::from_bytes(bytes)?;
        let (merkle_proof, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((AccountInformation::new(account, merkle_proof), remainder))
    }
}

/// A contract with its associated Wasm and merkle proof.
#[derive(Debug, PartialEq)]
pub struct ContractInformation {
    hash: ContractHash,
    contract: ValueWithProof<Contract>,
    wasm: Option<ValueWithProof<ContractWasm>>,
}

impl ContractInformation {
    /// Constructs new `ContractInformation`.
    pub fn new(
        hash: ContractHash,
        contract: ValueWithProof<Contract>,
        wasm: Option<ValueWithProof<ContractWasm>>,
    ) -> Self {
        Self {
            hash,
            contract,
            wasm,
        }
    }

    /// Returns the hash of the contract.
    pub fn hash(&self) -> ContractHash {
        self.hash
    }

    /// Returns the inner `Contract`.
    pub fn contract(&self) -> &Contract {
        &self.contract.value
    }

    /// Returns the Merkle proof of the contract.
    pub fn contract_proof(&self) -> &Vec<TrieMerkleProof<Key, StoredValue>> {
        &self.contract.merkle_proof
    }

    /// Returns the inner `ContractWasm` with its proof.
    pub fn wasm(&self) -> Option<&ValueWithProof<ContractWasm>> {
        self.wasm.as_ref()
    }

    /// Converts `self` into the contract hash, contract and Wasm.
    pub fn into_inner(
        self,
    ) -> (
        ContractHash,
        ValueWithProof<Contract>,
        Option<ValueWithProof<ContractWasm>>,
    ) {
        (self.hash, self.contract, self.wasm)
    }
}

impl ToBytes for ContractInformation {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.hash.write_bytes(writer)?;
        self.contract.write_bytes(writer)?;
        self.wasm.write_bytes(writer)
    }

    fn serialized_length(&self) -> usize {
        self.hash.serialized_length()
            + self.contract.serialized_length()
            + self.wasm.serialized_length()
    }
}

impl FromBytes for ContractInformation {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (hash, remainder) = FromBytes::from_bytes(bytes)?;
        let (contract, remainder) = FromBytes::from_bytes(remainder)?;
        let (wasm, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((ContractInformation::new(hash, contract, wasm), remainder))
    }
}

/// A contract entity with its associated ByteCode.
#[derive(Debug, PartialEq)]
pub struct AddressableEntityInformation {
    addr: EntityAddr,
    entity: ValueWithProof<AddressableEntity>,
    bytecode: Option<ValueWithProof<ByteCode>>,
}

impl AddressableEntityInformation {
    /// Constructs new contract entity with ByteCode.
    pub fn new(
        addr: EntityAddr,
        entity: ValueWithProof<AddressableEntity>,
        bytecode: Option<ValueWithProof<ByteCode>>,
    ) -> Self {
        Self {
            addr,
            entity,
            bytecode,
        }
    }

    /// Returns the entity address.
    pub fn addr(&self) -> EntityAddr {
        self.addr
    }

    /// Returns the inner `AddressableEntity`.
    pub fn entity(&self) -> &AddressableEntity {
        &self.entity.value
    }

    /// Returns the inner `ByteCodeWithProof`.
    pub fn entity_merkle_proof(&self) -> &Vec<TrieMerkleProof<Key, StoredValue>> {
        &self.entity.merkle_proof
    }

    /// Returns the inner `ByteCode`.
    pub fn bytecode(&self) -> Option<&ValueWithProof<ByteCode>> {
        self.bytecode.as_ref()
    }

    /// Converts `self` into the entity address, entity and ByteCode.
    pub fn into_inner(
        self,
    ) -> (
        EntityAddr,
        ValueWithProof<AddressableEntity>,
        Option<ValueWithProof<ByteCode>>,
    ) {
        (self.addr, self.entity, self.bytecode)
    }
}

impl ToBytes for AddressableEntityInformation {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.addr.write_bytes(writer)?;
        self.entity.write_bytes(writer)?;
        self.bytecode.write_bytes(writer)
    }

    fn serialized_length(&self) -> usize {
        self.addr.serialized_length()
            + self.entity.serialized_length()
            + self.bytecode.serialized_length()
    }
}

impl FromBytes for AddressableEntityInformation {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (addr, remainder) = FromBytes::from_bytes(bytes)?;
        let (entity, remainder) = FromBytes::from_bytes(remainder)?;
        let (bytecode, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((
            AddressableEntityInformation::new(addr, entity, bytecode),
            remainder,
        ))
    }
}

/// A value with its associated Merkle proof.
#[derive(Debug, PartialEq)]
pub struct ValueWithProof<T> {
    value: T,
    merkle_proof: Vec<TrieMerkleProof<Key, StoredValue>>,
}

impl<T> ValueWithProof<T> {
    /// Constructs a new `ValueWithProof`.
    pub fn new(value: T, merkle_proof: Vec<TrieMerkleProof<Key, StoredValue>>) -> Self {
        Self {
            value,
            merkle_proof,
        }
    }

    /// Returns the value.
    pub fn value(&self) -> &T {
        &self.value
    }

    /// Returns the Merkle proof.
    pub fn merkle_proof(&self) -> &[TrieMerkleProof<Key, StoredValue>] {
        &self.merkle_proof
    }

    /// Converts `self` into the value and Merkle proof.
    pub fn into_inner(self) -> (T, Vec<TrieMerkleProof<Key, StoredValue>>) {
        (self.value, self.merkle_proof)
    }
}

impl<T: ToBytes> ToBytes for ValueWithProof<T> {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        self.write_bytes(&mut buffer)?;
        Ok(buffer)
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.value.write_bytes(writer)?;
        self.merkle_proof.write_bytes(writer)
    }

    fn serialized_length(&self) -> usize {
        self.value.serialized_length() + self.merkle_proof.serialized_length()
    }
}

impl<T: FromBytes> FromBytes for ValueWithProof<T> {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (value, remainder) = FromBytes::from_bytes(bytes)?;
        let (merkle_proof, remainder) = FromBytes::from_bytes(remainder)?;
        Ok((ValueWithProof::new(value, merkle_proof), remainder))
    }
}

impl_bytesrepr_for_type_wrapper!(Uptime);
impl_bytesrepr_for_type_wrapper!(ConsensusValidatorChanges);
impl_bytesrepr_for_type_wrapper!(NetworkName);
impl_bytesrepr_for_type_wrapper!(ReactorStateName);
impl_bytesrepr_for_type_wrapper!(LastProgress);
impl_bytesrepr_for_type_wrapper!(GetTrieFullResult);

#[cfg(test)]
mod tests {
    use core::iter::FromIterator;
    use rand::Rng;

    use super::*;
    use casper_types::{
        contracts::ContractPackageHash, execution::ExecutionResult, testing::TestRng, BlockHash,
        CLValue, ContractWasmHash, StoredValue,
    };

    #[test]
    fn uptime_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&Uptime::new(rng.gen()));
    }

    #[test]
    fn consensus_validator_changes_roundtrip() {
        let rng = &mut TestRng::new();
        let map = BTreeMap::from_iter([(
            PublicKey::random(rng),
            vec![(EraId::random(rng), ValidatorChange::random(rng))],
        )]);
        bytesrepr::test_serialization_roundtrip(&ConsensusValidatorChanges::new(map));
    }

    #[test]
    fn network_name_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&NetworkName::new(rng.random_string(5..20)));
    }

    #[test]
    fn reactor_state_name_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&ReactorStateName::new(rng.random_string(5..20)));
    }

    #[test]
    fn last_progress_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&LastProgress::new(Timestamp::random(rng)));
    }

    #[test]
    fn get_trie_full_result_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&GetTrieFullResult::new(rng.gen()));
    }

    #[test]
    fn reward_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&RewardResponse::new(
            rng.gen(),
            EraId::random(rng),
            rng.gen(),
            BlockHash::random(rng),
        ));
    }

    #[test]
    fn consensus_status_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&ConsensusStatus::new(
            PublicKey::random(rng),
            Some(TimeDiff::from_millis(rng.gen())),
        ));
    }

    #[test]
    fn transaction_with_execution_info_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&TransactionWithExecutionInfo::new(
            Transaction::random(rng),
            rng.gen::<bool>().then(|| ExecutionInfo {
                block_hash: BlockHash::random(rng),
                block_height: rng.gen(),
                execution_result: rng.gen::<bool>().then(|| ExecutionResult::random(rng)),
            }),
        ));
    }

    #[test]
    fn dictionary_query_result_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&DictionaryQueryResult::new(
            Key::Account(rng.gen()),
            GlobalStateQueryResult::new(
                StoredValue::CLValue(CLValue::from_t(rng.gen::<i32>()).unwrap()),
                vec![],
            ),
        ));
    }

    #[test]
    fn contract_with_wasm_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&ContractInformation::new(
            ContractHash::new(rng.gen()),
            ValueWithProof::new(
                Contract::new(
                    ContractPackageHash::new(rng.gen()),
                    ContractWasmHash::new(rng.gen()),
                    Default::default(),
                    Default::default(),
                    Default::default(),
                ),
                Default::default(),
            ),
            rng.gen::<bool>().then(|| {
                ValueWithProof::new(
                    ContractWasm::new(rng.random_vec(10..50)),
                    Default::default(),
                )
            }),
        ));
    }

    #[test]
    fn addressable_entity_with_byte_code_roundtrip() {
        let rng = &mut TestRng::new();
        bytesrepr::test_serialization_roundtrip(&AddressableEntityInformation::new(
            rng.gen(),
            ValueWithProof::new(AddressableEntity::example().clone(), Default::default()),
            rng.gen::<bool>().then(|| {
                ValueWithProof::new(
                    ByteCode::new(rng.gen(), rng.random_vec(10..50)),
                    Default::default(),
                )
            }),
        ));
    }
}