Skip to main content

solana_program_runtime/
execution_budget.rs

1use {
2    solana_fee_structure::FeeDetails, solana_program_entrypoint::HEAP_LENGTH,
3    solana_transaction_context::MAX_INSTRUCTION_TRACE_LENGTH, std::num::NonZeroU32,
4};
5
6/// Max instruction stack depth. This is the maximum nesting of instructions that can happen during
7/// a transaction.
8pub const MAX_INSTRUCTION_STACK_DEPTH: usize = 5;
9/// Max instruction stack depth with SIMD-0268 enabled. Allows 8 nested CPIs.
10pub const MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268: usize = 9;
11
12fn get_max_instruction_stack_depth(simd_0268_active: bool) -> usize {
13    if simd_0268_active {
14        MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268
15    } else {
16        MAX_INSTRUCTION_STACK_DEPTH
17    }
18}
19
20//Default CPI invocation cost
21pub const DEFAULT_INVOCATION_COST: u64 = 946;
22
23/// Max call depth. This is the maximum nesting of SBF to SBF call that can happen within a program.
24pub const MAX_CALL_DEPTH: usize = 64;
25
26pub const MAX_COMPUTE_UNIT_LIMIT: u32 = 1_400_000;
27
28/// Roughly 0.5us/page, where page is 32K; given roughly 15CU/us, the
29/// default heap page cost = 0.5 * 15 ~= 8CU/page
30pub const DEFAULT_HEAP_COST: u64 = 8;
31pub const DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT: u32 = 200_000;
32// SIMD-170 defines max CUs to be allocated for any builtin program instructions, that
33// have not been migrated to sBPF programs.
34pub const MAX_BUILTIN_ALLOCATION_COMPUTE_UNIT_LIMIT: u32 = 3_000;
35pub const MAX_HEAP_FRAME_BYTES: u32 = 256 * 1024;
36pub const MIN_HEAP_FRAME_BYTES: u32 = HEAP_LENGTH as u32;
37
38/// The total accounts data a transaction can load is limited to 64MiB to not break
39/// anyone in Mainnet-beta today. It can be set by set_loaded_accounts_data_size_limit instruction
40pub const MAX_LOADED_ACCOUNTS_DATA_SIZE_BYTES: NonZeroU32 =
41    NonZeroU32::new(64 * 1024 * 1024).unwrap();
42
43#[cfg(test)]
44static_assertions::const_assert_eq!(
45    DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT,
46    solana_transaction_context::DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT,
47);
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct SVMTransactionExecutionBudget {
51    /// Number of compute units that a transaction or individual instruction is
52    /// allowed to consume. Compute units are consumed by program execution,
53    /// resources they use, etc...
54    pub compute_unit_limit: u64,
55    /// Maximum program instruction invocation stack depth. Invocation stack
56    /// depth starts at 1 for transaction instructions and the stack depth is
57    /// incremented each time a program invokes an instruction and decremented
58    /// when a program returns.
59    pub max_instruction_stack_depth: usize,
60    /// Maximum cross-program invocation and instructions per transaction
61    pub max_instruction_trace_length: usize,
62    /// Maximum number of slices hashed per syscall
63    pub sha256_max_slices: u64,
64    /// Maximum SBF to BPF call depth
65    pub max_call_depth: usize,
66    /// Size of a stack frame in bytes, must match the size specified in the LLVM SBF backend
67    pub stack_frame_size: usize,
68    /// program heap region size, default: solana_program_entrypoint::HEAP_LENGTH
69    pub heap_size: u32,
70}
71
72#[cfg(feature = "dev-context-only-utils")]
73impl Default for SVMTransactionExecutionBudget {
74    fn default() -> Self {
75        Self::new_with_defaults(/* simd_0268_active */ false)
76    }
77}
78
79impl SVMTransactionExecutionBudget {
80    pub fn new_with_defaults(simd_0268_active: bool) -> Self {
81        SVMTransactionExecutionBudget {
82            compute_unit_limit: u64::from(MAX_COMPUTE_UNIT_LIMIT),
83            max_instruction_stack_depth: get_max_instruction_stack_depth(simd_0268_active),
84            max_instruction_trace_length: MAX_INSTRUCTION_TRACE_LENGTH,
85            sha256_max_slices: 20_000,
86            max_call_depth: MAX_CALL_DEPTH,
87            stack_frame_size: solana_sbpf::vm::get_stack_frame_size(),
88            heap_size: u32::try_from(solana_program_entrypoint::HEAP_LENGTH).unwrap(),
89        }
90    }
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub struct SVMTransactionExecutionCost {
95    /// Number of compute units consumed by a log_u64 call
96    pub log_64_units: u64,
97    /// Number of compute units consumed by a create_program_address call
98    pub create_program_address_units: u64,
99    /// Number of compute units consumed by an invoke call (not including the cost incurred by
100    /// the called program)
101    pub invoke_units: u64,
102    /// Base number of compute units consumed to call SHA256
103    pub sha256_base_cost: u64,
104    /// Incremental number of units consumed by SHA256 (based on bytes)
105    pub sha256_byte_cost: u64,
106    /// Number of compute units consumed by logging a `Pubkey`
107    pub log_pubkey_units: u64,
108    /// Number of account data bytes per compute unit charged during a cross-program invocation
109    pub cpi_bytes_per_unit: u64,
110    /// Base number of compute units consumed to get a sysvar
111    pub sysvar_base_cost: u64,
112    /// Number of compute units consumed to call secp256k1_recover
113    pub secp256k1_recover_cost: u64,
114    /// Number of compute units consumed to do a syscall without any work
115    pub syscall_base_cost: u64,
116    /// Number of compute units consumed to validate a curve25519 edwards point
117    pub curve25519_edwards_validate_point_cost: u64,
118    /// Number of compute units consumed to add two curve25519 edwards points
119    pub curve25519_edwards_add_cost: u64,
120    /// Number of compute units consumed to subtract two curve25519 edwards points
121    pub curve25519_edwards_subtract_cost: u64,
122    /// Number of compute units consumed to multiply a curve25519 edwards point
123    pub curve25519_edwards_multiply_cost: u64,
124    /// Number of compute units consumed for a multiscalar multiplication (msm) of edwards points.
125    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
126    pub curve25519_edwards_msm_base_cost: u64,
127    /// Number of compute units consumed for a multiscalar multiplication (msm) of edwards points.
128    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
129    pub curve25519_edwards_msm_incremental_cost: u64,
130    /// Number of compute units consumed to validate a curve25519 ristretto point
131    pub curve25519_ristretto_validate_point_cost: u64,
132    /// Number of compute units consumed to add two curve25519 ristretto points
133    pub curve25519_ristretto_add_cost: u64,
134    /// Number of compute units consumed to subtract two curve25519 ristretto points
135    pub curve25519_ristretto_subtract_cost: u64,
136    /// Number of compute units consumed to multiply a curve25519 ristretto point
137    pub curve25519_ristretto_multiply_cost: u64,
138    /// Number of compute units consumed for a multiscalar multiplication (msm) of ristretto points.
139    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
140    pub curve25519_ristretto_msm_base_cost: u64,
141    /// Number of compute units consumed for a multiscalar multiplication (msm) of ristretto points.
142    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
143    pub curve25519_ristretto_msm_incremental_cost: u64,
144    /// Number of compute units per additional 32k heap above the default (~.5
145    /// us per 32k at 15 units/us rounded up)
146    pub heap_cost: u64,
147    /// Memory operation syscall base cost
148    pub mem_op_base_cost: u64,
149    /// Number of compute units consumed to call alt_bn128_g1_addition
150    pub alt_bn128_g1_addition_cost: u64,
151    /// Number of compute units consumed to call alt_bn128_g2_addition
152    pub alt_bn128_g2_addition_cost: u64,
153    /// Number of compute units consumed to call alt_bn128_g1_multiplication.
154    pub alt_bn128_g1_multiplication_cost: u64,
155    /// Number of compute units consumed to call alt_bn128_g2_multiplication.
156    pub alt_bn128_g2_multiplication_cost: u64,
157    /// Total cost will be alt_bn128_pairing_one_pair_cost_first
158    /// + alt_bn128_pairing_one_pair_cost_other * (num_elems - 1)
159    pub alt_bn128_pairing_one_pair_cost_first: u64,
160    pub alt_bn128_pairing_one_pair_cost_other: u64,
161    /// Big integer modular exponentiation base cost
162    pub big_modular_exponentiation_base_cost: u64,
163    /// Big integer modular exponentiation cost divisor.
164    /// The modular exponentiation cost is the SIMD-0529 operand complexity
165    /// times the number of multiplications for the exponent's 64-bit words,
166    /// divided by this divisor and rounded up, plus
167    /// `big_modular_exponentiation_base_cost`. An exponent of 1 is priced as a
168    /// single modular reduction with a fixed divisor of 15 instead.
169    pub big_modular_exponentiation_cost_divisor: u64,
170    /// Coefficient `a` of the quadratic function which determines the number
171    /// of compute units consumed to call poseidon syscall for a given number
172    /// of inputs.
173    pub poseidon_cost_coefficient_a: u64,
174    /// Coefficient `c` of the quadratic function which determines the number
175    /// of compute units consumed to call poseidon syscall for a given number
176    /// of inputs.
177    pub poseidon_cost_coefficient_c: u64,
178    /// Number of compute units consumed for accessing the remaining compute units.
179    pub get_remaining_compute_units_cost: u64,
180    /// Number of compute units consumed to call alt_bn128_g1_compress.
181    pub alt_bn128_g1_compress: u64,
182    /// Number of compute units consumed to call alt_bn128_g1_decompress.
183    pub alt_bn128_g1_decompress: u64,
184    /// Number of compute units consumed to call alt_bn128_g2_compress.
185    pub alt_bn128_g2_compress: u64,
186    /// Number of compute units consumed to call alt_bn128_g2_decompress.
187    pub alt_bn128_g2_decompress: u64,
188    /// Number of compute units consumed to add two bls12_381 g1 points.
189    pub bls12_381_g1_add_cost: u64,
190    /// Number of compute units consumed to add two bls12_381 g2 points.
191    pub bls12_381_g2_add_cost: u64,
192    /// Number of compute units consumed to subtract two bls12_381 g1 points.
193    pub bls12_381_g1_subtract_cost: u64,
194    /// Number of compute units consumed to subtract two bls12_381 g2 points.
195    pub bls12_381_g2_subtract_cost: u64,
196    /// Number of compute units consumed to multiply a bls12_381 g1 point.
197    pub bls12_381_g1_multiply_cost: u64,
198    /// Number of compute units consumed to multiply a bls12_381 g2 point.
199    pub bls12_381_g2_multiply_cost: u64,
200    /// Number of compute units consumed to decompress a bls12_381 g1 point.
201    pub bls12_381_g1_decompress_cost: u64,
202    /// Number of compute units consumed to decompress a bls12_381 g2 point.
203    pub bls12_381_g2_decompress_cost: u64,
204    /// Number of compute units consumed to validate a bls12_381 g1 point.
205    pub bls12_381_g1_validate_cost: u64,
206    /// Number of compute units consumed to validate a bls12_381 g2 point.
207    pub bls12_381_g2_validate_cost: u64,
208    /// Base number of compute units consumed to perform a bls12_381 pairing.
209    pub bls12_381_one_pair_cost: u64,
210    /// Incremental number of compute units consumed per pair in a bls12_381 pairing.
211    pub bls12_381_additional_pair_cost: u64,
212    /// Number of compute units consumed to add two secp256r1 points
213    pub secp256r1_add_cost: u64,
214    /// Number of compute units consumed to subtract two secp256r1 points
215    pub secp256r1_subtract_cost: u64,
216    /// Number of compute units consumed to multiply a secp256r1 point
217    pub secp256r1_multiply_cost: u64,
218    /// Number of compute units consumed for a multiscalar multiplication (msm) of secp256r1 points.
219    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
220    pub secp256r1_msm_base_cost: u64,
221    /// Number of compute units consumed for a multiscalar multiplication (msm) of secp256r1 points.
222    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
223    pub secp256r1_msm_incremental_cost: u64,
224    /// Number of compute units consumed to validate a secp256r1 point.
225    pub secp256r1_validate_cost: u64,
226    /// Number of compute units consumed to decompress a secp256r1 point.
227    pub secp256r1_decompress_cost: u64,
228}
229
230impl Default for SVMTransactionExecutionCost {
231    fn default() -> Self {
232        SVMTransactionExecutionCost {
233            log_64_units: 100,
234            create_program_address_units: 1500,
235            invoke_units: DEFAULT_INVOCATION_COST,
236            sha256_base_cost: 85,
237            sha256_byte_cost: 1,
238            log_pubkey_units: 100,
239            cpi_bytes_per_unit: 250, // ~50MB at 200,000 units
240            sysvar_base_cost: 100,
241            secp256k1_recover_cost: 25_000,
242            syscall_base_cost: 100,
243            curve25519_edwards_validate_point_cost: 159,
244            curve25519_edwards_add_cost: 473,
245            curve25519_edwards_subtract_cost: 475,
246            curve25519_edwards_multiply_cost: 2_177,
247            curve25519_edwards_msm_base_cost: 2_273,
248            curve25519_edwards_msm_incremental_cost: 758,
249            curve25519_ristretto_validate_point_cost: 169,
250            curve25519_ristretto_add_cost: 521,
251            curve25519_ristretto_subtract_cost: 519,
252            curve25519_ristretto_multiply_cost: 2_208,
253            curve25519_ristretto_msm_base_cost: 2303,
254            curve25519_ristretto_msm_incremental_cost: 788,
255            heap_cost: DEFAULT_HEAP_COST,
256            mem_op_base_cost: 10,
257            alt_bn128_g1_addition_cost: 334,
258            alt_bn128_g2_addition_cost: 535,
259            alt_bn128_g1_multiplication_cost: 3_840,
260            alt_bn128_g2_multiplication_cost: 15_670,
261            alt_bn128_pairing_one_pair_cost_first: 36_364,
262            alt_bn128_pairing_one_pair_cost_other: 12_121,
263            big_modular_exponentiation_base_cost: 50,
264            big_modular_exponentiation_cost_divisor: 4,
265            poseidon_cost_coefficient_a: 61,
266            poseidon_cost_coefficient_c: 542,
267            get_remaining_compute_units_cost: 100,
268            alt_bn128_g1_compress: 30,
269            alt_bn128_g1_decompress: 398,
270            alt_bn128_g2_compress: 86,
271            alt_bn128_g2_decompress: 13610,
272            bls12_381_g1_add_cost: 128,
273            bls12_381_g2_add_cost: 203,
274            bls12_381_g1_subtract_cost: 129,
275            bls12_381_g2_subtract_cost: 204,
276            bls12_381_g1_multiply_cost: 4_627,
277            bls12_381_g2_multiply_cost: 8_255,
278            bls12_381_g1_decompress_cost: 2_100,
279            bls12_381_g2_decompress_cost: 3_050,
280            bls12_381_g1_validate_cost: 1_565,
281            bls12_381_g2_validate_cost: 1_968,
282            bls12_381_one_pair_cost: 25_445,
283            bls12_381_additional_pair_cost: 13_023,
284            secp256r1_add_cost: 520,
285            secp256r1_subtract_cost: 520,
286            secp256r1_multiply_cost: 9_000,
287            secp256r1_msm_base_cost: 9_000,
288            secp256r1_msm_incremental_cost: 3_800,
289            secp256r1_validate_cost: 20,
290            secp256r1_decompress_cost: 610,
291        }
292    }
293}
294
295impl SVMTransactionExecutionCost {
296    /// Returns cost of the Poseidon hash function for the given number of
297    /// inputs is determined by the following quadratic function:
298    ///
299    /// 61*n^2 + 542
300    ///
301    /// Which approximates the results of benchmarks of light-posiedon
302    /// library[0]. These results assume 1 CU per 33 ns. Examples:
303    ///
304    /// * 1 input
305    ///   * light-poseidon benchmark: `18,303 / 33 ≈ 555`
306    ///   * function: `61*1^2 + 542 = 603`
307    /// * 2 inputs
308    ///   * light-poseidon benchmark: `25,866 / 33 ≈ 784`
309    ///   * function: `61*2^2 + 542 = 786`
310    /// * 3 inputs
311    ///   * light-poseidon benchmark: `37,549 / 33 ≈ 1,138`
312    ///   * function; `61*3^2 + 542 = 1091`
313    ///
314    /// [0] https://github.com/Lightprotocol/light-poseidon#performance
315    pub fn poseidon_cost(&self, nr_inputs: u64) -> Option<u64> {
316        let squared_inputs = nr_inputs.checked_pow(2)?;
317        let mul_result = self
318            .poseidon_cost_coefficient_a
319            .checked_mul(squared_inputs)?;
320        let final_result = mul_result.checked_add(self.poseidon_cost_coefficient_c)?;
321
322        Some(final_result)
323    }
324
325    /// Compute the operation cost of a big integer modular exponentiation, i.e. the
326    /// cost charged on top of the flat `big_modular_exponentiation_base_cost`.
327    pub fn big_mod_exp_operation_cost(
328        &self,
329        base_len: u64,
330        modulus_len: u64,
331        exponent: &[u8],
332    ) -> Option<u64> {
333        let input_len = base_len.max(modulus_len);
334        let mult_complexity = big_mod_exp_mult_complexity(input_len)?;
335        let (operation_complexity, divisor) = if big_mod_exp_is_one_le(exponent) {
336            (mult_complexity, BIG_MOD_EXP_MOD_REDUCTION_CU_DIVISOR)
337        } else {
338            let exponent_words = big_mod_exp_adjusted_exponent_length(exponent)
339                .checked_div(64)?
340                .checked_add(1)?;
341            let multiplications = BIG_MOD_EXP_MULTIPLICATIONS_PER_EXPONENT_WORD
342                .checked_mul(exponent_words)?
343                .checked_add(BIG_MOD_EXP_SETUP_MULTIPLICATIONS)?;
344            (
345                mult_complexity.checked_mul(u128::from(multiplications))?,
346                self.big_modular_exponentiation_cost_divisor,
347            )
348        };
349        let divisor = u128::from(divisor);
350        if divisor == 0 {
351            return None;
352        }
353
354        let operation_cost = operation_complexity
355            .checked_add(divisor.checked_sub(1)?)?
356            .checked_div(divisor)?;
357        u64::try_from(operation_cost).ok()
358    }
359}
360
361const BIG_MOD_EXP_MULT_COMPLEXITY_CONSTANT: u64 = 22;
362const BIG_MOD_EXP_SETUP_MULTIPLICATIONS: u64 = 12;
363const BIG_MOD_EXP_MULTIPLICATIONS_PER_EXPONENT_WORD: u64 = 80;
364const BIG_MOD_EXP_MOD_REDUCTION_CU_DIVISOR: u64 = 15;
365
366fn big_mod_exp_mult_complexity(input_len: u64) -> Option<u128> {
367    let operand_words = u128::from(input_len.div_ceil(8));
368    operand_words
369        .checked_mul(operand_words)?
370        .checked_add(u128::from(BIG_MOD_EXP_MULT_COMPLEXITY_CONSTANT))
371}
372
373fn big_mod_exp_highest_set_bit_index_le(bytes: &[u8]) -> Option<u64> {
374    bytes.iter().enumerate().rev().find_map(|(index, byte)| {
375        (*byte != 0).then(|| {
376            (index as u64)
377                .saturating_mul(u64::from(u8::BITS))
378                .saturating_add(u64::from(7_u32.saturating_sub(byte.leading_zeros())))
379        })
380    })
381}
382
383fn big_mod_exp_adjusted_exponent_length(exponent: &[u8]) -> u64 {
384    if exponent.len() <= 32 {
385        big_mod_exp_highest_set_bit_index_le(exponent).unwrap_or(0)
386    } else {
387        let (trailing_bytes, most_significant_32_bytes) =
388            exponent.split_at(exponent.len().saturating_sub(32));
389        (trailing_bytes.len() as u64)
390            .saturating_mul(u64::from(u8::BITS))
391            .saturating_add(
392                big_mod_exp_highest_set_bit_index_le(most_significant_32_bytes).unwrap_or(0),
393            )
394    }
395}
396
397fn big_mod_exp_is_one_le(bytes: &[u8]) -> bool {
398    matches!(bytes.split_first(), Some((1, rest)) if rest.iter().all(|byte| *byte == 0))
399}
400
401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402pub struct SVMTransactionExecutionAndFeeBudgetLimits {
403    pub budget: SVMTransactionExecutionBudget,
404    pub loaded_accounts_data_size_limit: u32,
405    pub fee_details: FeeDetails,
406}
407
408#[cfg(feature = "dev-context-only-utils")]
409impl Default for SVMTransactionExecutionAndFeeBudgetLimits {
410    fn default() -> Self {
411        Self {
412            budget: SVMTransactionExecutionBudget::default(),
413            loaded_accounts_data_size_limit: MAX_LOADED_ACCOUNTS_DATA_SIZE_BYTES.get(),
414            fee_details: FeeDetails::default(),
415        }
416    }
417}
418
419#[cfg(feature = "dev-context-only-utils")]
420impl SVMTransactionExecutionAndFeeBudgetLimits {
421    pub fn with_fee(fee_details: FeeDetails) -> Self {
422        Self {
423            fee_details,
424            ..SVMTransactionExecutionAndFeeBudgetLimits::default()
425        }
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432
433    #[test]
434    fn test_big_mod_exp_cost() {
435        let execution_cost = SVMTransactionExecutionCost::default();
436        let cost = |base_len: u64, modulus_len: u64, exponent: &[u8]| {
437            execution_cost.big_modular_exponentiation_base_cost
438                + execution_cost
439                    .big_mod_exp_operation_cost(base_len, modulus_len, exponent)
440                    .unwrap()
441        };
442
443        // Costs listed in SIMD-0529
444        let exponent_65537 = [0x01, 0x00, 0x01];
445        assert_eq!(cost(256, 256, &exponent_65537), 24_108);
446        assert_eq!(cost(512, 512, &exponent_65537), 94_764);
447        assert_eq!(cost(512, 512, &[0xff; 128]), 1_330_164);
448        assert_eq!(cost(8, 8, &[0xff; 512]), 29_559);
449        assert_eq!(cost(512, 256, &[0x01]), 325);
450
451        // The reduction path is chosen by the exponent value, not its encoded or adjusted length
452        assert_eq!(cost(512, 256, &[0x01, 0x00, 0x00]), 325);
453        assert_eq!(cost(512, 256, &[0x00]), cost(512, 256, &[0x01, 0x01]));
454    }
455}