everscale_types/models/block/
mod.rs

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
//! Block models.

#[cfg(feature = "sync")]
use std::sync::OnceLock;

use crate::cell::*;
use crate::dict::Dict;
use crate::error::Error;
use crate::merkle::MerkleUpdate;
use crate::num::*;
use crate::util::*;

use crate::models::currency::CurrencyCollection;
use crate::models::global_version::GlobalVersion;
use crate::models::Lazy;

pub use self::block_extra::*;
pub use self::block_id::*;
pub use self::block_proof::*;
pub use self::shard_hashes::*;

mod block_extra;
mod block_id;
mod block_proof;
mod shard_hashes;

#[cfg(test)]
mod tests;

/// Shard block.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Block {
    /// Global network id.
    pub global_id: i32,
    /// Block info.
    pub info: Lazy<BlockInfo>,
    /// Tokens flow info.
    pub value_flow: Lazy<ValueFlow>,
    /// Merkle update for the shard state.
    pub state_update: Lazy<MerkleUpdate>,
    /// Merkle updates for the outgoing messages queue.
    #[cfg(not(feature = "tycho"))]
    pub out_msg_queue_updates: Option<Dict<u32, Lazy<MerkleUpdate>>>,
    /// Out messages queue info.
    #[cfg(feature = "tycho")]
    pub out_msg_queue_updates: OutMsgQueueUpdates,
    /// Block content.
    pub extra: Lazy<BlockExtra>,
}

impl Block {
    #[cfg(not(feature = "tycho"))]
    const TAG_V1: u32 = 0x11ef55aa;
    const TAG_V2: u32 = 0x11ef55bb;

    const DATA_FOR_SIGN_SIZE: usize = 4 + 32 + 32;
    const DATA_FOR_SIGN_TAG: [u8; 4] = [0x70, 0x6e, 0x0b, 0xc5];

    /// Tries to load block info.
    pub fn load_info(&self) -> Result<BlockInfo, Error> {
        self.info.load()
    }

    /// Tries to load tokens flow info.
    pub fn load_value_flow(&self) -> Result<ValueFlow, Error> {
        self.value_flow.load()
    }

    /// Tries to load state update.
    pub fn load_state_update(&self) -> Result<MerkleUpdate, Error> {
        self.state_update.load()
    }

    /// Tries to load block content.
    pub fn load_extra(&self) -> Result<BlockExtra, Error> {
        self.extra.load()
    }

    /// Builds a data for validators to sign.
    pub fn build_data_for_sign(block_id: &BlockId) -> [u8; Self::DATA_FOR_SIGN_SIZE] {
        let mut data = [0u8; Self::DATA_FOR_SIGN_SIZE];
        data[0..4].copy_from_slice(&Self::DATA_FOR_SIGN_TAG);
        data[4..36].copy_from_slice(block_id.root_hash.as_ref());
        data[36..68].copy_from_slice(block_id.file_hash.as_ref());
        data
    }
}

impl Store for Block {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &mut dyn CellContext,
    ) -> Result<(), Error> {
        #[cfg(not(feature = "tycho"))]
        let tag = if self.out_msg_queue_updates.is_none() {
            Self::TAG_V1
        } else {
            Self::TAG_V2
        };
        #[cfg(feature = "tycho")]
        let tag = Self::TAG_V2;

        ok!(builder.store_u32(tag));
        ok!(builder.store_u32(self.global_id as u32));
        ok!(builder.store_reference(self.info.cell.clone()));
        ok!(builder.store_reference(self.value_flow.cell.clone()));

        #[cfg(not(feature = "tycho"))]
        let out_msg_queue_updates = self.out_msg_queue_updates.as_ref();
        #[cfg(feature = "tycho")]
        let out_msg_queue_updates = Some(&self.out_msg_queue_updates);

        ok!(if let Some(out_msg_queue_updates) = out_msg_queue_updates {
            let cell = {
                let mut builder = CellBuilder::new();
                ok!(self.state_update.store_into(&mut builder, context));
                ok!(out_msg_queue_updates.store_into(&mut builder, context));
                ok!(builder.build_ext(context))
            };
            builder.store_reference(cell)
        } else {
            self.state_update.store_into(builder, context)
        });

        self.extra.store_into(builder, context)
    }
}

impl<'a> Load<'a> for Block {
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        #[cfg(not(feature = "tycho"))]
        let with_out_msg_queue_updates = match ok!(slice.load_u32()) {
            Self::TAG_V1 => false,
            Self::TAG_V2 => true,
            _ => return Err(Error::InvalidTag),
        };

        #[cfg(feature = "tycho")]
        if ok!(slice.load_u32()) != Self::TAG_V2 {
            return Err(Error::InvalidTag);
        }

        let global_id = ok!(slice.load_u32()) as i32;
        let info = ok!(Lazy::load_from(slice));
        let value_flow = ok!(Lazy::load_from(slice));

        #[cfg(not(feature = "tycho"))]
        let (state_update, out_msg_queue_updates) = if with_out_msg_queue_updates {
            let slice = &mut ok!(slice.load_reference_as_slice());
            (
                ok!(Lazy::load_from(slice)),
                Some(ok!(Dict::load_from(slice))),
            )
        } else {
            (ok!(Lazy::load_from(slice)), None)
        };

        #[cfg(feature = "tycho")]
        let (state_update, out_msg_queue_updates) = {
            let slice = &mut ok!(slice.load_reference_as_slice());
            (ok!(<_>::load_from(slice)), ok!(<_>::load_from(slice)))
        };

        Ok(Self {
            global_id,
            info,
            value_flow,
            state_update,
            out_msg_queue_updates,
            extra: ok!(<_>::load_from(slice)),
        })
    }
}

/// Block info.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BlockInfo {
    /// Block model version.
    pub version: u32,
    /// Whether this block was produced after the shards were merged.
    pub after_merge: bool,
    /// Whether this block was produced before the shards split.
    pub before_split: bool,
    /// Whether this block was produced after the shards split.
    pub after_split: bool,
    /// Hint that the shard with this block should split.
    pub want_split: bool,
    /// Hint that the shard with this block should merge.
    pub want_merge: bool,
    /// Whether this block is a key block.
    pub key_block: bool,

    /// Block flags (currently only bit 1 is used, for [`gen_software`])
    ///
    /// [`gen_software`]: Self::gen_software
    pub flags: u8,
    /// Block sequence number.
    pub seqno: u32,
    /// Block vertical sequence number.
    pub vert_seqno: u32,

    /// Shard id where this block was produced.
    pub shard: ShardIdent,
    /// Unix timestamp when the block was created.
    pub gen_utime: u32,
    /// Milliseconds part of the timestamp when the block was created.
    #[cfg(any(feature = "venom", feature = "tycho"))]
    pub gen_utime_ms: u16,
    /// Logical time range start.
    pub start_lt: u64,
    /// Logical time range end.
    pub end_lt: u64,
    /// Last 4 bytes of the hash of the validator list.
    pub gen_validator_list_hash_short: u32,
    /// Seqno of the catchain session where this block was produced.
    pub gen_catchain_seqno: u32,
    /// Minimal referenced seqno of the masterchain block.
    pub min_ref_mc_seqno: u32,
    /// Previous key block seqno.
    pub prev_key_block_seqno: u32,
    /// The version and capabilities of the software that created this block.
    pub gen_software: GlobalVersion,

    /// Reference to the masterchain block which was used during the creation of this block.
    pub master_ref: Option<Lazy<BlockRef>>,
    /// Reference to the previous block (or blocks).
    #[cfg_attr(feature = "serde", serde(with = "serde_prev_block_ref"))]
    pub prev_ref: Cell,
    /// Optional reference to the previous vertical block.
    pub prev_vert_ref: Option<Lazy<BlockRef>>,
}

#[cfg(feature = "sync")]
impl Default for BlockInfo {
    fn default() -> Self {
        Self {
            version: 0,
            after_merge: false,
            before_split: false,
            after_split: false,
            want_split: false,
            want_merge: false,
            key_block: false,
            flags: 0,
            seqno: 0,
            vert_seqno: 0,
            shard: ShardIdent::MASTERCHAIN,
            gen_utime: 0,
            #[cfg(any(feature = "venom", feature = "tycho"))]
            gen_utime_ms: 0,
            start_lt: 0,
            end_lt: 0,
            gen_validator_list_hash_short: 0,
            gen_catchain_seqno: 0,
            min_ref_mc_seqno: 0,
            prev_key_block_seqno: 0,
            gen_software: Default::default(),
            master_ref: None,
            prev_ref: PrevBlockRef::empty_single_ref().clone(),
            prev_vert_ref: None,
        }
    }
}

impl BlockInfo {
    const TAG_V1: u32 = 0x9bc7a987;
    #[cfg(any(feature = "venom", feature = "tycho"))]
    const TAG_V2: u32 = 0x9bc7a988;
    const FLAG_WITH_GEN_SOFTWARE: u8 = 0x1;

    /// Set the version and capabilities of the software that created this block.
    pub fn set_gen_software(&mut self, gen_software: Option<GlobalVersion>) {
        if let Some(gen_software) = gen_software {
            self.gen_software = gen_software;
            self.flags |= BlockInfo::FLAG_WITH_GEN_SOFTWARE;
        } else {
            self.gen_software = Default::default();
            self.flags &= !BlockInfo::FLAG_WITH_GEN_SOFTWARE;
        }
    }

    /// Tries to load a reference to the masterchain block.
    pub fn load_master_ref(&self) -> Result<Option<BlockRef>, Error> {
        match &self.master_ref {
            Some(master_ref) => master_ref.load().map(Some),
            None => Ok(None),
        }
    }

    /// Tries to load a reference to the previous block (or blocks).
    pub fn load_prev_ref(&self) -> Result<PrevBlockRef, Error> {
        PrevBlockRef::load_from_cell(&self.prev_ref, self.after_merge)
    }

    /// Set previous block reference.
    pub fn set_prev_ref(&mut self, prev_ref: &PrevBlockRef) {
        match prev_ref {
            PrevBlockRef::Single(prev_ref) => self.set_prev_ref_single(prev_ref),
            PrevBlockRef::AfterMerge { left, right } => self.set_prev_ref_after_merge(left, right),
        }
    }

    /// Set previous block reference (direct).
    pub fn set_prev_ref_single(&mut self, prev_ref: &BlockRef) {
        // NOTE: Unwrap is ok because we control the input.
        self.prev_ref = CellBuilder::build_from(prev_ref).unwrap();
    }

    /// Set previous block reference (split).
    pub fn set_prev_ref_after_merge(&mut self, left: &BlockRef, right: &BlockRef) {
        fn store_split_ref(left: &BlockRef, right: &BlockRef) -> Result<Cell, Error> {
            let cx = &mut Cell::empty_context();
            let mut builder = CellBuilder::new();
            ok!(builder.store_reference(ok!(CellBuilder::build_from_ext(left, cx))));
            ok!(builder.store_reference(ok!(CellBuilder::build_from_ext(right, cx))));
            builder.build_ext(cx)
        }

        // NOTE: Unwrap is ok because we control the input.
        self.prev_ref = store_split_ref(left, right).unwrap();
    }
}

impl Store for BlockInfo {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &mut dyn CellContext,
    ) -> Result<(), Error> {
        let packed_flags = ((self.master_ref.is_some() as u8) << 7)
            | ((self.after_merge as u8) << 6)
            | ((self.before_split as u8) << 5)
            | ((self.after_split as u8) << 4)
            | ((self.want_split as u8) << 3)
            | ((self.want_merge as u8) << 2)
            | ((self.key_block as u8) << 1)
            | (self.prev_vert_ref.is_some() as u8);

        #[cfg(not(any(feature = "venom", feature = "tycho")))]
        ok!(builder.store_u32(Self::TAG_V1));
        #[cfg(any(feature = "venom", feature = "tycho"))]
        ok!(builder.store_u32(Self::TAG_V2));

        ok!(builder.store_u32(self.version));
        ok!(builder.store_u16(u16::from_be_bytes([packed_flags, self.flags])));
        ok!(builder.store_u32(self.seqno));
        ok!(builder.store_u32(self.vert_seqno));
        ok!(self.shard.store_into(builder, context));
        ok!(builder.store_u32(self.gen_utime));
        #[cfg(any(feature = "venom", feature = "tycho"))]
        ok!(builder.store_u16(self.gen_utime_ms));
        ok!(builder.store_u64(self.start_lt));
        ok!(builder.store_u64(self.end_lt));
        ok!(builder.store_u32(self.gen_validator_list_hash_short));
        ok!(builder.store_u32(self.gen_catchain_seqno));
        ok!(builder.store_u32(self.min_ref_mc_seqno));
        ok!(builder.store_u32(self.prev_key_block_seqno));

        if self.flags & Self::FLAG_WITH_GEN_SOFTWARE != 0 {
            ok!(self.gen_software.store_into(builder, context));
        }

        if let Some(master_ref) = &self.master_ref {
            ok!(builder.store_reference(master_ref.cell.clone()));
        }

        ok!(builder.store_reference(self.prev_ref.clone()));

        if let Some(prev_vert_ref) = &self.prev_vert_ref {
            builder.store_reference(prev_vert_ref.cell.clone())
        } else {
            Ok(())
        }
    }
}

impl<'a> Load<'a> for BlockInfo {
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        let with_ms = match slice.load_u32() {
            Ok(Self::TAG_V1) => false,
            #[cfg(any(feature = "venom", feature = "tycho"))]
            Ok(Self::TAG_V2) => true,
            Ok(_) => return Err(Error::InvalidTag),
            Err(e) => return Err(e),
        };

        #[cfg(not(any(feature = "venom", feature = "tycho")))]
        let _ = with_ms;

        let version = ok!(slice.load_u32());
        let [packed_flags, flags] = ok!(slice.load_u16()).to_be_bytes();
        let seqno = ok!(slice.load_u32());
        if seqno == 0 {
            return Err(Error::InvalidData);
        }
        let vert_seqno = ok!(slice.load_u32());
        let shard = ok!(ShardIdent::load_from(slice));
        let gen_utime = ok!(slice.load_u32());
        #[cfg(any(feature = "venom", feature = "tycho"))]
        let gen_utime_ms = if with_ms { ok!(slice.load_u16()) } else { 0 };
        let start_lt = ok!(slice.load_u64());
        let end_lt = ok!(slice.load_u64());
        let gen_validator_list_hash_short = ok!(slice.load_u32());
        let gen_catchain_seqno = ok!(slice.load_u32());
        let min_ref_mc_seqno = ok!(slice.load_u32());
        let prev_key_block_seqno = ok!(slice.load_u32());

        let gen_software = if flags & Self::FLAG_WITH_GEN_SOFTWARE != 0 {
            ok!(GlobalVersion::load_from(slice))
        } else {
            GlobalVersion::default()
        };

        let master_ref = if packed_flags & 0b10000000 != 0 {
            Some(ok!(Lazy::<BlockRef>::load_from(slice)))
        } else {
            None
        };

        let prev_ref = ok!(slice.load_reference_cloned());

        let prev_vert_ref = if packed_flags & 0b00000001 != 0 {
            Some(ok!(Lazy::<BlockRef>::load_from(slice)))
        } else {
            None
        };

        if vert_seqno < prev_vert_ref.is_some() as u32 {
            return Err(Error::InvalidData);
        }

        Ok(Self {
            version,
            after_merge: packed_flags & 0b01000000 != 0,
            before_split: packed_flags & 0b00100000 != 0,
            after_split: packed_flags & 0b00010000 != 0,
            want_split: packed_flags & 0b00001000 != 0,
            want_merge: packed_flags & 0b00000100 != 0,
            key_block: packed_flags & 0b00000010 != 0,
            flags,
            seqno,
            vert_seqno,
            shard,
            gen_utime,
            #[cfg(any(feature = "venom", feature = "tycho"))]
            gen_utime_ms,
            start_lt,
            end_lt,
            gen_validator_list_hash_short,
            gen_catchain_seqno,
            min_ref_mc_seqno,
            prev_key_block_seqno,
            gen_software,
            master_ref,
            prev_ref,
            prev_vert_ref,
        })
    }
}

#[cfg(feature = "serde")]
mod serde_prev_block_ref {
    use super::*;

    pub fn serialize<S: serde::Serializer>(value: &Cell, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::{Error, Serialize};

        if serializer.is_human_readable() {
            let prev_block_ref = ok!(PrevBlockRef::load_from_cell(
                value,
                value.reference_count() > 0
            )
            .map_err(Error::custom));
            prev_block_ref.serialize(serializer)
        } else {
            crate::boc::Boc::serialize(value, serializer)
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Cell, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{Deserialize, Error};

        if deserializer.is_human_readable() {
            PrevBlockRef::deserialize(deserializer).and_then(|prev_block_ref| {
                CellBuilder::build_from(prev_block_ref).map_err(Error::custom)
            })
        } else {
            crate::boc::Boc::deserialize(deserializer)
        }
    }
}

/// Reference to the previous block.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type", content = "id"))]
pub enum PrevBlockRef {
    /// Reference to the parent block (simple case).
    Single(BlockRef),
    /// Reference to both parent blocks (case after merge).
    AfterMerge {
        /// Block id from the "left" shard.
        ///
        /// See [`is_left_child`].
        ///
        /// [`is_left_child`]: ShardIdent::is_left_child
        left: BlockRef,
        /// Block id from the "right" shard.
        ///
        /// See [`is_right_child`].
        ///
        /// [`is_right_child`]: ShardIdent::is_right_child
        right: BlockRef,
    },
}

impl PrevBlockRef {
    /// Returns a static reference to an empty single reference.
    #[cfg(feature = "sync")]
    pub fn empty_single_ref() -> &'static Cell {
        static CELL: OnceLock<Cell> = OnceLock::new();
        CELL.get_or_init(|| {
            CellBuilder::build_from(&BlockRef {
                end_lt: 0,
                seqno: 0,
                root_hash: HashBytes::ZERO,
                file_hash: HashBytes::ZERO,
            })
            .unwrap()
        })
    }

    fn load_from_cell(value: &Cell, after_merge: bool) -> Result<Self, Error> {
        let mut s = ok!(value.as_slice());
        Ok(if unlikely(after_merge) {
            let left = ok!(BlockRef::load_from(&mut ok!(s.load_reference_as_slice())));
            let right = ok!(BlockRef::load_from(&mut ok!(s.load_reference_as_slice())));
            PrevBlockRef::AfterMerge { left, right }
        } else {
            PrevBlockRef::Single(ok!(BlockRef::load_from(&mut s)))
        })
    }
}

impl Store for PrevBlockRef {
    fn store_into(&self, builder: &mut CellBuilder, cx: &mut dyn CellContext) -> Result<(), Error> {
        match self {
            PrevBlockRef::Single(block_ref) => block_ref.store_into(builder, cx),
            PrevBlockRef::AfterMerge { left, right } => {
                ok!(builder.store_reference(ok!(CellBuilder::build_from_ext(left, cx))));
                builder.store_reference(ok!(CellBuilder::build_from_ext(right, cx)))
            }
        }
    }
}

/// Reference to the external block.
#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BlockRef {
    /// The end of the logical time of the referenced block.
    pub end_lt: u64,
    /// Sequence number of the referenced block.
    pub seqno: u32,
    /// Representation hash of the root cell of the referenced block.
    pub root_hash: HashBytes,
    /// Hash of the BOC encoded root cell of the referenced block.
    pub file_hash: HashBytes,
}

impl BlockRef {
    /// Converts a `BlockRef` to a `BlockId` given a shard identifier.
    pub fn as_block_id(&self, shard: ShardIdent) -> BlockId {
        BlockId {
            shard,
            seqno: self.seqno,
            root_hash: self.root_hash,
            file_hash: self.file_hash,
        }
    }
}

/// Tokens flow info.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValueFlow {
    /// Total amount transferred from the previous block.
    pub from_prev_block: CurrencyCollection,
    /// Total amount transferred to the next block.
    pub to_next_block: CurrencyCollection,
    /// Sum of all imported amounts from messages.
    pub imported: CurrencyCollection,
    /// Sum of all exported amounts of messages.
    pub exported: CurrencyCollection,

    /// Total fees collected in this block.
    pub fees_collected: CurrencyCollection,
    /// Shard fees imported to this block.
    pub fees_imported: CurrencyCollection,
    /// Fee recovery (?)
    pub recovered: CurrencyCollection,
    /// Block creation fees.
    pub created: CurrencyCollection,
    /// Minted extra currencies.
    pub minted: CurrencyCollection,

    /// Optional copyleft rewards.
    pub copyleft_rewards: Dict<HashBytes, Tokens>,
}

impl ValueFlow {
    const TAG_V1: u32 = 0xb8e48dfb;
    const TAG_V2: u32 = 0xe0864f6d;
}

impl Store for ValueFlow {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &mut dyn CellContext,
    ) -> Result<(), Error> {
        let tag = if self.copyleft_rewards.is_empty() {
            Self::TAG_V1
        } else {
            Self::TAG_V2
        };

        let cell1 = {
            let mut builder = CellBuilder::new();
            ok!(self.from_prev_block.store_into(&mut builder, context));
            ok!(self.to_next_block.store_into(&mut builder, context));
            ok!(self.imported.store_into(&mut builder, context));
            ok!(self.exported.store_into(&mut builder, context));
            ok!(builder.build_ext(context))
        };

        ok!(builder.store_u32(tag));
        ok!(builder.store_reference(cell1));

        ok!(self.fees_collected.store_into(builder, context));

        let cell2 = {
            let mut builder = CellBuilder::new();
            ok!(self.fees_imported.store_into(&mut builder, context));
            ok!(self.recovered.store_into(&mut builder, context));
            ok!(self.created.store_into(&mut builder, context));
            ok!(self.minted.store_into(&mut builder, context));
            ok!(builder.build_ext(context))
        };
        ok!(builder.store_reference(cell2));

        if !self.copyleft_rewards.is_empty() {
            self.copyleft_rewards.store_into(builder, context)
        } else {
            Ok(())
        }
    }
}

impl<'a> Load<'a> for ValueFlow {
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        let with_copyleft_rewards = match ok!(slice.load_u32()) {
            Self::TAG_V1 => false,
            Self::TAG_V2 => true,
            _ => return Err(Error::InvalidTag),
        };

        let fees_collected = ok!(CurrencyCollection::load_from(slice));
        let slice1 = &mut ok!(slice.load_reference_as_slice());
        let slice2 = &mut ok!(slice.load_reference_as_slice());
        let copyleft_rewards = if with_copyleft_rewards {
            ok!(Dict::load_from(slice))
        } else {
            Dict::new()
        };

        Ok(Self {
            from_prev_block: ok!(CurrencyCollection::load_from(slice1)),
            to_next_block: ok!(CurrencyCollection::load_from(slice1)),
            imported: ok!(CurrencyCollection::load_from(slice1)),
            exported: ok!(CurrencyCollection::load_from(slice1)),
            fees_collected,
            fees_imported: ok!(CurrencyCollection::load_from(slice2)),
            recovered: ok!(CurrencyCollection::load_from(slice2)),
            created: ok!(CurrencyCollection::load_from(slice2)),
            minted: ok!(CurrencyCollection::load_from(slice2)),
            copyleft_rewards,
        })
    }
}

/// Outgoing message queue updates.
#[cfg(feature = "tycho")]
#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[tlb(tag = "#1")]
pub struct OutMsgQueueUpdates {
    /// Hash of the serialized queue diff.
    pub diff_hash: HashBytes,
}