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
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Test utilities

use linera_base::{
    crypto::{AccountPublicKey, AccountSecretKey},
    data_types::{Amount, BlockHeight, Round, Timestamp},
    hashed::Hashed,
    identifiers::{ChainId, Owner},
};
use linera_execution::{
    committee::{Committee, Epoch, ValidatorState},
    system::Recipient,
    Message, MessageKind, Operation, ResourceControlPolicy, SystemOperation,
};

use crate::{
    block::ConfirmedBlock,
    data_types::{
        BlockProposal, IncomingBundle, PostedMessage, ProposedBlock, SignatureAggregator, Vote,
    },
    types::{CertificateValue, GenericCertificate},
};

/// Creates a new child of the given block, with the same timestamp.
pub fn make_child_block(parent: &Hashed<ConfirmedBlock>) -> ProposedBlock {
    let parent_value = parent.inner();
    let parent_header = &parent_value.block().header;
    ProposedBlock {
        epoch: parent_header.epoch,
        chain_id: parent_header.chain_id,
        incoming_bundles: vec![],
        operations: vec![],
        previous_block_hash: Some(parent.hash()),
        height: parent_header.height.try_add_one().unwrap(),
        authenticated_signer: parent_header.authenticated_signer,
        timestamp: parent_header.timestamp,
    }
}

/// Creates a block at height 0 for a new chain.
pub fn make_first_block(chain_id: ChainId) -> ProposedBlock {
    ProposedBlock {
        epoch: Epoch::ZERO,
        chain_id,
        incoming_bundles: vec![],
        operations: vec![],
        previous_block_hash: None,
        height: BlockHeight::ZERO,
        authenticated_signer: None,
        timestamp: Timestamp::default(),
    }
}

/// A helper trait to simplify constructing blocks for tests.
pub trait BlockTestExt: Sized {
    /// Returns the block with the given authenticated signer.
    fn with_authenticated_signer(self, authenticated_signer: Option<Owner>) -> Self;

    /// Returns the block with the given operation appended at the end.
    fn with_operation(self, operation: impl Into<Operation>) -> Self;

    /// Returns the block with a transfer operation appended at the end.
    fn with_transfer(self, owner: Option<Owner>, recipient: Recipient, amount: Amount) -> Self;

    /// Returns the block with a simple transfer operation appended at the end.
    fn with_simple_transfer(self, chain_id: ChainId, amount: Amount) -> Self;

    /// Returns the block with the given message appended at the end.
    fn with_incoming_bundle(self, incoming_bundle: IncomingBundle) -> Self;

    /// Returns the block with the specified timestamp.
    fn with_timestamp(self, timestamp: impl Into<Timestamp>) -> Self;

    /// Returns the block with the specified epoch.
    fn with_epoch(self, epoch: impl Into<Epoch>) -> Self;

    /// Returns a block proposal in the first round in a default ownership configuration
    /// (`Round::MultiLeader(0)`) without any hashed certificate values or validated block.
    fn into_first_proposal(self, key_pair: &AccountSecretKey) -> BlockProposal {
        self.into_proposal_with_round(key_pair, Round::MultiLeader(0))
    }

    /// Returns a block proposal without any hashed certificate values or validated block.
    fn into_proposal_with_round(self, key_pair: &AccountSecretKey, round: Round) -> BlockProposal;
}

impl BlockTestExt for ProposedBlock {
    fn with_authenticated_signer(mut self, authenticated_signer: Option<Owner>) -> Self {
        self.authenticated_signer = authenticated_signer;
        self
    }

    fn with_operation(mut self, operation: impl Into<Operation>) -> Self {
        self.operations.push(operation.into());
        self
    }

    fn with_transfer(self, owner: Option<Owner>, recipient: Recipient, amount: Amount) -> Self {
        self.with_operation(SystemOperation::Transfer {
            owner,
            recipient,
            amount,
        })
    }

    fn with_simple_transfer(self, chain_id: ChainId, amount: Amount) -> Self {
        self.with_transfer(None, Recipient::chain(chain_id), amount)
    }

    fn with_incoming_bundle(mut self, incoming_bundle: IncomingBundle) -> Self {
        self.incoming_bundles.push(incoming_bundle);
        self
    }

    fn with_timestamp(mut self, timestamp: impl Into<Timestamp>) -> Self {
        self.timestamp = timestamp.into();
        self
    }

    fn with_epoch(mut self, epoch: impl Into<Epoch>) -> Self {
        self.epoch = epoch.into();
        self
    }

    fn into_proposal_with_round(self, key_pair: &AccountSecretKey, round: Round) -> BlockProposal {
        BlockProposal::new_initial(round, self, key_pair)
    }
}

pub trait VoteTestExt<T>: Sized {
    /// Returns a certificate for a committee consisting only of this validator.
    fn into_certificate(self) -> GenericCertificate<T>;
}

impl<T: CertificateValue> VoteTestExt<T> for Vote<T> {
    fn into_certificate(self) -> GenericCertificate<T> {
        let state = ValidatorState {
            network_address: "".to_string(),
            votes: 100,
            account_public_key: AccountPublicKey::test_key(1),
        };
        let committee = Committee::new(
            vec![(self.public_key, state)].into_iter().collect(),
            ResourceControlPolicy::only_fuel(),
        );
        SignatureAggregator::new(self.value, self.round, &committee)
            .append(self.public_key, self.signature)
            .unwrap()
            .unwrap()
    }
}

/// Helper trait to simplify constructing messages for tests.
pub trait MessageTestExt: Sized {
    fn to_posted(self, index: u32, kind: MessageKind) -> PostedMessage;
}

impl<T: Into<Message>> MessageTestExt for T {
    fn to_posted(self, index: u32, kind: MessageKind) -> PostedMessage {
        PostedMessage {
            authenticated_signer: None,
            grant: Amount::ZERO,
            refund_grant_to: None,
            kind,
            index,
            message: self.into(),
        }
    }
}