solana.rs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  1. // SPDX-License-Identifier: Apache-2.0
  2. use crate::borsh_encoding::{decode_at_offset, encode_arguments, BorshToken};
  3. use base58::{FromBase58, ToBase58};
  4. use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
  5. use ethabi::RawLog;
  6. use libc::c_char;
  7. use rand::Rng;
  8. use serde::{Deserialize, Serialize};
  9. use sha2::{Digest, Sha256};
  10. use solana_rbpf::{
  11. ebpf,
  12. elf::Executable,
  13. error::EbpfError,
  14. memory_region::{AccessType, MemoryMapping, MemoryRegion},
  15. question_mark,
  16. syscalls::BpfSyscallContext,
  17. user_error::UserError,
  18. verifier::RequisiteVerifier,
  19. vm::{
  20. Config, EbpfVm, SyscallObject, SyscallRegistry, TestInstructionMeter, VerifiedExecutable,
  21. },
  22. };
  23. use solang::compile;
  24. use anchor_syn::idl::Idl;
  25. use solang::abi::anchor::{discriminator, generate_anchor_idl};
  26. use solang::{file_resolver::FileResolver, Target};
  27. use std::{
  28. cell::{RefCell, RefMut},
  29. collections::HashMap,
  30. convert::TryInto,
  31. ffi::OsStr,
  32. io::Write,
  33. mem::size_of,
  34. rc::Rc,
  35. };
  36. use tiny_keccak::{Hasher, Keccak};
  37. mod borsh_encoding;
  38. mod solana_tests;
  39. pub type Account = [u8; 32];
  40. pub fn account_new() -> Account {
  41. let mut rng = rand::thread_rng();
  42. let mut a = [0u8; 32];
  43. rng.fill(&mut a[..]);
  44. a
  45. }
  46. struct AccountState {
  47. data: Vec<u8>,
  48. owner: Option<Account>,
  49. lamports: u64,
  50. }
  51. /// We have a special callback function which tests that the correct
  52. /// parameters are passed in during CPI.
  53. type CallParametersCheck = fn(vm: &VirtualMachine, instr: &Instruction, pda: &[Pubkey]);
  54. struct VirtualMachine {
  55. account_data: HashMap<Account, AccountState>,
  56. origin: Account,
  57. programs: Vec<Contract>,
  58. stack: Vec<Contract>,
  59. logs: String,
  60. events: Vec<Vec<Vec<u8>>>,
  61. return_data: Option<(Account, Vec<u8>)>,
  62. call_params_check: HashMap<Pubkey, CallParametersCheck>,
  63. }
  64. #[derive(Clone)]
  65. struct Contract {
  66. program: Account,
  67. idl: Option<Idl>,
  68. data: Account,
  69. }
  70. #[derive(Serialize)]
  71. struct ClockLayout {
  72. slot: u64,
  73. epoch_start_timestamp: u64,
  74. epoch: u64,
  75. leader_schedule_epoch: u64,
  76. unix_timestamp: u64,
  77. }
  78. #[derive(Deserialize)]
  79. struct CreateAccount {
  80. instruction: u32,
  81. _lamports: u64,
  82. space: u64,
  83. program_id: Account,
  84. }
  85. #[derive(Deserialize)]
  86. struct CreateAccountWithSeed {
  87. instruction: u32,
  88. base: Account,
  89. seed: String,
  90. _lamports: u64,
  91. space: u64,
  92. program_id: Account,
  93. }
  94. #[derive(Deserialize)]
  95. struct Allocate {
  96. instruction: u32,
  97. space: u64,
  98. }
  99. #[derive(Deserialize)]
  100. struct Assign {
  101. instruction: u32,
  102. owner: Account,
  103. }
  104. fn build_solidity(src: &str) -> VirtualMachine {
  105. build_solidity_with_overflow_check(src, false)
  106. }
  107. fn build_solidity_with_overflow_check(src: &str, math_overflow_flag: bool) -> VirtualMachine {
  108. let mut cache = FileResolver::new();
  109. cache.set_file_contents("test.sol", src.to_string());
  110. let (res, ns) = compile(
  111. OsStr::new("test.sol"),
  112. &mut cache,
  113. inkwell::OptimizationLevel::Default,
  114. Target::Solana,
  115. math_overflow_flag,
  116. false,
  117. );
  118. ns.print_diagnostics_in_plain(&cache, false);
  119. assert!(!res.is_empty());
  120. let mut account_data = HashMap::new();
  121. let mut programs = Vec::new();
  122. for contract_no in 0..ns.contracts.len() {
  123. let contract = &ns.contracts[contract_no];
  124. if !contract.instantiable {
  125. continue;
  126. }
  127. let code = contract.code.get().unwrap();
  128. let idl = generate_anchor_idl(contract_no, &ns);
  129. let program = if let Some(program_id) = &contract.program_id {
  130. program_id.clone().try_into().unwrap()
  131. } else {
  132. account_new()
  133. };
  134. account_data.insert(
  135. program,
  136. AccountState {
  137. data: code.clone(),
  138. owner: None,
  139. lamports: 0,
  140. },
  141. );
  142. let data = account_new();
  143. account_data.insert(
  144. data,
  145. AccountState {
  146. data: [0u8; 4096].to_vec(),
  147. owner: Some(program),
  148. lamports: 0,
  149. },
  150. );
  151. programs.push(Contract {
  152. program,
  153. idl: Some(idl),
  154. data,
  155. });
  156. }
  157. // Add clock account
  158. let clock_account: Account = "SysvarC1ock11111111111111111111111111111111"
  159. .from_base58()
  160. .unwrap()
  161. .try_into()
  162. .unwrap();
  163. let clock_layout = ClockLayout {
  164. slot: 70818331,
  165. epoch: 102,
  166. epoch_start_timestamp: 946684800,
  167. leader_schedule_epoch: 1231231312,
  168. unix_timestamp: 1620656423,
  169. };
  170. account_data.insert(
  171. clock_account,
  172. AccountState {
  173. data: bincode::serialize(&clock_layout).unwrap(),
  174. owner: None,
  175. lamports: 0,
  176. },
  177. );
  178. let cur = programs.last().unwrap().clone();
  179. let origin = account_new();
  180. account_data.insert(
  181. origin,
  182. AccountState {
  183. data: Vec::new(),
  184. owner: None,
  185. lamports: 0,
  186. },
  187. );
  188. VirtualMachine {
  189. account_data,
  190. origin,
  191. programs,
  192. stack: vec![cur],
  193. logs: String::new(),
  194. events: Vec::new(),
  195. return_data: None,
  196. call_params_check: HashMap::new(),
  197. }
  198. }
  199. const MAX_PERMITTED_DATA_INCREASE: usize = 10 * 1024;
  200. struct AccountRef {
  201. account: Account,
  202. owner_offset: usize,
  203. data_offset: usize,
  204. length: usize,
  205. }
  206. fn serialize_parameters(
  207. input: &[u8],
  208. metas: &[AccountMeta],
  209. vm: &VirtualMachine,
  210. ) -> (Vec<u8>, Vec<AccountRef>) {
  211. let mut refs = Vec::new();
  212. let mut v: Vec<u8> = Vec::new();
  213. #[allow(clippy::ptr_arg)]
  214. fn serialize_account(
  215. v: &mut Vec<u8>,
  216. refs: &mut Vec<AccountRef>,
  217. meta: &AccountMeta,
  218. acc: &AccountState,
  219. ) {
  220. // dup_info
  221. v.write_u8(0xff).unwrap();
  222. // signer
  223. v.write_u8(meta.is_signer.into()).unwrap();
  224. // is_writable
  225. v.write_u8(meta.is_writable.into()).unwrap();
  226. // executable
  227. v.write_u8(1).unwrap();
  228. // padding
  229. v.write_all(&[0u8; 4]).unwrap();
  230. // key
  231. v.write_all(&meta.pubkey.0).unwrap();
  232. // owner
  233. let owner_offset = v.len();
  234. v.write_all(&acc.owner.unwrap_or([0u8; 32])).unwrap();
  235. // lamports
  236. v.write_u64::<LittleEndian>(acc.lamports).unwrap();
  237. // account data
  238. v.write_u64::<LittleEndian>(acc.data.len() as u64).unwrap();
  239. refs.push(AccountRef {
  240. account: meta.pubkey.0,
  241. owner_offset,
  242. data_offset: v.len(),
  243. length: acc.data.len(),
  244. });
  245. v.write_all(&acc.data).unwrap();
  246. v.write_all(&[0u8; MAX_PERMITTED_DATA_INCREASE]).unwrap();
  247. let padding = v.len() % 8;
  248. if padding != 0 {
  249. let mut p = Vec::new();
  250. p.resize(8 - padding, 0);
  251. v.extend_from_slice(&p);
  252. }
  253. // rent epoch
  254. v.write_u64::<LittleEndian>(0).unwrap();
  255. }
  256. // ka_num
  257. v.write_u64::<LittleEndian>(metas.len() as u64).unwrap();
  258. for account in metas {
  259. serialize_account(
  260. &mut v,
  261. &mut refs,
  262. account,
  263. &vm.account_data[&account.pubkey.0],
  264. );
  265. }
  266. // calldata
  267. v.write_u64::<LittleEndian>(input.len() as u64).unwrap();
  268. v.write_all(input).unwrap();
  269. // program id
  270. v.write_all(&vm.stack[0].program).unwrap();
  271. (v, refs)
  272. }
  273. // We want to extract the account data
  274. fn deserialize_parameters(
  275. input: &[u8],
  276. refs: &[AccountRef],
  277. accounts_data: &mut HashMap<Account, AccountState>,
  278. ) {
  279. for r in refs {
  280. if let Some(entry) = accounts_data.get_mut(&r.account) {
  281. let data = input[r.data_offset..r.data_offset + r.length].to_vec();
  282. entry.data = data;
  283. entry.lamports = u64::from_ne_bytes(
  284. input[r.data_offset - 16..r.data_offset - 8]
  285. .try_into()
  286. .unwrap(),
  287. );
  288. }
  289. }
  290. }
  291. // We want to extract the account data
  292. fn update_parameters(
  293. input: &[u8],
  294. mut refs: RefMut<&mut Vec<AccountRef>>,
  295. accounts_data: &HashMap<Account, AccountState>,
  296. ) {
  297. for r in refs.iter_mut() {
  298. if let Some(entry) = accounts_data.get(&r.account) {
  299. r.length = entry.data.len();
  300. unsafe {
  301. std::ptr::copy(
  302. r.length.to_le_bytes().as_ptr(),
  303. input[r.data_offset - 8..].as_ptr() as *mut u8,
  304. 8,
  305. );
  306. }
  307. unsafe {
  308. std::ptr::copy(
  309. entry.data.as_ptr(),
  310. input[r.data_offset..].as_ptr() as *mut u8,
  311. r.length,
  312. );
  313. }
  314. if let Some(owner) = &entry.owner {
  315. unsafe {
  316. std::ptr::copy(
  317. owner.as_ptr(),
  318. input[r.owner_offset..].as_ptr() as *mut u8,
  319. 32,
  320. );
  321. }
  322. }
  323. }
  324. }
  325. }
  326. #[derive(Clone)]
  327. struct SyscallContext<'a> {
  328. vm: Rc<RefCell<&'a mut VirtualMachine>>,
  329. input: &'a [u8],
  330. refs: Rc<RefCell<&'a mut Vec<AccountRef>>>,
  331. heap: *const u8,
  332. }
  333. impl<'a> SyscallContext<'a> {
  334. pub fn heap_verify(&self) {
  335. const VERBOSE: bool = false;
  336. let heap: &[u8] = unsafe { std::slice::from_raw_parts(self.heap, DEFAULT_HEAP_SIZE) };
  337. const HEAP_START: u64 = 0x3_0000_0000;
  338. let mut current_elem = HEAP_START;
  339. let mut last_elem = 0;
  340. let read_u64 = |offset: u64| {
  341. let offset = (offset - HEAP_START) as usize;
  342. u64::from_le_bytes(heap[offset..offset + 8].try_into().unwrap())
  343. };
  344. if VERBOSE {
  345. println!("heap verify:");
  346. }
  347. loop {
  348. let next: u64 = read_u64(current_elem);
  349. let prev: u64 = read_u64(current_elem + 8);
  350. let length: u64 = read_u64(current_elem + 16);
  351. let allocated: u64 = read_u64(current_elem + 24);
  352. if VERBOSE {
  353. println!(
  354. "next:{:08x} prev:{:08x} length:{} allocated:{}",
  355. next, prev, length, allocated
  356. );
  357. }
  358. let start = (current_elem + 8 * 4 - HEAP_START) as usize;
  359. let buf = &heap[start..start + length as usize];
  360. if allocated == 0 {
  361. if VERBOSE {
  362. println!("{:08x} {} not allocated", current_elem + 32, length);
  363. }
  364. } else {
  365. if VERBOSE {
  366. println!("{:08x} {} allocated", current_elem + 32, length);
  367. }
  368. assert_eq!(allocated & 0xffff, 1);
  369. for offset in (0..buf.len()).step_by(16) {
  370. use std::fmt::Write;
  371. let mut hex = "\t".to_string();
  372. let mut chars = "\t".to_string();
  373. for i in 0..16 {
  374. if offset + i >= buf.len() {
  375. break;
  376. }
  377. let b = buf[offset + i];
  378. write!(hex, " {:02x}", b).unwrap();
  379. if b.is_ascii() && !b.is_ascii_control() {
  380. write!(chars, " {}", b as char).unwrap();
  381. } else {
  382. chars.push_str(" ");
  383. }
  384. }
  385. if VERBOSE {
  386. println!("{}\n{}", hex, chars);
  387. }
  388. }
  389. }
  390. assert_eq!(last_elem, prev);
  391. if next == 0 {
  392. break;
  393. }
  394. last_elem = current_elem;
  395. current_elem = next;
  396. }
  397. if VERBOSE {
  398. println!("heap verify done");
  399. }
  400. }
  401. }
  402. struct SolPanic();
  403. impl SolPanic {
  404. /// new
  405. pub fn init<C, E>(_unused: C) -> Box<dyn SyscallObject<UserError>> {
  406. Box::new(Self {})
  407. }
  408. }
  409. impl SyscallObject<UserError> for SolPanic {
  410. fn call(
  411. &mut self,
  412. _src: u64,
  413. _len: u64,
  414. _dest: u64,
  415. _arg4: u64,
  416. _arg5: u64,
  417. _memory_mapping: &mut MemoryMapping,
  418. result: &mut Result<u64, EbpfError<UserError>>,
  419. ) {
  420. println!("sol_panic_()");
  421. *result = Err(EbpfError::ExecutionOverrun(0));
  422. }
  423. }
  424. struct SolLog<'a> {
  425. context: SyscallContext<'a>,
  426. }
  427. impl<'a> SolLog<'a> {
  428. /// new
  429. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  430. Box::new(Self { context })
  431. }
  432. }
  433. impl<'a> SyscallObject<UserError> for SolLog<'a> {
  434. fn call(
  435. &mut self,
  436. vm_addr: u64,
  437. len: u64,
  438. _arg3: u64,
  439. _arg4: u64,
  440. _arg5: u64,
  441. memory_mapping: &mut MemoryMapping,
  442. result: &mut Result<u64, EbpfError<UserError>>,
  443. ) {
  444. self.context.heap_verify();
  445. let host_addr = question_mark!(memory_mapping.map(AccessType::Load, vm_addr, len), result);
  446. let c_buf: *const c_char = host_addr as *const c_char;
  447. unsafe {
  448. for i in 0..len {
  449. let c = std::ptr::read(c_buf.offset(i as isize));
  450. if c == 0 {
  451. break;
  452. }
  453. }
  454. let message = std::str::from_utf8(std::slice::from_raw_parts(
  455. host_addr as *const u8,
  456. len as usize,
  457. ))
  458. .unwrap();
  459. println!("log: {}", message);
  460. if let Ok(mut vm) = self.context.vm.try_borrow_mut() {
  461. vm.logs.push_str(message);
  462. }
  463. *result = Ok(0)
  464. }
  465. }
  466. }
  467. struct SolLogPubKey<'a> {
  468. context: SyscallContext<'a>,
  469. }
  470. impl<'a> SolLogPubKey<'a> {
  471. /// new
  472. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  473. Box::new(Self { context })
  474. }
  475. }
  476. impl<'a> SyscallObject<UserError> for SolLogPubKey<'a> {
  477. fn call(
  478. &mut self,
  479. pubkey_addr: u64,
  480. _arg2: u64,
  481. _arg3: u64,
  482. _arg4: u64,
  483. _arg5: u64,
  484. memory_mapping: &mut MemoryMapping,
  485. result: &mut Result<u64, EbpfError<UserError>>,
  486. ) {
  487. self.context.heap_verify();
  488. let account = question_mark!(
  489. translate_slice::<Account>(memory_mapping, pubkey_addr, 1),
  490. result
  491. );
  492. let message = account[0].to_base58();
  493. println!("log pubkey: {}", message);
  494. if let Ok(mut vm) = self.context.vm.try_borrow_mut() {
  495. vm.logs.push_str(&message);
  496. }
  497. *result = Ok(0)
  498. }
  499. }
  500. struct SolLogU64<'a> {
  501. context: SyscallContext<'a>,
  502. }
  503. impl<'a> SolLogU64<'a> {
  504. /// new
  505. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  506. Box::new(Self { context })
  507. }
  508. }
  509. impl<'a> SyscallObject<UserError> for SolLogU64<'a> {
  510. fn call(
  511. &mut self,
  512. arg1: u64,
  513. arg2: u64,
  514. arg3: u64,
  515. arg4: u64,
  516. arg5: u64,
  517. _memory_mapping: &mut MemoryMapping,
  518. result: &mut Result<u64, EbpfError<UserError>>,
  519. ) {
  520. let message = format!(
  521. "{:#x}, {:#x}, {:#x}, {:#x}, {:#x}",
  522. arg1, arg2, arg3, arg4, arg5
  523. );
  524. println!("log64: {}", message);
  525. self.context.heap_verify();
  526. if let Ok(mut vm) = self.context.vm.try_borrow_mut() {
  527. vm.logs.push_str(&message);
  528. }
  529. *result = Ok(0)
  530. }
  531. }
  532. struct SolSha256<'a> {
  533. context: SyscallContext<'a>,
  534. }
  535. impl<'a> SolSha256<'a> {
  536. /// new
  537. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  538. Box::new(Self { context })
  539. }
  540. }
  541. impl<'a> SyscallObject<UserError> for SolSha256<'a> {
  542. fn call(
  543. &mut self,
  544. src: u64,
  545. len: u64,
  546. dest: u64,
  547. _arg4: u64,
  548. _arg5: u64,
  549. memory_mapping: &mut MemoryMapping,
  550. result: &mut Result<u64, EbpfError<UserError>>,
  551. ) {
  552. self.context.heap_verify();
  553. let arrays = question_mark!(
  554. translate_slice::<(u64, u64)>(memory_mapping, src, len),
  555. result
  556. );
  557. let mut hasher = Sha256::new();
  558. for (addr, len) in arrays {
  559. let buf = question_mark!(translate_slice::<u8>(memory_mapping, *addr, *len), result);
  560. println!("hashing: {}", hex::encode(buf));
  561. hasher.update(buf);
  562. }
  563. let hash = hasher.finalize();
  564. let hash_result = question_mark!(
  565. translate_slice_mut::<u8>(memory_mapping, dest, hash.len() as u64),
  566. result
  567. );
  568. hash_result.copy_from_slice(&hash);
  569. println!("sol_sha256: {}", hex::encode(hash));
  570. *result = Ok(0)
  571. }
  572. }
  573. struct SolKeccak256<'a> {
  574. context: SyscallContext<'a>,
  575. }
  576. impl<'a> SolKeccak256<'a> {
  577. /// new
  578. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  579. Box::new(Self { context })
  580. }
  581. }
  582. impl<'a> SyscallObject<UserError> for SolKeccak256<'a> {
  583. fn call(
  584. &mut self,
  585. src: u64,
  586. len: u64,
  587. dest: u64,
  588. _arg4: u64,
  589. _arg5: u64,
  590. memory_mapping: &mut MemoryMapping,
  591. result: &mut Result<u64, EbpfError<UserError>>,
  592. ) {
  593. self.context.heap_verify();
  594. let arrays = question_mark!(
  595. translate_slice::<(u64, u64)>(memory_mapping, src, len),
  596. result
  597. );
  598. let mut hasher = Keccak::v256();
  599. let mut hash = [0u8; 32];
  600. for (addr, len) in arrays {
  601. let buf = question_mark!(translate_slice::<u8>(memory_mapping, *addr, *len), result);
  602. println!("hashing: {}", hex::encode(buf));
  603. hasher.update(buf);
  604. }
  605. hasher.finalize(&mut hash);
  606. let hash_result = question_mark!(
  607. translate_slice_mut::<u8>(memory_mapping, dest, hash.len() as u64),
  608. result
  609. );
  610. hash_result.copy_from_slice(&hash);
  611. println!("sol_keccak256: {}", hex::encode(hash));
  612. *result = Ok(0)
  613. }
  614. }
  615. struct SolCreateProgramAddress();
  616. impl SolCreateProgramAddress {
  617. /// new
  618. pub fn init<C, E>(_unused: C) -> Box<dyn SyscallObject<UserError>> {
  619. Box::new(Self {})
  620. }
  621. }
  622. impl SyscallObject<UserError> for SolCreateProgramAddress {
  623. fn call(
  624. &mut self,
  625. seed_ptr: u64,
  626. seed_len: u64,
  627. program_id: u64,
  628. dest: u64,
  629. _arg5: u64,
  630. memory_mapping: &mut MemoryMapping,
  631. result: &mut Result<u64, EbpfError<UserError>>,
  632. ) {
  633. assert!(seed_len <= 16);
  634. let arrays = question_mark!(
  635. translate_slice::<(u64, u64)>(memory_mapping, seed_ptr, seed_len),
  636. result
  637. );
  638. let mut seeds = Vec::new();
  639. for (addr, len) in arrays {
  640. assert!(*len < 32);
  641. let buf = question_mark!(translate_slice::<u8>(memory_mapping, *addr, *len), result);
  642. println!("seed:{}", hex::encode(buf));
  643. seeds.push(buf);
  644. }
  645. let program_id = question_mark!(
  646. translate_type::<Account>(memory_mapping, program_id),
  647. result
  648. );
  649. println!("program_id:{}", program_id.to_base58());
  650. let pda = create_program_address(program_id, &seeds);
  651. let hash_result =
  652. question_mark!(translate_slice_mut::<u8>(memory_mapping, dest, 32), result);
  653. hash_result.copy_from_slice(&pda.0);
  654. println!("sol_create_program_address: {}", pda.0.to_base58());
  655. *result = Ok(0)
  656. }
  657. }
  658. struct SolTryFindProgramAddress();
  659. impl SolTryFindProgramAddress {
  660. /// new
  661. pub fn init<C, E>(_unused: C) -> Box<dyn SyscallObject<UserError>> {
  662. Box::new(Self {})
  663. }
  664. }
  665. impl SyscallObject<UserError> for SolTryFindProgramAddress {
  666. fn call(
  667. &mut self,
  668. seed_ptr: u64,
  669. seed_len: u64,
  670. program_id: u64,
  671. dest: u64,
  672. bump: u64,
  673. memory_mapping: &mut MemoryMapping,
  674. result: &mut Result<u64, EbpfError<UserError>>,
  675. ) {
  676. assert!(seed_len <= 16);
  677. let arrays = question_mark!(
  678. translate_slice::<(u64, u64)>(memory_mapping, seed_ptr, seed_len),
  679. result
  680. );
  681. let mut seeds = Vec::new();
  682. for (addr, len) in arrays {
  683. assert!(*len < 32);
  684. let buf = question_mark!(translate_slice::<u8>(memory_mapping, *addr, *len), result);
  685. println!("seed:{}", hex::encode(buf));
  686. seeds.push(buf);
  687. }
  688. let program_id = question_mark!(
  689. translate_type::<Account>(memory_mapping, program_id),
  690. result
  691. );
  692. println!("program_id:{}", program_id.to_base58());
  693. let bump_seed = [std::u8::MAX];
  694. let mut seeds_with_bump = seeds.to_vec();
  695. seeds_with_bump.push(&bump_seed);
  696. let pda = create_program_address(program_id, &seeds_with_bump);
  697. let hash_result =
  698. question_mark!(translate_slice_mut::<u8>(memory_mapping, dest, 32), result);
  699. hash_result.copy_from_slice(&pda.0);
  700. let bump_result =
  701. question_mark!(translate_slice_mut::<u8>(memory_mapping, bump, 1), result);
  702. bump_result.copy_from_slice(&bump_seed);
  703. println!(
  704. "sol_try_find_program_address: {} {:x}",
  705. pda.0.to_base58(),
  706. bump_seed[0]
  707. );
  708. *result = Ok(0)
  709. }
  710. }
  711. struct SyscallSetReturnData<'a> {
  712. context: SyscallContext<'a>,
  713. }
  714. impl<'a> SyscallSetReturnData<'a> {
  715. /// new
  716. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  717. Box::new(Self { context })
  718. }
  719. }
  720. impl<'a> SyscallObject<UserError> for SyscallSetReturnData<'a> {
  721. fn call(
  722. &mut self,
  723. addr: u64,
  724. len: u64,
  725. _arg3: u64,
  726. _arg4: u64,
  727. _arg5: u64,
  728. memory_mapping: &mut MemoryMapping,
  729. result: &mut Result<u64, EbpfError<UserError>>,
  730. ) {
  731. self.context.heap_verify();
  732. assert!(len <= 1024, "sol_set_return_data: length is {}", len);
  733. let buf = question_mark!(translate_slice::<u8>(memory_mapping, addr, len), result);
  734. println!("sol_set_return_data: {}", hex::encode(buf));
  735. if let Ok(mut vm) = self.context.vm.try_borrow_mut() {
  736. if len == 0 {
  737. vm.return_data = None;
  738. } else {
  739. vm.return_data = Some((vm.stack[0].program, buf.to_vec()));
  740. }
  741. *result = Ok(0);
  742. } else {
  743. panic!();
  744. }
  745. }
  746. }
  747. struct SyscallGetReturnData<'a> {
  748. context: SyscallContext<'a>,
  749. }
  750. impl<'a> SyscallGetReturnData<'a> {
  751. /// new
  752. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  753. Box::new(Self { context })
  754. }
  755. }
  756. impl<'a> SyscallObject<UserError> for SyscallGetReturnData<'a> {
  757. fn call(
  758. &mut self,
  759. addr: u64,
  760. len: u64,
  761. program_id_addr: u64,
  762. _arg4: u64,
  763. _arg5: u64,
  764. memory_mapping: &mut MemoryMapping,
  765. result: &mut Result<u64, EbpfError<UserError>>,
  766. ) {
  767. self.context.heap_verify();
  768. if let Ok(vm) = self.context.vm.try_borrow() {
  769. if let Some((program_id, return_data)) = &vm.return_data {
  770. let length = std::cmp::min(len, return_data.len() as u64);
  771. if len > 0 {
  772. let set_result = question_mark!(
  773. translate_slice_mut::<u8>(memory_mapping, addr, length),
  774. result
  775. );
  776. set_result.copy_from_slice(&return_data[..length as usize]);
  777. let program_id_result = question_mark!(
  778. translate_slice_mut::<u8>(memory_mapping, program_id_addr, 32),
  779. result
  780. );
  781. program_id_result.copy_from_slice(program_id);
  782. }
  783. *result = Ok(return_data.len() as u64);
  784. } else {
  785. *result = Ok(0);
  786. }
  787. } else {
  788. panic!();
  789. }
  790. }
  791. }
  792. struct SyscallLogData<'a> {
  793. context: SyscallContext<'a>,
  794. }
  795. impl<'a> SyscallLogData<'a> {
  796. /// new
  797. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  798. Box::new(Self { context })
  799. }
  800. }
  801. impl<'a> SyscallObject<UserError> for SyscallLogData<'a> {
  802. fn call(
  803. &mut self,
  804. addr: u64,
  805. len: u64,
  806. _arg3: u64,
  807. _arg4: u64,
  808. _arg5: u64,
  809. memory_mapping: &mut MemoryMapping,
  810. result: &mut Result<u64, EbpfError<UserError>>,
  811. ) {
  812. self.context.heap_verify();
  813. if let Ok(mut vm) = self.context.vm.try_borrow_mut() {
  814. print!("sol_log_data");
  815. let untranslated_events =
  816. question_mark!(translate_slice::<&[u8]>(memory_mapping, addr, len), result);
  817. let mut events = Vec::with_capacity(untranslated_events.len());
  818. for untranslated_event in untranslated_events {
  819. let event = question_mark!(
  820. translate_slice_mut::<u8>(
  821. memory_mapping,
  822. untranslated_event.as_ptr() as u64,
  823. untranslated_event.len() as u64,
  824. ),
  825. result
  826. );
  827. print!(" {}", hex::encode(&event));
  828. events.push(event.to_vec());
  829. }
  830. println!();
  831. vm.events.push(events.to_vec());
  832. *result = Ok(0);
  833. } else {
  834. panic!();
  835. }
  836. }
  837. }
  838. #[derive(Debug, Clone, PartialEq, Eq)]
  839. pub enum Ed25519SigCheckError {
  840. InvalidPublicKey,
  841. InvalidSignature,
  842. VerifyFailed,
  843. }
  844. impl From<u64> for Ed25519SigCheckError {
  845. fn from(v: u64) -> Ed25519SigCheckError {
  846. match v {
  847. 1 => Ed25519SigCheckError::InvalidPublicKey,
  848. 2 => Ed25519SigCheckError::InvalidSignature,
  849. 3 => Ed25519SigCheckError::VerifyFailed,
  850. _ => panic!("Unsupported Ed25519SigCheckError"),
  851. }
  852. }
  853. }
  854. impl From<Ed25519SigCheckError> for u64 {
  855. fn from(v: Ed25519SigCheckError) -> u64 {
  856. match v {
  857. Ed25519SigCheckError::InvalidPublicKey => 1,
  858. Ed25519SigCheckError::InvalidSignature => 2,
  859. Ed25519SigCheckError::VerifyFailed => 3,
  860. }
  861. }
  862. }
  863. const DEFAULT_HEAP_SIZE: usize = 32 * 1024;
  864. /// Rust representation of C's SolInstruction
  865. #[derive(Debug)]
  866. struct SolInstruction {
  867. program_id_addr: u64,
  868. accounts_addr: u64,
  869. accounts_len: usize,
  870. data_addr: u64,
  871. data_len: usize,
  872. }
  873. /// Rust representation of C's SolAccountMeta
  874. #[derive(Debug)]
  875. struct SolAccountMeta {
  876. pubkey_addr: u64,
  877. is_writable: bool,
  878. is_signer: bool,
  879. }
  880. /// Rust representation of C's SolSignerSeed
  881. #[derive(Debug)]
  882. struct SolSignerSeedC {
  883. addr: u64,
  884. len: u64,
  885. }
  886. /// Rust representation of C's SolSignerSeeds
  887. #[derive(Debug)]
  888. struct SolSignerSeedsC {
  889. addr: u64,
  890. len: u64,
  891. }
  892. #[derive(Debug)]
  893. pub struct Instruction {
  894. /// Pubkey of the instruction processor that executes this instruction
  895. pub program_id: Pubkey,
  896. /// Metadata for what accounts should be passed to the instruction processor
  897. pub accounts: Vec<AccountMeta>,
  898. /// Opaque data passed to the instruction processor
  899. pub data: Vec<u8>,
  900. }
  901. #[derive(Debug, PartialEq, Eq, Hash, Clone)]
  902. pub struct Pubkey([u8; 32]);
  903. impl Pubkey {
  904. fn is_system_instruction(&self) -> bool {
  905. self.0 == [0u8; 32]
  906. }
  907. }
  908. #[derive(Debug, PartialEq, Eq, Clone)]
  909. pub struct AccountMeta {
  910. /// An account's public key
  911. pub pubkey: Pubkey,
  912. /// True if an Instruction requires a Transaction signature matching `pubkey`.
  913. pub is_signer: bool,
  914. /// True if the `pubkey` can be loaded as a read-write account.
  915. pub is_writable: bool,
  916. }
  917. fn translate(
  918. memory_mapping: &MemoryMapping,
  919. access_type: AccessType,
  920. vm_addr: u64,
  921. len: u64,
  922. ) -> Result<u64, EbpfError<UserError>> {
  923. memory_mapping.map::<UserError>(access_type, vm_addr, len)
  924. }
  925. fn translate_type_inner<'a, T>(
  926. memory_mapping: &MemoryMapping,
  927. access_type: AccessType,
  928. vm_addr: u64,
  929. ) -> Result<&'a mut T, EbpfError<UserError>> {
  930. unsafe {
  931. translate(memory_mapping, access_type, vm_addr, size_of::<T>() as u64)
  932. .map(|value| &mut *(value as *mut T))
  933. }
  934. }
  935. fn translate_type<'a, T>(
  936. memory_mapping: &MemoryMapping,
  937. vm_addr: u64,
  938. ) -> Result<&'a T, EbpfError<UserError>> {
  939. translate_type_inner::<T>(memory_mapping, AccessType::Load, vm_addr).map(|value| &*value)
  940. }
  941. fn translate_slice<'a, T>(
  942. memory_mapping: &MemoryMapping,
  943. vm_addr: u64,
  944. len: u64,
  945. ) -> Result<&'a [T], EbpfError<UserError>> {
  946. translate_slice_inner::<T>(memory_mapping, AccessType::Load, vm_addr, len).map(|value| &*value)
  947. }
  948. fn translate_slice_mut<'a, T>(
  949. memory_mapping: &MemoryMapping,
  950. vm_addr: u64,
  951. len: u64,
  952. ) -> Result<&'a mut [T], EbpfError<UserError>> {
  953. translate_slice_inner::<T>(memory_mapping, AccessType::Store, vm_addr, len)
  954. }
  955. fn translate_slice_inner<'a, T>(
  956. memory_mapping: &MemoryMapping,
  957. access_type: AccessType,
  958. vm_addr: u64,
  959. len: u64,
  960. ) -> Result<&'a mut [T], EbpfError<UserError>> {
  961. if len == 0 {
  962. Ok(&mut [])
  963. } else {
  964. match translate(
  965. memory_mapping,
  966. access_type,
  967. vm_addr,
  968. len.saturating_mul(size_of::<T>() as u64),
  969. ) {
  970. Ok(value) => {
  971. Ok(unsafe { std::slice::from_raw_parts_mut(value as *mut T, len as usize) })
  972. }
  973. Err(e) => Err(e),
  974. }
  975. }
  976. }
  977. struct SyscallInvokeSignedC<'a> {
  978. context: SyscallContext<'a>,
  979. }
  980. impl<'a> SyscallInvokeSignedC<'a> {
  981. /// new
  982. pub fn init(context: SyscallContext<'a>) -> Box<(dyn SyscallObject<UserError> + 'a)> {
  983. Box::new(Self { context })
  984. }
  985. }
  986. impl<'a> SyscallInvokeSignedC<'a> {
  987. fn translate_instruction(
  988. &self,
  989. addr: u64,
  990. memory_mapping: &MemoryMapping,
  991. ) -> Result<Instruction, EbpfError<UserError>> {
  992. let ix_c = translate_type::<SolInstruction>(memory_mapping, addr)?;
  993. let program_id = translate_type::<Pubkey>(memory_mapping, ix_c.program_id_addr)?;
  994. let meta_cs = translate_slice::<SolAccountMeta>(
  995. memory_mapping,
  996. ix_c.accounts_addr,
  997. ix_c.accounts_len as u64,
  998. )?;
  999. let data =
  1000. translate_slice::<u8>(memory_mapping, ix_c.data_addr, ix_c.data_len as u64)?.to_vec();
  1001. let accounts = meta_cs
  1002. .iter()
  1003. .map(|meta_c| {
  1004. let pubkey = translate_type::<Pubkey>(memory_mapping, meta_c.pubkey_addr)?;
  1005. Ok(AccountMeta {
  1006. pubkey: pubkey.clone(),
  1007. is_signer: meta_c.is_signer,
  1008. is_writable: meta_c.is_writable,
  1009. })
  1010. })
  1011. .collect::<Result<Vec<AccountMeta>, EbpfError<UserError>>>()?;
  1012. Ok(Instruction {
  1013. program_id: program_id.clone(),
  1014. accounts,
  1015. data,
  1016. })
  1017. }
  1018. }
  1019. fn create_program_address(program_id: &Account, seeds: &[&[u8]]) -> Pubkey {
  1020. let mut hasher = Sha256::new();
  1021. for seed in seeds {
  1022. hasher.update(seed);
  1023. }
  1024. hasher.update(program_id);
  1025. hasher.update(b"ProgramDerivedAddress");
  1026. let hash = hasher.finalize();
  1027. let new_address: [u8; 32] = hash.try_into().unwrap();
  1028. // the real runtime does checks if this address exists on the ed25519 curve
  1029. Pubkey(new_address)
  1030. }
  1031. impl<'a> SyscallObject<UserError> for SyscallInvokeSignedC<'a> {
  1032. fn call(
  1033. &mut self,
  1034. instruction_addr: u64,
  1035. _account_infos_addr: u64,
  1036. _account_infos_len: u64,
  1037. signers_seeds_addr: u64,
  1038. signers_seeds_len: u64,
  1039. memory_mapping: &mut MemoryMapping,
  1040. result: &mut Result<u64, EbpfError<UserError>>,
  1041. ) {
  1042. let instruction = self
  1043. .translate_instruction(instruction_addr, memory_mapping)
  1044. .expect("instruction not valid");
  1045. println!(
  1046. "sol_invoke_signed_c input:{}",
  1047. hex::encode(&instruction.data)
  1048. );
  1049. let seeds = question_mark!(
  1050. translate_slice::<SolSignerSeedsC>(
  1051. memory_mapping,
  1052. signers_seeds_addr,
  1053. signers_seeds_len
  1054. ),
  1055. result
  1056. );
  1057. if let Ok(mut vm) = self.context.vm.try_borrow_mut() {
  1058. let signers: Vec<Pubkey> = seeds
  1059. .iter()
  1060. .map(|seed| {
  1061. let seeds: Vec<&[u8]> =
  1062. translate_slice::<SolSignerSeedC>(memory_mapping, seed.addr, seed.len)
  1063. .unwrap()
  1064. .iter()
  1065. .map(|seed| {
  1066. translate_slice::<u8>(memory_mapping, seed.addr, seed.len).unwrap()
  1067. })
  1068. .collect();
  1069. let pda = create_program_address(&vm.stack[0].program, &seeds);
  1070. println!(
  1071. "pda: {} seeds {}",
  1072. pda.0.to_base58(),
  1073. seeds
  1074. .iter()
  1075. .map(hex::encode)
  1076. .collect::<Vec<String>>()
  1077. .join(" ")
  1078. );
  1079. pda
  1080. })
  1081. .collect();
  1082. vm.return_data = None;
  1083. if let Some(handle) = vm.call_params_check.get(&instruction.program_id) {
  1084. handle(&vm, &instruction, &signers);
  1085. } else if instruction.program_id.is_system_instruction() {
  1086. match bincode::deserialize::<u32>(&instruction.data).unwrap() {
  1087. 0 => {
  1088. let create_account: CreateAccount =
  1089. bincode::deserialize(&instruction.data).unwrap();
  1090. let address = &instruction.accounts[1].pubkey;
  1091. assert!(instruction.accounts[1].is_signer);
  1092. println!("new address: {}", address.0.to_base58());
  1093. for s in &signers {
  1094. println!("signer: {}", s.0.to_base58());
  1095. }
  1096. if !signers.is_empty() {
  1097. assert!(signers.contains(address));
  1098. }
  1099. assert_eq!(create_account.instruction, 0);
  1100. println!(
  1101. "creating account {} with space {} owner {}",
  1102. address.0.to_base58(),
  1103. create_account.space,
  1104. create_account.program_id.to_base58()
  1105. );
  1106. assert_eq!(vm.account_data[&address.0].data.len(), 0);
  1107. if let Some(entry) = vm.account_data.get_mut(&address.0) {
  1108. entry.data = vec![0; create_account.space as usize];
  1109. entry.owner = Some(create_account.program_id);
  1110. }
  1111. let mut refs = self.context.refs.try_borrow_mut().unwrap();
  1112. for r in refs.iter_mut() {
  1113. if r.account == address.0 {
  1114. r.length = create_account.space as usize;
  1115. }
  1116. }
  1117. }
  1118. 1 => {
  1119. let assign: Assign = bincode::deserialize(&instruction.data).unwrap();
  1120. let address = &instruction.accounts[0].pubkey;
  1121. println!("assign address: {}", address.0.to_base58());
  1122. for s in &signers {
  1123. println!("signer: {}", s.0.to_base58());
  1124. }
  1125. assert!(signers.contains(address));
  1126. assert_eq!(assign.instruction, 1);
  1127. println!(
  1128. "assign account {} owner {}",
  1129. address.0.to_base58(),
  1130. assign.owner.to_base58(),
  1131. );
  1132. if let Some(entry) = vm.account_data.get_mut(&address.0) {
  1133. entry.owner = Some(assign.owner);
  1134. }
  1135. }
  1136. 3 => {
  1137. let create_account: CreateAccountWithSeed =
  1138. bincode::deserialize(&instruction.data).unwrap();
  1139. assert_eq!(create_account.instruction, 3);
  1140. let mut hasher = Sha256::new();
  1141. hasher.update(create_account.base);
  1142. hasher.update(create_account.seed);
  1143. hasher.update(create_account.program_id);
  1144. let hash = hasher.finalize();
  1145. let new_address: [u8; 32] = hash.try_into().unwrap();
  1146. println!(
  1147. "creating account {} with space {} owner {}",
  1148. hex::encode(new_address),
  1149. create_account.space,
  1150. hex::encode(create_account.program_id)
  1151. );
  1152. vm.account_data.insert(
  1153. new_address,
  1154. AccountState {
  1155. data: vec![0; create_account.space as usize],
  1156. owner: Some(create_account.program_id),
  1157. lamports: 0,
  1158. },
  1159. );
  1160. vm.programs.push(Contract {
  1161. program: create_account.program_id,
  1162. idl: None,
  1163. data: new_address,
  1164. });
  1165. }
  1166. 8 => {
  1167. let allocate: Allocate = bincode::deserialize(&instruction.data).unwrap();
  1168. let address = &instruction.accounts[0].pubkey;
  1169. println!("new address: {}", address.0.to_base58());
  1170. for s in &signers {
  1171. println!("signer: {}", s.0.to_base58());
  1172. }
  1173. assert!(signers.contains(address));
  1174. assert_eq!(allocate.instruction, 8);
  1175. println!(
  1176. "allocate account {} with space {}",
  1177. address.0.to_base58(),
  1178. allocate.space,
  1179. );
  1180. assert_eq!(vm.account_data[&address.0].data.len(), 0);
  1181. if let Some(entry) = vm.account_data.get_mut(&address.0) {
  1182. entry.data = vec![0; allocate.space as usize];
  1183. }
  1184. let mut refs = self.context.refs.try_borrow_mut().unwrap();
  1185. for r in refs.iter_mut() {
  1186. if r.account == address.0 {
  1187. r.length = allocate.space as usize;
  1188. }
  1189. }
  1190. }
  1191. instruction => panic!("instruction {} not supported", instruction),
  1192. }
  1193. } else {
  1194. let data_id: Account = instruction.accounts[0].pubkey.0;
  1195. println!(
  1196. "calling {} program_id {}",
  1197. data_id.to_base58(),
  1198. instruction.program_id.0.to_base58()
  1199. );
  1200. assert_eq!(data_id, instruction.accounts[0].pubkey.0);
  1201. let mut p = vm
  1202. .programs
  1203. .iter()
  1204. .find(|p| p.program == instruction.program_id.0)
  1205. .unwrap()
  1206. .clone();
  1207. p.data = data_id;
  1208. vm.stack.insert(0, p);
  1209. let res = vm.execute(&instruction.accounts, &instruction.data);
  1210. assert_eq!(res, Ok(0));
  1211. let refs = self.context.refs.try_borrow_mut().unwrap();
  1212. update_parameters(self.context.input, refs, &vm.account_data);
  1213. vm.stack.remove(0);
  1214. }
  1215. }
  1216. *result = Ok(0)
  1217. }
  1218. }
  1219. impl VirtualMachine {
  1220. fn execute(
  1221. &mut self,
  1222. metas: &[AccountMeta],
  1223. calldata: &[u8],
  1224. ) -> Result<u64, EbpfError<UserError>> {
  1225. println!("running bpf with calldata:{}", hex::encode(calldata));
  1226. let (mut parameter_bytes, mut refs) = serialize_parameters(calldata, metas, self);
  1227. let mut heap = vec![0_u8; DEFAULT_HEAP_SIZE];
  1228. let program = &self.stack[0];
  1229. let mut syscall_registry = SyscallRegistry::default();
  1230. syscall_registry
  1231. .register_syscall_by_name(
  1232. b"sol_panic_",
  1233. SolPanic::init::<BpfSyscallContext, UserError>,
  1234. SolPanic::call,
  1235. )
  1236. .unwrap();
  1237. syscall_registry
  1238. .register_syscall_by_name(b"sol_log_", SolLog::init, SolLog::call)
  1239. .unwrap();
  1240. syscall_registry
  1241. .register_syscall_by_name(b"sol_log_pubkey", SolLogPubKey::init, SolLogPubKey::call)
  1242. .unwrap();
  1243. syscall_registry
  1244. .register_syscall_by_name(b"sol_log_64_", SolLogU64::init, SolLogU64::call)
  1245. .unwrap();
  1246. syscall_registry
  1247. .register_syscall_by_name(b"sol_sha256", SolSha256::init, SolSha256::call)
  1248. .unwrap();
  1249. syscall_registry
  1250. .register_syscall_by_name(b"sol_keccak256", SolKeccak256::init, SolKeccak256::call)
  1251. .unwrap();
  1252. syscall_registry
  1253. .register_syscall_by_name(
  1254. b"sol_create_program_address",
  1255. SolCreateProgramAddress::init::<BpfSyscallContext, UserError>,
  1256. SolCreateProgramAddress::call,
  1257. )
  1258. .unwrap();
  1259. syscall_registry
  1260. .register_syscall_by_name(
  1261. b"sol_try_find_program_address",
  1262. SolTryFindProgramAddress::init::<BpfSyscallContext, UserError>,
  1263. SolTryFindProgramAddress::call,
  1264. )
  1265. .unwrap();
  1266. syscall_registry
  1267. .register_syscall_by_name(
  1268. b"sol_invoke_signed_c",
  1269. SyscallInvokeSignedC::init,
  1270. SyscallInvokeSignedC::call,
  1271. )
  1272. .unwrap();
  1273. syscall_registry
  1274. .register_syscall_by_name(
  1275. b"sol_set_return_data",
  1276. SyscallSetReturnData::init,
  1277. SyscallSetReturnData::call,
  1278. )
  1279. .unwrap();
  1280. syscall_registry
  1281. .register_syscall_by_name(
  1282. b"sol_get_return_data",
  1283. SyscallGetReturnData::init,
  1284. SyscallGetReturnData::call,
  1285. )
  1286. .unwrap();
  1287. syscall_registry
  1288. .register_syscall_by_name(b"sol_log_data", SyscallLogData::init, SyscallLogData::call)
  1289. .unwrap();
  1290. // program.program
  1291. println!("program: {}", program.program.to_base58());
  1292. let executable = Executable::<UserError, TestInstructionMeter>::from_elf(
  1293. &self.account_data[&program.program].data,
  1294. Config::default(),
  1295. syscall_registry,
  1296. )
  1297. .expect("should work");
  1298. let verified_executable = VerifiedExecutable::<
  1299. RequisiteVerifier,
  1300. UserError,
  1301. TestInstructionMeter,
  1302. >::from_executable(executable)
  1303. .unwrap();
  1304. let parameter_region =
  1305. MemoryRegion::new_writable(&mut parameter_bytes, ebpf::MM_INPUT_START);
  1306. let mut vm = EbpfVm::<RequisiteVerifier, UserError, TestInstructionMeter>::new(
  1307. &verified_executable,
  1308. &mut heap,
  1309. vec![parameter_region],
  1310. )
  1311. .unwrap();
  1312. let context = SyscallContext {
  1313. vm: Rc::new(RefCell::new(self)),
  1314. input: &parameter_bytes,
  1315. refs: Rc::new(RefCell::new(&mut refs)),
  1316. heap: heap.as_ptr(),
  1317. };
  1318. vm.bind_syscall_context_objects(context).unwrap();
  1319. let res = vm.execute_program_interpreted(&mut TestInstructionMeter { remaining: 1000000 });
  1320. deserialize_parameters(&parameter_bytes, &refs, &mut self.account_data);
  1321. self.validate_account_data_heap();
  1322. if let Some((_, return_data)) = &self.return_data {
  1323. println!("return: {}", hex::encode(return_data));
  1324. }
  1325. res
  1326. }
  1327. fn constructor(&mut self, args: &[BorshToken]) {
  1328. self.constructor_expected(0, args)
  1329. }
  1330. fn constructor_expected(&mut self, expected: u64, args: &[BorshToken]) {
  1331. self.return_data = None;
  1332. let program = &self.stack[0];
  1333. println!("constructor for {}", hex::encode(program.data));
  1334. let mut calldata = discriminator("global", "new");
  1335. if program
  1336. .idl
  1337. .as_ref()
  1338. .unwrap()
  1339. .instructions
  1340. .iter()
  1341. .any(|instr| instr.name == "new")
  1342. {
  1343. let mut encoded_data = encode_arguments(args);
  1344. calldata.append(&mut encoded_data);
  1345. };
  1346. let default_metas = self.default_metas();
  1347. let res = self.execute(&default_metas, &calldata);
  1348. println!("res:{:?}", res);
  1349. assert_eq!(res, Ok(expected));
  1350. if let Some((_, return_data)) = &self.return_data {
  1351. assert_eq!(return_data.len(), 0);
  1352. }
  1353. }
  1354. fn function(&mut self, name: &str, args: &[BorshToken]) -> Option<BorshToken> {
  1355. let default_metas = self.default_metas();
  1356. self.function_metas(&default_metas, name, args)
  1357. }
  1358. fn function_metas(
  1359. &mut self,
  1360. metas: &[AccountMeta],
  1361. name: &str,
  1362. args: &[BorshToken],
  1363. ) -> Option<BorshToken> {
  1364. self.return_data = None;
  1365. let program = &self.stack[0];
  1366. println!("function {} for {}", name, hex::encode(program.data));
  1367. let mut calldata = discriminator("global", name);
  1368. let instruction = if let Some(instr) = program
  1369. .idl
  1370. .as_ref()
  1371. .unwrap()
  1372. .instructions
  1373. .iter()
  1374. .find(|item| item.name == name)
  1375. {
  1376. instr.clone()
  1377. } else {
  1378. panic!("Function '{}' not found", name);
  1379. };
  1380. let mut encoded_args = encode_arguments(args);
  1381. calldata.append(&mut encoded_args);
  1382. println!("input: {}", hex::encode(&calldata));
  1383. let res = self.execute(metas, &calldata);
  1384. match res {
  1385. Ok(0) => (),
  1386. Ok(error_code) => panic!("unexpected return {:#x}", error_code),
  1387. Err(e) => panic!("error: {:?}", e),
  1388. };
  1389. let return_data = if let Some((_, return_data)) = &self.return_data {
  1390. return_data.as_slice()
  1391. } else {
  1392. &[]
  1393. };
  1394. if let Some(ret) = &instruction.returns {
  1395. let mut offset: usize = 0;
  1396. let decoded = decode_at_offset(
  1397. return_data,
  1398. &mut offset,
  1399. ret,
  1400. &self.stack[0].idl.as_ref().unwrap().types,
  1401. );
  1402. assert_eq!(offset, return_data.len());
  1403. Some(decoded)
  1404. } else {
  1405. assert_eq!(return_data.len(), 0);
  1406. None
  1407. }
  1408. }
  1409. fn function_must_fail(
  1410. &mut self,
  1411. name: &str,
  1412. args: &[BorshToken],
  1413. ) -> Result<u64, EbpfError<UserError>> {
  1414. let program = &self.stack[0];
  1415. println!("function for {}", hex::encode(program.data));
  1416. let mut calldata = Vec::new();
  1417. if !self.stack[0]
  1418. .idl
  1419. .as_ref()
  1420. .unwrap()
  1421. .instructions
  1422. .iter()
  1423. .any(|item| item.name == name)
  1424. {
  1425. panic!("Function '{}' not found", name);
  1426. }
  1427. let selector = discriminator("global", name);
  1428. calldata.extend_from_slice(&selector);
  1429. let mut encoded = encode_arguments(args);
  1430. calldata.append(&mut encoded);
  1431. let default_metas = self.default_metas();
  1432. println!("input: {}", hex::encode(&calldata));
  1433. self.execute(&default_metas, &calldata)
  1434. }
  1435. fn default_metas(&self) -> Vec<AccountMeta> {
  1436. // Just include everything
  1437. let mut accounts = vec![AccountMeta {
  1438. pubkey: Pubkey(self.stack[0].data),
  1439. is_writable: true,
  1440. is_signer: false,
  1441. }];
  1442. for acc in self.account_data.keys() {
  1443. if *acc != accounts[0].pubkey.0 {
  1444. accounts.push(AccountMeta {
  1445. pubkey: Pubkey(*acc),
  1446. is_signer: false,
  1447. is_writable: true,
  1448. });
  1449. }
  1450. }
  1451. accounts
  1452. }
  1453. fn data(&self) -> &Vec<u8> {
  1454. let program = &self.stack[0];
  1455. &self.account_data[&program.data].data
  1456. }
  1457. fn set_program(&mut self, no: usize) {
  1458. let cur = self.programs[no].clone();
  1459. self.stack = vec![cur];
  1460. }
  1461. fn create_pda(&mut self, program_id: &Account) -> (Account, Vec<u8>) {
  1462. let mut rng = rand::thread_rng();
  1463. let mut seed = [0u8; 7];
  1464. rng.fill(&mut seed[..]);
  1465. let pk = create_program_address(program_id, &[&seed]);
  1466. let account = pk.0;
  1467. println!(
  1468. "new empty account {} with seed {}",
  1469. account.to_base58(),
  1470. hex::encode(seed)
  1471. );
  1472. self.create_empty_account(&account, program_id);
  1473. (account, seed.to_vec())
  1474. }
  1475. fn create_empty_account(&mut self, account: &Account, program_id: &Account) {
  1476. self.account_data.insert(
  1477. *account,
  1478. AccountState {
  1479. data: vec![],
  1480. owner: Some([0u8; 32]),
  1481. lamports: 0,
  1482. },
  1483. );
  1484. self.programs.push(Contract {
  1485. program: *program_id,
  1486. idl: None,
  1487. data: *account,
  1488. });
  1489. }
  1490. fn validate_account_data_heap(&self) -> usize {
  1491. if let Some(acc) = self.account_data.get(&self.stack[0].data) {
  1492. let data = &acc.data;
  1493. let mut count = 0;
  1494. if data.len() < 4 || LittleEndian::read_u32(&data[0..]) == 0 {
  1495. return count;
  1496. }
  1497. let mut prev_offset = 0;
  1498. let return_len = LittleEndian::read_u32(&data[4..]) as usize;
  1499. let return_offset = LittleEndian::read_u32(&data[8..]) as usize;
  1500. let mut offset = LittleEndian::read_u32(&data[12..]) as usize;
  1501. // The return_offset/len fields are no longer used (we should remove them at some point)
  1502. assert_eq!(return_len, 0);
  1503. assert_eq!(return_offset, 0);
  1504. println!(
  1505. "static: length:{:x} {}",
  1506. offset - 16,
  1507. hex::encode(&data[16..offset])
  1508. );
  1509. if offset >= data.len() {
  1510. return count;
  1511. }
  1512. loop {
  1513. let next = LittleEndian::read_u32(&data[offset..]) as usize;
  1514. let prev = LittleEndian::read_u32(&data[offset + 4..]) as usize;
  1515. let length = LittleEndian::read_u32(&data[offset + 8..]) as usize;
  1516. let allocate = LittleEndian::read_u32(&data[offset + 12..]) as usize;
  1517. if allocate == 1 {
  1518. count += 1;
  1519. }
  1520. println!(
  1521. "offset:{:x} prev:{:x} next:{:x} length:{} allocated:{} {}",
  1522. offset + 16,
  1523. prev + 16,
  1524. next + 16,
  1525. length,
  1526. allocate,
  1527. hex::encode(&data[offset + 16..offset + 16 + length])
  1528. );
  1529. assert_eq!(prev, prev_offset);
  1530. prev_offset = offset;
  1531. if next == 0 {
  1532. assert_eq!(length, 0);
  1533. assert_eq!(allocate, 0);
  1534. break;
  1535. }
  1536. let space = next - offset - 16;
  1537. assert!(length <= space);
  1538. offset = next;
  1539. }
  1540. count
  1541. } else {
  1542. 0
  1543. }
  1544. }
  1545. pub fn events(&self) -> Vec<RawLog> {
  1546. self.events
  1547. .iter()
  1548. .map(|fields| {
  1549. assert_eq!(fields.len(), 1);
  1550. RawLog {
  1551. topics: vec![],
  1552. data: fields[0].clone(),
  1553. }
  1554. })
  1555. .collect()
  1556. }
  1557. }