tycho_types/models/config/
params.rs

1#[cfg(feature = "tycho")]
2use std::num::NonZeroU8;
3use std::num::{NonZeroU16, NonZeroU32};
4
5use tycho_crypto::ed25519;
6
7use crate::cell::*;
8use crate::dict::Dict;
9use crate::error::Error;
10use crate::models::block::ShardIdent;
11use crate::models::{CurrencyCollection, Signature};
12use crate::num::{Tokens, Uint12, VarUint248};
13
14/// Value flow burning config.
15#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17#[tlb(tag = "#01", validate_with = "Self::is_valid")]
18pub struct BurningConfig {
19    /// Address of the masterchain account which will burn all inbound message balance.
20    pub blackhole_addr: Option<HashBytes>,
21    /// Numerator of the potion of burned fees.
22    pub fee_burn_num: u32,
23    /// Denominator of the potion of burned fees.
24    pub fee_burn_denom: NonZeroU32,
25}
26
27impl Default for BurningConfig {
28    #[inline]
29    fn default() -> Self {
30        Self {
31            blackhole_addr: None,
32            fee_burn_num: 0,
33            fee_burn_denom: NonZeroU32::MIN,
34        }
35    }
36}
37
38impl BurningConfig {
39    /// Returns whether the config is well-formed.
40    pub fn is_valid(&self) -> bool {
41        self.fee_burn_num <= self.fee_burn_denom.get()
42    }
43
44    /// Computes how much fees to burn.
45    ///
46    /// NOTE: For a well-formed [`BurningConfig`] it never fails
47    ///       and returns a value not greater than `tokens`.
48    pub fn compute_burned_fees(&self, tokens: Tokens) -> Result<Tokens, Error> {
49        if self.fee_burn_num == 0 {
50            return Ok(Tokens::ZERO);
51        } else if !self.is_valid() {
52            return Err(Error::InvalidData);
53        }
54
55        let mut tokens = VarUint248::new(tokens.into_inner());
56        tokens *= self.fee_burn_num as u128;
57        tokens /= self.fee_burn_denom.get() as u128;
58        let (hi, lo) = tokens.into_words();
59        debug_assert_eq!(
60            hi, 0,
61            "burned fees must never be greater than original fees"
62        );
63        Ok(Tokens::new(lo))
64    }
65}
66
67/// One-time minting config (can be used by L2 to mint native currency).
68#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70#[tlb(tag = "#01")]
71pub struct MintOnceConfig {
72    /// Exact masterchain block seqno.
73    pub mint_at: u32,
74    /// Native and extra currencies to mint.
75    pub delta: CurrencyCollection,
76}
77
78/// Config voting setup params.
79#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
80#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
81#[tlb(tag = "#91")]
82pub struct ConfigVotingSetup {
83    /// Proposal configuration for non-critical params.
84    pub normal_params: Lazy<ConfigProposalSetup>,
85    /// Proposal configuration for critical params.
86    pub critical_params: Lazy<ConfigProposalSetup>,
87}
88
89/// Config proposal setup params.
90#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
91#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
92#[tlb(tag = "#36")]
93pub struct ConfigProposalSetup {
94    /// The minimal number of voting rounds for the proposal.
95    pub min_total_rounds: u8,
96    /// The maximum number of voting rounds for the proposal.
97    pub max_total_rounds: u8,
98    /// The minimum number of winned voting rounds.
99    pub min_wins: u8,
100    /// The maximum number of lost voting rounds.
101    pub max_losses: u8,
102    /// The minimal proposal lifetime duration in seconds.
103    pub min_store_sec: u32,
104    /// The maximum proposal lifetime duration in seconds.
105    pub max_store_sec: u32,
106    /// Bit price for storage price computation.
107    pub bit_price: u32,
108    /// Cell price for storage price computation.
109    pub cell_price: u32,
110}
111
112/// Workchain description.
113#[derive(Debug, Clone, Eq, PartialEq)]
114#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
115pub struct WorkchainDescription {
116    /// Unix timestamp from which blocks can be produced.
117    pub enabled_since: u32,
118    /// Unused stub.
119    pub actual_min_split: u8,
120    /// The minimal shards split depths.
121    pub min_split: u8,
122    /// The maximum shards split depths.
123    pub max_split: u8,
124    /// Whether the workchain is enabled.
125    pub active: bool,
126    /// Whether the workchain accepts messages.
127    pub accept_msgs: bool,
128    /// A hash of the zerostate root cell.
129    pub zerostate_root_hash: HashBytes,
130    /// A hash of the zerostate file.
131    pub zerostate_file_hash: HashBytes,
132    /// Workchain version.
133    pub version: u32,
134    /// Workchain format description.
135    pub format: WorkchainFormat,
136}
137
138impl WorkchainDescription {
139    const TAG: u8 = 0xa6;
140
141    /// Returns `true` if the workchain description is valid.
142    pub fn is_valid(&self) -> bool {
143        self.min_split <= self.max_split
144            && self.max_split <= ShardIdent::MAX_SPLIT_DEPTH
145            && self.format.is_valid()
146    }
147}
148
149impl Store for WorkchainDescription {
150    fn store_into(
151        &self,
152        builder: &mut CellBuilder,
153        context: &dyn CellContext,
154    ) -> Result<(), Error> {
155        if !self.is_valid() {
156            return Err(Error::InvalidData);
157        }
158
159        let flags: u16 = ((self.format.is_basic() as u16) << 15)
160            | ((self.active as u16) << 14)
161            | ((self.accept_msgs as u16) << 13);
162
163        ok!(builder.store_u8(Self::TAG));
164        ok!(builder.store_u32(self.enabled_since));
165        ok!(builder.store_u8(self.actual_min_split));
166        ok!(builder.store_u8(self.min_split));
167        ok!(builder.store_u8(self.max_split));
168        ok!(builder.store_u16(flags));
169        ok!(builder.store_u256(&self.zerostate_root_hash));
170        ok!(builder.store_u256(&self.zerostate_file_hash));
171        ok!(builder.store_u32(self.version));
172        self.format.store_into(builder, context)
173    }
174}
175
176impl<'a> Load<'a> for WorkchainDescription {
177    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
178        match slice.load_u8() {
179            Ok(Self::TAG) => {}
180            Ok(_) => return Err(Error::InvalidTag),
181            Err(e) => return Err(e),
182        }
183
184        let enabled_since = ok!(slice.load_u32());
185        let actual_min_split = ok!(slice.load_u8());
186        let min_split = ok!(slice.load_u8());
187        let max_split = ok!(slice.load_u8());
188        let flags = ok!(slice.load_u16());
189        if flags << 3 != 0 {
190            return Err(Error::InvalidData);
191        }
192
193        let result = Self {
194            enabled_since,
195            actual_min_split,
196            min_split,
197            max_split,
198            active: flags & 0b0100_0000_0000_0000 != 0,
199            accept_msgs: flags & 0b0010_0000_0000_0000 != 0,
200            zerostate_root_hash: ok!(slice.load_u256()),
201            zerostate_file_hash: ok!(slice.load_u256()),
202            version: ok!(slice.load_u32()),
203            format: ok!(WorkchainFormat::load_from(slice)),
204        };
205
206        let basic = flags & 0b1000_0000_0000_0000 != 0;
207        if basic != result.format.is_basic() {
208            return Err(Error::InvalidData);
209        }
210
211        Ok(result)
212    }
213}
214
215/// Workchain format description.
216#[derive(Debug, Copy, Clone, Eq, PartialEq)]
217#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
218#[cfg_attr(feature = "serde", serde(tag = "ty"))]
219pub enum WorkchainFormat {
220    /// Basic workchain format.
221    Basic(WorkchainFormatBasic),
222    /// Extended workchain format.
223    Extended(WorkchainFormatExtended),
224}
225
226impl WorkchainFormat {
227    /// Returns `true` if the workchain format is valid.
228    pub fn is_valid(&self) -> bool {
229        match self {
230            Self::Basic(_) => true,
231            Self::Extended(format) => format.is_valid(),
232        }
233    }
234
235    /// Returns `true` if the workchain format is [`Basic`].
236    ///
237    /// [`Basic`]: WorkchainFormatBasic
238    pub fn is_basic(&self) -> bool {
239        matches!(self, Self::Basic(_))
240    }
241}
242
243impl Store for WorkchainFormat {
244    fn store_into(
245        &self,
246        builder: &mut CellBuilder,
247        context: &dyn CellContext,
248    ) -> Result<(), Error> {
249        match self {
250            Self::Basic(value) => {
251                ok!(builder.store_small_uint(0x1, 4));
252                value.store_into(builder, context)
253            }
254            Self::Extended(value) => {
255                ok!(builder.store_small_uint(0x0, 4));
256                value.store_into(builder, context)
257            }
258        }
259    }
260}
261
262impl<'a> Load<'a> for WorkchainFormat {
263    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
264        Ok(match ok!(slice.load_small_uint(4)) {
265            0x1 => Self::Basic(ok!(WorkchainFormatBasic::load_from(slice))),
266            0x0 => Self::Extended(ok!(WorkchainFormatExtended::load_from(slice))),
267            _ => return Err(Error::InvalidTag),
268        })
269    }
270}
271
272/// Basic workchain format description.
273#[derive(Debug, Copy, Clone, Eq, PartialEq, Store, Load)]
274#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
275pub struct WorkchainFormatBasic {
276    /// VM version.
277    pub vm_version: i32,
278    /// VM mode.
279    pub vm_mode: u64,
280}
281
282/// Extended workchain format description.
283#[derive(Debug, Copy, Clone, Eq, PartialEq, Store, Load)]
284#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
285#[tlb(validate_with = "Self::is_valid")]
286pub struct WorkchainFormatExtended {
287    /// The minimal address length in bits.
288    pub min_addr_len: Uint12,
289    /// The maximal address length in bits.
290    pub max_addr_len: Uint12,
291    /// Address length step in bits.
292    pub addr_len_step: Uint12,
293    /// Extended workchain type id.
294    pub workchain_type_id: NonZeroU32,
295}
296
297impl WorkchainFormatExtended {
298    /// Returns `true` if the workchain format is valid.
299    pub fn is_valid(&self) -> bool {
300        self.min_addr_len >= Uint12::new(64)
301            && self.min_addr_len <= self.max_addr_len
302            && self.max_addr_len <= Uint12::new(1023)
303            && self.addr_len_step <= Uint12::new(1023)
304    }
305
306    /// Checks that address length is in a valid range and is aligned to the len step.
307    pub fn check_addr_len(&self, addr_len: u16) -> bool {
308        let addr_len = Uint12::new(addr_len);
309
310        let is_aligned = || {
311            if self.addr_len_step.is_zero() {
312                return false;
313            }
314
315            let var_part = addr_len - self.min_addr_len;
316            let step_rem = var_part.into_inner() % self.addr_len_step.into_inner();
317            step_rem == 0
318        };
319
320        addr_len >= self.min_addr_len
321            && addr_len <= self.max_addr_len
322            && (addr_len == self.min_addr_len || addr_len == self.max_addr_len || is_aligned())
323    }
324}
325
326/// Block creation reward.
327#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
328#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
329#[tlb(tag = "#6b")]
330pub struct BlockCreationRewards {
331    /// Reward for each created masterchain block.
332    pub masterchain_block_fee: Tokens,
333    /// Base reward for basechain blocks.
334    pub basechain_block_fee: Tokens,
335}
336
337/// Validators election timings.
338#[derive(Debug, Copy, Clone, Eq, PartialEq, Store, Load)]
339#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
340pub struct ElectionTimings {
341    /// Validation round length in seconds.
342    pub validators_elected_for: u32,
343    /// Duration in seconds until the end of the validation round when the election starts.
344    pub elections_start_before: u32,
345    /// Duration in seconds until the end of the validation round when the election ends.
346    pub elections_end_before: u32,
347    /// How long validator stake will be frozen after the validation round end.
348    pub stake_held_for: u32,
349}
350
351/// Range of number of validators.
352#[derive(Debug, Copy, Clone, Eq, PartialEq, Store, Load)]
353#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
354pub struct ValidatorCountParams {
355    /// The maximum number of validators.
356    pub max_validators: u16,
357    /// The maximum number of masterchain validators.
358    pub max_main_validators: u16,
359    /// The minimum number of validators.
360    pub min_validators: u16,
361}
362
363/// Validator stake range and factor.
364#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
365#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
366pub struct ValidatorStakeParams {
367    /// The minimum validator stake.
368    pub min_stake: Tokens,
369    /// The maximum validator stake.
370    pub max_stake: Tokens,
371    /// The minimum required total stake for elections to be successful.
372    pub min_total_stake: Tokens,
373    /// Stake constraint (shifted by 16 bits).
374    pub max_stake_factor: u32,
375}
376
377/// Storage prices for some interval.
378#[derive(Debug, Copy, Clone, Eq, PartialEq, Store, Load)]
379#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
380#[tlb(tag = "#cc")]
381pub struct StoragePrices {
382    /// Unix timestamp since which this prices are used.
383    pub utime_since: u32,
384    /// Bit price in base workchain.
385    pub bit_price_ps: u64,
386    /// Cell price in base workchain.
387    pub cell_price_ps: u64,
388    /// Bit price in masterchain.
389    pub mc_bit_price_ps: u64,
390    /// Cell price in masterchain.
391    pub mc_cell_price_ps: u64,
392}
393
394impl StoragePrices {
395    /// Computes the amount of fees for storing `stats` data for `delta` seconds.
396    pub fn compute_storage_fee(
397        &self,
398        is_masterchain: bool,
399        delta: u64,
400        stats: CellTreeStats,
401    ) -> Tokens {
402        let mut res = if is_masterchain {
403            (stats.cell_count as u128 * self.mc_cell_price_ps as u128)
404                .saturating_add(stats.bit_count as u128 * self.mc_bit_price_ps as u128)
405        } else {
406            (stats.cell_count as u128 * self.cell_price_ps as u128)
407                .saturating_add(stats.bit_count as u128 * self.bit_price_ps as u128)
408        };
409        res = res.saturating_mul(delta as u128);
410        Tokens::new(shift_ceil_price(res))
411    }
412}
413
414/// Gas limits and prices.
415#[derive(Default, Debug, Clone, Eq, PartialEq)]
416#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
417pub struct GasLimitsPrices {
418    /// The price of gas unit.
419    pub gas_price: u64,
420    /// The maximum amount of gas available for a compute phase of an ordinary transaction.
421    pub gas_limit: u64,
422    /// The maximum amount of gas available for a compute phase of a special transaction.
423    pub special_gas_limit: u64,
424    /// The maximum amount of gas available before `ACCEPT`.
425    pub gas_credit: u64,
426    /// The maximum amount of gas units per block.
427    pub block_gas_limit: u64,
428    /// Amount of debt (in tokens) after which the account will be frozen.
429    pub freeze_due_limit: u64,
430    /// Amount of debt (in tokens) after which the contract will be deleted.
431    pub delete_due_limit: u64,
432    /// Size of the first portion of gas with different price.
433    pub flat_gas_limit: u64,
434    /// The gas price for the first portion determinted by [`flat_gas_limit`].
435    ///
436    /// [`flat_gas_limit`]: GasLimitsPrices::flat_gas_limit
437    pub flat_gas_price: u64,
438}
439
440impl GasLimitsPrices {
441    /// Converts gas units into tokens.
442    pub fn compute_gas_fee(&self, gas_used: u64) -> Tokens {
443        let mut res = self.flat_gas_price as u128;
444        if let Some(extra_gas) = gas_used.checked_sub(self.flat_gas_limit) {
445            res = res.saturating_add(shift_ceil_price(self.gas_price as u128 * extra_gas as u128));
446        }
447        Tokens::new(res)
448    }
449}
450
451impl GasLimitsPrices {
452    const TAG_BASE: u8 = 0xdd;
453    const TAG_EXT: u8 = 0xde;
454    const TAG_FLAT_PFX: u8 = 0xd1;
455}
456
457impl Store for GasLimitsPrices {
458    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
459        ok!(builder.store_u8(Self::TAG_FLAT_PFX));
460        ok!(builder.store_u64(self.flat_gas_limit));
461        ok!(builder.store_u64(self.flat_gas_price));
462        ok!(builder.store_u8(Self::TAG_EXT));
463        ok!(builder.store_u64(self.gas_price));
464        ok!(builder.store_u64(self.gas_limit));
465        ok!(builder.store_u64(self.special_gas_limit));
466        ok!(builder.store_u64(self.gas_credit));
467        ok!(builder.store_u64(self.block_gas_limit));
468        ok!(builder.store_u64(self.freeze_due_limit));
469        builder.store_u64(self.delete_due_limit)
470    }
471}
472
473impl<'a> Load<'a> for GasLimitsPrices {
474    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
475        let mut result = Self::default();
476        loop {
477            match slice.load_u8() {
478                Ok(Self::TAG_FLAT_PFX) => {
479                    result.flat_gas_limit = ok!(slice.load_u64());
480                    result.flat_gas_price = ok!(slice.load_u64());
481                }
482                Ok(Self::TAG_EXT) => {
483                    result.gas_price = ok!(slice.load_u64());
484                    result.gas_limit = ok!(slice.load_u64());
485                    result.special_gas_limit = ok!(slice.load_u64());
486                    result.gas_credit = ok!(slice.load_u64());
487                    result.block_gas_limit = ok!(slice.load_u64());
488                    result.freeze_due_limit = ok!(slice.load_u64());
489                    result.delete_due_limit = ok!(slice.load_u64());
490                    return Ok(result);
491                }
492                Ok(Self::TAG_BASE) => {
493                    result.gas_price = ok!(slice.load_u64());
494                    result.gas_limit = ok!(slice.load_u64());
495                    result.gas_credit = ok!(slice.load_u64());
496                    result.block_gas_limit = ok!(slice.load_u64());
497                    result.freeze_due_limit = ok!(slice.load_u64());
498                    result.delete_due_limit = ok!(slice.load_u64());
499                    return Ok(result);
500                }
501                Ok(_) => return Err(Error::InvalidTag),
502                Err(e) => return Err(e),
503            }
504        }
505    }
506}
507
508/// Block limits parameter.
509#[derive(Debug, Copy, Clone, Eq, PartialEq, Store, Load)]
510#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
511#[tlb(tag = "#c3", validate_with = "Self::is_valid")]
512pub struct BlockParamLimits {
513    /// Value below which the parameter is considered underloaded.
514    pub underload: u32,
515    /// Soft limit.
516    pub soft_limit: u32,
517    /// Hard limit.
518    pub hard_limit: u32,
519}
520
521impl BlockParamLimits {
522    /// Returns `true` if parameter limits are valid.
523    pub fn is_valid(&self) -> bool {
524        self.underload <= self.soft_limit && self.soft_limit <= self.hard_limit
525    }
526}
527
528/// Block limits.
529#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
530#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
531#[tlb(tag = "#5d")]
532pub struct BlockLimits {
533    /// Block size limits in bytes.
534    pub bytes: BlockParamLimits,
535    /// Gas limits.
536    pub gas: BlockParamLimits,
537    /// Logical time delta limits.
538    pub lt_delta: BlockParamLimits,
539}
540
541/// Message forwarding prices.
542#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
543#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
544#[tlb(tag = "#ea")]
545pub struct MsgForwardPrices {
546    /// Fixed price in addition to the dynamic part.
547    pub lump_price: u64,
548    /// The price of bits in the message (bits in the root cell are not included).
549    pub bit_price: u64,
550    /// The price of cells in the message.
551    pub cell_price: u64,
552    /// TODO: add docs
553    pub ihr_price_factor: u32,
554    /// Part of fees that is included to the first block.
555    pub first_frac: u16,
556    /// Part of fees that goes to transit blocks.
557    pub next_frac: u16,
558}
559
560impl MsgForwardPrices {
561    /// Computes fees for forwarding the specified amount of data.
562    pub fn compute_fwd_fee(&self, stats: CellTreeStats) -> Tokens {
563        let lump = self.lump_price as u128;
564        let extra = shift_ceil_price(
565            (stats.cell_count as u128 * self.cell_price as u128)
566                .saturating_add(stats.bit_count as u128 * self.bit_price as u128),
567        );
568        Tokens::new(lump.saturating_add(extra))
569    }
570
571    /// Computes the part of the fees that is included to the total fees of the current block.
572    pub fn get_first_part(&self, total: Tokens) -> Tokens {
573        Tokens::new(total.into_inner().saturating_mul(self.first_frac as _) >> 16)
574    }
575
576    /// Computes the part of the fees that is included to the total fees of the transit block.
577    pub fn get_next_part(&self, total: Tokens) -> Tokens {
578        Tokens::new(total.into_inner().saturating_mul(self.next_frac as _) >> 16)
579    }
580}
581
582/// Catchain configuration params.
583#[cfg(not(feature = "tycho"))]
584#[derive(Debug, Copy, Clone, Eq, PartialEq)]
585#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
586pub struct CatchainConfig {
587    /// Exclude masterchain validators from a validators list for a base workchain.
588    pub isolate_mc_validators: bool,
589    /// Change the order of validators in the masterchain validators list.
590    pub shuffle_mc_validators: bool,
591    /// Masterchain catchain session lifetime in seconds.
592    pub mc_catchain_lifetime: u32,
593    /// Catchain session lifetime for shards in seconds.
594    pub shard_catchain_lifetime: u32,
595    /// Period in seconds for which the subset of validators is selected for each shard.
596    pub shard_validators_lifetime: u32,
597    /// The number of validators per shard.
598    pub shard_validators_num: u32,
599}
600
601#[cfg(not(feature = "tycho"))]
602impl CatchainConfig {
603    const TAG_V1: u8 = 0xc1;
604    const TAG_V2: u8 = 0xc2;
605}
606
607#[cfg(not(feature = "tycho"))]
608impl Store for CatchainConfig {
609    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
610        let flags = ((self.isolate_mc_validators as u8) << 1) | (self.shuffle_mc_validators as u8);
611        ok!(builder.store_u8(Self::TAG_V2));
612        ok!(builder.store_u8(flags));
613        ok!(builder.store_u32(self.mc_catchain_lifetime));
614        ok!(builder.store_u32(self.shard_catchain_lifetime));
615        ok!(builder.store_u32(self.shard_validators_lifetime));
616        builder.store_u32(self.shard_validators_num)
617    }
618}
619
620#[cfg(not(feature = "tycho"))]
621impl<'a> Load<'a> for CatchainConfig {
622    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
623        let flags = match slice.load_u8() {
624            Ok(Self::TAG_V1) => 0,
625            Ok(Self::TAG_V2) => ok!(slice.load_u8()),
626            Ok(_) => return Err(Error::InvalidTag),
627            Err(e) => return Err(e),
628        };
629        if flags >> 2 != 0 {
630            return Err(Error::InvalidData);
631        }
632        Ok(Self {
633            isolate_mc_validators: flags & 0b10 != 0,
634            shuffle_mc_validators: flags & 0b01 != 0,
635            mc_catchain_lifetime: ok!(slice.load_u32()),
636            shard_catchain_lifetime: ok!(slice.load_u32()),
637            shard_validators_lifetime: ok!(slice.load_u32()),
638            shard_validators_num: ok!(slice.load_u32()),
639        })
640    }
641}
642
643/// Collation configuration params.
644///
645/// ```text
646/// collation_config_tycho#a6
647///     shuffle_mc_validators:Bool
648///     mc_block_min_interval_ms:uint32
649///     empty_sc_block_interval_ms:uint32
650///     max_uncommitted_chain_length:uint8
651///     wu_used_to_import_next_anchor:uint64
652///     msgs_exec_params:MsgsExecutionParams
653///     work_units_params:WorkUnitsParams
654///     = CollationConfig;
655///
656/// collation_config_tycho#a7
657///     shuffle_mc_validators:Bool
658///     mc_block_min_interval_ms:uint32
659///     mc_block_max_interval_ms:uint32
660///     empty_sc_block_interval_ms:uint32
661///     max_uncommitted_chain_length:uint8
662///     wu_used_to_import_next_anchor:uint64
663///     msgs_exec_params:MsgsExecutionParams
664///     work_units_params:WorkUnitsParams
665///     = CollationConfig;
666/// ```
667#[cfg(feature = "tycho")]
668#[derive(Debug, Clone, Eq, PartialEq, Store, Load, Default)]
669#[tlb(tag = ["#a6", "#a7"])]
670#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
671pub struct CollationConfig {
672    /// Change the order of validators in the masterchain validators list.
673    pub shuffle_mc_validators: bool,
674
675    /// Minimum interval between master blocks.
676    pub mc_block_min_interval_ms: u32,
677
678    /// Maximum interval between master blocks.
679    #[tlb(since_tag = 1)]
680    pub mc_block_max_interval_ms: u32,
681
682    /// Time to wait before collating an empty shard block.
683    pub empty_sc_block_interval_ms: u32,
684
685    /// Maximum length on shard blocks chain after previous master block.
686    pub max_uncommitted_chain_length: u8,
687    /// Force import next anchor when wu used exceed limit.
688    pub wu_used_to_import_next_anchor: u64,
689
690    /// Messages execution params.
691    pub msgs_exec_params: MsgsExecutionParams,
692
693    /// Params to calculate the collation work in wu.
694    pub work_units_params: WorkUnitsParams,
695}
696
697/// Messages execution params.
698///
699/// ```text
700/// msgs_execution_params_tycho#00
701///     buffer_limit:uint32
702///     group_limit:uint16
703///     group_vert_size:uint16
704///     externals_expire_timeout:uint16
705///     open_ranges_limit:uint16
706///     par_0_int_msgs_count_limit:uint32
707///     par_0_ext_msgs_count_limit:uint32
708///     group_slots_fractions:(HashmapE 16 uint8)
709///     = MsgsExecutionParams;
710/// ```
711#[cfg(feature = "tycho")]
712#[derive(Debug, Clone, Eq, PartialEq, Store, Load, Default)]
713#[tlb(tag = ["#00", "#01"])]
714#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
715pub struct MsgsExecutionParams {
716    /// Maximum limit of messages buffer.
717    pub buffer_limit: u32,
718
719    /// The horizontal limit of one message group.
720    /// Shows how many slots can be.
721    /// One slot may contain messages for some accounts.
722    /// One account can exist only in one slot.
723    pub group_limit: u16,
724    /// The vertical limit of one message group.
725    /// Shows how many messages can be per one slot in the group.
726    pub group_vert_size: u16,
727
728    /// The timeout for externals in seconds.
729    pub externals_expire_timeout: u16,
730
731    /// The maximum number of ranges
732    /// that we should store in ProcessedUptoInfo maps
733    pub open_ranges_limit: u16,
734
735    /// The maximum number of incoming internal messages on account.
736    /// When the internal messages queue on the account exceeds the limit
737    /// then all messages on this account  will be processed in other partition.
738    pub par_0_int_msgs_count_limit: u32,
739
740    /// The maximum number of incoming externals messages on account.
741    /// When the external messages queue on the account exceeds the limit
742    /// then all messages on this account  will be processed in other partition.
743    pub par_0_ext_msgs_count_limit: u32,
744
745    /// The fractions of message group slots
746    /// for messages subgroups
747    pub group_slots_fractions: Dict<u16, u8>,
748
749    /// The maximum number of blocks messages in one range.
750    #[tlb(since_tag = 1)]
751    pub range_messages_limit: u32,
752}
753
754/// Params to calculate the collation work in wu.
755///
756/// ```text
757/// work_units_params_tycho#00
758///     prepare:WorkUnitParamsPrepare
759///     execute:WorkUnitParamsExecute
760///     finalize:WorkUnitParamsFinalize
761///     = WorkUnitsParams;
762/// ```
763#[cfg(feature = "tycho")]
764#[derive(Debug, Clone, Eq, PartialEq, Store, Load, Default)]
765#[tlb(tag = "#00")]
766#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
767pub struct WorkUnitsParams {
768    /// Params to calculate messages groups prepare work in wu.
769    pub prepare: WorkUnitsParamsPrepare,
770    /// Params to calculate messages execution work in wu.
771    pub execute: WorkUnitsParamsExecute,
772    /// Params to calculate block finalization work in wu.
773    pub finalize: WorkUnitsParamsFinalize,
774}
775
776/// Params to calculate messages groups prepare work in wu.
777///
778/// ```text
779/// work_units_params_prepare_tycho#00
780///     fixed:uint32
781///     msgs_stats:uint16
782///     remaning_msgs_stats:uint16
783///     read_ext_msgs:uint16
784///     read_int_msgs:uint16
785///     read_new_msgs:uint16
786///     add_to_msg_groups:uint16
787///     = WorkUnitsParamsPrepare;
788/// ```
789#[cfg(feature = "tycho")]
790#[derive(Debug, Clone, Eq, PartialEq, Store, Load, Default)]
791#[tlb(tag = "#00")]
792#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
793pub struct WorkUnitsParamsPrepare {
794    /// TODO: Add docs.
795    pub fixed_part: u32,
796    /// TODO: Add docs.
797    pub msgs_stats: u16,
798    /// TODO: Add docs.
799    pub remaning_msgs_stats: u16,
800    /// TODO: Add docs.
801    pub read_ext_msgs: u16,
802    /// TODO: Add docs.
803    pub read_int_msgs: u16,
804    /// TODO: Add docs.
805    pub read_new_msgs: u16,
806    /// TODO: Add docs.
807    pub add_to_msg_groups: u16,
808}
809
810/// Params to calculate messages execution work in wu.
811///
812/// ```text
813/// work_units_params_execute_tycho#00
814///     prepare:uint32
815///     execute:uint16
816///     execute_err:uint16
817///     execute_delimiter:uint32
818///     serialize_enqueue:uint16
819///     serialize_dequeue:uint16
820///     insert_new_msgs:uint16
821///     subgroup_size:uint16
822///     = WorkUnitsParamsExecute;
823/// ```
824#[cfg(feature = "tycho")]
825#[derive(Debug, Clone, Eq, PartialEq, Store, Load, Default)]
826#[tlb(tag = "#00")]
827#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
828pub struct WorkUnitsParamsExecute {
829    /// TODO: Add docs.
830    pub prepare: u32,
831    /// TODO: Add docs.
832    pub execute: u16,
833    /// TODO: Add docs.
834    pub execute_err: u16,
835    /// TODO: Add docs.
836    pub execute_delimiter: u32,
837    /// TODO: Add docs.
838    pub serialize_enqueue: u16,
839    /// TODO: Add docs.
840    pub serialize_dequeue: u16,
841    /// TODO: Add docs.
842    pub insert_new_msgs: u16,
843    /// TODO: Add docs.
844    pub subgroup_size: u16,
845}
846
847/// Params to calculate block finalization work in wu.
848///
849/// ```text
850/// work_units_params_finalize_tycho#00
851///     build_transactions:uint16
852///     build_accounts:uint16
853///     build_in_msg:uint16
854///     build_out_msg:uint16
855///     serialize_min:uint32
856///     serialize_accounts:uint16
857///     serialize_msg:uint16
858///     state_update_min:uint32
859///     state_update_accounts:uint16
860///     state_update_msg:uint16
861///     create_diff:uint16
862///     serialize_diff:uint16
863///     apply_diff:uint16
864///     diff_tail_len:uint16
865///     = WorkUnitsParamsFinalize;
866/// ```
867#[cfg(feature = "tycho")]
868#[derive(Debug, Clone, Eq, PartialEq, Store, Load, Default)]
869#[tlb(tag = "#00")]
870#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
871pub struct WorkUnitsParamsFinalize {
872    /// TODO: Add docs.
873    pub build_transactions: u16,
874    /// TODO: Add docs.
875    pub build_accounts: u16,
876    /// TODO: Add docs.
877    pub build_in_msg: u16,
878    /// TODO: Add docs.
879    pub build_out_msg: u16,
880    /// TODO: Add docs.
881    pub serialize_min: u32,
882    /// TODO: Add docs.
883    pub serialize_accounts: u16,
884    /// TODO: Add docs.
885    pub serialize_msg: u16,
886    /// TODO: Add docs.
887    pub state_update_min: u32,
888    /// TODO: Add docs.
889    pub state_update_accounts: u16,
890    /// TODO: Add docs.
891    pub state_update_msg: u16,
892    /// TODO: Add docs.
893    pub create_diff: u16,
894    /// TODO: Add docs.
895    pub serialize_diff: u16,
896    /// TODO: Add docs.
897    pub apply_diff: u16,
898    /// TODO: Add docs.
899    pub diff_tail_len: u16,
900}
901
902/// DAG Consensus configuration params
903///
904/// ```text
905/// consensus_config_tycho#d8
906///     clock_skew_millis:uint16
907///     payload_batch_bytes:uint32
908///     commit_history_rounds:uint8
909///     deduplicate_rounds:uint16
910///     max_consensus_lag_rounds:uint16
911///     payload_buffer_bytes:uint32
912///     broadcast_retry_millis:uint8
913///     download_retry_millis:uint8
914///     download_peers:uint8
915///     min_sign_attempts:uint8
916///     download_peer_queries:uint8
917///     sync_support_rounds:uint16
918///     = ConsensusConfig;
919/// ```
920#[cfg(feature = "tycho")]
921#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
922#[tlb(tag = "#d8")]
923#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
924pub struct ConsensusConfig {
925    /// How far a ready-to-be-signed point (with time in its body)
926    /// may be in the future compared with signer's local (wall) time.
927    /// Lower bound is defined by genesis, and then advanced by leaders with every anchor.
928    /// Anchor time is strictly increasing as it is inherited from anchor candidate in every point.
929    ///
930    /// Cannot be zero because time guarantees are essential for the collator.
931    ///
932    /// **NOTE: Affects overlay id.**
933    pub clock_skew_millis: NonZeroU16,
934
935    /// Hard limit on point payload. Excessive messages will be postponed.
936    ///
937    /// Cannot be zero because blockchain config change requires an external message.
938    ///
939    /// **NOTE: Affects overlay id.**
940    pub payload_batch_bytes: NonZeroU32,
941
942    /// Limits amount of rounds included in anchor history (points that appears in commit).
943    ///
944    /// Cannot be zero because commit history is essential.
945    ///
946    /// **NOTE: Affects overlay id.**
947    pub commit_history_rounds: NonZeroU16,
948
949    /// Size (amount of rounds) of a sliding window to deduplicate external messages across anchors.
950    ///
951    /// Zero disables deduplication.
952    ///
953    /// **NOTE: Affects overlay id.**
954    pub deduplicate_rounds: u16,
955
956    /// The max expected distance (amount of rounds) between two sequential top known anchors (TKA),
957    /// i.e. anchors from two sequential top known blocks (TKB, signed master chain blocks,
958    /// available to local node, and which state is not necessarily applied by local node). For
959    /// example, the last TKA=`7` and the config value is `210`, so a newer TKA is expected in
960    /// range `(8..=217).len() == 210`, i.e. some leader successfully completes its 3 rounds
961    /// in a row (collects 2F+1 signatures for its anchor trigger), and there are one or
962    /// two additional mempool rounds for the anchor trigger to be delivered to all nodes,
963    /// and every collator is expected to create and sign a block containing that new TKA and time.
964    /// Until a new TKA in range `11..=211'('7+4..<217-3-2`) is received by the local mempool,
965    /// it will not repeat its per-round routine at round `216` and keeps waiting in a "pause mode".
966    /// DAG will contain `217` round as it always does for the next round after current.
967    /// Switch of validator set may be scheduled for `218` round, as its round is not created.
968    ///
969    /// Effectively defines feedback from block validation consensus to mempool consensus.
970    ///
971    /// Cannot be zero because it must not be less than [`Self::commit_history_rounds`]
972    ///
973    /// **NOTE: Affects overlay id.**
974    pub max_consensus_lag_rounds: NonZeroU16,
975
976    /// Hard limit on ring buffer size to cache external messages before they are taken into
977    /// point payload. Newer messages may push older ones out of the buffer when limit is reached.
978    ///
979    /// Cannot be zero because it must not be less than [`Self::payload_batch_bytes`].
980    pub payload_buffer_bytes: NonZeroU32,
981
982    /// Every round an instance tries to gather as many points and signatures as it can
983    /// within some time frame. It is a tradeoff between breaking current round
984    /// on exactly 2F+1 items (points and/or signatures) and waiting for slow nodes.
985    ///
986    /// Cannot be zero because it is a timeout inside a loop.
987    pub broadcast_retry_millis: NonZeroU16,
988
989    /// Every missed dependency (point) is downloaded with a group of simultaneous requests to
990    /// neighbour peers. Every new group of requests is spawned after previous group completed
991    /// or this interval elapsed (in order not to wait for some slow responding peer).
992    ///
993    /// Cannot be zero because it is a timeout inside a loop.
994    pub download_retry_millis: NonZeroU16,
995
996    /// Amount of peers to request at first download attempt. Amount will increase
997    /// respectively at each attempt, until 2F peers successfully responded `None`
998    /// or a verifiable point is found (incorrectly signed points do not count).
999    ///
1000    /// Cannot be zero because downloads must not be disabled.
1001    pub download_peers: NonZeroU8,
1002
1003    /// Min required cycles to collect signatures before broadcast loop successfully finishes.
1004    /// Greater values increase point delivery and create artificial delay for stable point rate.
1005    ///
1006    /// Cannot be zero because first attempt is essential.
1007    pub min_sign_attempts: NonZeroU8,
1008
1009    /// Limits amount of simultaneous point downloads from one peer.
1010    ///
1011    /// Cannot be zero because downloads must not be disabled.
1012    ///
1013    /// **NOTE: Affects overlay id.**
1014    pub download_peer_queries: NonZeroU8,
1015
1016    /// Max duration (amount of rounds) at which local mempool is supposed to keep its history
1017    /// for neighbours to sync. Also limits DAG growth when it syncs, as sync takes time.
1018    ///
1019    /// Zero does not make any sense.
1020    ///
1021    /// **NOTE: Affects overlay id.**
1022    pub sync_support_rounds: NonZeroU16,
1023}
1024
1025/// Consensus configuration params.
1026#[cfg(not(feature = "tycho"))]
1027#[derive(Debug, Clone, Eq, PartialEq)]
1028#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1029pub struct ConsensusConfig {
1030    /// Allow new catchain ids.
1031    pub new_catchain_ids: bool,
1032    /// Number of block candidates per round.
1033    pub round_candidates: NonZeroU32,
1034    /// Delay in seconds before proposing a new candidate.
1035    pub next_candidate_delay_ms: u32,
1036    /// Catchain processing timeout in seconds.
1037    pub consensus_timeout_ms: u32,
1038    /// Maximum number of attempts per round.
1039    pub fast_attempts: u32,
1040    /// Duration of a round attempt in seconds.
1041    pub attempt_duration: u32,
1042    /// The maximum number of dependencies to merge.
1043    pub catchain_max_deps: u32,
1044    /// The maximum block size in bytes.
1045    pub max_block_bytes: u32,
1046    /// THe maximum size of a collated data in bytes.
1047    pub max_collated_bytes: u32,
1048}
1049
1050#[cfg(not(feature = "tycho"))]
1051impl ConsensusConfig {
1052    const TAG_V1: u8 = 0xd6;
1053    const TAG_V2: u8 = 0xd7;
1054}
1055
1056#[cfg(not(feature = "tycho"))]
1057impl Store for ConsensusConfig {
1058    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
1059        let flags = self.new_catchain_ids as u8;
1060
1061        ok!(builder.store_u8(Self::TAG_V2));
1062        ok!(builder.store_u8(flags));
1063        ok!(builder.store_u8(self.round_candidates.get() as u8));
1064        ok!(builder.store_u32(self.next_candidate_delay_ms));
1065        ok!(builder.store_u32(self.consensus_timeout_ms));
1066        ok!(builder.store_u32(self.fast_attempts));
1067        ok!(builder.store_u32(self.attempt_duration));
1068        ok!(builder.store_u32(self.catchain_max_deps));
1069        ok!(builder.store_u32(self.max_block_bytes));
1070        builder.store_u32(self.max_collated_bytes)
1071    }
1072}
1073
1074#[cfg(not(feature = "tycho"))]
1075impl<'a> Load<'a> for ConsensusConfig {
1076    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
1077        use std::num::NonZeroU8;
1078
1079        let (flags, round_candidates) = match slice.load_u8() {
1080            Ok(Self::TAG_V1) => (0, ok!(NonZeroU32::load_from(slice))),
1081            Ok(Self::TAG_V2) => {
1082                let flags = ok!(slice.load_u8());
1083                if flags >> 1 != 0 {
1084                    return Err(Error::InvalidData);
1085                }
1086                (flags, ok!(NonZeroU8::load_from(slice)).into())
1087            }
1088            Ok(_) => return Err(Error::InvalidTag),
1089            Err(e) => return Err(e),
1090        };
1091        Ok(Self {
1092            new_catchain_ids: flags & 0b1 != 0,
1093            round_candidates,
1094            next_candidate_delay_ms: ok!(slice.load_u32()),
1095            consensus_timeout_ms: ok!(slice.load_u32()),
1096            fast_attempts: ok!(slice.load_u32()),
1097            attempt_duration: ok!(slice.load_u32()),
1098            catchain_max_deps: ok!(slice.load_u32()),
1099            max_block_bytes: ok!(slice.load_u32()),
1100            max_collated_bytes: ok!(slice.load_u32()),
1101        })
1102    }
1103}
1104
1105/// Validator set.
1106#[derive(Debug, Clone, Eq, PartialEq)]
1107#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1108pub struct ValidatorSet {
1109    /// Unix timestamp from which this set will be active.
1110    pub utime_since: u32,
1111    /// Unix timestamp until which this set will be active.
1112    pub utime_until: u32,
1113    /// The number of masterchain validators.
1114    pub main: NonZeroU16,
1115    /// Total validators weight.
1116    pub total_weight: u64,
1117    /// Validators.
1118    pub list: Vec<ValidatorDescription>,
1119}
1120
1121impl ValidatorSet {
1122    const TAG_V1: u8 = 0x11;
1123    const TAG_V2: u8 = 0x12;
1124
1125    /// Computes a validator subset using a zero seed.
1126    #[cfg(not(feature = "tycho"))]
1127    pub fn compute_subset(
1128        &self,
1129        shard_ident: ShardIdent,
1130        cc_config: &CatchainConfig,
1131        cc_seqno: u32,
1132    ) -> Option<(Vec<ValidatorDescription>, u32)> {
1133        if shard_ident.is_masterchain() {
1134            return self.compute_mc_subset(cc_seqno, cc_config.shuffle_mc_validators);
1135        }
1136
1137        let total = self.list.len();
1138        let main = self.main.get() as usize;
1139
1140        let mut prng = ValidatorSetPRNG::new(shard_ident, cc_seqno);
1141
1142        let vset = if cc_config.isolate_mc_validators {
1143            if total <= main {
1144                return None;
1145            }
1146
1147            let mut list = self.list[main..].to_vec();
1148
1149            let mut total_weight = 0u64;
1150            for descr in &mut list {
1151                descr.prev_total_weight = total_weight;
1152                total_weight += descr.weight;
1153            }
1154
1155            std::borrow::Cow::Owned(Self {
1156                utime_since: self.utime_since,
1157                utime_until: self.utime_until,
1158                main: self.main,
1159                total_weight,
1160                list,
1161            })
1162        } else {
1163            std::borrow::Cow::Borrowed(self)
1164        };
1165
1166        let count = std::cmp::min(vset.list.len(), cc_config.shard_validators_num as usize);
1167
1168        let mut nodes = Vec::with_capacity(count);
1169        let mut holes = Vec::<(u64, u64)>::with_capacity(count);
1170        let mut total_wt = vset.total_weight;
1171
1172        for _ in 0..count {
1173            debug_assert!(total_wt > 0);
1174
1175            // Generate a pseudo-random number 0..total_wt-1
1176            let mut p = prng.next_ranged(total_wt);
1177
1178            for (prev_total_weight, weight) in &holes {
1179                if p < *prev_total_weight {
1180                    break;
1181                }
1182                p += weight;
1183            }
1184
1185            let entry = vset.at_weight(p);
1186
1187            nodes.push(ValidatorDescription {
1188                public_key: entry.public_key,
1189                weight: 1,
1190                adnl_addr: entry.adnl_addr,
1191                mc_seqno_since: 0,
1192                prev_total_weight: 0,
1193            });
1194            debug_assert!(total_wt >= entry.weight);
1195            total_wt -= entry.weight;
1196
1197            let new_hole = (entry.prev_total_weight, entry.weight);
1198            let i = holes.partition_point(|item| item <= &new_hole);
1199            debug_assert!(i == 0 || holes[i - 1] < new_hole);
1200
1201            holes.insert(i, new_hole);
1202        }
1203
1204        let hash_short = Self::compute_subset_hash_short(&nodes, cc_seqno);
1205
1206        Some((nodes, hash_short))
1207    }
1208
1209    /// Computes a masterchain validator subset using a zero seed.
1210    ///
1211    /// NOTE: In most cases you should use the more generic [`ValidatorSet::compute_subset`].
1212    pub fn compute_mc_subset(
1213        &self,
1214        cc_seqno: u32,
1215        shuffle: bool,
1216    ) -> Option<(Vec<ValidatorDescription>, u32)> {
1217        let total = self.list.len();
1218        let main = self.main.get() as usize;
1219
1220        let count = std::cmp::min(total, main);
1221        let subset = if !shuffle {
1222            self.list[0..count].to_vec()
1223        } else {
1224            let mut prng = ValidatorSetPRNG::new(ShardIdent::MASTERCHAIN, cc_seqno);
1225
1226            let mut indices = vec![0; count];
1227            for i in 0..count {
1228                let j = prng.next_ranged(i as u64 + 1) as usize; // number 0 .. i
1229                debug_assert!(j <= i);
1230                indices[i] = indices[j];
1231                indices[j] = i;
1232            }
1233
1234            let mut subset = Vec::with_capacity(count);
1235            for index in indices.into_iter().take(count) {
1236                subset.push(self.list[index].clone());
1237            }
1238            subset
1239        };
1240
1241        let hash_short = Self::compute_subset_hash_short(&subset, cc_seqno);
1242        Some((subset, hash_short))
1243    }
1244
1245    /// Computes a masterchain validator subset using a zero seed.
1246    /// Preserves original validator indexes inside vset.
1247    ///
1248    /// NOTE: In most cases you should use the more generic [`ValidatorSet::compute_subset`].
1249    pub fn compute_mc_subset_indexed(
1250        &self,
1251        cc_seqno: u32,
1252        shuffle: bool,
1253    ) -> Option<(Vec<IndexedValidatorDescription>, u32)> {
1254        let total = self.list.len();
1255        let main = self.main.get() as usize;
1256
1257        let count = std::cmp::min(total, main);
1258        let subset = if !shuffle {
1259            self.list[0..count]
1260                .iter()
1261                .enumerate()
1262                .map(|(i, desc)| IndexedValidatorDescription {
1263                    desc: desc.clone(),
1264                    validator_idx: i as u16,
1265                })
1266                .collect::<Vec<_>>()
1267        } else {
1268            let mut prng = ValidatorSetPRNG::new(ShardIdent::MASTERCHAIN, cc_seqno);
1269
1270            let mut indices = vec![0; count];
1271            for i in 0..count {
1272                let j = prng.next_ranged(i as u64 + 1) as usize; // number 0 .. i
1273                debug_assert!(j <= i);
1274                indices[i] = indices[j];
1275                indices[j] = i;
1276            }
1277
1278            let mut subset = Vec::with_capacity(count);
1279            for index in indices.into_iter().take(count) {
1280                subset.push(IndexedValidatorDescription {
1281                    desc: self.list[index].clone(),
1282                    validator_idx: index as u16,
1283                });
1284            }
1285            subset
1286        };
1287
1288        let hash_short =
1289            Self::compute_subset_hash_short(subset.iter().map(AsRef::as_ref), cc_seqno);
1290        Some((subset, hash_short))
1291    }
1292
1293    /// Compoutes a validator subset short hash.
1294    pub fn compute_subset_hash_short<'a, I>(subset: I, cc_seqno: u32) -> u32
1295    where
1296        I: IntoIterator<Item = &'a ValidatorDescription, IntoIter: ExactSizeIterator>,
1297    {
1298        const HASH_SHORT_MAGIC: u32 = 0x901660ED;
1299
1300        let subset = subset.into_iter();
1301
1302        let mut hash = crc32c::crc32c(&HASH_SHORT_MAGIC.to_le_bytes());
1303        hash = crc32c::crc32c_append(hash, &cc_seqno.to_le_bytes());
1304        hash = crc32c::crc32c_append(hash, &(subset.len() as u32).to_le_bytes());
1305
1306        for node in subset {
1307            hash = crc32c::crc32c_append(hash, node.public_key.as_slice());
1308            hash = crc32c::crc32c_append(hash, &node.weight.to_le_bytes());
1309            hash = crc32c::crc32c_append(
1310                hash,
1311                node.adnl_addr
1312                    .as_ref()
1313                    .unwrap_or(HashBytes::wrap(&[0u8; 32]))
1314                    .as_ref(),
1315            );
1316        }
1317
1318        hash
1319    }
1320
1321    #[cfg(not(feature = "tycho"))]
1322    fn at_weight(&self, weight_pos: u64) -> &ValidatorDescription {
1323        debug_assert!(weight_pos < self.total_weight);
1324        debug_assert!(!self.list.is_empty());
1325        let i = self
1326            .list
1327            .partition_point(|item| item.prev_total_weight <= weight_pos);
1328        debug_assert!(i != 0);
1329        &self.list[i - 1]
1330    }
1331}
1332
1333impl Store for ValidatorSet {
1334    fn store_into(
1335        &self,
1336        builder: &mut CellBuilder,
1337        context: &dyn CellContext,
1338    ) -> Result<(), Error> {
1339        let Ok(total) = u16::try_from(self.list.len()) else {
1340            return Err(Error::IntOverflow);
1341        };
1342
1343        // TODO: optimize
1344        let mut validators = Dict::<u16, ValidatorDescription>::new();
1345        for (i, item) in self.list.iter().enumerate() {
1346            ok!(validators.set_ext(i as u16, item, context));
1347        }
1348
1349        ok!(builder.store_u8(Self::TAG_V2));
1350        ok!(builder.store_u32(self.utime_since));
1351        ok!(builder.store_u32(self.utime_until));
1352        ok!(builder.store_u16(total));
1353        ok!(builder.store_u16(self.main.get()));
1354        ok!(builder.store_u64(self.total_weight));
1355        validators.store_into(builder, context)
1356    }
1357}
1358
1359impl<'a> Load<'a> for ValidatorSet {
1360    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
1361        let with_total_weight = match slice.load_u8() {
1362            Ok(Self::TAG_V1) => false,
1363            Ok(Self::TAG_V2) => true,
1364            Ok(_) => return Err(Error::InvalidTag),
1365            Err(e) => return Err(e),
1366        };
1367
1368        let utime_since = ok!(slice.load_u32());
1369        let utime_until = ok!(slice.load_u32());
1370        let total = ok!(slice.load_u16()) as usize;
1371        let main = ok!(NonZeroU16::load_from(slice));
1372        if main.get() as usize > total {
1373            return Err(Error::InvalidData);
1374        }
1375
1376        let context = Cell::empty_context();
1377
1378        let (mut total_weight, validators) = if with_total_weight {
1379            let total_weight = ok!(slice.load_u64());
1380            let dict = ok!(Dict::<u16, ValidatorDescription>::load_from(slice));
1381            (total_weight, dict)
1382        } else {
1383            let dict = ok!(Dict::<u16, ValidatorDescription>::load_from_root_ext(
1384                slice, context
1385            ));
1386            (0, dict)
1387        };
1388
1389        let mut computed_total_weight = 0u64;
1390        let mut list = Vec::with_capacity(std::cmp::min(total, 512));
1391        for (i, entry) in validators.iter().enumerate().take(total) {
1392            let mut descr = match entry {
1393                Ok((idx, descr)) if idx as usize == i => descr,
1394                Ok(_) => return Err(Error::InvalidData),
1395                Err(e) => return Err(e),
1396            };
1397
1398            descr.prev_total_weight = computed_total_weight;
1399            computed_total_weight = match computed_total_weight.checked_add(descr.weight) {
1400                Some(weight) => weight,
1401                None => return Err(Error::InvalidData),
1402            };
1403            list.push(descr);
1404        }
1405
1406        if list.is_empty() {
1407            return Err(Error::InvalidData);
1408        }
1409
1410        if with_total_weight {
1411            if total_weight != computed_total_weight {
1412                return Err(Error::InvalidData);
1413            }
1414        } else {
1415            total_weight = computed_total_weight;
1416        }
1417
1418        Ok(Self {
1419            utime_since,
1420            utime_until,
1421            main,
1422            total_weight,
1423            list,
1424        })
1425    }
1426}
1427
1428#[cfg(feature = "serde")]
1429impl<'de> serde::Deserialize<'de> for ValidatorSet {
1430    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1431        use serde::de::Error;
1432
1433        #[derive(serde::Deserialize)]
1434        struct ValidatorSetHelper {
1435            utime_since: u32,
1436            utime_until: u32,
1437            main: NonZeroU16,
1438            #[serde(default)]
1439            total_weight: u64,
1440            list: Vec<ValidatorDescription>,
1441        }
1442
1443        let parsed = ValidatorSetHelper::deserialize(deserializer)?;
1444        if parsed.list.is_empty() {
1445            return Err(Error::custom("empty validators list"));
1446        }
1447
1448        let mut result = Self {
1449            utime_since: parsed.utime_since,
1450            utime_until: parsed.utime_until,
1451            main: parsed.main,
1452            total_weight: 0,
1453            list: parsed.list,
1454        };
1455
1456        for descr in &mut result.list {
1457            descr.prev_total_weight = result.total_weight;
1458            let Some(new_total_weight) = result.total_weight.checked_add(descr.weight) else {
1459                return Err(Error::custom("total weight overflow"));
1460            };
1461            result.total_weight = new_total_weight;
1462        }
1463
1464        if parsed.total_weight > 0 && parsed.total_weight != result.total_weight {
1465            return Err(Error::custom("total weight mismatch"));
1466        }
1467
1468        Ok(result)
1469    }
1470}
1471
1472/// Validator description.
1473#[derive(Debug, Clone, Eq, PartialEq)]
1474#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1475pub struct ValidatorDescription {
1476    /// Validator public key.
1477    pub public_key: HashBytes, // TODO: replace with tycho_crypto::ed25519::PublicKey ?
1478    /// Validator weight in some units.
1479    pub weight: u64,
1480    /// Optional validator ADNL address.
1481    #[cfg_attr(feature = "serde", serde(default))]
1482    pub adnl_addr: Option<HashBytes>,
1483    /// Since which seqno this validator will be active.
1484    #[cfg_attr(feature = "serde", serde(default))]
1485    pub mc_seqno_since: u32,
1486
1487    /// Total weight of the previous validators in the list.
1488    /// The field is not serialized.
1489    #[cfg_attr(feature = "serde", serde(skip))]
1490    pub prev_total_weight: u64,
1491}
1492
1493impl ValidatorDescription {
1494    const TAG_BASIC: u8 = 0x53;
1495    const TAG_WITH_ADNL: u8 = 0x73;
1496    const TAG_WITH_MC_SEQNO: u8 = 0x93;
1497
1498    const PUBKEY_TAG: u32 = 0x8e81278a;
1499
1500    /// Verifies message signature and current public key.
1501    pub fn verify_signature(&self, data: &[u8], signature: &Signature) -> bool {
1502        if let Some(public_key) = ed25519::PublicKey::from_bytes(self.public_key.0) {
1503            public_key.verify_raw(data, signature.as_ref())
1504        } else {
1505            false
1506        }
1507    }
1508}
1509
1510impl Store for ValidatorDescription {
1511    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
1512        let with_mc_seqno = self.mc_seqno_since != 0;
1513
1514        let tag = if with_mc_seqno {
1515            Self::TAG_WITH_MC_SEQNO
1516        } else if self.adnl_addr.is_some() {
1517            Self::TAG_WITH_ADNL
1518        } else {
1519            Self::TAG_BASIC
1520        };
1521
1522        ok!(builder.store_u8(tag));
1523        ok!(builder.store_u32(Self::PUBKEY_TAG));
1524        ok!(builder.store_u256(&self.public_key));
1525        ok!(builder.store_u64(self.weight));
1526
1527        let mut adnl = self.adnl_addr.as_ref();
1528        if with_mc_seqno {
1529            adnl = Some(HashBytes::wrap(&[0; 32]));
1530        }
1531
1532        if let Some(adnl) = adnl {
1533            ok!(builder.store_u256(adnl));
1534        }
1535
1536        if with_mc_seqno {
1537            builder.store_u32(self.mc_seqno_since)
1538        } else {
1539            Ok(())
1540        }
1541    }
1542}
1543
1544impl<'a> Load<'a> for ValidatorDescription {
1545    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
1546        let (with_adnl, with_mc_seqno) = match slice.load_u8() {
1547            Ok(Self::TAG_BASIC) => (false, false),
1548            Ok(Self::TAG_WITH_ADNL) => (true, false),
1549            Ok(Self::TAG_WITH_MC_SEQNO) => (true, true),
1550            Ok(_) => return Err(Error::InvalidTag),
1551            Err(e) => return Err(e),
1552        };
1553
1554        Ok(Self {
1555            public_key: {
1556                match slice.load_u32() {
1557                    Ok(Self::PUBKEY_TAG) => ok!(slice.load_u256()),
1558                    Ok(_) => return Err(Error::InvalidTag),
1559                    Err(e) => return Err(e),
1560                }
1561            },
1562            weight: ok!(slice.load_u64()),
1563            adnl_addr: if with_adnl {
1564                Some(ok!(slice.load_u256()))
1565            } else {
1566                None
1567            },
1568            mc_seqno_since: if with_mc_seqno {
1569                ok!(slice.load_u32())
1570            } else {
1571                0
1572            },
1573            prev_total_weight: 0,
1574        })
1575    }
1576}
1577
1578/// Validator description with its original index in vset.
1579#[derive(Debug, Clone, Eq, PartialEq)]
1580#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1581pub struct IndexedValidatorDescription {
1582    /// Validator description.
1583    pub desc: ValidatorDescription,
1584    /// Index in the original validator set.
1585    pub validator_idx: u16,
1586}
1587
1588impl AsRef<ValidatorDescription> for IndexedValidatorDescription {
1589    #[inline]
1590    fn as_ref(&self) -> &ValidatorDescription {
1591        &self.desc
1592    }
1593}
1594
1595impl AsMut<ValidatorDescription> for IndexedValidatorDescription {
1596    #[inline]
1597    fn as_mut(&mut self) -> &mut ValidatorDescription {
1598        &mut self.desc
1599    }
1600}
1601
1602impl std::ops::Deref for IndexedValidatorDescription {
1603    type Target = ValidatorDescription;
1604
1605    #[inline]
1606    fn deref(&self) -> &Self::Target {
1607        &self.desc
1608    }
1609}
1610
1611impl std::ops::DerefMut for IndexedValidatorDescription {
1612    #[inline]
1613    fn deref_mut(&mut self) -> &mut Self::Target {
1614        &mut self.desc
1615    }
1616}
1617
1618/// Random generator used for validator subset calculation.
1619pub struct ValidatorSetPRNG {
1620    context: [u8; 48],
1621    bag: [u64; 8],
1622}
1623
1624impl ValidatorSetPRNG {
1625    /// Creates a new generator with zero seed.
1626    pub fn new(shard_ident: ShardIdent, cc_seqno: u32) -> Self {
1627        let seed = [0; 32];
1628        Self::with_seed(shard_ident, cc_seqno, &seed)
1629    }
1630
1631    /// Creates a new generator with the specified seed.
1632    pub fn with_seed(shard_ident: ShardIdent, cc_seqno: u32, seed: &[u8; 32]) -> Self {
1633        let mut context = [0u8; 48];
1634        context[..32].copy_from_slice(seed);
1635        context[32..40].copy_from_slice(&shard_ident.prefix().to_be_bytes());
1636        context[40..44].copy_from_slice(&shard_ident.workchain().to_be_bytes());
1637        context[44..48].copy_from_slice(&cc_seqno.to_be_bytes());
1638
1639        let mut res = ValidatorSetPRNG {
1640            context,
1641            bag: [0; 8],
1642        };
1643        res.bag[0] = 8;
1644        res
1645    }
1646
1647    /// Generates next `u64`.
1648    pub fn next_u64(&mut self) -> u64 {
1649        if self.cursor() < 7 {
1650            let next = self.bag[1 + self.cursor() as usize];
1651            self.bag[0] += 1;
1652            next
1653        } else {
1654            self.reset()
1655        }
1656    }
1657
1658    /// Generates next `u64` multiplied by the specified range.
1659    pub fn next_ranged(&mut self, range: u64) -> u64 {
1660        let val = self.next_u64();
1661        ((range as u128 * val as u128) >> 64) as u64
1662    }
1663
1664    fn reset(&mut self) -> u64 {
1665        use sha2::digest::Digest;
1666
1667        let hash: [u8; 64] = sha2::Sha512::digest(self.context).into();
1668
1669        for ctx in self.context[..32].iter_mut().rev() {
1670            *ctx = ctx.wrapping_add(1);
1671            if *ctx != 0 {
1672                break;
1673            }
1674        }
1675
1676        // SAFETY: `std::mem::size_of::<[u64; 8]>() == 64` and src alignment is 1
1677        unsafe {
1678            std::ptr::copy_nonoverlapping(hash.as_ptr(), self.bag.as_mut_ptr() as *mut u8, 64);
1679        }
1680
1681        // Swap bytes for little endian
1682        #[cfg(target_endian = "little")]
1683        self.bag
1684            .iter_mut()
1685            .for_each(|item| *item = item.swap_bytes());
1686
1687        // Reset and use bag[0] as counter
1688        std::mem::take(&mut self.bag[0])
1689    }
1690
1691    #[inline]
1692    const fn cursor(&self) -> u64 {
1693        self.bag[0]
1694    }
1695}
1696
1697/// size_limits_config_v2#02
1698///     max_msg_bits:uint32
1699///     max_msg_cells:uint32
1700///     max_library_cells:uint32
1701///     max_vm_data_depth:uint16
1702///     max_ext_msg_size:uint32
1703///     max_ext_msg_depth:uint16
1704///     max_acc_state_cells:uint32
1705///     max_acc_state_bits:uint32
1706///     max_acc_public_libraries:uint32
1707///     defer_out_queue_size_limit:uint32 = SizeLimitsConfig;
1708#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
1709#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1710#[tlb(tag = "#02")]
1711pub struct SizeLimitsConfig {
1712    /// Max number of bits in message.
1713    pub max_msg_bits: u32,
1714    /// Max number of cells in message.
1715    pub max_msg_cells: u32,
1716    /// Max number of cells in library.
1717    pub max_library_cells: u32,
1718    /// Max cell tree depth for VM data.
1719    pub max_vm_data_depth: u16,
1720    /// Max number of bytes of a BOC-encoded external message.
1721    pub max_ext_msg_size: u32,
1722    /// Max cell tree depth of an external message.
1723    pub max_ext_msg_depth: u16,
1724    /// Max number of cells per account.
1725    pub max_acc_state_cells: u32,
1726    /// Max number of bits per account.
1727    pub max_acc_state_bits: u32,
1728    /// Max number of public libraries per account.
1729    pub max_acc_public_libraries: u32,
1730    /// Size limit of a deferred out messages queue.
1731    pub defer_out_queue_size_limit: u32,
1732}
1733
1734const fn shift_ceil_price(value: u128) -> u128 {
1735    let r = value & 0xffff != 0;
1736    (value >> 16) + r as u128
1737}
1738
1739/// Authority marks configuration.
1740#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
1741#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1742#[tlb(tag = "#01")]
1743pub struct AuthorityMarksConfig {
1744    /// Addresses in masterchain that can manage authority marks.
1745    pub authority_addresses: Dict<HashBytes, ()>,
1746    /// Black mark extra currency id.
1747    pub black_mark_id: u32,
1748    /// White mark extra currency id.
1749    pub white_mark_id: u32,
1750}
1751
1752#[cfg(test)]
1753mod tests {
1754    use super::*;
1755
1756    #[test]
1757    fn validator_set_prng() {
1758        fn make_indices(cc_seqno: u32) -> Vec<usize> {
1759            let mut prng = ValidatorSetPRNG::new(ShardIdent::BASECHAIN, cc_seqno);
1760
1761            let count = 10;
1762            let mut indices = vec![0; count];
1763            for i in 0..count {
1764                let j = prng.next_ranged(i as u64 + 1) as usize;
1765                debug_assert!(j <= i);
1766                indices[i] = indices[j];
1767                indices[j] = i;
1768            }
1769
1770            indices
1771        }
1772
1773        let vs10_first = make_indices(10);
1774        let vs10_second = make_indices(10);
1775        assert_eq!(vs10_first, vs10_second);
1776
1777        let vs11_first = make_indices(11);
1778        let vs11_second = make_indices(11);
1779        assert_eq!(vs11_first, vs11_second);
1780        assert_ne!(vs10_first, vs11_second);
1781    }
1782}