db.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. use darkfi_sdk::crypto::{MerkleNode, Nullifier};
  2. use log::{debug, error};
  3. use wasmer::{AsStoreRef, FunctionEnvMut, WasmPtr};
  4. use crate::{
  5. node::state::ProgramState,
  6. runtime::{
  7. memory::MemoryManipulation,
  8. vm_runtime::{ContractSection, Env},
  9. },
  10. };
  11. /// Only deploy() can call this. Creates a new database instance for this contract.
  12. ///
  13. /// ```
  14. /// type DbHandle = u32;
  15. /// db_init(db_name) -> DbHandle
  16. /// ```
  17. pub(crate) fn db_init(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  18. let env = ctx.data();
  19. match env.contract_section {
  20. ContractSection::Deploy => {
  21. let env = ctx.data();
  22. let memory_view = env.memory_view(&ctx);
  23. match ptr.read_utf8_string(&memory_view, len) {
  24. Ok(db_name) => {
  25. // TODO:
  26. // * db_name = blake3_hash(contract_id, db_name)
  27. // * create db_name sled database
  28. }
  29. Err(_) => {
  30. error!(target: "wasm_runtime::drk_log", "Failed to read UTF-8 string from VM memory");
  31. return -2;
  32. }
  33. }
  34. 0
  35. }
  36. _ => -1,
  37. }
  38. }
  39. /// Everyone can call this. Will read a key from the key-value store.
  40. ///
  41. /// ```
  42. /// value = db_get(db_handle, key);
  43. /// ```
  44. pub(crate) fn db_get(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  45. let env = ctx.data();
  46. match env.contract_section {
  47. ContractSection::Update => 0,
  48. _ => -1,
  49. }
  50. }
  51. /// Only update() can call this. Starts an atomic transaction.
  52. ///
  53. /// ```
  54. /// tx_handle = db_begin_tx();
  55. /// ```
  56. pub(crate) fn db_begin_tx(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  57. let env = ctx.data();
  58. match env.contract_section {
  59. ContractSection::Update => 0,
  60. _ => -1,
  61. }
  62. }
  63. /// Only update() can call this. Set a value within the transaction.
  64. ///
  65. /// ```
  66. /// db_set(tx_handle, key, value);
  67. /// ```
  68. pub(crate) fn db_set(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  69. let env = ctx.data();
  70. match env.contract_section {
  71. ContractSection::Update => 0,
  72. _ => -1,
  73. }
  74. }
  75. /// Only update() can call this. This writes the atomic tx to the database.
  76. ///
  77. /// ```
  78. /// db_end_tx(db_handle, tx_handle);
  79. /// ```
  80. pub(crate) fn db_end_tx(mut ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i32 {
  81. let env = ctx.data();
  82. match env.contract_section {
  83. ContractSection::Update => 0,
  84. _ => -1,
  85. }
  86. }