linera_chain/test/
mod.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Test utilities
5
6mod http_server;
7
8use linera_base::{
9    crypto::{AccountPublicKey, Signer, ValidatorPublicKey},
10    data_types::{Amount, BlockHeight, Epoch, Round, Timestamp},
11    identifiers::{Account, AccountOwner, ChainId},
12};
13use linera_execution::{
14    committee::{Committee, ValidatorState},
15    Message, MessageKind, Operation, ResourceControlPolicy, SystemOperation,
16};
17
18pub use self::http_server::HttpServer;
19use crate::{
20    block::ConfirmedBlock,
21    data_types::{
22        BlockProposal, IncomingBundle, PostedMessage, ProposedBlock, SignatureAggregator,
23        Transaction, Vote,
24    },
25    types::{CertificateValue, GenericCertificate},
26};
27
28/// Creates a new child of the given block, with the same timestamp.
29pub fn make_child_block(parent: &ConfirmedBlock) -> ProposedBlock {
30    let parent_header = &parent.block().header;
31    ProposedBlock {
32        epoch: parent_header.epoch,
33        chain_id: parent_header.chain_id,
34        transactions: vec![],
35        previous_block_hash: Some(parent.hash()),
36        height: parent_header.height.try_add_one().unwrap(),
37        authenticated_signer: parent_header.authenticated_signer,
38        timestamp: parent_header.timestamp,
39    }
40}
41
42/// Creates a block at height 0 for a new chain.
43pub fn make_first_block(chain_id: ChainId) -> ProposedBlock {
44    ProposedBlock {
45        epoch: Epoch::ZERO,
46        chain_id,
47        transactions: vec![],
48        previous_block_hash: None,
49        height: BlockHeight::ZERO,
50        authenticated_signer: None,
51        timestamp: Timestamp::default(),
52    }
53}
54
55/// A helper trait to simplify constructing blocks for tests.
56#[allow(async_fn_in_trait)]
57pub trait BlockTestExt: Sized {
58    /// Returns the block with the given authenticated signer.
59    fn with_authenticated_signer(self, authenticated_signer: Option<AccountOwner>) -> Self;
60
61    /// Returns the block with the given operation appended at the end.
62    fn with_operation(self, operation: impl Into<Operation>) -> Self;
63
64    /// Returns the block with a transfer operation appended at the end.
65    fn with_transfer(self, owner: AccountOwner, recipient: Account, amount: Amount) -> Self;
66
67    /// Returns the block with a simple transfer operation appended at the end.
68    fn with_simple_transfer(self, chain_id: ChainId, amount: Amount) -> Self;
69
70    /// Returns the block with the given message appended at the end.
71    fn with_incoming_bundle(self, incoming_bundle: IncomingBundle) -> Self;
72
73    /// Returns the block with the specified timestamp.
74    fn with_timestamp(self, timestamp: impl Into<Timestamp>) -> Self;
75
76    /// Returns the block with the specified epoch.
77    fn with_epoch(self, epoch: impl Into<Epoch>) -> Self;
78
79    /// Returns the block with the burn operation (transfer to a special address) appended at the end.
80    fn with_burn(self, amount: Amount) -> Self;
81
82    /// Returns a block proposal in the first round in a default ownership configuration
83    /// (`Round::MultiLeader(0)`) without any hashed certificate values or validated block.
84    async fn into_first_proposal<S: Signer + ?Sized>(
85        self,
86        owner: AccountOwner,
87        signer: &S,
88    ) -> Result<BlockProposal, S::Error> {
89        self.into_proposal_with_round(owner, signer, Round::MultiLeader(0))
90            .await
91    }
92
93    /// Returns a block proposal without any hashed certificate values or validated block.
94    async fn into_proposal_with_round<S: Signer + ?Sized>(
95        self,
96        owner: AccountOwner,
97        signer: &S,
98        round: Round,
99    ) -> Result<BlockProposal, S::Error>;
100}
101
102impl BlockTestExt for ProposedBlock {
103    fn with_authenticated_signer(mut self, authenticated_signer: Option<AccountOwner>) -> Self {
104        self.authenticated_signer = authenticated_signer;
105        self
106    }
107
108    fn with_operation(mut self, operation: impl Into<Operation>) -> Self {
109        self.transactions
110            .push(Transaction::ExecuteOperation(operation.into()));
111        self
112    }
113
114    fn with_transfer(self, owner: AccountOwner, recipient: Account, amount: Amount) -> Self {
115        self.with_operation(SystemOperation::Transfer {
116            owner,
117            recipient,
118            amount,
119        })
120    }
121
122    fn with_simple_transfer(self, chain_id: ChainId, amount: Amount) -> Self {
123        self.with_transfer(AccountOwner::CHAIN, Account::chain(chain_id), amount)
124    }
125
126    fn with_burn(self, amount: Amount) -> Self {
127        let recipient = Account::burn_address(self.chain_id);
128        self.with_operation(SystemOperation::Transfer {
129            owner: AccountOwner::CHAIN,
130            recipient,
131            amount,
132        })
133    }
134
135    fn with_incoming_bundle(mut self, incoming_bundle: IncomingBundle) -> Self {
136        self.transactions
137            .push(Transaction::ReceiveMessages(incoming_bundle));
138        self
139    }
140
141    fn with_timestamp(mut self, timestamp: impl Into<Timestamp>) -> Self {
142        self.timestamp = timestamp.into();
143        self
144    }
145
146    fn with_epoch(mut self, epoch: impl Into<Epoch>) -> Self {
147        self.epoch = epoch.into();
148        self
149    }
150
151    async fn into_proposal_with_round<S: Signer + ?Sized>(
152        self,
153        owner: AccountOwner,
154        signer: &S,
155        round: Round,
156    ) -> Result<BlockProposal, S::Error> {
157        BlockProposal::new_initial(owner, round, self, signer).await
158    }
159}
160
161pub trait VoteTestExt<T: CertificateValue>: Sized {
162    /// Returns a certificate for a committee consisting only of this validator.
163    fn into_certificate(self, public_key: ValidatorPublicKey) -> GenericCertificate<T>;
164}
165
166impl<T: CertificateValue> VoteTestExt<T> for Vote<T> {
167    fn into_certificate(self, public_key: ValidatorPublicKey) -> GenericCertificate<T> {
168        let state = ValidatorState {
169            network_address: "".to_string(),
170            votes: 100,
171            account_public_key: AccountPublicKey::test_key(1),
172        };
173        let committee = Committee::new(
174            vec![(public_key, state)].into_iter().collect(),
175            ResourceControlPolicy::only_fuel(),
176        );
177        SignatureAggregator::new(self.value, self.round, &committee)
178            .append(public_key, self.signature)
179            .unwrap()
180            .unwrap()
181    }
182}
183
184/// Helper trait to simplify constructing messages for tests.
185pub trait MessageTestExt: Sized {
186    fn to_posted(self, index: u32, kind: MessageKind) -> PostedMessage;
187}
188
189impl<T: Into<Message>> MessageTestExt for T {
190    fn to_posted(self, index: u32, kind: MessageKind) -> PostedMessage {
191        PostedMessage {
192            authenticated_signer: None,
193            grant: Amount::ZERO,
194            refund_grant_to: None,
195            kind,
196            index,
197            message: self.into(),
198        }
199    }
200}