solana-program-runtime 4.5.0-beta.0

Solana program runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use {
    solana_fee_structure::FeeDetails, solana_program_entrypoint::HEAP_LENGTH,
    solana_transaction_context::MAX_INSTRUCTION_TRACE_LENGTH, std::num::NonZeroU32,
};

/// Max instruction stack depth. This is the maximum nesting of instructions that can happen during
/// a transaction.
pub const MAX_INSTRUCTION_STACK_DEPTH: usize = 5;
/// Max instruction stack depth with SIMD-0268 enabled. Allows 8 nested CPIs.
pub const MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268: usize = 9;

fn get_max_instruction_stack_depth(simd_0268_active: bool) -> usize {
    if simd_0268_active {
        MAX_INSTRUCTION_STACK_DEPTH_SIMD_0268
    } else {
        MAX_INSTRUCTION_STACK_DEPTH
    }
}

//Default CPI invocation cost
pub const DEFAULT_INVOCATION_COST: u64 = 946;

/// Max call depth. This is the maximum nesting of SBF to SBF call that can happen within a program.
pub const MAX_CALL_DEPTH: usize = 64;

pub const MAX_COMPUTE_UNIT_LIMIT: u32 = 1_400_000;

/// Roughly 0.5us/page, where page is 32K; given roughly 15CU/us, the
/// default heap page cost = 0.5 * 15 ~= 8CU/page
pub const DEFAULT_HEAP_COST: u64 = 8;
pub const DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT: u32 = 200_000;
// SIMD-170 defines max CUs to be allocated for any builtin program instructions, that
// have not been migrated to sBPF programs.
pub const MAX_BUILTIN_ALLOCATION_COMPUTE_UNIT_LIMIT: u32 = 3_000;
pub const MAX_HEAP_FRAME_BYTES: u32 = 256 * 1024;
pub const MIN_HEAP_FRAME_BYTES: u32 = HEAP_LENGTH as u32;

/// The total accounts data a transaction can load is limited to 64MiB to not break
/// anyone in Mainnet-beta today. It can be set by set_loaded_accounts_data_size_limit instruction
pub const MAX_LOADED_ACCOUNTS_DATA_SIZE_BYTES: NonZeroU32 =
    NonZeroU32::new(64 * 1024 * 1024).unwrap();

#[cfg(test)]
static_assertions::const_assert_eq!(
    DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT,
    solana_transaction_context::DEFAULT_INSTRUCTION_COMPUTE_UNIT_LIMIT,
);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SVMTransactionExecutionBudget {
    /// Number of compute units that a transaction or individual instruction is
    /// allowed to consume. Compute units are consumed by program execution,
    /// resources they use, etc...
    pub compute_unit_limit: u64,
    /// Maximum program instruction invocation stack depth. Invocation stack
    /// depth starts at 1 for transaction instructions and the stack depth is
    /// incremented each time a program invokes an instruction and decremented
    /// when a program returns.
    pub max_instruction_stack_depth: usize,
    /// Maximum cross-program invocation and instructions per transaction
    pub max_instruction_trace_length: usize,
    /// Maximum number of slices hashed per syscall
    pub sha256_max_slices: u64,
    /// Maximum SBF to BPF call depth
    pub max_call_depth: usize,
    /// Size of a stack frame in bytes, must match the size specified in the LLVM SBF backend
    pub stack_frame_size: usize,
    /// program heap region size, default: solana_program_entrypoint::HEAP_LENGTH
    pub heap_size: u32,
}

#[cfg(feature = "dev-context-only-utils")]
impl Default for SVMTransactionExecutionBudget {
    fn default() -> Self {
        Self::new_with_defaults(/* simd_0268_active */ false)
    }
}

impl SVMTransactionExecutionBudget {
    pub fn new_with_defaults(simd_0268_active: bool) -> Self {
        SVMTransactionExecutionBudget {
            compute_unit_limit: u64::from(MAX_COMPUTE_UNIT_LIMIT),
            max_instruction_stack_depth: get_max_instruction_stack_depth(simd_0268_active),
            max_instruction_trace_length: MAX_INSTRUCTION_TRACE_LENGTH,
            sha256_max_slices: 20_000,
            max_call_depth: MAX_CALL_DEPTH,
            stack_frame_size: solana_sbpf::vm::get_stack_frame_size(),
            heap_size: u32::try_from(solana_program_entrypoint::HEAP_LENGTH).unwrap(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SVMTransactionExecutionCost {
    /// Number of compute units consumed by a log_u64 call
    pub log_64_units: u64,
    /// Number of compute units consumed by a create_program_address call
    pub create_program_address_units: u64,
    /// Number of compute units consumed by an invoke call (not including the cost incurred by
    /// the called program)
    pub invoke_units: u64,
    /// Base number of compute units consumed to call SHA256
    pub sha256_base_cost: u64,
    /// Incremental number of units consumed by SHA256 (based on bytes)
    pub sha256_byte_cost: u64,
    /// Number of compute units consumed by logging a `Pubkey`
    pub log_pubkey_units: u64,
    /// Number of account data bytes per compute unit charged during a cross-program invocation
    pub cpi_bytes_per_unit: u64,
    /// Base number of compute units consumed to get a sysvar
    pub sysvar_base_cost: u64,
    /// Number of compute units consumed to call secp256k1_recover
    pub secp256k1_recover_cost: u64,
    /// Number of compute units consumed to do a syscall without any work
    pub syscall_base_cost: u64,
    /// Number of compute units consumed to validate a curve25519 edwards point
    pub curve25519_edwards_validate_point_cost: u64,
    /// Number of compute units consumed to add two curve25519 edwards points
    pub curve25519_edwards_add_cost: u64,
    /// Number of compute units consumed to subtract two curve25519 edwards points
    pub curve25519_edwards_subtract_cost: u64,
    /// Number of compute units consumed to multiply a curve25519 edwards point
    pub curve25519_edwards_multiply_cost: u64,
    /// Number of compute units consumed for a multiscalar multiplication (msm) of edwards points.
    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
    pub curve25519_edwards_msm_base_cost: u64,
    /// Number of compute units consumed for a multiscalar multiplication (msm) of edwards points.
    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
    pub curve25519_edwards_msm_incremental_cost: u64,
    /// Number of compute units consumed to validate a curve25519 ristretto point
    pub curve25519_ristretto_validate_point_cost: u64,
    /// Number of compute units consumed to add two curve25519 ristretto points
    pub curve25519_ristretto_add_cost: u64,
    /// Number of compute units consumed to subtract two curve25519 ristretto points
    pub curve25519_ristretto_subtract_cost: u64,
    /// Number of compute units consumed to multiply a curve25519 ristretto point
    pub curve25519_ristretto_multiply_cost: u64,
    /// Number of compute units consumed for a multiscalar multiplication (msm) of ristretto points.
    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
    pub curve25519_ristretto_msm_base_cost: u64,
    /// Number of compute units consumed for a multiscalar multiplication (msm) of ristretto points.
    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
    pub curve25519_ristretto_msm_incremental_cost: u64,
    /// Number of compute units per additional 32k heap above the default (~.5
    /// us per 32k at 15 units/us rounded up)
    pub heap_cost: u64,
    /// Memory operation syscall base cost
    pub mem_op_base_cost: u64,
    /// Number of compute units consumed to call alt_bn128_g1_addition
    pub alt_bn128_g1_addition_cost: u64,
    /// Number of compute units consumed to call alt_bn128_g2_addition
    pub alt_bn128_g2_addition_cost: u64,
    /// Number of compute units consumed to call alt_bn128_g1_multiplication.
    pub alt_bn128_g1_multiplication_cost: u64,
    /// Number of compute units consumed to call alt_bn128_g2_multiplication.
    pub alt_bn128_g2_multiplication_cost: u64,
    /// Total cost will be alt_bn128_pairing_one_pair_cost_first
    /// + alt_bn128_pairing_one_pair_cost_other * (num_elems - 1)
    pub alt_bn128_pairing_one_pair_cost_first: u64,
    pub alt_bn128_pairing_one_pair_cost_other: u64,
    /// Big integer modular exponentiation base cost
    pub big_modular_exponentiation_base_cost: u64,
    /// Big integer modular exponentiation cost divisor.
    /// The modular exponentiation cost is the SIMD-0529 operand complexity
    /// times the number of multiplications for the exponent's 64-bit words,
    /// divided by this divisor and rounded up, plus
    /// `big_modular_exponentiation_base_cost`. An exponent of 1 is priced as a
    /// single modular reduction with a fixed divisor of 15 instead.
    pub big_modular_exponentiation_cost_divisor: u64,
    /// Coefficient `a` of the quadratic function which determines the number
    /// of compute units consumed to call poseidon syscall for a given number
    /// of inputs.
    pub poseidon_cost_coefficient_a: u64,
    /// Coefficient `c` of the quadratic function which determines the number
    /// of compute units consumed to call poseidon syscall for a given number
    /// of inputs.
    pub poseidon_cost_coefficient_c: u64,
    /// Number of compute units consumed for accessing the remaining compute units.
    pub get_remaining_compute_units_cost: u64,
    /// Number of compute units consumed to call alt_bn128_g1_compress.
    pub alt_bn128_g1_compress: u64,
    /// Number of compute units consumed to call alt_bn128_g1_decompress.
    pub alt_bn128_g1_decompress: u64,
    /// Number of compute units consumed to call alt_bn128_g2_compress.
    pub alt_bn128_g2_compress: u64,
    /// Number of compute units consumed to call alt_bn128_g2_decompress.
    pub alt_bn128_g2_decompress: u64,
    /// Number of compute units consumed to add two bls12_381 g1 points.
    pub bls12_381_g1_add_cost: u64,
    /// Number of compute units consumed to add two bls12_381 g2 points.
    pub bls12_381_g2_add_cost: u64,
    /// Number of compute units consumed to subtract two bls12_381 g1 points.
    pub bls12_381_g1_subtract_cost: u64,
    /// Number of compute units consumed to subtract two bls12_381 g2 points.
    pub bls12_381_g2_subtract_cost: u64,
    /// Number of compute units consumed to multiply a bls12_381 g1 point.
    pub bls12_381_g1_multiply_cost: u64,
    /// Number of compute units consumed to multiply a bls12_381 g2 point.
    pub bls12_381_g2_multiply_cost: u64,
    /// Number of compute units consumed to decompress a bls12_381 g1 point.
    pub bls12_381_g1_decompress_cost: u64,
    /// Number of compute units consumed to decompress a bls12_381 g2 point.
    pub bls12_381_g2_decompress_cost: u64,
    /// Number of compute units consumed to validate a bls12_381 g1 point.
    pub bls12_381_g1_validate_cost: u64,
    /// Number of compute units consumed to validate a bls12_381 g2 point.
    pub bls12_381_g2_validate_cost: u64,
    /// Base number of compute units consumed to perform a bls12_381 pairing.
    pub bls12_381_one_pair_cost: u64,
    /// Incremental number of compute units consumed per pair in a bls12_381 pairing.
    pub bls12_381_additional_pair_cost: u64,
    /// Number of compute units consumed to add two secp256r1 points
    pub secp256r1_add_cost: u64,
    /// Number of compute units consumed to subtract two secp256r1 points
    pub secp256r1_subtract_cost: u64,
    /// Number of compute units consumed to multiply a secp256r1 point
    pub secp256r1_multiply_cost: u64,
    /// Number of compute units consumed for a multiscalar multiplication (msm) of secp256r1 points.
    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
    pub secp256r1_msm_base_cost: u64,
    /// Number of compute units consumed for a multiscalar multiplication (msm) of secp256r1 points.
    /// The total cost is calculated as `msm_base_cost + (length - 1) * msm_incremental_cost`.
    pub secp256r1_msm_incremental_cost: u64,
    /// Number of compute units consumed to validate a secp256r1 point.
    pub secp256r1_validate_cost: u64,
    /// Number of compute units consumed to decompress a secp256r1 point.
    pub secp256r1_decompress_cost: u64,
}

impl Default for SVMTransactionExecutionCost {
    fn default() -> Self {
        SVMTransactionExecutionCost {
            log_64_units: 100,
            create_program_address_units: 1500,
            invoke_units: DEFAULT_INVOCATION_COST,
            sha256_base_cost: 85,
            sha256_byte_cost: 1,
            log_pubkey_units: 100,
            cpi_bytes_per_unit: 250, // ~50MB at 200,000 units
            sysvar_base_cost: 100,
            secp256k1_recover_cost: 25_000,
            syscall_base_cost: 100,
            curve25519_edwards_validate_point_cost: 159,
            curve25519_edwards_add_cost: 473,
            curve25519_edwards_subtract_cost: 475,
            curve25519_edwards_multiply_cost: 2_177,
            curve25519_edwards_msm_base_cost: 2_273,
            curve25519_edwards_msm_incremental_cost: 758,
            curve25519_ristretto_validate_point_cost: 169,
            curve25519_ristretto_add_cost: 521,
            curve25519_ristretto_subtract_cost: 519,
            curve25519_ristretto_multiply_cost: 2_208,
            curve25519_ristretto_msm_base_cost: 2303,
            curve25519_ristretto_msm_incremental_cost: 788,
            heap_cost: DEFAULT_HEAP_COST,
            mem_op_base_cost: 10,
            alt_bn128_g1_addition_cost: 334,
            alt_bn128_g2_addition_cost: 535,
            alt_bn128_g1_multiplication_cost: 3_840,
            alt_bn128_g2_multiplication_cost: 15_670,
            alt_bn128_pairing_one_pair_cost_first: 36_364,
            alt_bn128_pairing_one_pair_cost_other: 12_121,
            big_modular_exponentiation_base_cost: 50,
            big_modular_exponentiation_cost_divisor: 4,
            poseidon_cost_coefficient_a: 61,
            poseidon_cost_coefficient_c: 542,
            get_remaining_compute_units_cost: 100,
            alt_bn128_g1_compress: 30,
            alt_bn128_g1_decompress: 398,
            alt_bn128_g2_compress: 86,
            alt_bn128_g2_decompress: 13610,
            bls12_381_g1_add_cost: 128,
            bls12_381_g2_add_cost: 203,
            bls12_381_g1_subtract_cost: 129,
            bls12_381_g2_subtract_cost: 204,
            bls12_381_g1_multiply_cost: 4_627,
            bls12_381_g2_multiply_cost: 8_255,
            bls12_381_g1_decompress_cost: 2_100,
            bls12_381_g2_decompress_cost: 3_050,
            bls12_381_g1_validate_cost: 1_565,
            bls12_381_g2_validate_cost: 1_968,
            bls12_381_one_pair_cost: 25_445,
            bls12_381_additional_pair_cost: 13_023,
            secp256r1_add_cost: 520,
            secp256r1_subtract_cost: 520,
            secp256r1_multiply_cost: 9_000,
            secp256r1_msm_base_cost: 9_000,
            secp256r1_msm_incremental_cost: 3_800,
            secp256r1_validate_cost: 20,
            secp256r1_decompress_cost: 610,
        }
    }
}

impl SVMTransactionExecutionCost {
    /// Returns cost of the Poseidon hash function for the given number of
    /// inputs is determined by the following quadratic function:
    ///
    /// 61*n^2 + 542
    ///
    /// Which approximates the results of benchmarks of light-posiedon
    /// library[0]. These results assume 1 CU per 33 ns. Examples:
    ///
    /// * 1 input
    ///   * light-poseidon benchmark: `18,303 / 33 ≈ 555`
    ///   * function: `61*1^2 + 542 = 603`
    /// * 2 inputs
    ///   * light-poseidon benchmark: `25,866 / 33 ≈ 784`
    ///   * function: `61*2^2 + 542 = 786`
    /// * 3 inputs
    ///   * light-poseidon benchmark: `37,549 / 33 ≈ 1,138`
    ///   * function; `61*3^2 + 542 = 1091`
    ///
    /// [0] https://github.com/Lightprotocol/light-poseidon#performance
    pub fn poseidon_cost(&self, nr_inputs: u64) -> Option<u64> {
        let squared_inputs = nr_inputs.checked_pow(2)?;
        let mul_result = self
            .poseidon_cost_coefficient_a
            .checked_mul(squared_inputs)?;
        let final_result = mul_result.checked_add(self.poseidon_cost_coefficient_c)?;

        Some(final_result)
    }

    /// Compute the operation cost of a big integer modular exponentiation, i.e. the
    /// cost charged on top of the flat `big_modular_exponentiation_base_cost`.
    pub fn big_mod_exp_operation_cost(
        &self,
        base_len: u64,
        modulus_len: u64,
        exponent: &[u8],
    ) -> Option<u64> {
        let input_len = base_len.max(modulus_len);
        let mult_complexity = big_mod_exp_mult_complexity(input_len)?;
        let (operation_complexity, divisor) = if big_mod_exp_is_one_le(exponent) {
            (mult_complexity, BIG_MOD_EXP_MOD_REDUCTION_CU_DIVISOR)
        } else {
            let exponent_words = big_mod_exp_adjusted_exponent_length(exponent)
                .checked_div(64)?
                .checked_add(1)?;
            let multiplications = BIG_MOD_EXP_MULTIPLICATIONS_PER_EXPONENT_WORD
                .checked_mul(exponent_words)?
                .checked_add(BIG_MOD_EXP_SETUP_MULTIPLICATIONS)?;
            (
                mult_complexity.checked_mul(u128::from(multiplications))?,
                self.big_modular_exponentiation_cost_divisor,
            )
        };
        let divisor = u128::from(divisor);
        if divisor == 0 {
            return None;
        }

        let operation_cost = operation_complexity
            .checked_add(divisor.checked_sub(1)?)?
            .checked_div(divisor)?;
        u64::try_from(operation_cost).ok()
    }
}

const BIG_MOD_EXP_MULT_COMPLEXITY_CONSTANT: u64 = 22;
const BIG_MOD_EXP_SETUP_MULTIPLICATIONS: u64 = 12;
const BIG_MOD_EXP_MULTIPLICATIONS_PER_EXPONENT_WORD: u64 = 80;
const BIG_MOD_EXP_MOD_REDUCTION_CU_DIVISOR: u64 = 15;

fn big_mod_exp_mult_complexity(input_len: u64) -> Option<u128> {
    let operand_words = u128::from(input_len.div_ceil(8));
    operand_words
        .checked_mul(operand_words)?
        .checked_add(u128::from(BIG_MOD_EXP_MULT_COMPLEXITY_CONSTANT))
}

fn big_mod_exp_highest_set_bit_index_le(bytes: &[u8]) -> Option<u64> {
    bytes.iter().enumerate().rev().find_map(|(index, byte)| {
        (*byte != 0).then(|| {
            (index as u64)
                .saturating_mul(u64::from(u8::BITS))
                .saturating_add(u64::from(7_u32.saturating_sub(byte.leading_zeros())))
        })
    })
}

fn big_mod_exp_adjusted_exponent_length(exponent: &[u8]) -> u64 {
    if exponent.len() <= 32 {
        big_mod_exp_highest_set_bit_index_le(exponent).unwrap_or(0)
    } else {
        let (trailing_bytes, most_significant_32_bytes) =
            exponent.split_at(exponent.len().saturating_sub(32));
        (trailing_bytes.len() as u64)
            .saturating_mul(u64::from(u8::BITS))
            .saturating_add(
                big_mod_exp_highest_set_bit_index_le(most_significant_32_bytes).unwrap_or(0),
            )
    }
}

fn big_mod_exp_is_one_le(bytes: &[u8]) -> bool {
    matches!(bytes.split_first(), Some((1, rest)) if rest.iter().all(|byte| *byte == 0))
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SVMTransactionExecutionAndFeeBudgetLimits {
    pub budget: SVMTransactionExecutionBudget,
    pub loaded_accounts_data_size_limit: u32,
    pub fee_details: FeeDetails,
}

#[cfg(feature = "dev-context-only-utils")]
impl Default for SVMTransactionExecutionAndFeeBudgetLimits {
    fn default() -> Self {
        Self {
            budget: SVMTransactionExecutionBudget::default(),
            loaded_accounts_data_size_limit: MAX_LOADED_ACCOUNTS_DATA_SIZE_BYTES.get(),
            fee_details: FeeDetails::default(),
        }
    }
}

#[cfg(feature = "dev-context-only-utils")]
impl SVMTransactionExecutionAndFeeBudgetLimits {
    pub fn with_fee(fee_details: FeeDetails) -> Self {
        Self {
            fee_details,
            ..SVMTransactionExecutionAndFeeBudgetLimits::default()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_big_mod_exp_cost() {
        let execution_cost = SVMTransactionExecutionCost::default();
        let cost = |base_len: u64, modulus_len: u64, exponent: &[u8]| {
            execution_cost.big_modular_exponentiation_base_cost
                + execution_cost
                    .big_mod_exp_operation_cost(base_len, modulus_len, exponent)
                    .unwrap()
        };

        // Costs listed in SIMD-0529
        let exponent_65537 = [0x01, 0x00, 0x01];
        assert_eq!(cost(256, 256, &exponent_65537), 24_108);
        assert_eq!(cost(512, 512, &exponent_65537), 94_764);
        assert_eq!(cost(512, 512, &[0xff; 128]), 1_330_164);
        assert_eq!(cost(8, 8, &[0xff; 512]), 29_559);
        assert_eq!(cost(512, 256, &[0x01]), 325);

        // The reduction path is chosen by the exponent value, not its encoded or adjusted length
        assert_eq!(cost(512, 256, &[0x01, 0x00, 0x00]), 325);
        assert_eq!(cost(512, 256, &[0x00]), cost(512, 256, &[0x01, 0x01]));
    }
}