solana.rs 52 KB

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