Skip to main content

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///     _unused:uint8
909///     commit_history_rounds:uint8
910///     deduplicate_rounds:uint16
911///     max_consensus_lag_rounds:uint16
912///     payload_buffer_bytes:uint32
913///     broadcast_retry_millis:uint16
914///     download_retry_millis:uint16
915///     download_peers:uint8
916///     min_sign_attempts:uint8
917///     download_peer_queries:uint8
918///     sync_support_rounds:uint16
919///     = ConsensusConfig;
920/// ```
921#[cfg(feature = "tycho")]
922#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
923#[tlb(tag = "#d8")]
924#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
925pub struct ConsensusConfig {
926    /// How far a ready-to-be-signed point (with time in its body)
927    /// may be in the future compared with signer's local (wall) time.
928    /// Lower bound is defined by genesis, and then advanced by leaders with every anchor.
929    /// Anchor time is strictly increasing as it is inherited from anchor candidate in every point.
930    ///
931    /// Cannot be zero because time guarantees are essential for the collator.
932    ///
933    /// **NOTE: Affects overlay id.**
934    pub clock_skew_millis: NonZeroU16,
935
936    /// Hard limit on point payload. Excessive messages will be postponed.
937    ///
938    /// Cannot be zero because blockchain config change requires an external message.
939    ///
940    /// **NOTE: Affects overlay id.**
941    pub payload_batch_bytes: NonZeroU32,
942
943    /// Free space, previously part of the next too large field
944    #[cfg_attr(feature = "serde", serde(default))]
945    pub _unused: u8,
946
947    /// Limits amount of rounds included in anchor history (points that appears in commit).
948    ///
949    /// Cannot be zero because commit history is essential.
950    ///
951    /// **NOTE: Affects overlay id.**
952    pub commit_history_rounds: NonZeroU8,
953
954    /// Size (amount of rounds) of a sliding window to deduplicate external messages across anchors.
955    ///
956    /// Zero disables deduplication.
957    ///
958    /// **NOTE: Affects overlay id.**
959    pub deduplicate_rounds: u16,
960
961    /// The max expected distance (amount of rounds) between two sequential top known anchors (TKA),
962    /// i.e. anchors from two sequential top known blocks (TKB, signed master chain blocks,
963    /// available to local node, and which state is not necessarily applied by local node). For
964    /// example, the last TKA=`7` and the config value is `210`, so a newer TKA is expected in
965    /// range `(8..=217).len() == 210`, i.e. some leader successfully completes its 3 rounds
966    /// in a row (collects 2F+1 signatures for its anchor trigger), and there are one or
967    /// two additional mempool rounds for the anchor trigger to be delivered to all nodes,
968    /// and every collator is expected to create and sign a block containing that new TKA and time.
969    /// Until a new TKA in range `11..=211'('7+4..<217-3-2`) is received by the local mempool,
970    /// it will not repeat its per-round routine at round `216` and keeps waiting in a "pause mode".
971    /// DAG will contain `217` round as it always does for the next round after current.
972    /// Switch of validator set may be scheduled for `218` round, as its round is not created.
973    ///
974    /// Effectively defines feedback from block validation consensus to mempool consensus.
975    ///
976    /// Cannot be zero because it must not be less than [`Self::commit_history_rounds`]
977    ///
978    /// **NOTE: Affects overlay id.**
979    pub max_consensus_lag_rounds: NonZeroU16,
980
981    /// Hard limit on ring buffer size to cache external messages before they are taken into
982    /// point payload. Newer messages may push older ones out of the buffer when limit is reached.
983    ///
984    /// Cannot be zero because it must not be less than [`Self::payload_batch_bytes`].
985    pub payload_buffer_bytes: NonZeroU32,
986
987    /// Every round an instance tries to gather as many points and signatures as it can
988    /// within some time frame. It is a tradeoff between breaking current round
989    /// on exactly 2F+1 items (points and/or signatures) and waiting for slow nodes.
990    ///
991    /// Cannot be zero because it is a timeout inside a loop.
992    pub broadcast_retry_millis: NonZeroU16,
993
994    /// Every missed dependency (point) is downloaded with a group of simultaneous requests to
995    /// neighbour peers. Every new group of requests is spawned after previous group completed
996    /// or this interval elapsed (in order not to wait for some slow responding peer).
997    ///
998    /// Cannot be zero because it is a timeout inside a loop.
999    pub download_retry_millis: NonZeroU16,
1000
1001    /// Amount of peers to request at first download attempt. Amount will increase
1002    /// respectively at each attempt, until 2F peers successfully responded `None`
1003    /// or a verifiable point is found (incorrectly signed points do not count).
1004    ///
1005    /// Cannot be zero because downloads must not be disabled.
1006    pub download_peers: NonZeroU8,
1007
1008    /// Min required cycles to collect signatures before broadcast loop successfully finishes.
1009    /// Greater values increase point delivery and create artificial delay for stable point rate.
1010    ///
1011    /// Cannot be zero because first attempt is essential.
1012    pub min_sign_attempts: NonZeroU8,
1013
1014    /// Limits amount of simultaneous point downloads from one peer.
1015    ///
1016    /// Cannot be zero because downloads must not be disabled.
1017    ///
1018    /// **NOTE: Affects overlay id.**
1019    pub download_peer_queries: NonZeroU8,
1020
1021    /// Max duration (amount of rounds) at which local mempool is supposed to keep its history
1022    /// for neighbours to sync. Also limits DAG growth when it syncs, as sync takes time.
1023    ///
1024    /// Zero does not make any sense.
1025    ///
1026    /// **NOTE: Affects overlay id.**
1027    pub sync_support_rounds: NonZeroU16,
1028}
1029
1030/// Consensus configuration params.
1031#[cfg(not(feature = "tycho"))]
1032#[derive(Debug, Clone, Eq, PartialEq)]
1033#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1034pub struct ConsensusConfig {
1035    /// Allow new catchain ids.
1036    pub new_catchain_ids: bool,
1037    /// Number of block candidates per round.
1038    pub round_candidates: NonZeroU32,
1039    /// Delay in seconds before proposing a new candidate.
1040    pub next_candidate_delay_ms: u32,
1041    /// Catchain processing timeout in seconds.
1042    pub consensus_timeout_ms: u32,
1043    /// Maximum number of attempts per round.
1044    pub fast_attempts: u32,
1045    /// Duration of a round attempt in seconds.
1046    pub attempt_duration: u32,
1047    /// The maximum number of dependencies to merge.
1048    pub catchain_max_deps: u32,
1049    /// The maximum block size in bytes.
1050    pub max_block_bytes: u32,
1051    /// THe maximum size of a collated data in bytes.
1052    pub max_collated_bytes: u32,
1053}
1054
1055#[cfg(not(feature = "tycho"))]
1056impl ConsensusConfig {
1057    const TAG_V1: u8 = 0xd6;
1058    const TAG_V2: u8 = 0xd7;
1059}
1060
1061#[cfg(not(feature = "tycho"))]
1062impl Store for ConsensusConfig {
1063    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
1064        let flags = self.new_catchain_ids as u8;
1065
1066        ok!(builder.store_u8(Self::TAG_V2));
1067        ok!(builder.store_u8(flags));
1068        ok!(builder.store_u8(self.round_candidates.get() as u8));
1069        ok!(builder.store_u32(self.next_candidate_delay_ms));
1070        ok!(builder.store_u32(self.consensus_timeout_ms));
1071        ok!(builder.store_u32(self.fast_attempts));
1072        ok!(builder.store_u32(self.attempt_duration));
1073        ok!(builder.store_u32(self.catchain_max_deps));
1074        ok!(builder.store_u32(self.max_block_bytes));
1075        builder.store_u32(self.max_collated_bytes)
1076    }
1077}
1078
1079#[cfg(not(feature = "tycho"))]
1080impl<'a> Load<'a> for ConsensusConfig {
1081    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
1082        use std::num::NonZeroU8;
1083
1084        let (flags, round_candidates) = match slice.load_u8() {
1085            Ok(Self::TAG_V1) => (0, ok!(NonZeroU32::load_from(slice))),
1086            Ok(Self::TAG_V2) => {
1087                let flags = ok!(slice.load_u8());
1088                if flags >> 1 != 0 {
1089                    return Err(Error::InvalidData);
1090                }
1091                (flags, ok!(NonZeroU8::load_from(slice)).into())
1092            }
1093            Ok(_) => return Err(Error::InvalidTag),
1094            Err(e) => return Err(e),
1095        };
1096        Ok(Self {
1097            new_catchain_ids: flags & 0b1 != 0,
1098            round_candidates,
1099            next_candidate_delay_ms: ok!(slice.load_u32()),
1100            consensus_timeout_ms: ok!(slice.load_u32()),
1101            fast_attempts: ok!(slice.load_u32()),
1102            attempt_duration: ok!(slice.load_u32()),
1103            catchain_max_deps: ok!(slice.load_u32()),
1104            max_block_bytes: ok!(slice.load_u32()),
1105            max_collated_bytes: ok!(slice.load_u32()),
1106        })
1107    }
1108}
1109
1110/// Validator set.
1111#[derive(Debug, Clone, Eq, PartialEq)]
1112#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1113pub struct ValidatorSet {
1114    /// Unix timestamp from which this set will be active.
1115    pub utime_since: u32,
1116    /// Unix timestamp until which this set will be active.
1117    pub utime_until: u32,
1118    /// The number of masterchain validators.
1119    pub main: NonZeroU16,
1120    /// Total validators weight.
1121    pub total_weight: u64,
1122    /// Validators.
1123    pub list: Vec<ValidatorDescription>,
1124}
1125
1126impl ValidatorSet {
1127    const TAG_V1: u8 = 0x11;
1128    const TAG_V2: u8 = 0x12;
1129
1130    /// Computes a validator subset using a zero seed.
1131    #[cfg(not(feature = "tycho"))]
1132    pub fn compute_subset(
1133        &self,
1134        shard_ident: ShardIdent,
1135        cc_config: &CatchainConfig,
1136        cc_seqno: u32,
1137    ) -> Option<(Vec<ValidatorDescription>, u32)> {
1138        if shard_ident.is_masterchain() {
1139            return self.compute_mc_subset(cc_seqno, cc_config.shuffle_mc_validators);
1140        }
1141
1142        let total = self.list.len();
1143        let main = self.main.get() as usize;
1144
1145        let mut prng = ValidatorSetPRNG::new(shard_ident, cc_seqno);
1146
1147        let vset = if cc_config.isolate_mc_validators {
1148            if total <= main {
1149                return None;
1150            }
1151
1152            let mut list = self.list[main..].to_vec();
1153
1154            let mut total_weight = 0u64;
1155            for descr in &mut list {
1156                descr.prev_total_weight = total_weight;
1157                total_weight += descr.weight;
1158            }
1159
1160            std::borrow::Cow::Owned(Self {
1161                utime_since: self.utime_since,
1162                utime_until: self.utime_until,
1163                main: self.main,
1164                total_weight,
1165                list,
1166            })
1167        } else {
1168            std::borrow::Cow::Borrowed(self)
1169        };
1170
1171        let count = std::cmp::min(vset.list.len(), cc_config.shard_validators_num as usize);
1172
1173        let mut nodes = Vec::with_capacity(count);
1174        let mut holes = Vec::<(u64, u64)>::with_capacity(count);
1175        let mut total_wt = vset.total_weight;
1176
1177        for _ in 0..count {
1178            debug_assert!(total_wt > 0);
1179
1180            // Generate a pseudo-random number 0..total_wt-1
1181            let mut p = prng.next_ranged(total_wt);
1182
1183            for (prev_total_weight, weight) in &holes {
1184                if p < *prev_total_weight {
1185                    break;
1186                }
1187                p += weight;
1188            }
1189
1190            let entry = vset.at_weight(p);
1191
1192            nodes.push(ValidatorDescription {
1193                public_key: entry.public_key,
1194                weight: 1,
1195                adnl_addr: entry.adnl_addr,
1196                mc_seqno_since: 0,
1197                prev_total_weight: 0,
1198            });
1199            debug_assert!(total_wt >= entry.weight);
1200            total_wt -= entry.weight;
1201
1202            let new_hole = (entry.prev_total_weight, entry.weight);
1203            let i = holes.partition_point(|item| item <= &new_hole);
1204            debug_assert!(i == 0 || holes[i - 1] < new_hole);
1205
1206            holes.insert(i, new_hole);
1207        }
1208
1209        let hash_short = Self::compute_subset_hash_short(&nodes, cc_seqno);
1210
1211        Some((nodes, hash_short))
1212    }
1213
1214    /// Computes a masterchain validator subset using a zero seed.
1215    ///
1216    /// NOTE: In most cases you should use the more generic [`ValidatorSet::compute_subset`].
1217    pub fn compute_mc_subset(
1218        &self,
1219        cc_seqno: u32,
1220        shuffle: bool,
1221    ) -> Option<(Vec<ValidatorDescription>, u32)> {
1222        let total = self.list.len();
1223        let main = self.main.get() as usize;
1224
1225        let count = std::cmp::min(total, main);
1226        let subset = if !shuffle {
1227            self.list[0..count].to_vec()
1228        } else {
1229            let mut prng = ValidatorSetPRNG::new(ShardIdent::MASTERCHAIN, cc_seqno);
1230
1231            let mut indices = vec![0; count];
1232            for i in 0..count {
1233                let j = prng.next_ranged(i as u64 + 1) as usize; // number 0 .. i
1234                debug_assert!(j <= i);
1235                indices[i] = indices[j];
1236                indices[j] = i;
1237            }
1238
1239            let mut subset = Vec::with_capacity(count);
1240            for index in indices.into_iter().take(count) {
1241                subset.push(self.list[index].clone());
1242            }
1243            subset
1244        };
1245
1246        let hash_short = Self::compute_subset_hash_short(&subset, cc_seqno);
1247        Some((subset, hash_short))
1248    }
1249
1250    /// Computes a masterchain validator subset using a zero seed.
1251    /// Preserves original validator indexes inside vset.
1252    ///
1253    /// NOTE: In most cases you should use the more generic [`ValidatorSet::compute_subset`].
1254    pub fn compute_mc_subset_indexed(
1255        &self,
1256        cc_seqno: u32,
1257        shuffle: bool,
1258    ) -> Option<(Vec<IndexedValidatorDescription>, u32)> {
1259        let total = self.list.len();
1260        let main = self.main.get() as usize;
1261
1262        let count = std::cmp::min(total, main);
1263        let subset = if !shuffle {
1264            self.list[0..count]
1265                .iter()
1266                .enumerate()
1267                .map(|(i, desc)| IndexedValidatorDescription {
1268                    desc: desc.clone(),
1269                    validator_idx: i as u16,
1270                })
1271                .collect::<Vec<_>>()
1272        } else {
1273            let mut prng = ValidatorSetPRNG::new(ShardIdent::MASTERCHAIN, cc_seqno);
1274
1275            let mut indices = vec![0; count];
1276            for i in 0..count {
1277                let j = prng.next_ranged(i as u64 + 1) as usize; // number 0 .. i
1278                debug_assert!(j <= i);
1279                indices[i] = indices[j];
1280                indices[j] = i;
1281            }
1282
1283            let mut subset = Vec::with_capacity(count);
1284            for index in indices.into_iter().take(count) {
1285                subset.push(IndexedValidatorDescription {
1286                    desc: self.list[index].clone(),
1287                    validator_idx: index as u16,
1288                });
1289            }
1290            subset
1291        };
1292
1293        let hash_short =
1294            Self::compute_subset_hash_short(subset.iter().map(AsRef::as_ref), cc_seqno);
1295        Some((subset, hash_short))
1296    }
1297
1298    /// Compoutes a validator subset short hash.
1299    pub fn compute_subset_hash_short<'a, I>(subset: I, cc_seqno: u32) -> u32
1300    where
1301        I: IntoIterator<Item = &'a ValidatorDescription, IntoIter: ExactSizeIterator>,
1302    {
1303        const HASH_SHORT_MAGIC: u32 = 0x901660ED;
1304
1305        let subset = subset.into_iter();
1306
1307        let mut hash = crc32c::crc32c(&HASH_SHORT_MAGIC.to_le_bytes());
1308        hash = crc32c::crc32c_append(hash, &cc_seqno.to_le_bytes());
1309        hash = crc32c::crc32c_append(hash, &(subset.len() as u32).to_le_bytes());
1310
1311        for node in subset {
1312            hash = crc32c::crc32c_append(hash, node.public_key.as_slice());
1313            hash = crc32c::crc32c_append(hash, &node.weight.to_le_bytes());
1314            hash = crc32c::crc32c_append(
1315                hash,
1316                node.adnl_addr
1317                    .as_ref()
1318                    .unwrap_or(HashBytes::wrap(&[0u8; 32]))
1319                    .as_ref(),
1320            );
1321        }
1322
1323        hash
1324    }
1325
1326    #[cfg(not(feature = "tycho"))]
1327    fn at_weight(&self, weight_pos: u64) -> &ValidatorDescription {
1328        debug_assert!(weight_pos < self.total_weight);
1329        debug_assert!(!self.list.is_empty());
1330        let i = self
1331            .list
1332            .partition_point(|item| item.prev_total_weight <= weight_pos);
1333        debug_assert!(i != 0);
1334        &self.list[i - 1]
1335    }
1336}
1337
1338impl Store for ValidatorSet {
1339    fn store_into(
1340        &self,
1341        builder: &mut CellBuilder,
1342        context: &dyn CellContext,
1343    ) -> Result<(), Error> {
1344        let Ok(total) = u16::try_from(self.list.len()) else {
1345            return Err(Error::IntOverflow);
1346        };
1347
1348        // TODO: optimize
1349        let mut validators = Dict::<u16, ValidatorDescription>::new();
1350        for (i, item) in self.list.iter().enumerate() {
1351            ok!(validators.set_ext(i as u16, item, context));
1352        }
1353
1354        ok!(builder.store_u8(Self::TAG_V2));
1355        ok!(builder.store_u32(self.utime_since));
1356        ok!(builder.store_u32(self.utime_until));
1357        ok!(builder.store_u16(total));
1358        ok!(builder.store_u16(self.main.get()));
1359        ok!(builder.store_u64(self.total_weight));
1360        validators.store_into(builder, context)
1361    }
1362}
1363
1364impl<'a> Load<'a> for ValidatorSet {
1365    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
1366        let with_total_weight = match slice.load_u8() {
1367            Ok(Self::TAG_V1) => false,
1368            Ok(Self::TAG_V2) => true,
1369            Ok(_) => return Err(Error::InvalidTag),
1370            Err(e) => return Err(e),
1371        };
1372
1373        let utime_since = ok!(slice.load_u32());
1374        let utime_until = ok!(slice.load_u32());
1375        let total = ok!(slice.load_u16()) as usize;
1376        let main = ok!(NonZeroU16::load_from(slice));
1377        if main.get() as usize > total {
1378            return Err(Error::InvalidData);
1379        }
1380
1381        let context = Cell::empty_context();
1382
1383        let (mut total_weight, validators) = if with_total_weight {
1384            let total_weight = ok!(slice.load_u64());
1385            let dict = ok!(Dict::<u16, ValidatorDescription>::load_from(slice));
1386            (total_weight, dict)
1387        } else {
1388            let dict = ok!(Dict::<u16, ValidatorDescription>::load_from_root_ext(
1389                slice, context
1390            ));
1391            (0, dict)
1392        };
1393
1394        let mut computed_total_weight = 0u64;
1395        let mut list = Vec::with_capacity(std::cmp::min(total, 512));
1396        for (i, entry) in validators.iter().enumerate().take(total) {
1397            let mut descr = match entry {
1398                Ok((idx, descr)) if idx as usize == i => descr,
1399                Ok(_) => return Err(Error::InvalidData),
1400                Err(e) => return Err(e),
1401            };
1402
1403            descr.prev_total_weight = computed_total_weight;
1404            computed_total_weight = match computed_total_weight.checked_add(descr.weight) {
1405                Some(weight) => weight,
1406                None => return Err(Error::InvalidData),
1407            };
1408            list.push(descr);
1409        }
1410
1411        if list.is_empty() {
1412            return Err(Error::InvalidData);
1413        }
1414
1415        if with_total_weight {
1416            if total_weight != computed_total_weight {
1417                return Err(Error::InvalidData);
1418            }
1419        } else {
1420            total_weight = computed_total_weight;
1421        }
1422
1423        Ok(Self {
1424            utime_since,
1425            utime_until,
1426            main,
1427            total_weight,
1428            list,
1429        })
1430    }
1431}
1432
1433#[cfg(feature = "serde")]
1434impl<'de> serde::Deserialize<'de> for ValidatorSet {
1435    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1436        use serde::de::Error;
1437
1438        #[derive(serde::Deserialize)]
1439        struct ValidatorSetHelper {
1440            utime_since: u32,
1441            utime_until: u32,
1442            main: NonZeroU16,
1443            #[serde(default)]
1444            total_weight: u64,
1445            list: Vec<ValidatorDescription>,
1446        }
1447
1448        let parsed = ValidatorSetHelper::deserialize(deserializer)?;
1449        if parsed.list.is_empty() {
1450            return Err(Error::custom("empty validators list"));
1451        }
1452
1453        let mut result = Self {
1454            utime_since: parsed.utime_since,
1455            utime_until: parsed.utime_until,
1456            main: parsed.main,
1457            total_weight: 0,
1458            list: parsed.list,
1459        };
1460
1461        for descr in &mut result.list {
1462            descr.prev_total_weight = result.total_weight;
1463            let Some(new_total_weight) = result.total_weight.checked_add(descr.weight) else {
1464                return Err(Error::custom("total weight overflow"));
1465            };
1466            result.total_weight = new_total_weight;
1467        }
1468
1469        if parsed.total_weight > 0 && parsed.total_weight != result.total_weight {
1470            return Err(Error::custom("total weight mismatch"));
1471        }
1472
1473        Ok(result)
1474    }
1475}
1476
1477/// Validator description.
1478#[derive(Debug, Clone, Eq, PartialEq)]
1479#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1480pub struct ValidatorDescription {
1481    /// Validator public key.
1482    pub public_key: HashBytes, // TODO: replace with tycho_crypto::ed25519::PublicKey ?
1483    /// Validator weight in some units.
1484    pub weight: u64,
1485    /// Optional validator ADNL address.
1486    #[cfg_attr(feature = "serde", serde(default))]
1487    pub adnl_addr: Option<HashBytes>,
1488    /// Since which seqno this validator will be active.
1489    #[cfg_attr(feature = "serde", serde(default))]
1490    pub mc_seqno_since: u32,
1491
1492    /// Total weight of the previous validators in the list.
1493    /// The field is not serialized.
1494    #[cfg_attr(feature = "serde", serde(skip))]
1495    pub prev_total_weight: u64,
1496}
1497
1498impl ValidatorDescription {
1499    const TAG_BASIC: u8 = 0x53;
1500    const TAG_WITH_ADNL: u8 = 0x73;
1501    const TAG_WITH_MC_SEQNO: u8 = 0x93;
1502
1503    const PUBKEY_TAG: u32 = 0x8e81278a;
1504
1505    /// Verifies message signature and current public key.
1506    pub fn verify_signature(&self, data: &[u8], signature: &Signature) -> bool {
1507        if let Some(public_key) = ed25519::PublicKey::from_bytes(self.public_key.0) {
1508            public_key.verify_raw(data, signature.as_ref())
1509        } else {
1510            false
1511        }
1512    }
1513}
1514
1515impl Store for ValidatorDescription {
1516    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
1517        let with_mc_seqno = self.mc_seqno_since != 0;
1518
1519        let tag = if with_mc_seqno {
1520            Self::TAG_WITH_MC_SEQNO
1521        } else if self.adnl_addr.is_some() {
1522            Self::TAG_WITH_ADNL
1523        } else {
1524            Self::TAG_BASIC
1525        };
1526
1527        ok!(builder.store_u8(tag));
1528        ok!(builder.store_u32(Self::PUBKEY_TAG));
1529        ok!(builder.store_u256(&self.public_key));
1530        ok!(builder.store_u64(self.weight));
1531
1532        let mut adnl = self.adnl_addr.as_ref();
1533        if with_mc_seqno {
1534            adnl = Some(HashBytes::wrap(&[0; 32]));
1535        }
1536
1537        if let Some(adnl) = adnl {
1538            ok!(builder.store_u256(adnl));
1539        }
1540
1541        if with_mc_seqno {
1542            builder.store_u32(self.mc_seqno_since)
1543        } else {
1544            Ok(())
1545        }
1546    }
1547}
1548
1549impl<'a> Load<'a> for ValidatorDescription {
1550    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
1551        let (with_adnl, with_mc_seqno) = match slice.load_u8() {
1552            Ok(Self::TAG_BASIC) => (false, false),
1553            Ok(Self::TAG_WITH_ADNL) => (true, false),
1554            Ok(Self::TAG_WITH_MC_SEQNO) => (true, true),
1555            Ok(_) => return Err(Error::InvalidTag),
1556            Err(e) => return Err(e),
1557        };
1558
1559        Ok(Self {
1560            public_key: {
1561                match slice.load_u32() {
1562                    Ok(Self::PUBKEY_TAG) => ok!(slice.load_u256()),
1563                    Ok(_) => return Err(Error::InvalidTag),
1564                    Err(e) => return Err(e),
1565                }
1566            },
1567            weight: ok!(slice.load_u64()),
1568            adnl_addr: if with_adnl {
1569                Some(ok!(slice.load_u256()))
1570            } else {
1571                None
1572            },
1573            mc_seqno_since: if with_mc_seqno {
1574                ok!(slice.load_u32())
1575            } else {
1576                0
1577            },
1578            prev_total_weight: 0,
1579        })
1580    }
1581}
1582
1583/// Validator description with its original index in vset.
1584#[derive(Debug, Clone, Eq, PartialEq)]
1585#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1586pub struct IndexedValidatorDescription {
1587    /// Validator description.
1588    pub desc: ValidatorDescription,
1589    /// Index in the original validator set.
1590    pub validator_idx: u16,
1591}
1592
1593impl AsRef<ValidatorDescription> for IndexedValidatorDescription {
1594    #[inline]
1595    fn as_ref(&self) -> &ValidatorDescription {
1596        &self.desc
1597    }
1598}
1599
1600impl AsMut<ValidatorDescription> for IndexedValidatorDescription {
1601    #[inline]
1602    fn as_mut(&mut self) -> &mut ValidatorDescription {
1603        &mut self.desc
1604    }
1605}
1606
1607impl std::ops::Deref for IndexedValidatorDescription {
1608    type Target = ValidatorDescription;
1609
1610    #[inline]
1611    fn deref(&self) -> &Self::Target {
1612        &self.desc
1613    }
1614}
1615
1616impl std::ops::DerefMut for IndexedValidatorDescription {
1617    #[inline]
1618    fn deref_mut(&mut self) -> &mut Self::Target {
1619        &mut self.desc
1620    }
1621}
1622
1623/// Random generator used for validator subset calculation.
1624pub struct ValidatorSetPRNG {
1625    context: [u8; 48],
1626    bag: [u64; 8],
1627}
1628
1629impl ValidatorSetPRNG {
1630    /// Creates a new generator with zero seed.
1631    pub fn new(shard_ident: ShardIdent, cc_seqno: u32) -> Self {
1632        let seed = [0; 32];
1633        Self::with_seed(shard_ident, cc_seqno, &seed)
1634    }
1635
1636    /// Creates a new generator with the specified seed.
1637    pub fn with_seed(shard_ident: ShardIdent, cc_seqno: u32, seed: &[u8; 32]) -> Self {
1638        let mut context = [0u8; 48];
1639        context[..32].copy_from_slice(seed);
1640        context[32..40].copy_from_slice(&shard_ident.prefix().to_be_bytes());
1641        context[40..44].copy_from_slice(&shard_ident.workchain().to_be_bytes());
1642        context[44..48].copy_from_slice(&cc_seqno.to_be_bytes());
1643
1644        let mut res = ValidatorSetPRNG {
1645            context,
1646            bag: [0; 8],
1647        };
1648        res.bag[0] = 8;
1649        res
1650    }
1651
1652    /// Generates next `u64`.
1653    pub fn next_u64(&mut self) -> u64 {
1654        if self.cursor() < 7 {
1655            let next = self.bag[1 + self.cursor() as usize];
1656            self.bag[0] += 1;
1657            next
1658        } else {
1659            self.reset()
1660        }
1661    }
1662
1663    /// Generates next `u64` multiplied by the specified range.
1664    pub fn next_ranged(&mut self, range: u64) -> u64 {
1665        let val = self.next_u64();
1666        ((range as u128 * val as u128) >> 64) as u64
1667    }
1668
1669    fn reset(&mut self) -> u64 {
1670        use sha2::digest::Digest;
1671
1672        let hash: [u8; 64] = sha2::Sha512::digest(self.context).into();
1673
1674        for ctx in self.context[..32].iter_mut().rev() {
1675            *ctx = ctx.wrapping_add(1);
1676            if *ctx != 0 {
1677                break;
1678            }
1679        }
1680
1681        // SAFETY: `std::mem::size_of::<[u64; 8]>() == 64` and src alignment is 1
1682        unsafe {
1683            std::ptr::copy_nonoverlapping(hash.as_ptr(), self.bag.as_mut_ptr() as *mut u8, 64);
1684        }
1685
1686        // Swap bytes for little endian
1687        #[cfg(target_endian = "little")]
1688        self.bag
1689            .iter_mut()
1690            .for_each(|item| *item = item.swap_bytes());
1691
1692        // Reset and use bag[0] as counter
1693        std::mem::take(&mut self.bag[0])
1694    }
1695
1696    #[inline]
1697    const fn cursor(&self) -> u64 {
1698        self.bag[0]
1699    }
1700}
1701
1702/// size_limits_config_v2#02
1703///     max_msg_bits:uint32
1704///     max_msg_cells:uint32
1705///     max_library_cells:uint32
1706///     max_vm_data_depth:uint16
1707///     max_ext_msg_size:uint32
1708///     max_ext_msg_depth:uint16
1709///     max_acc_state_cells:uint32
1710///     max_acc_state_bits:uint32
1711///     max_acc_public_libraries:uint32
1712///     defer_out_queue_size_limit:uint32 = SizeLimitsConfig;
1713#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
1714#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1715#[tlb(tag = "#02")]
1716pub struct SizeLimitsConfig {
1717    /// Max number of bits in message.
1718    pub max_msg_bits: u32,
1719    /// Max number of cells in message.
1720    pub max_msg_cells: u32,
1721    /// Max number of cells in library.
1722    pub max_library_cells: u32,
1723    /// Max cell tree depth for VM data.
1724    pub max_vm_data_depth: u16,
1725    /// Max number of bytes of a BOC-encoded external message.
1726    pub max_ext_msg_size: u32,
1727    /// Max cell tree depth of an external message.
1728    pub max_ext_msg_depth: u16,
1729    /// Max number of cells per account.
1730    pub max_acc_state_cells: u32,
1731    /// Max number of bits per account.
1732    pub max_acc_state_bits: u32,
1733    /// Max number of public libraries per account.
1734    pub max_acc_public_libraries: u32,
1735    /// Size limit of a deferred out messages queue.
1736    pub defer_out_queue_size_limit: u32,
1737}
1738
1739const fn shift_ceil_price(value: u128) -> u128 {
1740    let r = value & 0xffff != 0;
1741    (value >> 16) + r as u128
1742}
1743
1744/// Authority marks configuration.
1745#[derive(Debug, Clone, Eq, PartialEq, Store, Load)]
1746#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1747#[tlb(tag = "#01")]
1748pub struct AuthorityMarksConfig {
1749    /// Addresses in masterchain that can manage authority marks.
1750    pub authority_addresses: Dict<HashBytes, ()>,
1751    /// Black mark extra currency id.
1752    pub black_mark_id: u32,
1753    /// White mark extra currency id.
1754    pub white_mark_id: u32,
1755}
1756
1757#[cfg(test)]
1758mod tests {
1759    use super::*;
1760
1761    #[test]
1762    fn validator_set_prng() {
1763        fn make_indices(cc_seqno: u32) -> Vec<usize> {
1764            let mut prng = ValidatorSetPRNG::new(ShardIdent::BASECHAIN, cc_seqno);
1765
1766            let count = 10;
1767            let mut indices = vec![0; count];
1768            for i in 0..count {
1769                let j = prng.next_ranged(i as u64 + 1) as usize;
1770                debug_assert!(j <= i);
1771                indices[i] = indices[j];
1772                indices[j] = i;
1773            }
1774
1775            indices
1776        }
1777
1778        let vs10_first = make_indices(10);
1779        let vs10_second = make_indices(10);
1780        assert_eq!(vs10_first, vs10_second);
1781
1782        let vs11_first = make_indices(11);
1783        let vs11_second = make_indices(11);
1784        assert_eq!(vs11_first, vs11_second);
1785        assert_ne!(vs10_first, vs11_second);
1786    }
1787}