util.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::io::Cursor;
  19. use darkfi_serial::Decodable;
  20. use log::{debug, error};
  21. use wasmer::{FunctionEnvMut, WasmPtr};
  22. use super::acl::acl_allow;
  23. use crate::runtime::vm_runtime::{ContractSection, Env};
  24. /// Host function for logging strings.
  25. pub(crate) fn drk_log(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) {
  26. let (env, mut store) = ctx.data_and_store_mut();
  27. // Subtract used gas. Here we count the length of the string.
  28. env.subtract_gas(&mut store, len as u64);
  29. let memory_view = env.memory_view(&store);
  30. match ptr.read_utf8_string(&memory_view, len) {
  31. Ok(msg) => {
  32. let mut logs = env.logs.borrow_mut();
  33. logs.push(msg);
  34. std::mem::drop(logs);
  35. }
  36. Err(_) => {
  37. error!(
  38. target: "runtime::util::drk_log",
  39. "[WASM] [{}] drk_log(): Failed to read UTF-8 string from VM memory",
  40. env.contract_id,
  41. );
  42. }
  43. }
  44. }
  45. /// Writes data to the `contract_return_data` field of [`Env`].
  46. /// The data will be read from `ptr` at a memory offset specified by `len`.
  47. ///
  48. /// Returns `SUCCESS` on success, otherwise returns an error code corresponding
  49. /// to a [`ContractError`].
  50. pub(crate) fn set_return_data(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i64 {
  51. let (env, mut store) = ctx.data_and_store_mut();
  52. let cid = &env.contract_id;
  53. // Enforce function ACL
  54. if let Err(e) = acl_allow(env, &[ContractSection::Metadata, ContractSection::Exec]) {
  55. error!(
  56. target: "runtime::util::set_return_data",
  57. "[WASM] [{}] set_return_data(): Called in unauthorized section: {}", cid, e,
  58. );
  59. return darkfi_sdk::error::CALLER_ACCESS_DENIED
  60. }
  61. // Subtract used gas. Here we count the length read from the memory slice.
  62. env.subtract_gas(&mut store, len as u64);
  63. let memory_view = env.memory_view(&store);
  64. let Ok(slice) = ptr.slice(&memory_view, len) else { return darkfi_sdk::error::INTERNAL_ERROR };
  65. let Ok(return_data) = slice.read_to_vec() else { return darkfi_sdk::error::INTERNAL_ERROR };
  66. // This function should only ever be called once on the runtime.
  67. if env.contract_return_data.take().is_some() {
  68. return darkfi_sdk::error::SET_RETVAL_ERROR
  69. }
  70. env.contract_return_data.set(Some(return_data));
  71. darkfi_sdk::entrypoint::SUCCESS
  72. }
  73. /// Appends a new object to the [`Env`] objects store.
  74. /// The data for the object is read from `ptr`.
  75. ///
  76. /// Returns an index corresponding to the new object's index in the objects
  77. /// store. (This index is equal to the last index in the store.)
  78. pub(crate) fn put_object_bytes(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i64 {
  79. let (env, mut store) = ctx.data_and_store_mut();
  80. let cid = env.contract_id;
  81. // Subtract used gas. Here we count the length read from the memory slice.
  82. env.subtract_gas(&mut store, len as u64);
  83. let memory_view = env.memory_view(&store);
  84. //debug!(target: "runtime::util", "diagnostic:");
  85. let pages = memory_view.size().0;
  86. //debug!(target: "runtime::util", " pages: {}", pages);
  87. let Ok(slice) = ptr.slice(&memory_view, len) else {
  88. error!(
  89. target: "runtime::util::put_object_bytes",
  90. "[WASM] [{}] put_object_bytes(): Failed to make slice from ptr", cid,
  91. );
  92. return darkfi_sdk::error::INTERNAL_ERROR
  93. };
  94. let mut buf = vec![0_u8; len as usize];
  95. if let Err(e) = slice.read_slice(&mut buf) {
  96. error!(
  97. target: "runtime::util::put_object_bytes",
  98. "[WASM] [{}] put_object_bytes(): Failed to read from memory slice: {}", cid, e,
  99. );
  100. return darkfi_sdk::error::INTERNAL_ERROR
  101. };
  102. // There would be a serious problem if this is zero.
  103. // The number of pages is calculated as a quantity X + 1 where X >= 0
  104. assert!(pages > 0);
  105. //debug!(target: "runtime::util", " memory: {:02x?}", &buf[0..32]);
  106. //debug!(target: "runtime::util", " {:x?}", &buf[32..64]);
  107. //debug!(target: "runtime::util", " ptr location: {}", ptr.offset());
  108. let mut objects = env.objects.borrow_mut();
  109. objects.push(buf);
  110. let obj_idx = objects.len() - 1;
  111. if obj_idx > u32::MAX as usize {
  112. return darkfi_sdk::error::DATA_TOO_LARGE
  113. }
  114. obj_idx as i64
  115. }
  116. /// Retrieve an object from the object store specified by the index `idx`.
  117. /// The object's data is written to `ptr`.
  118. ///
  119. /// Returns `SUCCESS` on success and an error code otherwise.
  120. pub(crate) fn get_object_bytes(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, idx: u32) -> i64 {
  121. // Get the slice, where we will read the size of the buffer
  122. let (env, mut store) = ctx.data_and_store_mut();
  123. let cid = env.contract_id;
  124. // Get the object from env
  125. let objects = env.objects.borrow();
  126. if idx as usize >= objects.len() {
  127. error!(
  128. target: "runtime::util::get_object_bytes",
  129. "[WASM] [{}] get_object_bytes(): Tried to access object out of bounds", cid,
  130. );
  131. return darkfi_sdk::error::DATA_TOO_LARGE
  132. }
  133. let obj = objects[idx as usize].clone();
  134. drop(objects);
  135. if obj.len() > u32::MAX as usize {
  136. return darkfi_sdk::error::DATA_TOO_LARGE
  137. }
  138. // Subtract used gas. Here we count the bytes written to the memory slice
  139. env.subtract_gas(&mut store, obj.len() as u64);
  140. // Read N bytes from the object and write onto the ptr.
  141. let memory_view = env.memory_view(&store);
  142. let Ok(slice) = ptr.slice(&memory_view, obj.len() as u32) else {
  143. error!(
  144. target: "runtime::util::get_object_bytes",
  145. "[WASM] [{}] get_object_bytes(): Failed to make slice from ptr", cid,
  146. );
  147. return darkfi_sdk::error::INTERNAL_ERROR
  148. };
  149. // Put the result in the VM
  150. if let Err(e) = slice.write_slice(&obj) {
  151. error!(
  152. target: "runtime::util::get_object_bytes",
  153. "[WASM] [{}] get_object_bytes(): Failed to write to memory slice: {}", cid, e,
  154. );
  155. return darkfi_sdk::error::INTERNAL_ERROR
  156. };
  157. darkfi_sdk::entrypoint::SUCCESS
  158. }
  159. /// Returns the size (number of bytes) of an object in the object store
  160. /// specified by index `idx`.
  161. pub(crate) fn get_object_size(mut ctx: FunctionEnvMut<Env>, idx: u32) -> i64 {
  162. // Get the slice, where we will read the size of the buffer
  163. let (env, mut store) = ctx.data_and_store_mut();
  164. let cid = env.contract_id;
  165. // Get the object from env
  166. let objects = env.objects.borrow();
  167. if idx as usize >= objects.len() {
  168. error!(
  169. target: "runtime::util::get_object_size",
  170. "[WASM] [{}] get_object_size(): Tried to access object out of bounds", cid,
  171. );
  172. return darkfi_sdk::error::DATA_TOO_LARGE
  173. }
  174. let obj = &objects[idx as usize];
  175. let obj_len = obj.len();
  176. drop(objects);
  177. if obj_len > u32::MAX as usize {
  178. return darkfi_sdk::error::DATA_TOO_LARGE
  179. }
  180. // Subtract used gas. Here we count the size of the object.
  181. // TODO: This could probably be fixed-cost
  182. env.subtract_gas(&mut store, obj_len as u64);
  183. obj_len as i64
  184. }
  185. /// Will return current runtime configured verifying block height number
  186. pub(crate) fn get_verifying_block_height(mut ctx: FunctionEnvMut<Env>) -> u64 {
  187. let (env, mut store) = ctx.data_and_store_mut();
  188. // Subtract used gas. Here we count the size of the object.
  189. // u64 is 8 bytes.
  190. env.subtract_gas(&mut store, 8);
  191. env.verifying_block_height
  192. }
  193. /// Will return current runtime configured transaction hash
  194. pub(crate) fn get_tx_hash(mut ctx: FunctionEnvMut<Env>) -> i64 {
  195. let (env, mut store) = ctx.data_and_store_mut();
  196. let cid = env.contract_id;
  197. if let Err(e) =
  198. acl_allow(env, &[ContractSection::Deploy, ContractSection::Exec, ContractSection::Metadata])
  199. {
  200. error!(
  201. target: "runtime::util::get_tx",
  202. "[WASM] [{}] get_tx(): Called in unauthorized section: {}", cid, e,
  203. );
  204. return darkfi_sdk::error::CALLER_ACCESS_DENIED
  205. }
  206. // Subtract used gas. Here we count the size of the object.
  207. env.subtract_gas(&mut store, 32);
  208. // Return the length of the objects Vector.
  209. // This is the location of the data that was retrieved and pushed
  210. let mut objects = env.objects.borrow_mut();
  211. objects.push(env.tx_hash.inner().to_vec());
  212. (objects.len() - 1) as i64
  213. }
  214. /// Will return current runtime configured verifying block height number
  215. pub(crate) fn get_call_index(mut ctx: FunctionEnvMut<Env>) -> u32 {
  216. let (env, mut store) = ctx.data_and_store_mut();
  217. // Subtract used gas. Here we count the size of the object.
  218. // u32 is 4 bytes.
  219. env.subtract_gas(&mut store, 4);
  220. env.call_idx
  221. }
  222. /// Will return current blockchain timestamp,
  223. /// defined as the last block's timestamp.
  224. pub(crate) fn get_blockchain_time(mut ctx: FunctionEnvMut<Env>) -> i64 {
  225. let (env, mut store) = ctx.data_and_store_mut();
  226. let cid = &env.contract_id;
  227. // Grab current last block
  228. let timestamp = match env.blockchain.lock().unwrap().last_block_timestamp() {
  229. Ok(b) => b,
  230. Err(e) => {
  231. error!(
  232. target: "runtime::util::get_blockchain_time",
  233. "[WASM] [{}] get_blockchain_time(): Internal error getting from blocks tree: {}", cid, e,
  234. );
  235. return darkfi_sdk::error::DB_GET_FAILED
  236. }
  237. };
  238. // Subtract used gas. Here we count the size of the object.
  239. // u64 is 8 bytes.
  240. env.subtract_gas(&mut store, 8);
  241. // Create the return object
  242. let mut ret = Vec::with_capacity(8);
  243. ret.extend_from_slice(&timestamp.inner().to_be_bytes());
  244. // Copy Vec<u8> to the VM
  245. let mut objects = env.objects.borrow_mut();
  246. objects.push(ret.to_vec());
  247. if objects.len() > u32::MAX as usize {
  248. return darkfi_sdk::error::DATA_TOO_LARGE
  249. }
  250. (objects.len() - 1) as i64
  251. }
  252. /// Grabs last block from the `Blockchain` overlay and then copies its
  253. /// height to the VM's object store.
  254. ///
  255. /// On success, returns the index of the new object in the object store.
  256. /// Otherwise, returns an error code.
  257. pub(crate) fn get_last_block_height(mut ctx: FunctionEnvMut<Env>) -> i64 {
  258. let (env, mut store) = ctx.data_and_store_mut();
  259. let cid = &env.contract_id;
  260. // Enforce function ACL
  261. if let Err(e) = acl_allow(env, &[ContractSection::Exec]) {
  262. error!(
  263. target: "runtime::util::get_last_block_height",
  264. "[WASM] [{}] get_last_block_height(): Called in unauthorized section: {}", cid, e,
  265. );
  266. return darkfi_sdk::error::CALLER_ACCESS_DENIED
  267. }
  268. // Grab current last block height
  269. let height = match env.blockchain.lock().unwrap().last_block_height() {
  270. Ok(b) => b,
  271. Err(e) => {
  272. error!(
  273. target: "runtime::util::get_last_block_height",
  274. "[WASM] [{}] get_last_block_height(): Internal error getting from blocks tree: {}", cid, e,
  275. );
  276. return darkfi_sdk::error::DB_GET_FAILED
  277. }
  278. };
  279. // Subtract used gas. Here we count the size of the object.
  280. // u64 is 8 bytes.
  281. env.subtract_gas(&mut store, 8);
  282. // Create the return object
  283. let mut ret = Vec::with_capacity(8);
  284. ret.extend_from_slice(&darkfi_serial::serialize(&height));
  285. // Copy Vec<u8> to the VM
  286. let mut objects = env.objects.borrow_mut();
  287. objects.push(ret.to_vec());
  288. if objects.len() > u32::MAX as usize {
  289. return darkfi_sdk::error::DATA_TOO_LARGE
  290. }
  291. (objects.len() - 1) as i64
  292. }
  293. /// Reads a transaction by hash from the transactions store.
  294. ///
  295. /// This function can be called from the Exec or Metadata [`ContractSection`].
  296. ///
  297. /// On success, returns the length of the transaction bytes vector in the environment.
  298. /// Otherwise, returns an error code.
  299. pub(crate) fn get_tx(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>) -> i64 {
  300. let (env, mut store) = ctx.data_and_store_mut();
  301. let cid = env.contract_id;
  302. if let Err(e) = acl_allow(env, &[ContractSection::Exec, ContractSection::Metadata]) {
  303. error!(
  304. target: "runtime::util::get_tx",
  305. "[WASM] [{}] get_tx(): Called in unauthorized section: {}", cid, e,
  306. );
  307. return darkfi_sdk::error::CALLER_ACCESS_DENIED
  308. }
  309. // Subtract used gas. Here we count the length of the looked-up hash.
  310. env.subtract_gas(&mut store, blake3::OUT_LEN as u64);
  311. // Ensure that it is possible to read memory
  312. let memory_view = env.memory_view(&store);
  313. let Ok(mem_slice) = ptr.slice(&memory_view, blake3::OUT_LEN as u32) else {
  314. error!(
  315. target: "runtime::util::get_tx",
  316. "[WASM] [{}] get_tx(): Failed to make slice from ptr", cid,
  317. );
  318. return darkfi_sdk::error::DB_GET_FAILED
  319. };
  320. let mut buf = vec![0_u8; blake3::OUT_LEN];
  321. if let Err(e) = mem_slice.read_slice(&mut buf) {
  322. error!(
  323. target: "runtime::util::get_tx",
  324. "[WASM] [{}] get_tx(): Failed to read from memory slice: {}", cid, e,
  325. );
  326. return darkfi_sdk::error::DB_GET_FAILED
  327. };
  328. let mut buf_reader = Cursor::new(buf);
  329. // Decode hash bytes for transaction that we wish to retrieve
  330. let hash: [u8; blake3::OUT_LEN] = match Decodable::decode(&mut buf_reader) {
  331. Ok(v) => v,
  332. Err(e) => {
  333. error!(
  334. target: "runtime::util::get_tx",
  335. "[WASM] [{}] get_tx(): Failed to decode hash from vec: {}", cid, e,
  336. );
  337. return darkfi_sdk::error::DB_GET_FAILED
  338. }
  339. };
  340. // Make sure there are no trailing bytes in the buffer. This means we've used all data that was
  341. // supplied.
  342. if buf_reader.position() != blake3::OUT_LEN as u64 {
  343. error!(
  344. target: "runtime::util::get_tx",
  345. "[WASM] [{}] get_tx(): Trailing bytes in argument stream", cid,
  346. );
  347. return darkfi_sdk::error::DB_GET_FAILED
  348. }
  349. // Retrieve transaction using the `hash`
  350. let ret = match env.blockchain.lock().unwrap().transactions.get_raw(&hash) {
  351. Ok(v) => v,
  352. Err(e) => {
  353. error!(
  354. target: "runtime::util::get_tx",
  355. "[WASM] [{}] get_tx(): Internal error getting from tree: {}", cid, e,
  356. );
  357. return darkfi_sdk::error::DB_GET_FAILED
  358. }
  359. };
  360. // Return special error if the data is empty
  361. let Some(return_data) = ret else {
  362. debug!(
  363. target: "runtime::util::get_tx",
  364. "[WASM] [{}] get_tx(): Return data is empty", cid,
  365. );
  366. return darkfi_sdk::error::DB_GET_EMPTY
  367. };
  368. if return_data.len() > u32::MAX as usize {
  369. return darkfi_sdk::error::DATA_TOO_LARGE
  370. }
  371. // Subtract used gas. Here we count the length of the data read from db.
  372. env.subtract_gas(&mut store, return_data.len() as u64);
  373. // Copy the data (Vec<u8>) to the VM by pushing it to the objects Vector.
  374. let mut objects = env.objects.borrow_mut();
  375. if objects.len() == u32::MAX as usize {
  376. return darkfi_sdk::error::DATA_TOO_LARGE
  377. }
  378. // Return the length of the objects Vector.
  379. // This is the location of the data that was retrieved and pushed
  380. objects.push(return_data.to_vec());
  381. (objects.len() - 1) as i64
  382. }
  383. /// Reads a transaction location by hash from the transactions store.
  384. ///
  385. /// This function can be called from the Exec or Metadata [`ContractSection`].
  386. ///
  387. /// On success, returns the length of the transaction location bytes vector in
  388. /// the environment. Otherwise, returns an error code.
  389. pub(crate) fn get_tx_location(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>) -> i64 {
  390. let (env, mut store) = ctx.data_and_store_mut();
  391. let cid = env.contract_id;
  392. if let Err(e) = acl_allow(env, &[ContractSection::Exec, ContractSection::Metadata]) {
  393. error!(
  394. target: "runtime::util::get_tx_location",
  395. "[WASM] [{}] get_tx_location(): Called in unauthorized section: {}", cid, e,
  396. );
  397. return darkfi_sdk::error::CALLER_ACCESS_DENIED
  398. }
  399. // Subtract used gas. Here we count the length of the looked-up hash.
  400. env.subtract_gas(&mut store, blake3::OUT_LEN as u64);
  401. // Ensure that it is possible to read memory
  402. let memory_view = env.memory_view(&store);
  403. let Ok(mem_slice) = ptr.slice(&memory_view, blake3::OUT_LEN as u32) else {
  404. error!(
  405. target: "runtime::util::get_tx_location",
  406. "[WASM] [{}] get_tx_location(): Failed to make slice from ptr", cid,
  407. );
  408. return darkfi_sdk::error::DB_GET_FAILED
  409. };
  410. let mut buf = vec![0_u8; blake3::OUT_LEN];
  411. if let Err(e) = mem_slice.read_slice(&mut buf) {
  412. error!(
  413. target: "runtime::util::get_tx_location",
  414. "[WASM] [{}] get_tx_location(): Failed to read from memory slice: {}", cid, e,
  415. );
  416. return darkfi_sdk::error::DB_GET_FAILED
  417. };
  418. let mut buf_reader = Cursor::new(buf);
  419. // Decode hash bytes for transaction that we wish to retrieve
  420. let hash: [u8; blake3::OUT_LEN] = match Decodable::decode(&mut buf_reader) {
  421. Ok(v) => v,
  422. Err(e) => {
  423. error!(
  424. target: "runtime::util::get_tx_location",
  425. "[WASM] [{}] get_tx_location(): Failed to decode hash from vec: {}", cid, e,
  426. );
  427. return darkfi_sdk::error::DB_GET_FAILED
  428. }
  429. };
  430. // Make sure there are no trailing bytes in the buffer. This means we've used all data that was
  431. // supplied.
  432. if buf_reader.position() != blake3::OUT_LEN as u64 {
  433. error!(
  434. target: "runtime::util::get_tx_location",
  435. "[WASM] [{}] get_tx_location(): Trailing bytes in argument stream", cid,
  436. );
  437. return darkfi_sdk::error::DB_GET_FAILED
  438. }
  439. // Retrieve transaction using the `hash`
  440. let ret = match env.blockchain.lock().unwrap().transactions.get_location_raw(&hash) {
  441. Ok(v) => v,
  442. Err(e) => {
  443. error!(
  444. target: "runtime::util::get_tx_location",
  445. "[WASM] [{}] get_tx_location(): Internal error getting from tree: {}", cid, e,
  446. );
  447. return darkfi_sdk::error::DB_GET_FAILED
  448. }
  449. };
  450. // Return special error if the data is empty
  451. let Some(return_data) = ret else {
  452. debug!(
  453. target: "runtime::util::get_tx_location",
  454. "[WASM] [{}] get_tx_location(): Return data is empty", cid,
  455. );
  456. return darkfi_sdk::error::DB_GET_EMPTY
  457. };
  458. if return_data.len() > u32::MAX as usize {
  459. return darkfi_sdk::error::DATA_TOO_LARGE
  460. }
  461. // Subtract used gas. Here we count the length of the data read from db.
  462. env.subtract_gas(&mut store, return_data.len() as u64);
  463. // Copy the data (Vec<u8>) to the VM by pushing it to the objects Vector.
  464. let mut objects = env.objects.borrow_mut();
  465. if objects.len() == u32::MAX as usize {
  466. return darkfi_sdk::error::DATA_TOO_LARGE
  467. }
  468. // Return the length of the objects Vector.
  469. // This is the location of the data that was retrieved and pushed
  470. objects.push(return_data.to_vec());
  471. (objects.len() - 1) as i64
  472. }