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

use std::{collections::BTreeSet, fmt::Debug};

use async_graphql::SimpleObject;
use linera_base::{
    crypto::{BcsHashable, CryptoHash},
    data_types::{BlockHeight, Event, OracleResponse, Timestamp},
    hashed::Hashed,
    identifiers::{BlobId, BlobType, ChainId, MessageId, Owner},
};
use linera_execution::{committee::Epoch, BlobState, Operation, SystemOperation};
use serde::{ser::SerializeStruct, Deserialize, Serialize};
use thiserror::Error;

use crate::{
    data_types::{
        BlockExecutionOutcome, ExecutedBlock, IncomingBundle, Medium, MessageBundle,
        OutgoingMessage, ProposedBlock,
    },
    types::CertificateValue,
    ChainError,
};

/// Wrapper around an `ExecutedBlock` that has been validated.
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ValidatedBlock(Hashed<Block>);

impl ValidatedBlock {
    /// Creates a new `ValidatedBlock` from an `ExecutedBlock`.
    pub fn new(block: ExecutedBlock) -> Self {
        Self(Hashed::new(Block::new(block.block, block.outcome)))
    }

    pub fn from_hashed(block: Hashed<Block>) -> Self {
        Self(block)
    }

    pub fn inner(&self) -> &Hashed<Block> {
        &self.0
    }

    /// Returns a reference to the [`Block`] contained in this `ValidatedBlock`.
    pub fn block(&self) -> &Block {
        self.0.inner()
    }

    /// Consumes this `ValidatedBlock`, returning the [`Block`] it contains.
    pub fn into_inner(self) -> Block {
        self.0.into_inner()
    }

    pub fn to_log_str(&self) -> &'static str {
        "validated_block"
    }

    pub fn chain_id(&self) -> ChainId {
        self.0.inner().header.chain_id
    }

    pub fn height(&self) -> BlockHeight {
        self.0.inner().header.height
    }

    pub fn epoch(&self) -> Epoch {
        self.0.inner().header.epoch
    }
}

impl<'de> BcsHashable<'de> for ValidatedBlock {}

/// Wrapper around an `ExecutedBlock` that has been confirmed.
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ConfirmedBlock(Hashed<Block>);

#[async_graphql::Object(cache_control(no_cache))]
impl ConfirmedBlock {
    #[graphql(derived(name = "block"))]
    async fn _block(&self) -> Block {
        self.0.inner().clone()
    }

    async fn status(&self) -> String {
        "confirmed".to_string()
    }
}

impl<'de> BcsHashable<'de> for ConfirmedBlock {}

impl ConfirmedBlock {
    pub fn new(block: ExecutedBlock) -> Self {
        Self(Hashed::new(Block::new(block.block, block.outcome)))
    }

    pub fn from_hashed(block: Hashed<Block>) -> Self {
        Self(block)
    }

    pub fn inner(&self) -> &Hashed<Block> {
        &self.0
    }

    pub fn into_inner(self) -> Hashed<Block> {
        self.0
    }

    /// Returns a reference to the `ExecutedBlock` contained in this `ConfirmedBlock`.
    pub fn block(&self) -> &Block {
        self.0.inner()
    }

    /// Consumes this `ConfirmedBlock`, returning the `ExecutedBlock` it contains.
    pub fn into_block(self) -> Block {
        self.0.into_inner()
    }

    pub fn chain_id(&self) -> ChainId {
        self.0.inner().header.chain_id
    }

    pub fn height(&self) -> BlockHeight {
        self.0.inner().header.height
    }

    pub fn to_log_str(&self) -> &'static str {
        "confirmed_block"
    }

    /// Creates a `HashedCertificateValue` without checking that this is the correct hash!
    pub fn with_hash_unchecked(self, hash: CryptoHash) -> Hashed<ConfirmedBlock> {
        Hashed::unchecked_new(self, hash)
    }

    fn with_hash(self) -> Hashed<Self> {
        let hash = CryptoHash::new(&self);
        Hashed::unchecked_new(self, hash)
    }

    /// Creates a `HashedCertificateValue` checking that this is the correct hash.
    pub fn with_hash_checked(self, hash: CryptoHash) -> Result<Hashed<ConfirmedBlock>, ChainError> {
        let hashed_certificate_value = self.with_hash();
        if hashed_certificate_value.hash() == hash {
            Ok(hashed_certificate_value)
        } else {
            Err(ChainError::CertificateValueHashMismatch {
                expected: hash,
                actual: hashed_certificate_value.hash(),
            })
        }
    }

    /// Returns whether this block matches the proposal.
    pub fn matches_proposed_block(&self, block: &ProposedBlock) -> bool {
        let ProposedBlock {
            chain_id,
            epoch,
            incoming_bundles,
            operations,
            height,
            timestamp,
            authenticated_signer,
            previous_block_hash,
        } = block;
        *chain_id == self.chain_id()
            && *epoch == self.epoch()
            && *incoming_bundles == self.block().body.incoming_bundles
            && *operations == self.block().body.operations
            && *height == self.block().header.height
            && *timestamp == self.block().header.timestamp
            && *authenticated_signer == self.block().header.authenticated_signer
            && *previous_block_hash == self.block().header.previous_block_hash
    }

    /// Returns a blob state that applies to all blobs used by this block.
    pub fn to_blob_state(&self) -> BlobState {
        BlobState {
            last_used_by: self.0.hash(),
            chain_id: self.chain_id(),
            block_height: self.height(),
            epoch: self.epoch(),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Hash, Clone, Deserialize, Serialize)]
pub struct Timeout {
    pub chain_id: ChainId,
    pub height: BlockHeight,
    pub epoch: Epoch,
}

impl Timeout {
    pub fn new(chain_id: ChainId, height: BlockHeight, epoch: Epoch) -> Self {
        Self {
            chain_id,
            height,
            epoch,
        }
    }

    pub fn to_log_str(&self) -> &'static str {
        "timeout"
    }

    pub fn chain_id(&self) -> ChainId {
        self.chain_id
    }

    pub fn height(&self) -> BlockHeight {
        self.height
    }

    pub fn epoch(&self) -> Epoch {
        self.epoch
    }
}

impl<'de> BcsHashable<'de> for Timeout {}

/// Failure to convert a `Certificate` into one of the expected certificate types.
#[derive(Clone, Copy, Debug, Error)]
pub enum ConversionError {
    /// Failure to convert to [`ConfirmedBlock`] certificate.
    #[error("Expected a `ConfirmedBlockCertificate` value")]
    ConfirmedBlock,

    /// Failure to convert to [`ValidatedBlock`] certificate.
    #[error("Expected a `ValidatedBlockCertificate` value")]
    ValidatedBlock,

    /// Failure to convert to [`Timeout`] certificate.
    #[error("Expected a `TimeoutCertificate` value")]
    Timeout,
}

/// Block defines the atomic unit of growth of the Linera chain.
///
/// As part of the block body, contains all the incoming messages
/// and operations to execute which define a state transition of the chain.
/// Resulting messages produced by the operations are also included in the block body,
/// together with oracle responses and events.
#[derive(Debug, PartialEq, Eq, Hash, Clone, SimpleObject)]
pub struct Block {
    /// Header of the block containing metadata of the block.
    pub header: BlockHeader,
    /// Body of the block containing all of the data.
    pub body: BlockBody,
}

impl Serialize for Block {
    fn serialize<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut state = serializer.serialize_struct("Block", 2)?;

        let header = SerializedHeader {
            chain_id: self.header.chain_id,
            epoch: self.header.epoch,
            height: self.header.height,
            timestamp: self.header.timestamp,
            state_hash: self.header.state_hash,
            previous_block_hash: self.header.previous_block_hash,
            authenticated_signer: self.header.authenticated_signer,
        };
        state.serialize_field("header", &header)?;
        state.serialize_field("body", &self.body)?;
        state.end()
    }
}

impl<'de> Deserialize<'de> for Block {
    fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(rename = "Block")]
        struct Inner {
            header: SerializedHeader,
            body: BlockBody,
        }
        let inner = Inner::deserialize(deserializer)?;

        let bundles_hash = hashing::hash_vec(&inner.body.incoming_bundles);
        let messages_hash = hashing::hash_vec_vec(&inner.body.messages);
        let operations_hash = hashing::hash_vec(&inner.body.operations);
        let oracle_responses_hash = hashing::hash_vec_vec(&inner.body.oracle_responses);
        let events_hash = hashing::hash_vec_vec(&inner.body.events);

        let header = BlockHeader {
            chain_id: inner.header.chain_id,
            epoch: inner.header.epoch,
            height: inner.header.height,
            timestamp: inner.header.timestamp,
            state_hash: inner.header.state_hash,
            previous_block_hash: inner.header.previous_block_hash,
            authenticated_signer: inner.header.authenticated_signer,
            bundles_hash,
            operations_hash,
            messages_hash,
            oracle_responses_hash,
            events_hash,
        };

        Ok(Self {
            header,
            body: inner.body,
        })
    }
}

/// Succinct representation of a block.
/// Contains all the metadata to follow the chain of blocks or verifying
/// inclusion (event, message, oracle response, etc.) in the block's body.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, SimpleObject)]
pub struct BlockHeader {
    /// The chain to which this block belongs.
    pub chain_id: ChainId,
    /// The number identifying the current configuration.
    pub epoch: Epoch,
    /// The block height.
    pub height: BlockHeight,
    /// The timestamp when this block was created.
    pub timestamp: Timestamp,
    /// The hash of the chain's execution state after this block.
    pub state_hash: CryptoHash,
    /// Certified hash of the previous block in the chain, if any.
    pub previous_block_hash: Option<CryptoHash>,
    /// The user signing for the operations in the block and paying for their execution
    /// fees. If set, this must be the `owner` in the block proposal. `None` means that
    /// the default account of the chain is used. This value is also used as recipient of
    /// potential refunds for the message grants created by the operations.
    pub authenticated_signer: Option<Owner>,

    // Inputs to the block, chosen by the block proposer.
    /// Cryptographic hash of all the incoming bundles in the block.
    pub bundles_hash: CryptoHash,
    /// Cryptographic hash of all the operations in the block.
    pub operations_hash: CryptoHash,

    // Outcome of the block execution.
    /// Cryptographic hash of all the messages in the block.
    pub messages_hash: CryptoHash,
    /// Cryptographic hash of all the oracle responses in the block.
    pub oracle_responses_hash: CryptoHash,
    /// Cryptographic hash of all the events in the block.
    pub events_hash: CryptoHash,
}

/// The body of a block containing all the data included in the block.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, SimpleObject)]
pub struct BlockBody {
    /// A selection of incoming messages to be executed first. Successive messages of the same
    /// sender and height are grouped together for conciseness.
    pub incoming_bundles: Vec<IncomingBundle>,
    /// The operations to execute.
    pub operations: Vec<Operation>,
    /// The list of outgoing messages for each transaction.
    pub messages: Vec<Vec<OutgoingMessage>>,
    /// The record of oracle responses for each transaction.
    pub oracle_responses: Vec<Vec<OracleResponse>>,
    /// The list of events produced by each transaction.
    pub events: Vec<Vec<Event>>,
}

impl Block {
    pub fn new(block: ProposedBlock, outcome: BlockExecutionOutcome) -> Self {
        let bundles_hash = hashing::hash_vec(&block.incoming_bundles);
        let messages_hash = hashing::hash_vec_vec(&outcome.messages);
        let operations_hash = hashing::hash_vec(&block.operations);
        let oracle_responses_hash = hashing::hash_vec_vec(&outcome.oracle_responses);
        let events_hash = hashing::hash_vec_vec(&outcome.events);

        let header = BlockHeader {
            chain_id: block.chain_id,
            epoch: block.epoch,
            height: block.height,
            timestamp: block.timestamp,
            state_hash: outcome.state_hash,
            previous_block_hash: block.previous_block_hash,
            authenticated_signer: block.authenticated_signer,
            bundles_hash,
            operations_hash,
            messages_hash,
            oracle_responses_hash,
            events_hash,
        };

        let body = BlockBody {
            incoming_bundles: block.incoming_bundles,
            operations: block.operations,
            messages: outcome.messages,
            oracle_responses: outcome.oracle_responses,
            events: outcome.events,
        };

        Self { header, body }
    }

    /// Returns the bundles of messages sent via the given medium to the specified
    /// recipient. Messages originating from different transactions of the original block
    /// are kept in separate bundles. If the medium is a channel, does not verify that the
    /// recipient is actually subscribed to that channel.
    pub fn message_bundles_for<'a>(
        &'a self,
        medium: &'a Medium,
        recipient: ChainId,
        certificate_hash: CryptoHash,
    ) -> impl Iterator<Item = (Epoch, MessageBundle)> + 'a {
        let mut index = 0u32;
        let block_height = self.header.height;
        let block_timestamp = self.header.timestamp;
        let block_epoch = self.header.epoch;

        (0u32..)
            .zip(self.messages())
            .filter_map(move |(transaction_index, txn_messages)| {
                let messages = (index..)
                    .zip(txn_messages)
                    .filter(|(_, message)| message.has_destination(medium, recipient))
                    .map(|(idx, message)| message.clone().into_posted(idx))
                    .collect::<Vec<_>>();
                index += txn_messages.len() as u32;
                (!messages.is_empty()).then(|| {
                    let bundle = MessageBundle {
                        height: block_height,
                        timestamp: block_timestamp,
                        certificate_hash,
                        transaction_index,
                        messages,
                    };
                    (block_epoch, bundle)
                })
            })
    }

    /// Returns the `message_index`th outgoing message created by the `operation_index`th operation,
    /// or `None` if there is no such operation or message.
    pub fn message_id_for_operation(
        &self,
        operation_index: usize,
        message_index: u32,
    ) -> Option<MessageId> {
        let block = &self.body;
        let transaction_index = block.incoming_bundles.len().checked_add(operation_index)?;
        if message_index >= u32::try_from(self.body.messages.get(transaction_index)?.len()).ok()? {
            return None;
        }
        let first_message_index = u32::try_from(
            self.body
                .messages
                .iter()
                .take(transaction_index)
                .map(Vec::len)
                .sum::<usize>(),
        )
        .ok()?;
        let index = first_message_index.checked_add(message_index)?;
        Some(self.message_id(index))
    }

    /// Returns the message ID belonging to the `index`th outgoing message in this block.
    pub fn message_id(&self, index: u32) -> MessageId {
        MessageId {
            chain_id: self.header.chain_id,
            height: self.header.height,
            index,
        }
    }

    /// Returns the outgoing message with the specified id, or `None` if there is no such message.
    pub fn message_by_id(&self, message_id: &MessageId) -> Option<&OutgoingMessage> {
        let MessageId {
            chain_id,
            height,
            index,
        } = message_id;
        if self.header.chain_id != *chain_id || self.header.height != *height {
            return None;
        }
        let mut index = usize::try_from(*index).ok()?;
        for messages in self.messages() {
            if let Some(message) = messages.get(index) {
                return Some(message);
            }
            index -= messages.len();
        }
        None
    }

    /// Returns all the blob IDs required by this block.
    /// Either as oracle responses or as published blobs.
    pub fn required_blob_ids(&self) -> BTreeSet<BlobId> {
        let mut blob_ids = self.oracle_blob_ids();
        blob_ids.extend(self.published_blob_ids());
        blob_ids
    }

    /// Returns whether this block requires the blob with the specified ID.
    pub fn requires_blob(&self, blob_id: &BlobId) -> bool {
        self.oracle_blob_ids().contains(blob_id) || self.published_blob_ids().contains(blob_id)
    }

    /// Returns all the published blob IDs in this block's operations.
    fn published_blob_ids(&self) -> BTreeSet<BlobId> {
        let mut blob_ids = BTreeSet::new();
        for operation in &self.body.operations {
            if let Operation::System(SystemOperation::PublishDataBlob { blob_hash }) = operation {
                blob_ids.insert(BlobId::new(*blob_hash, BlobType::Data));
            }
            if let Operation::System(SystemOperation::PublishBytecode { bytecode_id }) = operation {
                blob_ids.extend([
                    BlobId::new(bytecode_id.contract_blob_hash, BlobType::ContractBytecode),
                    BlobId::new(bytecode_id.service_blob_hash, BlobType::ServiceBytecode),
                ]);
            }
        }

        blob_ids
    }

    /// Returns set of blob IDs that were a result of an oracle call.
    pub fn oracle_blob_ids(&self) -> BTreeSet<BlobId> {
        let mut required_blob_ids = BTreeSet::new();
        for responses in &self.body.oracle_responses {
            for response in responses {
                if let OracleResponse::Blob(blob_id) = response {
                    required_blob_ids.insert(*blob_id);
                }
            }
        }

        required_blob_ids
    }

    /// Returns reference to the outgoing messages in the block.
    pub fn messages(&self) -> &Vec<Vec<OutgoingMessage>> {
        &self.body.messages
    }
}

impl From<Block> for ExecutedBlock {
    fn from(block: Block) -> Self {
        let Block {
            header:
                BlockHeader {
                    chain_id,
                    epoch,
                    height,
                    timestamp,
                    state_hash,
                    previous_block_hash,
                    authenticated_signer,
                    bundles_hash: _,
                    operations_hash: _,
                    messages_hash: _,
                    oracle_responses_hash: _,
                    events_hash: _,
                },
            body:
                BlockBody {
                    incoming_bundles,
                    operations,
                    messages,
                    oracle_responses,
                    events,
                },
        } = block;

        let block = ProposedBlock {
            chain_id,
            epoch,
            height,
            timestamp,
            incoming_bundles,
            operations,
            authenticated_signer,
            previous_block_hash,
        };

        let outcome = BlockExecutionOutcome {
            state_hash,
            messages,
            oracle_responses,
            events,
        };

        ExecutedBlock { block, outcome }
    }
}

impl<'de> BcsHashable<'de> for Block {}

#[derive(Serialize, Deserialize)]
#[serde(rename = "BlockHeader")]
struct SerializedHeader {
    chain_id: ChainId,
    epoch: Epoch,
    height: BlockHeight,
    timestamp: Timestamp,
    state_hash: CryptoHash,
    previous_block_hash: Option<CryptoHash>,
    authenticated_signer: Option<Owner>,
}

mod hashing {
    use linera_base::crypto::{BcsHashable, CryptoHash, CryptoHashVec};

    pub(super) fn hash_vec<'de, T: BcsHashable<'de>>(it: impl AsRef<[T]>) -> CryptoHash {
        let v = CryptoHashVec(it.as_ref().iter().map(CryptoHash::new).collect::<Vec<_>>());
        CryptoHash::new(&v)
    }

    pub(super) fn hash_vec_vec<'de, T: BcsHashable<'de>>(it: impl AsRef<[Vec<T>]>) -> CryptoHash {
        let v = CryptoHashVec(it.as_ref().iter().map(hash_vec).collect::<Vec<_>>());
        CryptoHash::new(&v)
    }
}