walletdb.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. use crate::crypto::{coin::Coin, merkle::IncrementalWitness, merkle_node::MerkleNode, note::Note};
  2. use crate::serial;
  3. use crate::serial::{deserialize, serialize, Decodable, Encodable};
  4. use crate::util::join_config_path;
  5. use crate::{Error, Result};
  6. use async_std::sync::{Arc, Mutex};
  7. use ff::Field;
  8. use log::*;
  9. use rand::rngs::OsRng;
  10. use rusqlite::{named_params, params, Connection};
  11. use std::path::PathBuf;
  12. pub type WalletPtr = Arc<WalletDb>;
  13. pub type OwnCoins = Vec<(Coin, Note, jubjub::Fr, IncrementalWitness<MerkleNode>)>;
  14. pub struct WalletDb {
  15. pub path: PathBuf,
  16. pub secrets: Vec<jubjub::Fr>,
  17. pub cashier_secrets: Vec<jubjub::Fr>,
  18. pub coins: Mutex<Vec<Coin>>,
  19. pub notes: Mutex<Vec<Note>>,
  20. pub witnesses: Mutex<Vec<IncrementalWitness<MerkleNode>>>,
  21. pub cashier_public: jubjub::SubgroupPoint,
  22. pub public: jubjub::SubgroupPoint,
  23. pub password: String,
  24. }
  25. impl WalletDb {
  26. pub fn new(wallet: &str, password: String) -> Result<Self> {
  27. debug!(target: "walletdb", "new() Constructor called");
  28. let path = join_config_path(&PathBuf::from(wallet))?;
  29. let cashier_secret = jubjub::Fr::random(&mut OsRng);
  30. let secret = jubjub::Fr::random(&mut OsRng);
  31. let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  32. let cashier_public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * cashier_secret;
  33. let coins = Mutex::new(Vec::new());
  34. let notes = Mutex::new(Vec::new());
  35. let witnesses = Mutex::new(Vec::new());
  36. Ok(Self {
  37. path,
  38. cashier_secrets: vec![cashier_secret.clone()],
  39. secrets: vec![secret.clone()],
  40. cashier_public,
  41. public,
  42. coins,
  43. notes,
  44. witnesses,
  45. password,
  46. //conn,
  47. })
  48. }
  49. pub fn init_db(&self) -> Result<()> {
  50. if !self.password.trim().is_empty() {
  51. let contents = include_str!("../../res/schema.sql");
  52. let conn = Connection::open(&self.path)?;
  53. debug!(target: "walletdb", "OPENED CONNECTION AT PATH {:?}", self.path);
  54. conn.pragma_update(None, "key", &self.password)?;
  55. conn.execute_batch(&contents)?;
  56. } else {
  57. info!("Password is empty. You must set a password to use the wallet.");
  58. info!("Current password: {}", self.password);
  59. return Err(Error::EmptyPassword);
  60. }
  61. Ok(())
  62. }
  63. pub fn init_cashier_db(&self) -> Result<()> {
  64. let conn = Connection::open(&self.path)?;
  65. debug!(target: "cashierdb", "OPENED CONNECTION AT PATH {:?}", self.path);
  66. let contents = include_str!("../../res/schema.sql");
  67. conn.execute_batch(&contents)?;
  68. Ok(())
  69. }
  70. pub fn get_own_coins(&self) -> Result<OwnCoins> {
  71. // open connection
  72. let conn = Connection::open(&self.path)?;
  73. // unlock database
  74. conn.pragma_update(None, "key", &self.password)?;
  75. let mut coins = conn.prepare("SELECT * FROM coins")?;
  76. let rows = coins.query_map([], |row| {
  77. let coin = self.get_value_deserialized(row.get(1)?).unwrap();
  78. // note
  79. let serial = self.get_value_deserialized(row.get(2)?).unwrap();
  80. let coin_blind = self.get_value_deserialized(row.get(3)?).unwrap();
  81. let valcom_blind = self.get_value_deserialized(row.get(4)?).unwrap();
  82. let value: u64 = row.get(5)?;
  83. let asset_id: u64 = row.get(6)?;
  84. let note = Note {
  85. serial,
  86. value,
  87. asset_id,
  88. coin_blind,
  89. valcom_blind,
  90. };
  91. let witness = self.get_value_deserialized(row.get(7)?).unwrap();
  92. let key_id: u64 = row.get(8)?;
  93. // return key_private from key_id
  94. let mut get_private_key =
  95. conn.prepare("SELECT key_private FROM keys WHERE key_id = :key_id")?;
  96. let rows = get_private_key.query_map(&[(":key_id", &key_id)], |row| row.get(0))?;
  97. let mut secret = Vec::new();
  98. for id in rows {
  99. secret.push(id?)
  100. }
  101. let secret: jubjub::Fr = self
  102. .get_value_deserialized(
  103. secret
  104. .pop()
  105. .expect("unable to load public_key from walletdb"),
  106. )
  107. .unwrap();
  108. Ok((coin, note, secret, witness))
  109. })?;
  110. let mut own_coins = Vec::new();
  111. for id in rows {
  112. own_coins.push(id?)
  113. }
  114. Ok(own_coins)
  115. }
  116. pub fn put_own_coins(
  117. &self,
  118. coin: Coin,
  119. note: Note,
  120. witness: IncrementalWitness<MerkleNode>,
  121. secret: jubjub::Fr,
  122. ) -> Result<()> {
  123. // prepare the values
  124. let coin = self.get_value_serialized(&coin.repr)?;
  125. let serial = self.get_value_serialized(&note.serial)?;
  126. let coin_blind = self.get_value_serialized(&note.coin_blind)?;
  127. let valcom_blind = self.get_value_serialized(&note.valcom_blind)?;
  128. let value: u64 = note.value;
  129. let asset_id: u64 = note.asset_id;
  130. let witness = self.get_value_serialized(&witness)?;
  131. let secret = self.get_value_serialized(&secret)?;
  132. // open connection
  133. let conn = Connection::open(&self.path)?;
  134. // unlock database
  135. conn.pragma_update(None, "key", &self.password)?;
  136. // return key_id from key_private
  137. let mut get_id =
  138. conn.prepare("SELECT key_id FROM keys WHERE key_private = :key_private")?;
  139. let rows = get_id.query_map::<u64, _, _>(&[(":key_private", &secret)], |row| row.get(0))?;
  140. let mut key_id = Vec::new();
  141. for id in rows {
  142. key_id.push(id?)
  143. }
  144. conn.execute(
  145. "INSERT INTO coins(coin, serial, value, asset_id, coin_blind, valcom_blind, witness, key_id)
  146. VALUES (:coin, :serial, :value, :asset_id, :coin_blind, :valcom_blind, :witness, :key_id)",
  147. named_params! {
  148. ":coin": coin,
  149. ":serial": serial,
  150. ":value": value,
  151. ":asset_id": asset_id,
  152. ":coin_blind": coin_blind,
  153. ":valcom_blind": valcom_blind,
  154. ":witness": witness,
  155. ":key_id": key_id.pop().expect("key_id not found!"),
  156. },
  157. )?;
  158. Ok(())
  159. }
  160. pub fn key_gen(&self) -> (Vec<u8>, Vec<u8>) {
  161. debug!(target: "key_gen", "Attempting to generate keys...");
  162. let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
  163. let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  164. let pubkey = serial::serialize(&public);
  165. let privkey = serial::serialize(&secret);
  166. (pubkey, privkey)
  167. }
  168. pub fn cash_key_gen(&self) -> (Vec<u8>, Vec<u8>) {
  169. debug!(target: "cash key_gen", "Generating cashier keys...");
  170. let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
  171. let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  172. let pubkey = serial::serialize(&public);
  173. let privkey = serial::serialize(&secret);
  174. (pubkey, privkey)
  175. }
  176. pub fn put_keypair(&self, key_public: Vec<u8>, key_private: Vec<u8>) -> Result<()> {
  177. let conn = Connection::open(&self.path)?;
  178. conn.pragma_update(None, "key", &self.password)?;
  179. conn.execute(
  180. "INSERT INTO keys(key_public, key_private) VALUES (?1, ?2)",
  181. params![key_public, key_private],
  182. )?;
  183. Ok(())
  184. }
  185. pub fn put_cashier_pub(&self, key_public: Vec<u8>) -> Result<()> {
  186. debug!(target: "save_cash_key", "Save cashier keys...");
  187. let conn = Connection::open(&self.path)?;
  188. conn.pragma_update(None, "key", &self.password)?;
  189. conn.execute(
  190. "INSERT INTO cashier(key_public) VALUES (?1)",
  191. params![key_public],
  192. )?;
  193. Ok(())
  194. }
  195. pub fn get_public(&self) -> Result<jubjub::SubgroupPoint> {
  196. debug!(target: "get", "Returning keys...");
  197. let conn = Connection::open(&self.path)?;
  198. conn.pragma_update(None, "key", &self.password)?;
  199. let mut stmt = conn.prepare("SELECT key_public FROM keys")?;
  200. // this just gets the first key. maybe we should randomize this
  201. let key_iter = stmt.query_map([], |row| row.get(0))?;
  202. let mut pub_keys = Vec::new();
  203. for key in key_iter {
  204. pub_keys.push(key?);
  205. }
  206. let public: jubjub::SubgroupPoint = self.get_value_deserialized(
  207. pub_keys
  208. .pop()
  209. .expect("unable to load public_key from walletdb"),
  210. )?;
  211. Ok(public)
  212. }
  213. pub fn get_cashier_public(&self) -> Result<jubjub::SubgroupPoint> {
  214. debug!(target: "get_cashier_public", "Returning keys...");
  215. let conn = Connection::open(&self.path)?;
  216. conn.pragma_update(None, "key", &self.password)?;
  217. let mut stmt = conn.prepare("SELECT key_public FROM cashier")?;
  218. let key_iter = stmt.query_map([], |row| row.get(0))?;
  219. let mut pub_keys = Vec::new();
  220. for key in key_iter {
  221. pub_keys.push(key?);
  222. }
  223. let public: jubjub::SubgroupPoint = self.get_value_deserialized(
  224. pub_keys
  225. .pop()
  226. .expect("unable to load cashier public_key from walletdb"),
  227. )?;
  228. Ok(public)
  229. }
  230. pub fn get_private(&self) -> Result<jubjub::Fr> {
  231. debug!(target: "get", "Returning keys...");
  232. let conn = Connection::open(&self.path)?;
  233. conn.pragma_update(None, "key", &self.password)?;
  234. let mut stmt = conn.prepare("SELECT key_private FROM keys")?;
  235. let key_iter = stmt.query_map([], |row| row.get(0))?;
  236. let mut keys = Vec::new();
  237. for key in key_iter {
  238. keys.push(key?);
  239. }
  240. let private: jubjub::Fr = self.get_value_deserialized(
  241. keys.pop()
  242. .expect("unable to load private key from walletdb"),
  243. )?;
  244. Ok(private)
  245. }
  246. pub fn test_wallet(&self) -> Result<()> {
  247. let conn = Connection::open(&self.path)?;
  248. conn.pragma_update(None, "key", &self.password)?;
  249. let mut stmt = conn.prepare("SELECT * FROM keys")?;
  250. let _rows = stmt.query([])?;
  251. Ok(())
  252. }
  253. pub fn get_value_serialized<T: Encodable>(&self, data: &T) -> Result<Vec<u8>> {
  254. let v = serialize(data);
  255. Ok(v)
  256. }
  257. pub fn get_value_deserialized<D: Decodable>(&self, key: Vec<u8>) -> Result<D> {
  258. let v: D = deserialize(&key)?;
  259. Ok(v)
  260. }
  261. }
  262. #[cfg(test)]
  263. mod tests {
  264. use super::*;
  265. #[test]
  266. pub fn test_save_and_load_keypair() -> Result<()> {
  267. let wallet = WalletDb::new("test_wallet.db", "darkfi".into())?;
  268. wallet.init_db()?;
  269. let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
  270. let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  271. let key_public = serial::serialize(&public);
  272. let key_private = serial::serialize(&secret);
  273. wallet.put_keypair(key_public, key_private)?;
  274. let public2 = wallet.get_public()?;
  275. let secret2 = wallet.get_private()?;
  276. assert_eq!(public, public2);
  277. assert_eq!(secret, secret2);
  278. Ok(())
  279. }
  280. // This test will fail
  281. #[test]
  282. pub fn test_put_and_get_own_coins() -> Result<()> {
  283. let wallet = WalletDb::new("test_wallet.db", "darkfi".into())?;
  284. wallet.init_db()?;
  285. let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
  286. let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  287. let key_public = serial::serialize(&public);
  288. let key_private = serial::serialize(&secret);
  289. wallet.put_keypair(key_public, key_private)?;
  290. let note = Note {
  291. serial: jubjub::Fr::random(&mut OsRng),
  292. value: 110,
  293. asset_id: 1,
  294. coin_blind: jubjub::Fr::random(&mut OsRng),
  295. valcom_blind: jubjub::Fr::random(&mut OsRng),
  296. };
  297. let tree = crate::crypto::merkle::CommitmentTree::empty();
  298. let witness = IncrementalWitness::from_tree(&tree);
  299. let coin = Coin::new([0; 32]);
  300. wallet.put_own_coins(coin.clone(), note.clone(), witness, secret)?;
  301. println!("put_own_coins done");
  302. let own_coin = wallet.get_own_coins()?[0].clone();
  303. println!("get_own_coins done");
  304. assert_eq!(own_coin.2, secret);
  305. Ok(())
  306. }
  307. //#[test]
  308. // let password = "roseiscool2021";
  309. // let path = join_config_path(&PathBuf::from("wallet.db"))?;
  310. // let contents = include_str!("../../res/schema.sql");
  311. // let conn = Connection::open(&path)?;
  312. // debug!(target: "walletdb", "OPENED CONNECTION AT PATH {:?}", path);
  313. // conn.pragma_update(None, "key", &password)?;
  314. // conn.execute_batch(&contents)?;
  315. // Ok(())
  316. //}
  317. //#[test]
  318. //pub fn test_keypair() -> Result<()> {
  319. // let path = join_config_path(&PathBuf::from("wallet.db"))?;
  320. // let conn = Connection::open(path)?;
  321. // let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
  322. // let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  323. // let key_public = serial::serialize(&public);
  324. // let key_private = serial::serialize(&secret);
  325. // let mut stmt = conn.prepare("PRAGMA key = 'testkey'")?;
  326. // let _rows = stmt.query([])?;
  327. // conn.execute(
  328. // "INSERT INTO keys(key_public, key_private) VALUES (?1, ?2)",
  329. // params![key_public, key_private],
  330. // )?;
  331. // Ok(())
  332. //}
  333. //#[test]
  334. //pub fn test_get_id() -> Result<()> {
  335. // let path = join_config_path(&PathBuf::from("wallet.db"))?;
  336. // let conn = Connection::open(path)?;
  337. // let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
  338. // let key_private = serial::serialize(&secret);
  339. // let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  340. // let key_public = serial::serialize(&public);
  341. // let mut stmt = conn.prepare("PRAGMA key = 'testkey'")?;
  342. // let _rows = stmt.query([])?;
  343. // conn.execute(
  344. // "INSERT INTO keys(key_public, key_private) VALUES (?1, ?2)",
  345. // params![key_public, key_private],
  346. // )?;
  347. // let mut get_id =
  348. // conn.prepare("SELECT key_id FROM keys WHERE key_private = :key_private")?;
  349. // let rows =
  350. // get_id.query_map::<u8, _, _>(&[(":key_private", &key_private)], |row| row.get(0))?;
  351. // let mut key_id = Vec::new();
  352. // for id in rows {
  353. // key_id.push(id?)
  354. // }
  355. // println!("FOUND ID: {:?}", key_id.pop().unwrap());
  356. // Ok(())
  357. //}
  358. //#[test]
  359. //pub fn test_own_coins() -> Result<()> {
  360. // let key_private = Vec::new();
  361. // let coin = Vec::new();
  362. // let serial = Vec::new();
  363. // let coin_blind = Vec::new();
  364. // let valcom_blind = Vec::new();
  365. // let value = Vec::new();
  366. // let asset_id = Vec::new();
  367. // let witness = Vec::new();
  368. // let path = join_config_path(&PathBuf::from("wallet.db"))?;
  369. // let conn = Connection::open(path)?;
  370. // let contents = include_str!("../../res/schema.sql");
  371. // match conn.execute_batch(&contents) {
  372. // Ok(v) => println!("Database initalized successfully {:?}", v),
  373. // Err(err) => println!("Error: {}", err),
  374. // };
  375. // //let mut unlock = conn.prepare("PRAGMA key = 'testkey'")?;
  376. // //let _rows = unlock.query([])?;
  377. // let mut get_id =
  378. // conn.prepare("SELECT key_id FROM keys WHERE key_private = :key_private")?;
  379. // let rows =
  380. // get_id.query_map::<u8, _, _>(&[(":key_private", &key_private)], |row| row.get(0))?;
  381. // let mut key_id = Vec::new();
  382. // for id in rows {
  383. // key_id.push(id?)
  384. // }
  385. // conn.execute(
  386. // "INSERT INTO coins(coin, serial, value, asset_id, coin_blind, valcom_blind, witness, key_id)
  387. // VALUES (:coin, :serial, :value, :asset_id, :coin_blind, :valcom_blind, :witness, :key_id)",
  388. // named_params! {
  389. // ":coin": coin,
  390. // ":serial": serial,
  391. // ":value": value,
  392. // ":asset_id": asset_id,
  393. // ":coin_blind": coin_blind,
  394. // ":valcom_blind": valcom_blind,
  395. // ":witness": witness,
  396. // ":key_id": key_id.pop().expect("key_id not found!"),
  397. // },
  398. // )?;
  399. // Ok(())
  400. //}
  401. }