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
// Copyright (c) 2021-2024 Espresso Systems (espressosys.com)
// This file is part of the HotShot repository.

// You should have received a copy of the MIT License
// along with the HotShot repository. If not, see <https://mit-license.org/>.

use std::{
    fmt::{Debug, Display},
    mem::size_of,
    sync::Arc,
};

use async_trait::async_trait;
use committable::{Commitment, Committable, RawCommitmentBuilder};
use hotshot_types::{
    data::{BlockError, Leaf2},
    traits::{
        block_contents::{BlockHeader, BuilderFee, EncodeBytes, TestableBlock, Transaction},
        node_implementation::NodeType,
        BlockPayload, ValidatedState,
    },
    utils::BuilderCommitment,
    vid::{VidCommitment, VidCommon},
};
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use sha3::{Digest, Keccak256};
use thiserror::Error;
use time::OffsetDateTime;
use vbs::version::Version;

use crate::{
    auction_results_provider_types::TestAuctionResult,
    node_types::TestTypes,
    state_types::{TestInstanceState, TestValidatedState},
    testable_delay::{DelayConfig, SupportedTraitTypesForAsyncDelay, TestableDelay},
};

/// The transaction in a [`TestBlockPayload`].
#[derive(Default, PartialEq, Eq, Hash, Serialize, Deserialize, Clone, Debug)]
#[serde(try_from = "Vec<u8>")]
pub struct TestTransaction(Vec<u8>);

#[derive(Debug, Error)]
pub enum TransactionError {
    #[error("Transaction too long")]
    TransactionTooLong,
}

impl TryFrom<Vec<u8>> for TestTransaction {
    type Error = TransactionError;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        Self::try_new(value).ok_or(TransactionError::TransactionTooLong)
    }
}

impl TestTransaction {
    /// Construct a new transaction
    ///
    /// # Panics
    /// If `bytes.len()` > `u32::MAX`
    pub fn new(bytes: Vec<u8>) -> Self {
        Self::try_new(bytes).expect("Vector too long")
    }

    /// Construct a new transaction.
    /// Returns `None` if `bytes.len()` > `u32::MAX`
    /// for cross-platform compatibility
    pub fn try_new(bytes: Vec<u8>) -> Option<Self> {
        if u32::try_from(bytes.len()).is_err() {
            None
        } else {
            Some(Self(bytes))
        }
    }

    /// Get reference to raw bytes of transaction
    pub fn bytes(&self) -> &Vec<u8> {
        &self.0
    }

    /// Convert transaction to raw vector of bytes
    pub fn into_bytes(self) -> Vec<u8> {
        self.0
    }

    /// Encode a list of transactions into bytes.
    ///
    /// # Errors
    /// If the transaction length conversion fails.
    pub fn encode(transactions: &[Self]) -> Vec<u8> {
        let mut encoded = Vec::new();

        for txn in transactions {
            // The transaction length is converted from `usize` to `u32` to ensure consistent
            // number of bytes on different platforms.
            let txn_size = u32::try_from(txn.0.len())
                .expect("Invalid transaction length")
                .to_le_bytes();

            // Concatenate the bytes of the transaction size and the transaction itself.
            encoded.extend(txn_size);
            encoded.extend(&txn.0);
        }

        encoded
    }
}

impl Committable for TestTransaction {
    fn commit(&self) -> Commitment<Self> {
        let builder = committable::RawCommitmentBuilder::new("Txn Comm");
        let mut hasher = Keccak256::new();
        hasher.update(&self.0);
        let generic_array = hasher.finalize();
        builder.generic_byte_array(&generic_array).finalize()
    }

    fn tag() -> String {
        "TEST_TXN".to_string()
    }
}

impl Transaction for TestTransaction {
    fn minimum_block_size(&self) -> u64 {
        // the estimation on transaction size is the length of the transaction
        self.0.len() as u64
    }
}

/// A [`BlockPayload`] that contains a list of `TestTransaction`.
#[derive(PartialEq, Eq, Hash, Serialize, Deserialize, Clone, Debug)]
pub struct TestBlockPayload {
    /// List of transactions.
    pub transactions: Vec<TestTransaction>,
}

impl TestBlockPayload {
    /// Create a genesis block payload with bytes `vec![0]`, to be used for
    /// consensus task initiation.
    /// # Panics
    /// If the `VidScheme` construction fails.
    #[must_use]
    pub fn genesis() -> Self {
        TestBlockPayload {
            transactions: vec![],
        }
    }
}

impl Display for TestBlockPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "BlockPayload #txns={}", self.transactions.len())
    }
}

impl<TYPES: NodeType> TestableBlock<TYPES> for TestBlockPayload {
    fn genesis() -> Self {
        Self::genesis()
    }

    fn txn_count(&self) -> u64 {
        self.transactions.len() as u64
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TestMetadata {
    pub num_transactions: u64,
}

impl EncodeBytes for TestMetadata {
    fn encode(&self) -> Arc<[u8]> {
        Arc::new([])
    }
}

impl EncodeBytes for TestBlockPayload {
    fn encode(&self) -> Arc<[u8]> {
        TestTransaction::encode(&self.transactions).into()
    }
}

#[async_trait]
impl<TYPES: NodeType> BlockPayload<TYPES> for TestBlockPayload {
    type Error = BlockError;
    type Instance = TestInstanceState;
    type Transaction = TestTransaction;
    type Metadata = TestMetadata;
    type ValidatedState = TestValidatedState;

    async fn from_transactions(
        transactions: impl IntoIterator<Item = Self::Transaction> + Send,
        _validated_state: &Self::ValidatedState,
        _instance_state: &Self::Instance,
    ) -> Result<(Self, Self::Metadata), Self::Error> {
        let txns_vec: Vec<TestTransaction> = transactions.into_iter().collect();
        let metadata = TestMetadata {
            num_transactions: txns_vec.len() as u64,
        };
        Ok((
            Self {
                transactions: txns_vec,
            },
            metadata,
        ))
    }

    fn from_bytes(encoded_transactions: &[u8], _metadata: &Self::Metadata) -> Self {
        let mut transactions = Vec::new();
        let mut current_index = 0;
        while current_index < encoded_transactions.len() {
            // Decode the transaction length.
            let txn_start_index = current_index + size_of::<u32>();
            let mut txn_len_bytes = [0; size_of::<u32>()];
            txn_len_bytes.copy_from_slice(&encoded_transactions[current_index..txn_start_index]);
            let txn_len: usize = u32::from_le_bytes(txn_len_bytes) as usize;

            // Get the transaction.
            let next_index = txn_start_index + txn_len;
            transactions.push(TestTransaction(
                encoded_transactions[txn_start_index..next_index].to_vec(),
            ));
            current_index = next_index;
        }

        Self { transactions }
    }

    fn empty() -> (Self, Self::Metadata) {
        (
            Self::genesis(),
            TestMetadata {
                num_transactions: 0,
            },
        )
    }

    fn builder_commitment(&self, _metadata: &Self::Metadata) -> BuilderCommitment {
        let mut digest = sha2::Sha256::new();
        for txn in &self.transactions {
            digest.update(&txn.0);
        }
        BuilderCommitment::from_raw_digest(digest.finalize())
    }

    fn transactions<'a>(
        &'a self,
        _metadata: &'a Self::Metadata,
    ) -> impl 'a + Iterator<Item = Self::Transaction> {
        self.transactions.iter().cloned()
    }
}

/// A [`BlockHeader`] that commits to [`TestBlockPayload`].
#[derive(PartialEq, Eq, Hash, Clone, Debug, Deserialize, Serialize)]
pub struct TestBlockHeader {
    /// Block number.
    pub block_number: u64,
    /// VID commitment to the payload.
    pub payload_commitment: VidCommitment,
    /// Fast commitment for builder verification
    pub builder_commitment: BuilderCommitment,
    /// block metadata
    pub metadata: TestMetadata,
    /// Timestamp when this header was created.
    pub timestamp: u64,
    /// random
    pub random: u64,
}

impl TestBlockHeader {
    pub fn new<TYPES: NodeType<BlockHeader = Self>>(
        parent_leaf: &Leaf2<TYPES>,
        payload_commitment: VidCommitment,
        builder_commitment: BuilderCommitment,
        metadata: TestMetadata,
    ) -> Self {
        let parent = parent_leaf.block_header();

        let mut timestamp = OffsetDateTime::now_utc().unix_timestamp() as u64;
        if timestamp < parent.timestamp {
            // Prevent decreasing timestamps.
            timestamp = parent.timestamp;
        }

        let random = thread_rng().gen_range(0..=u64::MAX);

        Self {
            block_number: parent.block_number + 1,
            payload_commitment,
            builder_commitment,
            metadata,
            timestamp,
            random,
        }
    }
}

impl<
        TYPES: NodeType<
            BlockHeader = Self,
            BlockPayload = TestBlockPayload,
            InstanceState = TestInstanceState,
            AuctionResult = TestAuctionResult,
        >,
    > BlockHeader<TYPES> for TestBlockHeader
{
    type Error = std::convert::Infallible;

    async fn new_legacy(
        _parent_state: &TYPES::ValidatedState,
        instance_state: &<TYPES::ValidatedState as ValidatedState<TYPES>>::Instance,
        parent_leaf: &Leaf2<TYPES>,
        payload_commitment: VidCommitment,
        builder_commitment: BuilderCommitment,
        metadata: <TYPES::BlockPayload as BlockPayload<TYPES>>::Metadata,
        _builder_fee: BuilderFee<TYPES>,
        _vid_common: VidCommon,
        _version: Version,
    ) -> Result<Self, Self::Error> {
        Self::run_delay_settings_from_config(&instance_state.delay_config).await;
        Ok(Self::new(
            parent_leaf,
            payload_commitment,
            builder_commitment,
            metadata,
        ))
    }

    async fn new_marketplace(
        _parent_state: &TYPES::ValidatedState,
        instance_state: &<TYPES::ValidatedState as ValidatedState<TYPES>>::Instance,
        parent_leaf: &Leaf2<TYPES>,
        payload_commitment: VidCommitment,
        builder_commitment: BuilderCommitment,
        metadata: <TYPES::BlockPayload as BlockPayload<TYPES>>::Metadata,
        _builder_fee: Vec<BuilderFee<TYPES>>,
        _view_number: u64,
        _vid_common: VidCommon,
        _auction_results: Option<TYPES::AuctionResult>,
        _version: Version,
    ) -> Result<Self, Self::Error> {
        Self::run_delay_settings_from_config(&instance_state.delay_config).await;
        Ok(Self::new(
            parent_leaf,
            payload_commitment,
            builder_commitment,
            metadata,
        ))
    }

    fn genesis(
        _instance_state: &<TYPES::ValidatedState as ValidatedState<TYPES>>::Instance,
        payload_commitment: VidCommitment,
        builder_commitment: BuilderCommitment,
        _metadata: <TYPES::BlockPayload as BlockPayload<TYPES>>::Metadata,
    ) -> Self {
        let metadata = TestMetadata {
            num_transactions: 0,
        };

        Self {
            block_number: 0,
            payload_commitment,
            builder_commitment,
            metadata,
            timestamp: 0,
            random: 0,
        }
    }

    fn block_number(&self) -> u64 {
        self.block_number
    }

    fn payload_commitment(&self) -> VidCommitment {
        self.payload_commitment
    }

    fn metadata(&self) -> &<TYPES::BlockPayload as BlockPayload<TYPES>>::Metadata {
        &self.metadata
    }

    fn builder_commitment(&self) -> BuilderCommitment {
        self.builder_commitment.clone()
    }

    fn get_auction_results(&self) -> Option<TYPES::AuctionResult> {
        Some(TYPES::AuctionResult { urls: vec![] })
    }
}

impl Committable for TestBlockHeader {
    fn commit(&self) -> Commitment<Self> {
        RawCommitmentBuilder::new("Header Comm")
            .u64_field(
                "block number",
                <TestBlockHeader as BlockHeader<TestTypes>>::block_number(self),
            )
            .constant_str("payload commitment")
            .fixed_size_bytes(
                <TestBlockHeader as BlockHeader<TestTypes>>::payload_commitment(self)
                    .as_ref()
                    .as_ref(),
            )
            .finalize()
    }

    fn tag() -> String {
        "TEST_HEADER".to_string()
    }
}

#[async_trait]
impl TestableDelay for TestBlockHeader {
    async fn run_delay_settings_from_config(delay_config: &DelayConfig) {
        if let Some(settings) =
            delay_config.get_setting(&SupportedTraitTypesForAsyncDelay::BlockHeader)
        {
            Self::handle_async_delay(settings).await;
        }
    }
}