db.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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_sdk::{
  20. crypto::ContractId,
  21. db::{
  22. CALLER_ACCESS_DENIED, DB_CONTAINS_KEY_FAILED, DB_GET_FAILED, DB_INIT_FAILED,
  23. DB_LOOKUP_FAILED, DB_SET_FAILED, DB_SUCCESS,
  24. },
  25. };
  26. use darkfi_serial::Decodable;
  27. use log::{debug, error};
  28. use wasmer::{FunctionEnvMut, WasmPtr};
  29. use crate::{
  30. runtime::vm_runtime::{ContractSection, Env},
  31. Result,
  32. };
  33. /// Internal wasm runtime API for sled trees
  34. pub struct DbHandle {
  35. pub contract_id: ContractId,
  36. tree: sled::Tree,
  37. }
  38. impl DbHandle {
  39. pub fn new(contract_id: ContractId, tree: sled::Tree) -> Self {
  40. Self { contract_id, tree }
  41. }
  42. pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
  43. if let Some(v) = self.tree.get(key)? {
  44. return Ok(Some(v.to_vec()))
  45. };
  46. Ok(None)
  47. }
  48. pub fn contains_key(&self, key: &[u8]) -> Result<bool> {
  49. Ok(self.tree.contains_key(key)?)
  50. }
  51. pub fn apply_batch(&self, batch: sled::Batch) -> Result<()> {
  52. Ok(self.tree.apply_batch(batch)?)
  53. }
  54. pub fn flush(&self) -> Result<()> {
  55. let _ = self.tree.flush()?;
  56. Ok(())
  57. }
  58. }
  59. /// Only deploy() can call this. Creates a new database instance for this contract.
  60. pub(crate) fn db_init(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  61. let env = ctx.data();
  62. match env.contract_section {
  63. ContractSection::Deploy => {
  64. let memory_view = env.memory_view(&ctx);
  65. let db = &env.blockchain.sled_db;
  66. let contracts = &env.blockchain.contracts;
  67. let contract_id = &env.contract_id;
  68. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  69. error!(target: "wasm_runtime::db_init", "Failed to make slice from ptr");
  70. return DB_INIT_FAILED
  71. };
  72. let mut buf = vec![0_u8; len as usize];
  73. if let Err(e) = mem_slice.read_slice(&mut buf) {
  74. error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
  75. return DB_INIT_FAILED
  76. };
  77. let mut buf_reader = Cursor::new(buf);
  78. let cid: ContractId = match Decodable::decode(&mut buf_reader) {
  79. Ok(v) => v,
  80. Err(e) => {
  81. error!(target: "runtime::db::db_init()", "Failed to decode ContractId: {}", e);
  82. return DB_INIT_FAILED
  83. }
  84. };
  85. let db_name: String = match Decodable::decode(&mut buf_reader) {
  86. Ok(v) => v,
  87. Err(e) => {
  88. error!(target: "runtime::db::db_init()", "Failed to decode db_name: {}", e);
  89. return DB_INIT_FAILED
  90. }
  91. };
  92. // TODO: Ensure we've read the entire buffer above.
  93. if &cid != contract_id {
  94. error!(target: "runtime::db::db_init()", "Unauthorized ContractId for db_init");
  95. return CALLER_ACCESS_DENIED
  96. }
  97. let tree_handle = match contracts.init(db, &cid, &db_name) {
  98. Ok(v) => v,
  99. Err(e) => {
  100. error!(target: "runtime::db::db_init()", "Failed to init db: {}", e);
  101. return DB_INIT_FAILED
  102. }
  103. };
  104. // TODO: Make sure we don't duplicate the DbHandle in the vec.
  105. // It should behave like an ordered set.
  106. // In `lookup()` we also create a `sled::Batch`. This is done for
  107. // some simplicity reasons, and also for possible future changes.
  108. // However, we make sure that unauthorized writes are not available
  109. // from other functions that interface with the databases.
  110. let mut db_handles = env.db_handles.borrow_mut();
  111. let mut db_batches = env.db_batches.borrow_mut();
  112. db_handles.push(DbHandle::new(cid, tree_handle));
  113. db_batches.push(sled::Batch::default());
  114. (db_handles.len() - 1) as i32
  115. }
  116. _ => {
  117. error!(target: "runtime::db::db_init()", "db_init called in unauthorized section");
  118. CALLER_ACCESS_DENIED
  119. }
  120. }
  121. }
  122. /// Everyone can call this. Lookups up a database handle from its name.
  123. pub(crate) fn db_lookup(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  124. let env = ctx.data();
  125. match env.contract_section {
  126. ContractSection::Deploy |
  127. ContractSection::Exec |
  128. ContractSection::Update |
  129. ContractSection::Metadata => {
  130. let memory_view = env.memory_view(&ctx);
  131. let db = &env.blockchain.sled_db;
  132. let contracts = &env.blockchain.contracts;
  133. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  134. error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
  135. return DB_LOOKUP_FAILED
  136. };
  137. let mut buf = vec![0_u8; len as usize];
  138. if let Err(e) = mem_slice.read_slice(&mut buf) {
  139. error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
  140. return DB_LOOKUP_FAILED
  141. };
  142. let mut buf_reader = Cursor::new(buf);
  143. let cid: ContractId = match Decodable::decode(&mut buf_reader) {
  144. Ok(v) => v,
  145. Err(e) => {
  146. error!(target: "runtime::db::db_init()", "Failed to decode ContractId: {}", e);
  147. return DB_LOOKUP_FAILED
  148. }
  149. };
  150. let db_name: String = match Decodable::decode(&mut buf_reader) {
  151. Ok(v) => v,
  152. Err(e) => {
  153. error!(target: "runtime::db::db_init()", "Failed to decode db_name: {}", e);
  154. return DB_LOOKUP_FAILED
  155. }
  156. };
  157. // TODO: Ensure we've read the entire buffer above.
  158. let tree_handle = match contracts.lookup(db, &cid, &db_name) {
  159. Ok(v) => v,
  160. Err(e) => {
  161. error!(target: "runtime::db::db_init()", "Failed to lookup db: {}", e);
  162. return DB_LOOKUP_FAILED
  163. }
  164. };
  165. // TODO: Make sure we don't duplicate the DbHandle in the vec.
  166. // It should behave like an ordered set.
  167. // In `lookup()` we also create a `sled::Batch`. This is done for
  168. // some simplicity reasons, and also for possible future changes.
  169. // However, we make sure that unauthorized writes are not available
  170. // from other functions that interface with the databases.
  171. let mut db_handles = env.db_handles.borrow_mut();
  172. let mut db_batches = env.db_batches.borrow_mut();
  173. db_handles.push(DbHandle::new(cid, tree_handle));
  174. db_batches.push(sled::Batch::default());
  175. (db_handles.len() - 1) as i32
  176. }
  177. _ => {
  178. error!(target: "runtime::db::db_init()", "db_lookup called in unauthorized section");
  179. CALLER_ACCESS_DENIED
  180. }
  181. }
  182. }
  183. /// Only update() can call this. Set a value within the transaction.
  184. pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  185. let env = ctx.data();
  186. match env.contract_section {
  187. ContractSection::Deploy | ContractSection::Update => {
  188. let memory_view = env.memory_view(&ctx);
  189. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  190. error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
  191. return DB_SET_FAILED
  192. };
  193. let mut buf = vec![0_u8; len as usize];
  194. if let Err(e) = mem_slice.read_slice(&mut buf) {
  195. error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
  196. return DB_SET_FAILED
  197. };
  198. let mut buf_reader = Cursor::new(buf);
  199. // FIXME: There's a type DbHandle=u32, but this should maybe be renamed
  200. let db_handle: u32 = match Decodable::decode(&mut buf_reader) {
  201. Ok(v) => v,
  202. Err(e) => {
  203. error!(target: "runtime::db::db_init()", "Failed to decode DbHandle: {}", e);
  204. return DB_SET_FAILED
  205. }
  206. };
  207. let db_handle = db_handle as usize;
  208. let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  209. Ok(v) => v,
  210. Err(e) => {
  211. error!(target: "runtime::db::db_init()", "Failed to decode key vec: {}", e);
  212. return DB_SET_FAILED
  213. }
  214. };
  215. let value: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  216. Ok(v) => v,
  217. Err(e) => {
  218. error!(target: "runtime::db::db_init()", "Failed to decode value vec: {}", e);
  219. return DB_SET_FAILED
  220. }
  221. };
  222. // TODO: Ensure we've read the entire buffer above.
  223. let db_handles = env.db_handles.borrow();
  224. let mut db_batches = env.db_batches.borrow_mut();
  225. if db_handles.len() <= db_handle || db_batches.len() <= db_handle {
  226. error!(target: "runtime::db::db_init()", "Requested DbHandle that is out of bounds");
  227. return DB_SET_FAILED
  228. }
  229. let handle_idx = db_handle;
  230. let db_handle = &db_handles[handle_idx];
  231. let db_batch = &mut db_batches[handle_idx];
  232. if db_handle.contract_id != env.contract_id {
  233. error!(target: "runtime::db::db_init()", "Unauthorized to write to DbHandle");
  234. return CALLER_ACCESS_DENIED
  235. }
  236. db_batch.insert(key, value);
  237. DB_SUCCESS
  238. }
  239. _ => CALLER_ACCESS_DENIED,
  240. }
  241. }
  242. /// Everyone can call this. Will read a key from the key-value store.
  243. pub(crate) fn db_get(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i64 {
  244. let env = ctx.data();
  245. match env.contract_section {
  246. ContractSection::Deploy | ContractSection::Exec | ContractSection::Metadata => {
  247. let memory_view = env.memory_view(&ctx);
  248. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  249. error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
  250. return DB_GET_FAILED.into()
  251. };
  252. let mut buf = vec![0_u8; len as usize];
  253. if let Err(e) = mem_slice.read_slice(&mut buf) {
  254. error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
  255. return DB_GET_FAILED.into()
  256. };
  257. let mut buf_reader = Cursor::new(buf);
  258. // FIXME: There's a type DbHandle=u32, but this should maybe be renamed
  259. let db_handle: u32 = match Decodable::decode(&mut buf_reader) {
  260. Ok(v) => v,
  261. Err(e) => {
  262. error!(target: "runtime::db::db_init()", "Failed to decode DbHandle: {}", e);
  263. return DB_GET_FAILED.into()
  264. }
  265. };
  266. let db_handle = db_handle as usize;
  267. let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  268. Ok(v) => v,
  269. Err(e) => {
  270. error!(target: "runtime::db::db_init()", "Failed to decode key from vec: {}", e);
  271. return DB_GET_FAILED.into()
  272. }
  273. };
  274. // TODO: Ensure we've read the entire buffer above.
  275. let db_handles = env.db_handles.borrow();
  276. if db_handles.len() <= db_handle {
  277. error!(target: "runtime::db::db_init()", "Requested DbHandle that is out of bounds");
  278. return DB_GET_FAILED.into()
  279. }
  280. let handle_idx = db_handle;
  281. let db_handle = &db_handles[handle_idx];
  282. let ret = match db_handle.get(&key) {
  283. Ok(v) => v,
  284. Err(e) => {
  285. error!(target: "runtime::db::db_init()", "Internal error getting from tree: {}", e);
  286. return DB_GET_FAILED.into()
  287. }
  288. };
  289. let Some(return_data) = ret else {
  290. debug!(target: "runtime::db::db_init()", "returned empty vec");
  291. return -127
  292. };
  293. // Copy Vec<u8> to the VM
  294. let mut objects = env.objects.borrow_mut();
  295. objects.push(return_data);
  296. (objects.len() - 1) as i64
  297. }
  298. _ => CALLER_ACCESS_DENIED.into(),
  299. }
  300. }
  301. /// Everyone can call this. Will check if a given db contains given key.
  302. pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  303. let env = ctx.data();
  304. match env.contract_section {
  305. ContractSection::Deploy |
  306. ContractSection::Exec |
  307. ContractSection::Update |
  308. ContractSection::Metadata => {
  309. let memory_view = env.memory_view(&ctx);
  310. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  311. error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
  312. return DB_CONTAINS_KEY_FAILED
  313. };
  314. let mut buf = vec![0_u8; len as usize];
  315. if let Err(e) = mem_slice.read_slice(&mut buf) {
  316. error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
  317. return DB_CONTAINS_KEY_FAILED
  318. };
  319. let mut buf_reader = Cursor::new(buf);
  320. // FIXME: There's a type DbHandle=u32, but this should maybe be renamed
  321. let db_handle: u32 = match Decodable::decode(&mut buf_reader) {
  322. Ok(v) => v,
  323. Err(e) => {
  324. error!(target: "runtime::db::db_init()", "Failed to decode DbHandle: {}", e);
  325. return DB_CONTAINS_KEY_FAILED
  326. }
  327. };
  328. let db_handle = db_handle as usize;
  329. let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  330. Ok(v) => v,
  331. Err(e) => {
  332. error!(target: "runtime::db::db_init()", "Failed to decode key vec: {}", e);
  333. return DB_CONTAINS_KEY_FAILED
  334. }
  335. };
  336. // TODO: Ensure we've read the entire buffer above.
  337. let db_handles = env.db_handles.borrow();
  338. if db_handles.len() <= db_handle {
  339. error!(target: "runtime::db::db_init()", "Requested DbHandle that is out of bounds");
  340. return DB_CONTAINS_KEY_FAILED
  341. }
  342. let handle_idx = db_handle;
  343. let db_handle = &db_handles[handle_idx];
  344. match db_handle.contains_key(&key) {
  345. Ok(v) => i32::from(v), // <- 0=false, 1=true
  346. Err(e) => {
  347. error!(target: "runtime::db::db_init()", "sled.tree.contains_key failed: {}", e);
  348. DB_CONTAINS_KEY_FAILED
  349. }
  350. }
  351. }
  352. _ => CALLER_ACCESS_DENIED,
  353. }
  354. }