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
#![cfg(feature = "full")]

use {
    crate::{
        entrypoint::HEAP_LENGTH as MIN_HEAP_FRAME_BYTES,
        feature_set::{requestable_heap_size, FeatureSet},
        process_instruction::BpfComputeBudget,
        transaction::{Transaction, TransactionError},
    },
    borsh::{BorshDeserialize, BorshSchema, BorshSerialize},
    solana_sdk::{
        borsh::try_from_slice_unchecked,
        instruction::{Instruction, InstructionError},
    },
    std::sync::Arc,
};

crate::declare_id!("ComputeBudget111111111111111111111111111111");

const MAX_UNITS: u32 = 1_000_000;
const MAX_HEAP_FRAME_BYTES: u32 = 256 * 1024;

/// Compute Budget Instructions
#[derive(
    Serialize,
    Deserialize,
    BorshSerialize,
    BorshDeserialize,
    BorshSchema,
    Debug,
    Clone,
    PartialEq,
    AbiExample,
    AbiEnumVisitor,
)]
pub enum ComputeBudgetInstruction {
    /// Request a specific maximum number of compute units the transaction is
    /// allowed to consume.
    RequestUnits(u32),
    /// Request a specific transaction-wide program heap frame size in bytes.
    /// The value requested must be a multiple of 1024. This new heap frame size
    /// applies to each program executed, including all calls to CPIs.
    RequestHeapFrame(u32),
}

/// Create a `ComputeBudgetInstruction::RequestUnits` `Instruction`
pub fn request_units(units: u32) -> Instruction {
    Instruction::new_with_borsh(id(), &ComputeBudgetInstruction::RequestUnits(units), vec![])
}

/// Create a `ComputeBudgetInstruction::RequestHeapFrame` `Instruction`
pub fn request_heap_frame(bytes: u32) -> Instruction {
    Instruction::new_with_borsh(
        id(),
        &ComputeBudgetInstruction::RequestHeapFrame(bytes),
        vec![],
    )
}

pub fn process_request(
    compute_budget: &mut BpfComputeBudget,
    tx: &Transaction,
    feature_set: Arc<FeatureSet>,
) -> Result<(), TransactionError> {
    let error = TransactionError::InstructionError(0, InstructionError::InvalidInstructionData);
    // Compute budget instruction must be in the 1st 3 instructions (avoid
    // nonce marker), otherwise ignored
    for instruction in tx.message().instructions.iter().take(3) {
        if check_id(instruction.program_id(&tx.message().account_keys)) {
            match try_from_slice_unchecked(&instruction.data) {
                Ok(ComputeBudgetInstruction::RequestUnits(units)) => {
                    if units > MAX_UNITS {
                        return Err(error);
                    }
                    compute_budget.max_units = units as u64;
                }
                Ok(ComputeBudgetInstruction::RequestHeapFrame(bytes)) => {
                    if !feature_set.is_active(&requestable_heap_size::id())
                        || bytes > MAX_HEAP_FRAME_BYTES
                        || bytes < MIN_HEAP_FRAME_BYTES as u32
                        || bytes % 1024 != 0
                    {
                        return Err(error);
                    }
                    compute_budget.heap_size = Some(bytes as usize);
                }
                _ => return Err(error),
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::{hash::Hash, message::Message, pubkey::Pubkey, signature::Keypair, signer::Signer},
    };

    macro_rules! test {
        ( $instructions: expr, $expected_error: expr, $expected_budget: expr ) => {
            let payer_keypair = Keypair::new();
            let tx = Transaction::new(
                &[&payer_keypair],
                Message::new($instructions, Some(&payer_keypair.pubkey())),
                Hash::default(),
            );
            let feature_set = Arc::new(FeatureSet::all_enabled());
            let mut compute_budget = BpfComputeBudget::default();
            let result = process_request(&mut compute_budget, &tx, feature_set);
            assert_eq!($expected_error as Result<(), TransactionError>, result);
            assert_eq!(compute_budget, $expected_budget);
        };
    }

    #[test]
    fn test_process_request() {
        // Units
        test!(&[], Ok(()), BpfComputeBudget::default());
        test!(
            &[
                request_units(1),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
            ],
            Ok(()),
            BpfComputeBudget {
                max_units: 1,
                ..BpfComputeBudget::default()
            }
        );
        test!(
            &[
                request_units(MAX_UNITS + 1),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
            ],
            Err(TransactionError::InstructionError(
                0,
                InstructionError::InvalidInstructionData,
            )),
            BpfComputeBudget::default()
        );
        test!(
            &[
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                request_units(MAX_UNITS),
            ],
            Ok(()),
            BpfComputeBudget {
                max_units: MAX_UNITS as u64,
                ..BpfComputeBudget::default()
            }
        );
        test!(
            &[
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                request_units(1),
            ],
            Ok(()),
            BpfComputeBudget::default()
        );

        // HeapFrame
        test!(&[], Ok(()), BpfComputeBudget::default());
        test!(
            &[
                request_heap_frame(40 * 1024),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
            ],
            Ok(()),
            BpfComputeBudget {
                heap_size: Some(40 * 1024),
                ..BpfComputeBudget::default()
            }
        );
        test!(
            &[
                request_heap_frame(40 * 1024 + 1),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
            ],
            Err(TransactionError::InstructionError(
                0,
                InstructionError::InvalidInstructionData,
            )),
            BpfComputeBudget::default()
        );
        test!(
            &[
                request_heap_frame(31 * 1024),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
            ],
            Err(TransactionError::InstructionError(
                0,
                InstructionError::InvalidInstructionData,
            )),
            BpfComputeBudget::default()
        );
        test!(
            &[
                request_heap_frame(MAX_HEAP_FRAME_BYTES + 1),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
            ],
            Err(TransactionError::InstructionError(
                0,
                InstructionError::InvalidInstructionData,
            )),
            BpfComputeBudget::default()
        );
        test!(
            &[
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                request_heap_frame(MAX_HEAP_FRAME_BYTES),
            ],
            Ok(()),
            BpfComputeBudget {
                heap_size: Some(MAX_HEAP_FRAME_BYTES as usize),
                ..BpfComputeBudget::default()
            }
        );
        test!(
            &[
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                request_heap_frame(1), // ignored
            ],
            Ok(()),
            BpfComputeBudget::default()
        );

        // Combined
        test!(
            &[
                Instruction::new_with_bincode(Pubkey::new_unique(), &0, vec![]),
                request_heap_frame(MAX_HEAP_FRAME_BYTES),
                request_units(MAX_UNITS),
            ],
            Ok(()),
            BpfComputeBudget {
                max_units: MAX_UNITS as u64,
                heap_size: Some(MAX_HEAP_FRAME_BYTES as usize),
                ..BpfComputeBudget::default()
            }
        );
    }
}