db.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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_DEL_FAILED, DB_GET_FAILED, DB_INIT_FAILED,
  23. DB_LOOKUP_FAILED, DB_SET_FAILED, DB_SUCCESS,
  24. },
  25. };
  26. use darkfi_serial::{deserialize, serialize, Decodable};
  27. use log::{debug, error, info};
  28. use wasmer::{FunctionEnvMut, WasmPtr};
  29. use crate::{
  30. blockchain::contract_store::SMART_CONTRACT_ZKAS_DB_NAME,
  31. runtime::vm_runtime::{ContractSection, Env},
  32. zk::{empty_witnesses, VerifyingKey, ZkCircuit},
  33. zkas::ZkBinary,
  34. };
  35. /// Internal wasm runtime API for sled trees
  36. pub struct DbHandle {
  37. pub contract_id: ContractId,
  38. pub tree: [u8; 32],
  39. }
  40. impl DbHandle {
  41. pub fn new(contract_id: ContractId, tree: [u8; 32]) -> Self {
  42. Self { contract_id, tree }
  43. }
  44. }
  45. /// Only deploy() can call this. Creates a new database instance for this contract.
  46. pub(crate) fn db_init(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  47. let env = ctx.data();
  48. // Exit as soon as possible
  49. if env.contract_section != ContractSection::Deploy {
  50. error!(target: "runtime::db::db_init()", "db_init called in unauthorized section");
  51. return CALLER_ACCESS_DENIED
  52. }
  53. let memory_view = env.memory_view(&ctx);
  54. let contracts = &env.blockchain.lock().unwrap().contracts;
  55. let contract_id = &env.contract_id;
  56. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  57. error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
  58. return DB_INIT_FAILED
  59. };
  60. let mut buf = vec![0_u8; len as usize];
  61. if let Err(e) = mem_slice.read_slice(&mut buf) {
  62. error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
  63. return DB_INIT_FAILED
  64. };
  65. let mut buf_reader = Cursor::new(buf);
  66. let cid: ContractId = match Decodable::decode(&mut buf_reader) {
  67. Ok(v) => v,
  68. Err(e) => {
  69. error!(target: "runtime::db::db_init()", "Failed to decode ContractId: {}", e);
  70. return DB_INIT_FAILED
  71. }
  72. };
  73. let db_name: String = match Decodable::decode(&mut buf_reader) {
  74. Ok(v) => v,
  75. Err(e) => {
  76. error!(target: "runtime::db::db_init()", "Failed to decode db_name: {}", e);
  77. return DB_INIT_FAILED
  78. }
  79. };
  80. // TODO: Disabled until cursor_remaining feature is available on master.
  81. // Then enable #![feature(cursor_remaining)] in src/lib.rs
  82. // unstable feature, open issue https://github.com/rust-lang/rust/issues/86369
  83. /*if !buf_reader.is_empty() {
  84. error!(target: "runtime::db::db_init()", "Trailing bytes in argument stream");
  85. return DB_DEL_FAILED
  86. }*/
  87. if db_name == SMART_CONTRACT_ZKAS_DB_NAME {
  88. error!(target: "runtime::db::db_init()", "Attempted to lookup zkas db");
  89. return CALLER_ACCESS_DENIED
  90. }
  91. if &cid != contract_id {
  92. error!(target: "runtime::db::db_init()", "Unauthorized ContractId for db_init");
  93. return CALLER_ACCESS_DENIED
  94. }
  95. let tree_handle = match contracts.init(&cid, &db_name) {
  96. Ok(v) => v,
  97. Err(e) => {
  98. error!(target: "runtime::db::db_init()", "Failed to init db: {}", e);
  99. return DB_INIT_FAILED
  100. }
  101. };
  102. // TODO: Make sure we don't duplicate the DbHandle in the vec.
  103. // It should behave like an ordered set.
  104. let mut db_handles = env.db_handles.borrow_mut();
  105. db_handles.push(DbHandle::new(cid, tree_handle));
  106. (db_handles.len() - 1) as i32
  107. }
  108. /// Everyone can call this. Lookups up a database handle from its name.
  109. pub(crate) fn db_lookup(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  110. let env = ctx.data();
  111. match env.contract_section {
  112. ContractSection::Deploy |
  113. ContractSection::Exec |
  114. ContractSection::Update |
  115. ContractSection::Metadata => {
  116. // pass
  117. }
  118. _ => {
  119. error!(target: "runtime::db::db_lookup()", "db_lookup called in unauthorized section");
  120. return CALLER_ACCESS_DENIED
  121. }
  122. }
  123. let memory_view = env.memory_view(&ctx);
  124. let contracts = &env.blockchain.lock().unwrap().contracts;
  125. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  126. error!(target: "runtime::db::db_lookup()", "Failed to make slice from ptr");
  127. return DB_LOOKUP_FAILED
  128. };
  129. let mut buf = vec![0_u8; len as usize];
  130. if let Err(e) = mem_slice.read_slice(&mut buf) {
  131. error!(target: "runtime::db::db_lookup()", "Failed to read from memory slice: {}", e);
  132. return DB_LOOKUP_FAILED
  133. };
  134. let mut buf_reader = Cursor::new(buf);
  135. let cid: ContractId = match Decodable::decode(&mut buf_reader) {
  136. Ok(v) => v,
  137. Err(e) => {
  138. error!(target: "runtime::db::db_lookup()", "Failed to decode ContractId: {}", e);
  139. return DB_LOOKUP_FAILED
  140. }
  141. };
  142. let db_name: String = match Decodable::decode(&mut buf_reader) {
  143. Ok(v) => v,
  144. Err(e) => {
  145. error!(target: "runtime::db::db_lookup()", "Failed to decode db_name: {}", e);
  146. return DB_LOOKUP_FAILED
  147. }
  148. };
  149. if db_name == SMART_CONTRACT_ZKAS_DB_NAME {
  150. error!(target: "runtime::db::db_lookup()", "Attempted to lookup zkas db");
  151. return CALLER_ACCESS_DENIED
  152. }
  153. // TODO: Disabled until cursor_remaining feature is available on master.
  154. // Then enable #![feature(cursor_remaining)] in src/lib.rs
  155. // unstable feature, open issue https://github.com/rust-lang/rust/issues/86369
  156. /*if !buf_reader.is_empty() {
  157. error!(target: "runtime::db::db_lookup()", "Trailing bytes in argument stream");
  158. return DB_LOOKUP_FAILED
  159. }*/
  160. let tree_handle = match contracts.lookup(&cid, &db_name) {
  161. Ok(v) => v,
  162. Err(_) => return DB_LOOKUP_FAILED,
  163. };
  164. // TODO: Make sure we don't duplicate the DbHandle in the vec.
  165. // It should behave like an ordered set.
  166. let mut db_handles = env.db_handles.borrow_mut();
  167. db_handles.push(DbHandle::new(cid, tree_handle));
  168. (db_handles.len() - 1) as i32
  169. }
  170. /// Set a value within the transaction.
  171. pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  172. let env = ctx.data();
  173. if env.contract_section != ContractSection::Deploy &&
  174. env.contract_section != ContractSection::Update
  175. {
  176. error!(target: "runtime::db::db_set()", "db_set called in unauthorized section");
  177. return CALLER_ACCESS_DENIED
  178. }
  179. let memory_view = env.memory_view(&ctx);
  180. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  181. error!(target: "runtime::db::db_set()", "Failed to make slice from ptr");
  182. return DB_SET_FAILED
  183. };
  184. let mut buf = vec![0_u8; len as usize];
  185. if let Err(e) = mem_slice.read_slice(&mut buf) {
  186. error!(target: "runtime::db::db_set()", "Failed to read from memory slice: {}", e);
  187. return DB_SET_FAILED
  188. };
  189. let mut buf_reader = Cursor::new(buf);
  190. let db_handle_index: u32 = match Decodable::decode(&mut buf_reader) {
  191. Ok(v) => v,
  192. Err(e) => {
  193. error!(target: "runtime::db::db_set()", "Failed to decode DbHandle: {}", e);
  194. return DB_SET_FAILED
  195. }
  196. };
  197. let db_handle_index = db_handle_index as usize;
  198. let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  199. Ok(v) => v,
  200. Err(e) => {
  201. error!(target: "runtime::db::db_set()", "Failed to decode key vec: {}", e);
  202. return DB_SET_FAILED
  203. }
  204. };
  205. let value: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  206. Ok(v) => v,
  207. Err(e) => {
  208. error!(target: "runtime::db::db_set()", "Failed to decode value vec: {}", e);
  209. return DB_SET_FAILED
  210. }
  211. };
  212. // TODO: Disabled until cursor_remaining feature is available on master.
  213. // Then enable #![feature(cursor_remaining)] in src/lib.rs
  214. // unstable feature, open issue https://github.com/rust-lang/rust/issues/86369
  215. /*if !buf_reader.is_empty() {
  216. error!(target: "runtime::db::db_set()", "Trailing bytes in argument stream");
  217. return DB_DEL_FAILED
  218. }*/
  219. let db_handles = env.db_handles.borrow();
  220. if db_handles.len() <= db_handle_index {
  221. error!(target: "runtime::db::db_set()", "Requested DbHandle that is out of bounds");
  222. return DB_SET_FAILED
  223. }
  224. let db_handle = &db_handles[db_handle_index];
  225. if db_handle.contract_id != env.contract_id {
  226. error!(target: "runtime::db::db_set()", "Unauthorized to write to DbHandle");
  227. return CALLER_ACCESS_DENIED
  228. }
  229. if env
  230. .blockchain
  231. .lock()
  232. .unwrap()
  233. .overlay
  234. .lock()
  235. .unwrap()
  236. .insert(&db_handle.tree, &key, &value)
  237. .is_err()
  238. {
  239. error!(target: "runtime::db::db_set()", "Couldn't insert to db_handle tree");
  240. return DB_SET_FAILED
  241. }
  242. DB_SUCCESS
  243. }
  244. /// Remove a key from the database.
  245. pub(crate) fn db_del(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  246. let env = ctx.data();
  247. if env.contract_section != ContractSection::Deploy &&
  248. env.contract_section != ContractSection::Update
  249. {
  250. error!(target: "runtime::db::db_del()", "db_del called in unauthorized section");
  251. return CALLER_ACCESS_DENIED
  252. }
  253. let memory_view = env.memory_view(&ctx);
  254. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  255. error!(target: "runtime::db::db_del()", "Failed to make slice from ptr");
  256. return DB_DEL_FAILED
  257. };
  258. let mut buf = vec![0_u8; len as usize];
  259. if let Err(e) = mem_slice.read_slice(&mut buf) {
  260. error!(target: "runtime::db::db_del()", "Failed to read from memory slice: {}", e);
  261. return DB_DEL_FAILED
  262. };
  263. let mut buf_reader = Cursor::new(buf);
  264. let db_handle_index: u32 = match Decodable::decode(&mut buf_reader) {
  265. Ok(v) => v,
  266. Err(e) => {
  267. error!(target: "runtime::db::db_del()", "Failed to decode DbHandle: {}", e);
  268. return DB_DEL_FAILED
  269. }
  270. };
  271. let db_handle_index = db_handle_index as usize;
  272. let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  273. Ok(v) => v,
  274. Err(e) => {
  275. error!(target: "runtime::db::db_del()", "Failed to decode key vec: {}", e);
  276. return DB_DEL_FAILED
  277. }
  278. };
  279. // TODO: Disabled until cursor_remaining feature is available on master.
  280. // Then enable #![feature(cursor_remaining)] in src/lib.rs
  281. // unstable feature, open issue https://github.com/rust-lang/rust/issues/86369
  282. /*if !buf_reader.is_empty() {
  283. error!(target: "runtime::db::db_del()", "Trailing bytes in argument stream");
  284. return DB_DEL_FAILED
  285. }*/
  286. let db_handles = env.db_handles.borrow();
  287. if db_handles.len() <= db_handle_index {
  288. error!(target: "runtime::db::db_del()", "Requested DbHandle that is out of bounds");
  289. return DB_DEL_FAILED
  290. }
  291. let db_handle = &db_handles[db_handle_index];
  292. if db_handle.contract_id != env.contract_id {
  293. error!(target: "runtime::db::db_del()", "Unauthorized to write to DbHandle");
  294. return CALLER_ACCESS_DENIED
  295. }
  296. if env.blockchain.lock().unwrap().overlay.lock().unwrap().remove(&db_handle.tree, &key).is_err()
  297. {
  298. error!(target: "runtime::db::db_del()", "Couldn't remove key from db_handle tree");
  299. return DB_DEL_FAILED
  300. }
  301. DB_SUCCESS
  302. }
  303. /// Will read a key from the key-value store.
  304. pub(crate) fn db_get(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i64 {
  305. let env = ctx.data();
  306. if env.contract_section != ContractSection::Deploy &&
  307. env.contract_section != ContractSection::Exec &&
  308. env.contract_section != ContractSection::Metadata
  309. {
  310. error!(target: "runtime::db::db_get()", "db_get called in unauthorized section");
  311. return CALLER_ACCESS_DENIED.into()
  312. }
  313. let memory_view = env.memory_view(&ctx);
  314. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  315. error!(target: "runtime::db::db_get()", "Failed to make slice from ptr");
  316. return DB_GET_FAILED.into()
  317. };
  318. let mut buf = vec![0_u8; len as usize];
  319. if let Err(e) = mem_slice.read_slice(&mut buf) {
  320. error!(target: "runtime::db::db_get()", "Failed to read from memory slice: {}", e);
  321. return DB_GET_FAILED.into()
  322. };
  323. let mut buf_reader = Cursor::new(buf);
  324. let db_handle_index: u32 = match Decodable::decode(&mut buf_reader) {
  325. Ok(v) => v,
  326. Err(e) => {
  327. error!(target: "runtime::db::db_get()", "Failed to decode DbHandle: {}", e);
  328. return DB_GET_FAILED.into()
  329. }
  330. };
  331. let db_handle_index = db_handle_index as usize;
  332. let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  333. Ok(v) => v,
  334. Err(e) => {
  335. error!(target: "runtime::db::db_get()", "Failed to decode key from vec: {}", e);
  336. return DB_GET_FAILED.into()
  337. }
  338. };
  339. // TODO: Disabled until cursor_remaining feature is available on master.
  340. // Then enable #![feature(cursor_remaining)] in src/lib.rs
  341. // unstable feature, open issue https://github.com/rust-lang/rust/issues/86369
  342. /*if !buf_reader.is_empty() {
  343. error!(target: "runtime::db::db_get()", "Trailing bytes in argument stream");
  344. return DB_GET_FAILED.into()
  345. }*/
  346. let db_handles = env.db_handles.borrow();
  347. if db_handles.len() <= db_handle_index {
  348. error!(target: "runtime::db::db_get()", "Requested DbHandle that is out of bounds");
  349. return DB_GET_FAILED.into()
  350. }
  351. let db_handle = &db_handles[db_handle_index];
  352. let ret =
  353. match env.blockchain.lock().unwrap().overlay.lock().unwrap().get(&db_handle.tree, &key) {
  354. Ok(v) => v,
  355. Err(e) => {
  356. error!(target: "runtime::db::db_get()", "Internal error getting from tree: {}", e);
  357. return DB_GET_FAILED.into()
  358. }
  359. };
  360. let Some(return_data) = ret else {
  361. debug!(target: "runtime::db::db_get()", "returned empty vec");
  362. return -127
  363. };
  364. // Copy Vec<u8> to the VM
  365. let mut objects = env.objects.borrow_mut();
  366. objects.push(return_data.to_vec());
  367. (objects.len() - 1) as i64
  368. }
  369. /// Everyone can call this. Will check if a given db contains given key.
  370. pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  371. let env = ctx.data();
  372. if env.contract_section != ContractSection::Deploy &&
  373. env.contract_section != ContractSection::Exec &&
  374. env.contract_section != ContractSection::Update &&
  375. env.contract_section != ContractSection::Metadata
  376. {
  377. error!(target: "runtime::db::db_contains_key()", "db_contains_key called in unauthorized section");
  378. return CALLER_ACCESS_DENIED
  379. }
  380. let memory_view = env.memory_view(&ctx);
  381. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  382. error!(target: "runtime::db::db_contains_key()", "Failed to make slice from ptr");
  383. return DB_CONTAINS_KEY_FAILED
  384. };
  385. let mut buf = vec![0_u8; len as usize];
  386. if let Err(e) = mem_slice.read_slice(&mut buf) {
  387. error!(target: "runtime::db::db_contains_key()", "Failed to read from memory slice: {}", e);
  388. return DB_CONTAINS_KEY_FAILED
  389. };
  390. let mut buf_reader = Cursor::new(buf);
  391. let db_handle_index: u32 = match Decodable::decode(&mut buf_reader) {
  392. Ok(v) => v,
  393. Err(e) => {
  394. error!(target: "runtime::db::db_contains_key()", "Failed to decode DbHandle: {}", e);
  395. return DB_CONTAINS_KEY_FAILED
  396. }
  397. };
  398. let db_handle_index = db_handle_index as usize;
  399. let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  400. Ok(v) => v,
  401. Err(e) => {
  402. error!(target: "runtime::db::db_contains_key()", "Failed to decode key vec: {}", e);
  403. return DB_CONTAINS_KEY_FAILED
  404. }
  405. };
  406. // TODO: Disabled until cursor_remaining feature is available on master.
  407. // Then enable #![feature(cursor_remaining)] in src/lib.rs
  408. // unstable feature, open issue https://github.com/rust-lang/rust/issues/86369
  409. /*if !buf_reader.is_empty() {
  410. error!(target: "runtime::db::db_contains_key()", "Trailing bytes in argument stream");
  411. return DB_CONTAINS_KEY_FAILED
  412. }*/
  413. let db_handles = env.db_handles.borrow();
  414. if db_handles.len() <= db_handle_index {
  415. error!(target: "runtime::db::db_contains_key()", "Requested DbHandle that is out of bounds");
  416. return DB_CONTAINS_KEY_FAILED
  417. }
  418. let db_handle = &db_handles[db_handle_index];
  419. match env.blockchain.lock().unwrap().overlay.lock().unwrap().contains_key(&db_handle.tree, &key)
  420. {
  421. Ok(v) => i32::from(v), // <- 0=false, 1=true
  422. Err(e) => {
  423. error!(target: "runtime::db::db_contains_key()", "sled.tree.contains_key failed: {}", e);
  424. DB_CONTAINS_KEY_FAILED
  425. }
  426. }
  427. }
  428. /// Only `deploy()` can call this. Given a zkas circuit, create a VerifyingKey and insert
  429. /// them both into the db.
  430. pub(crate) fn zkas_db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  431. let env = ctx.data();
  432. if env.contract_section != ContractSection::Deploy {
  433. error!(target: "runtime::db::zkas_db_set()", "zkas_db_set called in unauthorized section");
  434. return CALLER_ACCESS_DENIED
  435. }
  436. let memory_view = env.memory_view(&ctx);
  437. let contract_id = &env.contract_id;
  438. let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
  439. error!(target: "runtime::db::zkas_db_set()", "Failed to make slice from ptr");
  440. return DB_SET_FAILED
  441. };
  442. let mut buf = vec![0u8; len as usize];
  443. if let Err(e) = mem_slice.read_slice(&mut buf) {
  444. error!(target: "runtime::db::zkas_db_set()", "Failed to read from memory slice: {}", e);
  445. return DB_SET_FAILED
  446. };
  447. let mut buf_reader = Cursor::new(buf);
  448. let zkas_bincode: Vec<u8> = match Decodable::decode(&mut buf_reader) {
  449. Ok(v) => v,
  450. Err(e) => {
  451. error!(target: "runtime::db::zkas_db_set()", "Failed to decode zkas bincode bytes: {}", e);
  452. return DB_SET_FAILED
  453. }
  454. };
  455. // Make sure that we're actually working on legitimate bincode.
  456. let Ok(zkbin) = ZkBinary::decode(&zkas_bincode) else {
  457. error!(target: "runtime::db::zkas_db_set()", "Invalid zkas bincode passed to function");
  458. return DB_SET_FAILED
  459. };
  460. // Because of `Runtime::Deploy`, we should be sure that the zkas db is index zero.
  461. let db_handles = env.db_handles.borrow();
  462. let db_handle = &db_handles[0];
  463. // Redundant check
  464. if &db_handle.contract_id != contract_id {
  465. error!(target: "runtime::db::zkas_db_set()", "Internal error, zkas db at index 0 incorrect");
  466. return DB_SET_FAILED
  467. }
  468. // Check if there is existing bincode and compare it. Return DB_SUCCESS if
  469. // they're the same. The assumption should be that VerifyingKey was generated
  470. // already so we can skip things after this guard.
  471. match env
  472. .blockchain
  473. .lock()
  474. .unwrap()
  475. .overlay
  476. .lock()
  477. .unwrap()
  478. .get(&db_handle.tree, &serialize(&zkbin.namespace))
  479. {
  480. Ok(v) => {
  481. if let Some(bytes) = v {
  482. // We allow a panic here because this db should never be corrupted in this way.
  483. let (existing_zkbin, _): (Vec<u8>, Vec<u8>) =
  484. deserialize(&bytes).expect("deserialize tuple");
  485. if existing_zkbin == zkas_bincode {
  486. debug!(target: "runtime::db::zkas_db_set()", "Existing zkas bincode is the same. Skipping.");
  487. return DB_SUCCESS
  488. }
  489. }
  490. }
  491. Err(e) => {
  492. error!(target: "runtime::db::zkas_db_set()", "Internal error getting from tree: {}", e);
  493. return DB_SET_FAILED
  494. }
  495. };
  496. // We didn't find any existing bincode, so let's create a new VerifyingKey and write it all.
  497. info!(target: "runtime::db::zkas_db_set()", "Creating VerifyingKey for {} zkas circuit", zkbin.namespace);
  498. let witnesses = match empty_witnesses(&zkbin) {
  499. Ok(w) => w,
  500. Err(e) => {
  501. error!(target: "runtime::db::zkas_db_set()", "Failed to create empty witnesses: {}", e);
  502. return DB_SET_FAILED
  503. }
  504. };
  505. // Construct the circuit and build the VerifyingKey
  506. let circuit = ZkCircuit::new(witnesses, &zkbin);
  507. let vk = VerifyingKey::build(zkbin.k, &circuit);
  508. let mut vk_buf = vec![];
  509. if let Err(e) = vk.write(&mut vk_buf) {
  510. error!(target: "runtime::db::zkas_db_set()", "Failed to serialize VerifyingKey: {}", e);
  511. return DB_SET_FAILED
  512. }
  513. let key = serialize(&zkbin.namespace);
  514. let value = serialize(&(zkas_bincode, vk_buf));
  515. if env
  516. .blockchain
  517. .lock()
  518. .unwrap()
  519. .overlay
  520. .lock()
  521. .unwrap()
  522. .insert(&db_handle.tree, &key, &value)
  523. .is_err()
  524. {
  525. error!(target: "runtime::db::zkas_db_set()", "Couldn't insert to db_handle tree");
  526. return DB_SET_FAILED
  527. }
  528. DB_SUCCESS
  529. }