sbpf-runtime 0.2.3

Lightweight runtime for sBPF programs
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
pub mod builtins;
pub mod request;
pub mod sync;
pub mod validate;

use {
    crate::{
        config::{ExecutionCost, RuntimeConfig, SysvarContext},
        elf::load_elf,
        errors::{RuntimeError, RuntimeResult},
        runtime::LogCollector,
        serialize,
        syscalls::RuntimeSyscallHandler,
    },
    base64::{Engine, engine::general_purpose::STANDARD as BASE64},
    request::CpiRequest,
    sbpf_vm::{
        compute::ComputeMeter,
        memory::Memory,
        vm::{SbpfVm, SbpfVmConfig},
    },
    solana_account::Account,
    solana_address::Address,
    solana_instruction::AccountMeta,
    std::collections::HashMap,
};

pub type ReturnData = Option<(Address, Vec<u8>)>;

pub struct CpiOutput {
    pub exit_code: u64,
    pub return_data: ReturnData,
    pub compute_consumed: u64,
}

pub type CpiExecResult = RuntimeResult<CpiOutput>;

pub struct CpiContext<'a> {
    pub request: CpiRequest,
    pub programs: &'a HashMap<Address, Vec<u8>>,
    pub accounts: &'a mut HashMap<Address, Account>,
    pub config: &'a RuntimeConfig,
    pub sysvars: &'a SysvarContext,
    pub compute_remaining: u64,
    pub cpi_depth: usize,
    pub caller_account_metas: &'a [AccountMeta],
    pub log_collector: &'a LogCollector,
}

pub fn execute_cpi(ctx: &mut CpiContext) -> CpiExecResult {
    if ctx.cpi_depth >= ctx.config.max_cpi_depth {
        return Err(RuntimeError::CpiDepthExceeded(ctx.config.max_cpi_depth));
    }

    validate::check_privileges(&ctx.request, ctx.caller_account_metas)?;

    ctx.log_collector.borrow_mut().push(format!(
        "Program {} invoke [{}]",
        ctx.request.program_id,
        ctx.cpi_depth + 1
    ));

    if builtins::is_builtin(&ctx.request.program_id) {
        let mut all_signers = ctx.request.signers.clone();
        for meta in &ctx.request.accounts {
            if meta.is_signer && !all_signers.contains(&meta.pubkey) {
                all_signers.push(meta.pubkey);
            }
        }
        let consumed = builtins::execute_builtin(
            &ctx.request.program_id,
            ctx.accounts,
            &ctx.request,
            &all_signers,
            ctx.compute_remaining,
        )?;
        ctx.log_collector.borrow_mut().push(format!(
            "Program {} consumed {} of {} compute units",
            ctx.request.program_id, consumed, ctx.compute_remaining
        ));
        ctx.log_collector
            .borrow_mut()
            .push(format!("Program {} success", ctx.request.program_id));
        return Ok(CpiOutput {
            exit_code: 0,
            return_data: None,
            compute_consumed: consumed,
        });
    }

    execute_elf_cpi(ctx)
}

fn execute_elf_cpi(ctx: &mut CpiContext) -> CpiExecResult {
    let elf_bytes = ctx
        .programs
        .get(&ctx.request.program_id)
        .ok_or_else(|| RuntimeError::ProgramNotFound(ctx.request.program_id.to_string()))?;

    let (instructions, rodata, entrypoint) = load_elf(elf_bytes)?;

    let account_metas: Vec<AccountMeta> = ctx
        .request
        .accounts
        .iter()
        .map(|a| AccountMeta {
            pubkey: a.pubkey,
            is_signer: a.is_signer,
            is_writable: a.is_writable,
        })
        .collect();

    let (input, pre_lens, instruction_data_offset) = serialize::serialize_parameters(
        ctx.accounts,
        &account_metas,
        &ctx.request.data,
        &ctx.request.program_id,
    )?;

    let vm_config = SbpfVmConfig {
        compute_unit_limit: ctx.compute_remaining,
        max_call_depth: ctx.config.max_call_depth,
        heap_size: ctx.config.heap_size,
    };

    let handler = RuntimeSyscallHandler::new(
        ExecutionCost::default(),
        ctx.request.program_id,
        ctx.sysvars.clone(),
        ctx.log_collector.clone(),
    );

    let mut callee_vm = SbpfVm::new_with_config(instructions, input, rodata, handler, vm_config);
    callee_vm.compute_meter = ComputeMeter::new(ctx.compute_remaining);
    callee_vm.set_entrypoint(entrypoint);
    callee_vm.registers[2] = Memory::INPUT_START + instruction_data_offset as u64;

    loop {
        if let Err(e) = callee_vm.step() {
            return Err(e.into());
        }

        if let Some(nested_request) = callee_vm.syscall_handler.pending_cpi.take() {
            sync::sync_from_caller(
                &callee_vm.memory,
                &nested_request.caller_accounts,
                ctx.accounts,
            )?;

            let caller_accounts_for_sync = nested_request.caller_accounts;
            let nested_consumed = callee_vm.compute_meter.get_consumed();
            let nested_remaining = ctx.compute_remaining.saturating_sub(nested_consumed);

            let nested_cpi_request = CpiRequest {
                program_id: nested_request.program_id,
                accounts: nested_request.accounts,
                data: nested_request.data,
                caller_accounts: Vec::new(),
                signers: nested_request.signers,
            };

            let mut nested_ctx = CpiContext {
                request: nested_cpi_request,
                programs: ctx.programs,
                accounts: ctx.accounts,
                config: ctx.config,
                sysvars: ctx.sysvars,
                compute_remaining: nested_remaining,
                cpi_depth: ctx.cpi_depth + 1,
                caller_account_metas: &account_metas,
                log_collector: ctx.log_collector,
            };

            let nested_output = execute_cpi(&mut nested_ctx)?;

            callee_vm
                .compute_meter
                .consume(nested_output.compute_consumed)?;
            callee_vm.syscall_handler.return_data = nested_output.return_data;

            if nested_output.exit_code != 0 {
                let consumed = callee_vm.compute_meter.get_consumed();
                return Ok(CpiOutput {
                    exit_code: nested_output.exit_code,
                    return_data: callee_vm.syscall_handler.return_data.take(),
                    compute_consumed: consumed,
                });
            }

            sync::sync_to_caller(
                &mut callee_vm.memory,
                &caller_accounts_for_sync,
                ctx.accounts,
            )?;
        }

        if callee_vm.halted {
            break;
        }
    }

    let exit_code = callee_vm.exit_code.unwrap_or(0);
    let callee_return_data = callee_vm.syscall_handler.return_data.take();
    let consumed = callee_vm.compute_meter.get_consumed();

    if exit_code != 0 {
        ctx.log_collector.borrow_mut().push(format!(
            "Program {} consumed {} of {} compute units",
            ctx.request.program_id, consumed, ctx.compute_remaining
        ));
        ctx.log_collector.borrow_mut().push(format!(
            "Program {} failed: exit code {}",
            ctx.request.program_id, exit_code
        ));
        return Ok(CpiOutput {
            exit_code,
            return_data: callee_return_data,
            compute_consumed: consumed,
        });
    }

    serialize::deserialize_parameters(
        ctx.accounts,
        &account_metas,
        &callee_vm.memory.input,
        &pre_lens,
        &ctx.request.program_id,
    )?;

    if let Some((ref pid, ref data)) = callee_return_data
        && !data.is_empty()
    {
        ctx.log_collector.borrow_mut().push(format!(
            "Program return: {} {}",
            pid,
            BASE64.encode(data)
        ));
    }

    ctx.log_collector.borrow_mut().push(format!(
        "Program {} consumed {} of {} compute units",
        ctx.request.program_id, consumed, ctx.compute_remaining
    ));
    ctx.log_collector
        .borrow_mut()
        .push(format!("Program {} success", ctx.request.program_id));

    Ok(CpiOutput {
        exit_code: 0,
        return_data: callee_return_data,
        compute_consumed: consumed,
    })
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::cpi::request::CpiAccountMeta,
        solana_system_interface::{instruction::SystemInstruction, program as system_program},
        std::{cell::RefCell, rc::Rc},
    };

    fn addr(seed: u8) -> Address {
        Address::new_from_array([seed; 32])
    }

    fn log_collector() -> LogCollector {
        Rc::new(RefCell::new(Vec::new()))
    }

    fn system_account(lamports: u64) -> Account {
        Account {
            lamports,
            data: vec![],
            owner: system_program::ID,
            executable: false,
            rent_epoch: 0,
        }
    }

    #[test]
    fn execute_cpi_program_not_found() {
        let config = RuntimeConfig::default();
        let sysvars = SysvarContext::default();
        let programs: HashMap<Address, Vec<u8>> = HashMap::new();
        let mut accounts: HashMap<Address, Account> = HashMap::new();
        let logs = log_collector();

        // Non-builtin program that was never registered via add_program.
        let request = CpiRequest {
            program_id: addr(9),
            accounts: Vec::new(),
            data: Vec::new(),
            caller_accounts: Vec::new(),
            signers: Vec::new(),
        };
        let mut ctx = CpiContext {
            request,
            programs: &programs,
            accounts: &mut accounts,
            config: &config,
            sysvars: &sysvars,
            compute_remaining: 200_000,
            cpi_depth: 0,
            caller_account_metas: &[],
            log_collector: &logs,
        };

        match execute_cpi(&mut ctx) {
            Err(RuntimeError::ProgramNotFound(_)) => {}
            Err(other) => panic!("expected ProgramNotFound, got {other:?}"),
            Ok(_) => panic!("expected ProgramNotFound error"),
        }
    }

    #[test]
    fn execute_cpi_depth_exceeded() {
        let config = RuntimeConfig::default();
        let sysvars = SysvarContext::default();
        let programs: HashMap<Address, Vec<u8>> = HashMap::new();
        let mut accounts: HashMap<Address, Account> = HashMap::new();
        let logs = log_collector();

        let request = CpiRequest {
            program_id: addr(9),
            accounts: Vec::new(),
            data: Vec::new(),
            caller_accounts: Vec::new(),
            signers: Vec::new(),
        };
        let mut ctx = CpiContext {
            request,
            programs: &programs,
            accounts: &mut accounts,
            config: &config,
            sysvars: &sysvars,
            compute_remaining: 200_000,
            cpi_depth: config.max_cpi_depth, // already at the limit
            caller_account_metas: &[],
            log_collector: &logs,
        };

        match execute_cpi(&mut ctx) {
            Err(RuntimeError::CpiDepthExceeded(_)) => {}
            Err(other) => panic!("expected CpiDepthExceeded, got {other:?}"),
            Ok(_) => panic!("expected CpiDepthExceeded error"),
        }
    }

    #[test]
    fn execute_cpi_dispatches_system_transfer_builtin() {
        let config = RuntimeConfig::default();
        let sysvars = SysvarContext::default();
        let programs: HashMap<Address, Vec<u8>> = HashMap::new();
        let logs = log_collector();

        let from = addr(1);
        let to = addr(2);
        let mut accounts =
            HashMap::from([(from, system_account(1_000_000)), (to, system_account(0))]);

        let request = CpiRequest {
            program_id: system_program::ID,
            accounts: vec![
                CpiAccountMeta {
                    pubkey: from,
                    is_signer: true,
                    is_writable: true,
                },
                CpiAccountMeta {
                    pubkey: to,
                    is_signer: false,
                    is_writable: true,
                },
            ],
            data: wincode::serialize(&SystemInstruction::Transfer { lamports: 400_000 }).unwrap(),
            caller_accounts: Vec::new(),
            signers: Vec::new(),
        };

        let caller_metas = vec![
            AccountMeta {
                pubkey: from,
                is_signer: true,
                is_writable: true,
            },
            AccountMeta {
                pubkey: to,
                is_signer: false,
                is_writable: true,
            },
        ];

        let mut ctx = CpiContext {
            request,
            programs: &programs,
            accounts: &mut accounts,
            config: &config,
            sysvars: &sysvars,
            compute_remaining: 200_000,
            cpi_depth: 0,
            caller_account_metas: &caller_metas,
            log_collector: &logs,
        };

        let output = execute_cpi(&mut ctx).unwrap();
        assert_eq!(output.exit_code, 0);
        assert_eq!(accounts[&from].lamports, 600_000);
        assert_eq!(accounts[&to].lamports, 400_000);
        assert!(logs.borrow().iter().any(|l| l.contains("invoke [1]")));
        assert!(logs.borrow().iter().any(|l| l.contains("success")));
    }
}